@graphrefly/graphrefly 0.33.0 → 0.34.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-3Y4BXFFR.js +1 -0
- package/dist/chunk-65WWQ5CB.js +43 -0
- package/dist/chunk-A3GDELMY.js +61 -0
- package/dist/chunk-KN2UMFT6.js +5 -0
- package/dist/{index--BTb6HUO.d.ts → index-3L3RC3VJ.d.ts} +250 -4
- package/dist/{index-C_cXlbu0.d.cts → index-CQtnGFrZ.d.cts} +250 -4
- package/dist/{index-DDf8PoPO.d.ts → index-CbCNoogR.d.ts} +71 -16
- package/dist/{index-Dgcd59CJ.d.cts → index-IxinNgAH.d.cts} +71 -16
- package/dist/index.cjs +57 -57
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/patterns/ai/browser.cjs +5 -5
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +19 -19
- package/dist/patterns/ai/index.d.cts +1 -1
- package/dist/patterns/ai/index.d.ts +1 -1
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/harness/index.cjs +10 -10
- package/dist/patterns/harness/index.d.cts +3 -3
- package/dist/patterns/harness/index.d.ts +3 -3
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +7 -7
- package/dist/patterns/orchestration/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-DUK7LTJO.js +0 -43
- package/dist/chunk-HIJ2RKVP.js +0 -1
- package/dist/chunk-O2WY22L7.js +0 -5
- package/dist/chunk-Z4GXBOWO.js +0 -61
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Ht=Object.defineProperty;var Dr=Object.getOwnPropertyDescriptor;var Gr=Object.getOwnPropertyNames;var Lr=Object.prototype.hasOwnProperty;var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var Pr=(t,e)=>{for(var n in e)Ht(t,n,{get:e[n],enumerable:!0})},$r=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Gr(e))!Lr.call(t,s)&&s!==n&&Ht(t,s,{get:()=>e[s],enumerable:!(r=Dr(e,s))||r.enumerable});return t};var Fr=t=>$r(Ht({},"__esModule",{value:!0}),t);function kn(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let s=2+n.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=Kt,o[i++]=n.length,o.set(n,i),i+=n.length,o[i++]=r>>>8&255,o[i++]=r&255,o.set(e,i),o}function On(t,e){if(t.length<Nn)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Nn})`);let n=0,r=t[n++];if(r!==Kt)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Kt})`);let s=t[n++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+s+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+s+2} bytes, have ${t.length})`);let o=new TextDecoder().decode(t.subarray(n,n+s));n+=s;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),d=e.lookupCodec(o);if(d==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function Rn(t){t.registerCodec(Vr)}var Vr,Kt,Nn,Ut=be(()=>{"use strict";Vr={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}},Kt=1,Nn=4});function ht(t){if(t==null)return Ke;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Ke,mt=be(()=>{"use strict";Ke={type:"system",id:""}});function ot(){return Ue>0||nt}function Sn(){return Ue>0}function st(t){Ue>0?rt.push(t):t()}function ie(t){Ue+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ue-=1,Ue===0)if(e){if(!nt){let n=rt.splice(0);for(let r of n)try{r()}catch{}Ve.length=0,je.length=0,qe.length=0}}else jr()}}function jr(){let t=!nt;t&&(nt=!0);let e=[],n=0;try{for(;Ve.length>0||je.length>0||qe.length>0||t&&rt.length>0;){if(t&&rt.length>0){let o=rt.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Ve.length=0,je.length=0,qe.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(Ve.length>0?Ve:je.length>0?je:qe).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{t&&(nt=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function it(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!ot()){t(e);return}(u>=5?qe:u===4?je:Ve).push(()=>t(e));return}let r=e.length,s=r,o=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(s=a;a<r&&n(e[a][0])===3;)a++;for(o=a;a<r&&n(e[a][0])===4;)a++;i=a;let d=ot();if(s>0){let u=e.slice(0,s);t(u)}if(o>s){let u=e.slice(s,o);d?Ve.push(()=>t(u)):t(u)}if(i>o){let u=e.slice(o,i);d?je.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?qe.push(()=>t(u)):t(u)}}var Ue,nt,Ve,je,qe,rt,Ce=be(()=>{"use strict";Ue=0,nt=!1,Ve=[],je=[],qe=[],rt=[]});function q(){return Math.trunc(performance.now()*1e6)}function gt(){return Date.now()*1e6}var Ge=be(()=>{"use strict"});var Le,F,Y,Q,ye,we,Ie,le,B,L,ze,bt,An,yt,Mn,Cn,vt,qt,Wt,Yt,Tt,fe=be(()=>{"use strict";Le=Symbol.for("graphrefly/START"),F=Symbol.for("graphrefly/DATA"),Y=Symbol.for("graphrefly/DIRTY"),Q=Symbol.for("graphrefly/RESOLVED"),ye=Symbol.for("graphrefly/INVALIDATE"),we=Symbol.for("graphrefly/PAUSE"),Ie=Symbol.for("graphrefly/RESUME"),le=Symbol.for("graphrefly/TEARDOWN"),B=Symbol.for("graphrefly/COMPLETE"),L=Symbol.for("graphrefly/ERROR"),ze=Object.freeze([Y]),bt=Object.freeze([Q]),An=Object.freeze([ye]),yt=Object.freeze([Le]),Mn=Object.freeze([B]),Cn=Object.freeze([le]),vt=Object.freeze([ze]),qt=Object.freeze([bt]),Wt=Object.freeze([An]),Yt=Object.freeze([Mn]),Tt=Object.freeze([Cn])});function In(t){t.registerMessageType(Le,{tier:0,wireCrossing:!1}),t.registerMessageType(Y,{tier:1,wireCrossing:!1}),t.registerMessageType(ye,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(we,{tier:2,wireCrossing:!1}),t.registerMessageType(Ie,{tier:2,wireCrossing:!1}),t.registerMessageType(F,{tier:3,wireCrossing:!0}),t.registerMessageType(Q,{tier:3,wireCrossing:!0}),t.registerMessageType(B,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(le,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var xt,Dn=be(()=>{"use strict";fe();xt=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Jt(t){let e=zr.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var ve,zr,at=be(()=>{"use strict";ve=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}},zr=["human","llm","wallet","system"]});function Qt(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(Qt);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Qt(t[n]);return e}return null}function Kr(t){let e=Hr.encode(t),n=e.length,r=n*8,s=n+9+63&-64,o=new Uint8Array(s);o.set(e),o[n]=128;let i=new DataView(o.buffer);i.setUint32(s-4,r>>>0,!1),i.setUint32(s-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,p=1359893119,f=2600822924,h=528734635,l=1541459225,m=new Uint32Array(64),b=(v,y)=>v>>>y|v<<32-y;for(let v=0;v<s;v+=64){for(let S=0;S<16;S++)m[S]=i.getUint32(v+S*4,!1);for(let S=16;S<64;S++){let D=m[S-15],M=m[S-2],H=b(D,7)^b(D,18)^D>>>3,X=b(M,17)^b(M,19)^M>>>10;m[S]=m[S-16]+H+m[S-7]+X>>>0}let y=a,x=d,E=u,T=c,w=p,N=f,k=h,C=l;for(let S=0;S<64;S++){let D=b(w,6)^b(w,11)^b(w,25),M=w&N^~w&k,H=C+D+M+Br[S]+m[S]>>>0,X=b(y,2)^b(y,13)^b(y,22),ne=y&x^y&E^x&E,me=X+ne>>>0;C=k,k=N,N=w,w=T+H>>>0,T=E,E=x,x=y,y=H+me>>>0}a=a+y>>>0,d=d+x>>>0,u=u+E>>>0,c=c+T>>>0,p=p+w>>>0,f=f+N>>>0,h=h+k>>>0,l=l+C>>>0}let g=v=>v.toString(16).padStart(8,"0");return g(a)+g(d)+g(u)+g(c)+g(p)+g(f)+g(h)+g(l)}function Xt(t){let e=Qt(t??null),n=JSON.stringify(e);return Kr(n).slice(0,16)}function Ur(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function Zt(t,e,n){let r=n?.id??Ur();if(t===0)return{id:r,version:0};let o=(n?.hash??Xt)(e);return{id:r,version:0,cid:o,prev:null}}function Gn(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var Br,Hr,Ln=be(()=>{"use strict";Br=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Hr=new TextEncoder});function Fn(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function en(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function wt(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ae(t,e,n){let r=Vn(t)?t:[],s=typeof t=="function"?t:typeof e=="function"?e:void 0,o={};return Vn(t)?o=(tn(e)?e:n)??{}:tn(t)?o=t:o=(tn(e)?e:n)??{},new Z(r,s,o)}var Pn,$n,qr,Wr,We,Z,Vn,tn,Re=be(()=>{"use strict";Ut();mt();Ce();Ge();Dn();at();fe();Ln();Pn=()=>{},$n=100;qr=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Wr=(t,e,n,r)=>{let s=t;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[yt]:[yt,[F,o]];s._status==="dirty"&&i.push(ze),it(e,i,s._config.tierOf)},We=new xt({onMessage:qr,onSubscribe:Wr});In(We);Rn(We);Z=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??We,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Xt;let s=r.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?Zt(s,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Fn);let o={};for(let[a,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),o[a]=new t([],void 0,u)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[F,a]])},down(a){i._emit(wt(a))},up(a){i._emitUp(wt(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let s=n?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,d=i?.version??0,u=Zt(e,o,{id:a,hash:s});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=ht(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let s=ht(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new ve({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new ve({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:gt()}}down(e,n){let r=wt(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[F,e]])}up(e,n){if(this._deps.length===0)return;let r=wt(e);if(r.length===0)return;this._checkGuard(n);let s=n??{internal:!0};this._validateUpTiers(r);for(let o of this._deps)o.node.up?.(r,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let s=n(r[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let d=ht(n);if(!this._guard(d,"observe"))throw new ve({actor:d,action:"observe",nodeName:this.name})}let s=this._isTerminal&&this._resubscribable;if(s){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)en(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof o=="function"&&o(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let s=r,o=this._deps[r];o.unsub=Pn,o.unsub=o.node.subscribe(i=>{if(o.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:s},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let s=0;s<n;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}en(o)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let n=this._deps.length,r=Fn(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(vt),r.unsub=Pn;try{r.unsub=e.subscribe(s=>{if(r.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[L,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(s){this._emit([[L,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let r of this._deps){if(r.unsub!=null){let s=r.unsub;r.unsub=null;try{s()}catch{}}en(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],s=n[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(o)}if(s!==Le){if(s===Y){this._depDirtied(r);return}if(s===ye){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Wt);return}if(s===we||s===Ie){this._emit([n]);return}if(s===le){this._emit(Tt);return}if(s===F)this._depSettledAsData(r,n[1]);else if(s===Q)this._depSettledAsResolved(r);else if(s===B)this._depSettledAsTerminal(r,!0);else if(s===L)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(s===F||s===Q)&&this._emit([n]),(s===B||s===L)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(vt))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(qt),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[L,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Yt)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[L,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[L,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:r,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,o);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[L,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>$n?(this._rerunDepth=0,this._emit([[L,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${$n} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[ze,e[0]]:e;let r=!0,s=!1,o=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(s=!0),d[0]===Y&&(o=!0),i=u}let a=e;if(!r){let d=e.map((u,c)=>({m:u,i:c,tier:n(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[ze,...a]:[...a.slice(0,d),ze,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===L&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===le||d[0]===ye);if(a.length===0)return;n=a}n=this._frameBatch(n);let s=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==we&&u!==Ie){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===we?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let p=d[1];if(u===we)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(p),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(p))c=!1;else if(this._pauseLocks.delete(p),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let f=this._pauseBuffer;this._pauseBuffer=[],this._emit(f)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(d):s==null&&(s=n.slice(0,a))}if(s!=null){if(s.length===0)return;n=s}if(this._hasMeta&&n.some(a=>a[0]===le))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Tt)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(n);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of o)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[L,i]])}_updateState(e){let n=this._config.tierOf,r,s,o=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===F){d=c;break}}for(let c=0;c<e.length;c++){let p=e[c],f=p[0];if(f===F){if(p.length>=2){let h=!1;if(a&&this._cached!==void 0)try{h=this._equals(this._cached,p[1])}catch(l){s=this._wrapFnError("equals threw",l),o=c;break}if(h){r==null&&(r=e.slice(0,c)),r.push(bt),this._status="resolved";continue}this._cached=p[1],this._versioning!=null&&(d<0||c===d)&&Gn(this._versioning,p[1],this._hashFn)}this._status="settled",r?.push(p)}else if(r?.push(p),f===Y)this._status="dirty";else if(f===Q)this._status="resolved";else if(f===B){this._status="completed";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(f===L){this._status="errored";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(f===ye){if(this._cached!==void 0){let l=this._config.rigorRecorder;if(l!=null)try{l.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let l=h.invalidate;if(typeof l=="function")try{l()}catch{}}}else f===le&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?r??e.slice(0,o):r??e;return s!=null?{finalMessages:u,equalsError:s}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Sn()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],st(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}it(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);it(this._deliverToSinks,n,this._config.tierOf)}},Vn=t=>Array.isArray(t),tn=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function G(t,e){return ae([],{...e,initial:t})}function Te(t,e){return ae((r,s,o)=>t(s,o)??void 0,{describeKind:"producer",...e})}function I(t,e,n){return ae(t,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);o.emit(e(a,i))},{describeKind:"derived",...n})}function ue(t,e,n){return ae(t,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,o,i)??void 0},{describeKind:"effect",...n})}var de=be(()=>{"use strict";Re()});function nn(t){return{describeKind:"producer",...t}}function jn(t,e){return Te(n=>{let r=!1;try{for(let s of t){if(r)return;n.emit(s)}r||n.down([[B]])}catch(s){r||n.down([[L,s]])}return()=>{r=!0}},nn(e))}function Yr(t){return t!=null&&typeof t.then=="function"}function Jr(t,e){let{signal:n,...r}=e??{};return Te(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[L,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{o||(o=!0,n?.removeEventListener("abort",i),s.emit(a),s.down([[B]]))},a=>{o||(o=!0,n?.removeEventListener("abort",i),s.down([[L,a]]))}),()=>{o=!0,n?.removeEventListener("abort",i)}},nn(r))}function Qr(t,e){let{signal:n,...r}=e??{};return Te(s=>{let o=new AbortController,i=()=>o.abort(n?.reason);n?.aborted?o.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??o.signal,d=!1,u=t[Symbol.asyncIterator](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(p=>{if(!(d||a.aborted)){if(p.done){s.down([[B]]);return}s.emit(p.value),c()}},p=>{!d&&!a.aborted&&s.down([[L,p]])})};return c(),()=>{d=!0,n?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},nn(r))}function Xr(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Ye(t,e){if(Xr(t))return t;if(Yr(t))return Jr(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Qr(t,e);if(typeof n[Symbol.iterator]=="function")return jn(t,e)}return Zr(t)}function Zr(...t){return jn(t,void 0)}function zn(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),s,o=!1,i=()=>{s?(s(),s=void 0):o=!0};return s=t.subscribe(a=>{if(!n.signal.aborted)for(let d of a){if(d[0]===F&&d[1]===!0){n.abort(r),i();return}if(d[0]===L){n.abort(d[1]),i();return}if(d[0]===B){i();return}}}),o&&(s?.(),s=void 0),{signal:n.signal,dispose:()=>{s&&(s(),s=void 0)}}}function xe(t){return t.subscribe(()=>{})}var Je=be(()=>{"use strict";fe();de()});var Ot,Hn=be(()=>{"use strict";Ot=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Ms={};Pr(Ms,{DEFAULT_DECAY_RATE:()=>Ze,DEFAULT_EXECUTE_PROMPT:()=>on,DEFAULT_QUEUE_CONFIGS:()=>Et,DEFAULT_SEVERITY_WEIGHTS:()=>Xe,DEFAULT_TRIAGE_PROMPT:()=>rn,DEFAULT_VERIFY_PROMPT:()=>sn,HarnessGraph:()=>zt,QUEUE_NAMES:()=>pe,affectedTaskFilter:()=>io,beforeAfterCompare:()=>so,codeChangeBridge:()=>ao,createIntakeBridge:()=>no,defaultErrorClassifier:()=>Nt,defaultLlmExecutor:()=>Ar,defaultLlmVerifier:()=>Mr,evalIntakeBridge:()=>ro,evalSource:()=>oo,evalVerifier:()=>vr,harnessEvalPair:()=>ms,harnessLoop:()=>Ns,harnessProfile:()=>Os,harnessTrace:()=>Ss,notifyEffect:()=>uo,priorityScore:()=>_s,refineExecutor:()=>yn,resolvePromptFn:()=>dt,strategyKey:()=>et,strategyModel:()=>wn});module.exports=Fr(Ms);de();fe();Re();de();Je();function _t(t){return{describeKind:"derived",...t}}function eo(t){return{describeKind:"derived",partial:!0,...t}}function Qe(t,e,n){return ae([t],(r,s)=>{let o=r[0];if(o==null||o.length===0){s.down([[Q]]);return}let i=!1;for(let a of o)e(a)&&(s.emit(a),i=!0);i||s.down([[Q]])},_t(n))}function ut(t,e,n){return ae([t,e],(r,s,o)=>{let i=r[0],a=r[1],d=a!=null&&a.length>0?a.at(-1):o.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&o.prevData[1]===void 0){s.down([[Q]]);return}for(let u of i)s.emit([u,d])}else s.down([[Q]])},eo(n))}function Bn(...t){return t.length===0?Te(e=>{e.down([[B]])},_t()):Te(e=>{let n=t.length,r=0,s=[];for(let o of t){let i=o.subscribe(a=>{for(let d of a)d[0]===F?e.emit(d[1]):d[0]===B?(r+=1,r>=n&&e.down([[B]])):d[0]===L&&e.down([d])});s.push(i)}return()=>{for(let o of s)o()}},_t())}function to(t,e,n){let r,s=!1,o=()=>{s||(s=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==Le&&(u[0]===F?e.emit(u[1]):u[0]===B?a=!0:u[0]===L?(d=!0,e.down([u])):(u[0]===Y||u[0]===Q)&&e.down([u]));d?(r?.(),r=void 0,o()):a&&o()}),()=>{r?.(),r=void 0}}function Se(t,e,n){let r,s=!1;function o(){r?.(),r=void 0}return ae([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){o();return}if(d.terminalDeps[0]===!0){s=!0,r||a.down([[B]]);return}let u=i[0];if(!(u==null||u.length===0))return o(),r=to(Ye(e(u[u.length-1])),a,()=>{o(),s&&a.down([[B]])}),{deactivate:()=>{o(),s=!1}}},{..._t(n),completeWhenDepsComplete:!1})}Je();function no(t,e,n,r){return ue([t],([s])=>{if(s==null)return;let o=n(s);for(let i of o)e.publish(i)},{name:r?.name??"intake-bridge"})}function ro(t,e,n){let r=n?.defaultSeverity??"medium";return ue([t],([s])=>{if(s==null)return;let o=Array.isArray(s)?s:[s];for(let i of o)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(d=>d.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let d of a.judge_scores)d.pass||e.publish({source:"eval",summary:`${a.task_id}: ${d.claim} (model: ${i.model})`,evidence:d.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function oo(t,e){return Se(t,()=>Ye(e()))}function so(t,e){return I([t,e],([n,r])=>{let s=n,o=r,i=new Map(s.tasks.map(f=>[f.task_id,f])),a=new Map(o.tasks.map(f=>[f.task_id,f])),d=new Set([...i.keys(),...a.keys()]),u=[],c=[],p=[];for(let f of d){let h=i.get(f),l=a.get(f),m=h?.valid??!1,b=l?.valid??!1,g=h?.judge_scores?h.judge_scores.filter(x=>x.pass).length:void 0,v=l?.judge_scores?l.judge_scores.filter(x=>x.pass).length:void 0,y=g!==void 0&&v!==void 0?v-g:void 0;u.push({taskId:f,before:m,after:b,scoreDiff:y}),m&&!b&&c.push(f),!m&&b&&p.push(f)}return{newFailures:c,resolved:p,taskDeltas:u,overallImproved:p.length>c.length}},{name:"eval-delta"})}function io(t,e){let n=e==null?null:Array.isArray(e)?G(e):e,r=[t];return n&&r.push(n),I(r,s=>{let o=s[0],i=n?new Set(s[1]):null,a=new Set;for(let d of o)for(let u of d.affectsEvalTasks??[])(i==null||i.has(u))&&a.add(u);return[...a].sort()},{name:"affected-task-filter"})}function ao(t,e,n,r){let s=r?.defaultSeverity??"high";function o(a){let d=[];for(let u of a.lintErrors??[])d.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:s});for(let u of a.testFailures??[])d.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:s});return d}let i=n??o;return ue([t],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:r?.name??"code-change-bridge"})}function uo(t,e,n){return ue([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var pe=["auto-fix","needs-decision","investigation","backlog"],Et={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},Xe={critical:100,high:70,medium:40,low:10},Ze=Math.LN2/(168*3600);function et(t,e){return`${t}\u2192${e}`}var lo=/\b(parse|json|config|validation|syntax)\b/i,Nt=t=>lo.test(t.detail)?"self-correctable":"structural",rn=`You are a triage classifier for a reactive collaboration harness.
|
|
1
|
+
"use strict";var Bt=Object.defineProperty;var Gr=Object.getOwnPropertyDescriptor;var Lr=Object.getOwnPropertyNames;var Pr=Object.prototype.hasOwnProperty;var ye=(t,e)=>()=>(t&&(e=t(t=0)),e);var $r=(t,e)=>{for(var n in e)Bt(t,n,{get:e[n],enumerable:!0})},Fr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Lr(e))!Pr.call(t,s)&&s!==n&&Bt(t,s,{get:()=>e[s],enumerable:!(r=Gr(e,s))||r.enumerable});return t};var Vr=t=>Fr(Bt({},"__esModule",{value:!0}),t);var Le,G,Y,Q,ve,_e,Ie,fe,$,L,ze,ht,Nn,mt,Rn,On,gt,Kt,Ut,qt,bt,le=ye(()=>{"use strict";Le=Symbol.for("graphrefly/START"),G=Symbol.for("graphrefly/DATA"),Y=Symbol.for("graphrefly/DIRTY"),Q=Symbol.for("graphrefly/RESOLVED"),ve=Symbol.for("graphrefly/INVALIDATE"),_e=Symbol.for("graphrefly/PAUSE"),Ie=Symbol.for("graphrefly/RESUME"),fe=Symbol.for("graphrefly/TEARDOWN"),$=Symbol.for("graphrefly/COMPLETE"),L=Symbol.for("graphrefly/ERROR"),ze=Object.freeze([Y]),ht=Object.freeze([Q]),Nn=Object.freeze([ve]),mt=Object.freeze([Le]),Rn=Object.freeze([$]),On=Object.freeze([fe]),gt=Object.freeze([ze]),Kt=Object.freeze([ht]),Ut=Object.freeze([Nn]),qt=Object.freeze([Rn]),bt=Object.freeze([On])});function Sn(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let s=2+n.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=Wt,o[i++]=n.length,o.set(n,i),i+=n.length,o[i++]=r>>>8&255,o[i++]=r&255,o.set(e,i),o}function An(t,e){if(t.length<kn)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${kn})`);let n=0,r=t[n++];if(r!==Wt)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Wt})`);let s=t[n++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+s+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+s+2} bytes, have ${t.length})`);let o=new TextDecoder().decode(t.subarray(n,n+s));n+=s;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),d=e.lookupCodec(o);if(d==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function Mn(t){t.registerCodec(jr)}var jr,Wt,kn,Yt=ye(()=>{"use strict";jr={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}},Wt=1,kn=4});function yt(t){if(t==null)return We;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var We,vt=ye(()=>{"use strict";We={type:"system",id:""}});function ot(){return Ye>0||nt}function In(){return Ye>0}function st(t){Ye>0?rt.push(t):t()}function ae(t){Ye+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ye-=1,Ye===0)if(e){if(!nt){let n=rt.splice(0);for(let r of n)try{r()}catch{}He.length=0,Be.length=0,Je.length=0}}else zr()}}function zr(){let t=!nt;t&&(nt=!0);let e=[],n=0;try{for(;He.length>0||Be.length>0||Je.length>0||t&&rt.length>0;){if(t&&rt.length>0){let o=rt.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw He.length=0,Be.length=0,Je.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(He.length>0?He:Be.length>0?Be:Je).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{t&&(nt=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function it(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!ot()){t(e);return}(u>=5?Je:u===4?Be:He).push(()=>t(e));return}let r=e.length,s=r,o=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(s=a;a<r&&n(e[a][0])===3;)a++;for(o=a;a<r&&n(e[a][0])===4;)a++;i=a;let d=ot();if(s>0){let u=e.slice(0,s);t(u)}if(o>s){let u=e.slice(s,o);d?He.push(()=>t(u)):t(u)}if(i>o){let u=e.slice(o,i);d?Be.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?Je.push(()=>t(u)):t(u)}}var Ye,nt,He,Be,Je,rt,Ce=ye(()=>{"use strict";Ye=0,nt=!1,He=[],Be=[],Je=[],rt=[]});function q(){return Math.trunc(performance.now()*1e6)}function Tt(){return Date.now()*1e6}var Pe=ye(()=>{"use strict"});function Cn(t){t.registerMessageType(Le,{tier:0,wireCrossing:!1}),t.registerMessageType(Y,{tier:1,wireCrossing:!1}),t.registerMessageType(ve,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(_e,{tier:2,wireCrossing:!1}),t.registerMessageType(Ie,{tier:2,wireCrossing:!1}),t.registerMessageType(G,{tier:3,wireCrossing:!0}),t.registerMessageType(Q,{tier:3,wireCrossing:!0}),t.registerMessageType($,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(fe,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var xt,Dn=ye(()=>{"use strict";le();xt=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Jt(t){let e=Hr.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var Te,Hr,at=ye(()=>{"use strict";Te=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}},Hr=["human","llm","wallet","system"]});function Qt(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(Qt);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Qt(t[n]);return e}return null}function Ur(t){let e=Kr.encode(t),n=e.length,r=n*8,s=n+9+63&-64,o=new Uint8Array(s);o.set(e),o[n]=128;let i=new DataView(o.buffer);i.setUint32(s-4,r>>>0,!1),i.setUint32(s-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,p=1359893119,f=2600822924,h=528734635,l=1541459225,m=new Uint32Array(64),g=(v,y)=>v>>>y|v<<32-y;for(let v=0;v<s;v+=64){for(let S=0;S<16;S++)m[S]=i.getUint32(v+S*4,!1);for(let S=16;S<64;S++){let D=m[S-15],M=m[S-2],B=g(D,7)^g(D,18)^D>>>3,X=g(M,17)^g(M,19)^M>>>10;m[S]=m[S-16]+B+m[S-7]+X>>>0}let y=a,x=d,E=u,T=c,w=p,N=f,R=h,C=l;for(let S=0;S<64;S++){let D=g(w,6)^g(w,11)^g(w,25),M=w&N^~w&R,B=C+D+M+Br[S]+m[S]>>>0,X=g(y,2)^g(y,13)^g(y,22),ne=y&x^y&E^x&E,ge=X+ne>>>0;C=R,R=N,N=w,w=T+B>>>0,T=E,E=x,x=y,y=B+ge>>>0}a=a+y>>>0,d=d+x>>>0,u=u+E>>>0,c=c+T>>>0,p=p+w>>>0,f=f+N>>>0,h=h+R>>>0,l=l+C>>>0}let b=v=>v.toString(16).padStart(8,"0");return b(a)+b(d)+b(u)+b(c)+b(p)+b(f)+b(h)+b(l)}function Xt(t){let e=Qt(t??null),n=JSON.stringify(e);return Ur(n).slice(0,16)}function qr(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function Zt(t,e,n){let r=n?.id??qr();if(t===0)return{id:r,version:0};let o=(n?.hash??Xt)(e);return{id:r,version:0,cid:o,prev:null}}function Gn(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var Br,Kr,Ln=ye(()=>{"use strict";Br=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Kr=new TextEncoder});function Fn(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function en(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function wt(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ue(t,e,n){let r=Vn(t)?t:[],s=typeof t=="function"?t:typeof e=="function"?e:void 0,o={};return Vn(t)?o=(tn(e)?e:n)??{}:tn(t)?o=t:o=(tn(e)?e:n)??{},new Z(r,s,o)}var Pn,$n,Wr,Yr,Qe,Z,Vn,tn,Se=ye(()=>{"use strict";Yt();vt();Ce();Pe();Dn();at();le();Ln();Pn=()=>{},$n=100;Wr=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Yr=(t,e,n,r)=>{let s=t;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[mt]:[mt,[G,o]];s._status==="dirty"&&i.push(ze),it(e,i,s._config.tierOf)},Qe=new xt({onMessage:Wr,onSubscribe:Yr});Cn(Qe);Mn(Qe);Z=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??Qe,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Xt;let s=r.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?Zt(s,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Fn);let o={};for(let[a,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),o[a]=new t([],void 0,u)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[G,a]])},down(a){i._emit(wt(a))},up(a){i._emitUp(wt(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let s=n?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,d=i?.version??0,u=Zt(e,o,{id:a,hash:s});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=yt(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let s=yt(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new Te({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new Te({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:Tt()}}down(e,n){let r=wt(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[G,e]])}up(e,n){if(this._deps.length===0)return;let r=wt(e);if(r.length===0)return;this._checkGuard(n);let s=n??{internal:!0};this._validateUpTiers(r);for(let o of this._deps)o.node.up?.(r,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let s=n(r[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let d=yt(n);if(!this._guard(d,"observe"))throw new Te({actor:d,action:"observe",nodeName:this.name})}let s=this._isTerminal&&this._resubscribable;if(s){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)en(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof o=="function"&&o(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let s=r,o=this._deps[r];o.unsub=Pn,o.unsub=o.node.subscribe(i=>{if(o.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:s},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let s=0;s<n;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}en(o)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let n=this._deps.length,r=Fn(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(gt),r.unsub=Pn;try{r.unsub=e.subscribe(s=>{if(r.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[L,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(s){this._emit([[L,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let r of this._deps){if(r.unsub!=null){let s=r.unsub;r.unsub=null;try{s()}catch{}}en(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],s=n[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(o)}if(s!==Le){if(s===Y){this._depDirtied(r);return}if(s===ve){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Ut);return}if(s===_e||s===Ie){this._emit([n]);return}if(s===fe){this._emit(bt);return}if(s===G)this._depSettledAsData(r,n[1]);else if(s===Q)this._depSettledAsResolved(r);else if(s===$)this._depSettledAsTerminal(r,!0);else if(s===L)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(s===G||s===Q)&&this._emit([n]),(s===$||s===L)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(gt))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(Kt),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[L,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(qt)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[L,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[L,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:r,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,o);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[L,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>$n?(this._rerunDepth=0,this._emit([[L,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${$n} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[ze,e[0]]:e;let r=!0,s=!1,o=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(s=!0),d[0]===Y&&(o=!0),i=u}let a=e;if(!r){let d=e.map((u,c)=>({m:u,i:c,tier:n(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[ze,...a]:[...a.slice(0,d),ze,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===L&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===fe||d[0]===ve);if(a.length===0)return;n=a}n=this._frameBatch(n);let s=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==_e&&u!==Ie){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===_e?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let p=d[1];if(u===_e)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(p),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(p))c=!1;else if(this._pauseLocks.delete(p),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let f=this._pauseBuffer;this._pauseBuffer=[],this._emit(f)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(d):s==null&&(s=n.slice(0,a))}if(s!=null){if(s.length===0)return;n=s}if(this._hasMeta&&n.some(a=>a[0]===fe))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(bt)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(n);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of o)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[L,i]])}_updateState(e){let n=this._config.tierOf,r,s,o=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===G){d=c;break}}for(let c=0;c<e.length;c++){let p=e[c],f=p[0];if(f===G){if(p.length>=2){let h=!1;if(a&&this._cached!==void 0)try{h=this._equals(this._cached,p[1])}catch(l){s=this._wrapFnError("equals threw",l),o=c;break}if(h){r==null&&(r=e.slice(0,c)),r.push(ht),this._status="resolved";continue}this._cached=p[1],this._versioning!=null&&(d<0||c===d)&&Gn(this._versioning,p[1],this._hashFn)}this._status="settled",r?.push(p)}else if(r?.push(p),f===Y)this._status="dirty";else if(f===Q)this._status="resolved";else if(f===$){this._status="completed";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(f===L){this._status="errored";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(f===ve){if(this._cached!==void 0){let l=this._config.rigorRecorder;if(l!=null)try{l.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let l=h.invalidate;if(typeof l=="function")try{l()}catch{}}}else f===fe&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?r??e.slice(0,o):r??e;return s!=null?{finalMessages:u,equalsError:s}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(In()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],st(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}it(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);it(this._deliverToSinks,n,this._config.tierOf)}},Vn=t=>Array.isArray(t),tn=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function P(t,e){return ue([],{...e,initial:t})}function de(t,e){return ue((r,s,o)=>t(s,o)??void 0,{describeKind:"producer",...e})}function I(t,e,n){return ue(t,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);o.emit(e(a,i))},{describeKind:"derived",...n})}function ce(t,e,n){return ue(t,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,o,i)??void 0},{describeKind:"effect",...n})}var re=ye(()=>{"use strict";Se()});function nn(t){return{describeKind:"producer",...t}}function jn(t,e){return de(n=>{let r=!1;try{for(let s of t){if(r)return;n.emit(s)}r||n.down([[$]])}catch(s){r||n.down([[L,s]])}return()=>{r=!0}},nn(e))}function Jr(t){return t!=null&&typeof t.then=="function"}function Qr(t,e){let{signal:n,...r}=e??{};return de(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[L,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{o||(o=!0,n?.removeEventListener("abort",i),s.emit(a),s.down([[$]]))},a=>{o||(o=!0,n?.removeEventListener("abort",i),s.down([[L,a]]))}),()=>{o=!0,n?.removeEventListener("abort",i)}},nn(r))}function Xr(t,e){let{signal:n,...r}=e??{};return de(s=>{let o=new AbortController,i=()=>o.abort(n?.reason);n?.aborted?o.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??o.signal,d=!1,u=t[Symbol.asyncIterator](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(p=>{if(!(d||a.aborted)){if(p.done){s.down([[$]]);return}s.emit(p.value),c()}},p=>{!d&&!a.aborted&&s.down([[L,p]])})};return c(),()=>{d=!0,n?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},nn(r))}function Zr(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function $e(t,e){if(Zr(t))return t;if(Jr(t))return Qr(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Xr(t,e);if(typeof n[Symbol.iterator]=="function")return jn(t,e)}return eo(t)}function eo(...t){return jn(t,void 0)}function zn(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),s,o=!1,i=()=>{s?(s(),s=void 0):o=!0};return s=t.subscribe(a=>{if(!n.signal.aborted)for(let d of a){if(d[0]===G&&d[1]===!0){n.abort(r),i();return}if(d[0]===L){n.abort(d[1]),i();return}if(d[0]===$){i();return}}}),o&&(s?.(),s=void 0),{signal:n.signal,dispose:()=>{s&&(s(),s=void 0)}}}function xe(t){return t.subscribe(()=>{})}var Ke=ye(()=>{"use strict";le();re()});var Ot,Bn=ye(()=>{"use strict";Ot=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Ps={};$r(Ps,{DEFAULT_DECAY_RATE:()=>Ze,DEFAULT_EXECUTE_PROMPT:()=>on,DEFAULT_QUEUE_CONFIGS:()=>Et,DEFAULT_SEVERITY_WEIGHTS:()=>Xe,DEFAULT_TRIAGE_PROMPT:()=>rn,DEFAULT_VERIFY_PROMPT:()=>sn,HarnessGraph:()=>zt,QUEUE_NAMES:()=>he,actuatorExecutor:()=>ao,affectedTaskFilter:()=>ho,autoSolidify:()=>uo,beforeAfterCompare:()=>po,codeChangeBridge:()=>mo,createIntakeBridge:()=>lo,defaultErrorClassifier:()=>Nt,defaultLlmExecutor:()=>Mr,defaultLlmVerifier:()=>Ir,evalIntakeBridge:()=>co,evalSource:()=>fo,evalVerifier:()=>vr,harnessEvalPair:()=>ws,harnessLoop:()=>Ms,harnessProfile:()=>Cs,harnessTrace:()=>Gs,notifyEffect:()=>go,priorityScore:()=>Ss,refineExecutor:()=>yn,resolvePromptFn:()=>dt,strategyKey:()=>et,strategyModel:()=>wn});module.exports=Vr(Ps);le();re();le();Se();re();Ke();function _t(t){return{describeKind:"derived",...t}}function to(t){return{describeKind:"derived",partial:!0,...t}}function De(t,e,n){return ue([t],(r,s)=>{let o=r[0];if(o==null||o.length===0){s.down([[Q]]);return}let i=!1;for(let a of o)e(a)&&(s.emit(a),i=!0);i||s.down([[Q]])},_t(n))}function ut(t,e,n){return ue([t,e],(r,s,o)=>{let i=r[0],a=r[1],d=a!=null&&a.length>0?a.at(-1):o.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&o.prevData[1]===void 0){s.down([[Q]]);return}for(let u of i)s.emit([u,d])}else s.down([[Q]])},to(n))}function Hn(...t){return t.length===0?de(e=>{e.down([[$]])},_t()):de(e=>{let n=t.length,r=0,s=[];for(let o of t){let i=o.subscribe(a=>{for(let d of a)d[0]===G?e.emit(d[1]):d[0]===$?(r+=1,r>=n&&e.down([[$]])):d[0]===L&&e.down([d])});s.push(i)}return()=>{for(let o of s)o()}},_t())}function no(t,e,n){let r,s=!1,o=()=>{s||(s=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==Le&&(u[0]===G?e.emit(u[1]):u[0]===$?a=!0:u[0]===L?(d=!0,e.down([u])):(u[0]===Y||u[0]===Q)&&e.down([u]));d?(r?.(),r=void 0,o()):a&&o()}),()=>{r?.(),r=void 0}}function we(t,e,n){let r,s=!1;function o(){r?.(),r=void 0}return ue([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){o();return}if(d.terminalDeps[0]===!0){s=!0,r||a.down([[$]]);return}let u=i[0];if(!(u==null||u.length===0))return o(),r=no($e(e(u[u.length-1])),a,()=>{o(),s&&a.down([[$]])}),{deactivate:()=>{o(),s=!1}}},{..._t(n),completeWhenDepsComplete:!1})}Ke();function ro(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${io(e.summary)}`,artifact:t}}function oo(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function so(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function io(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function ao(t){let e=t.name??"actuator-executor",n=t.toOutput??ro,r=t.onError??oo,s=t.skipDetail??so;return o=>{let i=De(o,d=>d!=null,{name:`${e}/gate-in`}),a=we(i,d=>t.shouldApply&&!t.shouldApply(d)?de(u=>(u.down([[G,{outcome:"failure",detail:s(d)}],[$]]),()=>{}),{name:`${e}/skip`}):de(u=>{let c=new AbortController,p=!1,f=null,h=m=>{p||(p=!0,u.down([[G,m],[$]]),f?.(),f=null)},l;try{let m=t.apply(d,{signal:c.signal});l=$e(m,{signal:c.signal})}catch(m){return h(r(m,d)),()=>{c.abort()}}return f=l.subscribe(m=>{for(let g of m){if(p)return;if(g[0]===G){h(n(g[1],d));return}if(g[0]===L){h(r(g[1],d));return}if(g[0]===$){h(r(new Error("actuator inner completed without emitting DATA"),d));return}}}),p&&f&&(f(),f=null),()=>{c.abort(),f?.(),f=null}},{name:`${e}/inner`}),{name:e});return De(a,d=>d!=null,{name:`${e}/gate-out`})}}le();re();function uo(t){let e=t.name??"auto-solidify",n=t.extract??(s=>s.execution.artifact??null),r=t.predicate??(()=>!0);return de(s=>{let o=null,i=!1,a=()=>{i||(i=!0,o?.(),o=null)},d=u=>{i||(s.down([[L,u]]),a())};return o=t.verifyResults.subscribe(u=>{if(!i)for(let c of u){if(i)return;if(c[0]!==G){if(c[0]===$){s.down([[$]]),a();return}continue}let p=c[1];if(p==null||!p.verified)continue;let f;try{f=r(p)}catch(l){d(l);return}if(!f)continue;let h;try{h=n(p)}catch(l){d(l);return}if(h!=null){try{t.write(h,p)}catch(l){d(l);return}s.down([[G,h]])}}}),i&&o&&(o(),o=null),()=>{a()}},{name:e})}re();Ke();function lo(t,e,n,r){return ce([t],([s])=>{if(s==null)return;let o=n(s);for(let i of o)e.publish(i)},{name:r?.name??"intake-bridge"})}function co(t,e,n){let r=n?.defaultSeverity??"medium";return ce([t],([s])=>{if(s==null)return;let o=Array.isArray(s)?s:[s];for(let i of o)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(d=>d.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let d of a.judge_scores)d.pass||e.publish({source:"eval",summary:`${a.task_id}: ${d.claim} (model: ${i.model})`,evidence:d.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function fo(t,e){return we(t,()=>$e(e()))}function po(t,e){return I([t,e],([n,r])=>{let s=n,o=r,i=new Map(s.tasks.map(f=>[f.task_id,f])),a=new Map(o.tasks.map(f=>[f.task_id,f])),d=new Set([...i.keys(),...a.keys()]),u=[],c=[],p=[];for(let f of d){let h=i.get(f),l=a.get(f),m=h?.valid??!1,g=l?.valid??!1,b=h?.judge_scores?h.judge_scores.filter(x=>x.pass).length:void 0,v=l?.judge_scores?l.judge_scores.filter(x=>x.pass).length:void 0,y=b!==void 0&&v!==void 0?v-b:void 0;u.push({taskId:f,before:m,after:g,scoreDiff:y}),m&&!g&&c.push(f),!m&&g&&p.push(f)}return{newFailures:c,resolved:p,taskDeltas:u,overallImproved:p.length>c.length}},{name:"eval-delta"})}function ho(t,e){let n=e==null?null:Array.isArray(e)?P(e):e,r=[t];return n&&r.push(n),I(r,s=>{let o=s[0],i=n?new Set(s[1]):null,a=new Set;for(let d of o)for(let u of d.affectsEvalTasks??[])(i==null||i.has(u))&&a.add(u);return[...a].sort()},{name:"affected-task-filter"})}function mo(t,e,n,r){let s=r?.defaultSeverity??"high";function o(a){let d=[];for(let u of a.lintErrors??[])d.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:s});for(let u of a.testFailures??[])d.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:s});return d}let i=n??o;return ce([t],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:r?.name??"code-change-bridge"})}function go(t,e,n){return ce([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var he=["auto-fix","needs-decision","investigation","backlog"],Et={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},Xe={critical:100,high:70,medium:40,low:10},Ze=Math.LN2/(168*3600);function et(t,e){return`${t}\u2192${e}`}var bo=/\b(parse|json|config|validation|syntax)\b/i,Nt=t=>bo.test(t.detail)?"self-correctable":"structural",rn=`You are a triage classifier for a reactive collaboration harness.
|
|
2
2
|
|
|
3
3
|
Given an intake item, classify it and output JSON:
|
|
4
4
|
{
|
|
@@ -39,12 +39,12 @@ Output JSON:
|
|
|
39
39
|
"verified": true/false,
|
|
40
40
|
"findings": ["<finding1>", ...],
|
|
41
41
|
"errorClass": "self-correctable" | "structural" // only if verified=false
|
|
42
|
-
}`;function dt(t,e,n){if(typeof t=="function")return t;let r=t??e;return s=>n(r,s)}
|
|
43
|
-
`)}function mo(t,e,n,r,s){let{x:o,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&Un(t,e,o,i,a,s);return}Pe(t,e,o,i,n.boxTL);for(let c=o+1;c<o+a-1;c+=1)Pe(t,e,c,i,n.boxH);Pe(t,e,o+a-1,i,n.boxTR);for(let c=i+1;c<i+d-1;c+=1){Pe(t,e,o,c,n.boxV);for(let p=o+1;p<o+a-1;p+=1)Jn(t,e,p,c," ","empty");Pe(t,e,o+a-1,c,n.boxV)}Pe(t,e,o,i+d-1,n.boxBL);for(let c=o+1;c<o+a-1;c+=1)Pe(t,e,c,i+d-1,n.boxH);Pe(t,e,o+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);Un(t,e,o+1,u,a-2,s)}function Pe(t,e,n,r,s){Jn(t,e,n,r,s,s===" "?"empty":s==="\u2500"||s==="-"?"boxH":s==="\u2502"||s==="|"?"boxV":"boxCorner")}function Jn(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=s,e[r][n]=o)}function Un(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=n,a=s;for(let d of o){let u=Rt(d);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=d,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function go(t,e,n,r){let s=r.points;if(s.length<2)return;for(let d=0;d+1<s.length;d+=1)bo(t,e,n,s[d],s[d+1]);for(let d=1;d+1<s.length;d+=1){let u=s[d-1],c=s[d],p=s[d+1],f=yo(u,c,p,n);f&&Wn(t,e,c.x,c.y,f,"edgeCorner")}let o=s[s.length-1],i=s[s.length-2],a=vo(i,o,n);a&&Wn(t,e,o.x,o.y,a,"arrow")}function bo(t,e,n,r,s){if(!(r.x===s.x&&r.y===s.y)){if(r.y===s.y){let o=r.y,i=Math.min(r.x,s.x),a=Math.max(r.x,s.x);for(let d=i;d<=a;d+=1)qn(t,e,d,o,n,"h")}else if(r.x===s.x){let o=r.x,i=Math.min(r.y,s.y),a=Math.max(r.y,s.y);for(let d=i;d<=a;d+=1)qn(t,e,o,d,n,"v")}}}function qn(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=o==="h"?s.horizontal:s.vertical,e[r][n]=o==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&o==="v"){i[n]=s.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&o==="h"){i[n]=s.cross,e[r][n]="edgeCorner";return}}}function Wn(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=s,e[r][n]=o)}function yo(t,e,n,r){let s=t.y===e.y,o=e.y===n.y;if(s===o)return;if(s){let d=t.x<e.x,u=n.y>e.y;return d&&u?r.cornerTR:d&&!u?r.cornerBR:!d&&u?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function vo(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function To(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Zn(t){let e=xo(t);wo(e),_o(e),Eo(e),No(e,t);let n=Ro(e,t),{width:r,height:s}=Ao(e),o=[];for(let i of e.layers)for(let a of i)a.isVirtual||o.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:o,edges:n,width:r,height:s}}function xo(t){let e=new Map;for(let s of t.nodes)e.set(s,{id:s,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(s),h:t.heightCells(s),in:[],out:[]});let n=[],r=0;for(let s of t.edges){if(s.from===s.to)continue;let o=e.get(s.from),i=e.get(s.to);if(!o||!i)continue;let a={chainId:r++,chainFrom:s.from,chainTo:s.to,fromId:s.from,toId:s.to,hopIndex:0,chainLen:1};o.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function wo(t){let e=new Map;for(let o of t.nodes.values())e.set(o.id,o.in.length);let n=[];for(let o of t.nodes.values())(e.get(o.id)??0)===0&&(o.layer=0,n.push(o));let r=new Set,s=0;for(;s<n.length;){let o=n[s++];if(!r.has(o.id)){r.add(o.id);for(let i of o.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,o.layer+1);let d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let o of t.nodes.values())o.layer<0&&(o.layer=0)}function _o(t){let e=Math.max(0,...Array.from(t.nodes.values(),o=>o.layer)),n=Array.from({length:e+1},()=>[]);for(let o of t.nodes.values())n[o.layer].push(o);let r=[],s=0;for(let o of t.hops){let i=t.nodes.get(o.fromId),a=t.nodes.get(o.toId),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(p=>p!==o),a.in=a.in.filter(p=>p!==o);continue}if(d===1){o.hopIndex=0,o.chainLen=1,r.push(o);continue}i.out=i.out.filter(p=>p!==o),a.in=a.in.filter(p=>p!==o);let u=i;for(let p=1;p<d;p+=1){let f=`__virt_${s++}__`,h={id:f,isVirtual:!0,layer:i.layer+p,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(f,h),n[h.layer].push(h);let l={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:f,hopIndex:p-1,chainLen:d};u.out.push(l),h.in.push(l),r.push(l),u=h}let c={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(c),a.in.push(c),r.push(c)}for(let o of n)for(let i=0;i<o.length;i+=1)o[i].order=i;t.layers=n,t.hops=r}function Eo(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Qn(t,t.layers[r],"in"),St(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Qn(t,t.layers[r],"out"),St(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let s=1;s<t.layers.length;s+=1){let o=t.layers[s];for(let i=0;i+1<o.length;i+=1){let a=Xn(t,o[i],o[i+1],"in");[o[i],o[i+1]]=[o[i+1],o[i]],St(o),Xn(t,o[i],o[i+1],"in")<a?r=!0:([o[i],o[i+1]]=[o[i+1],o[i]],St(o))}}if(!r)break}}function Qn(t,e,n){let r=new Map;for(let s of e){let o=n==="in"?s.in:s.out;if(o.length===0){r.set(s.id,s.order);continue}let i=0,a=0;for(let d of o){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.order,a+=1)}r.set(s.id,a===0?s.order:i/a)}e.sort((s,o)=>{let i=r.get(s.id),a=r.get(o.id);return i!==a?i-a:s.order-o.order})}function St(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Xn(t,e,n,r){let s=r==="in"?e.in:e.out,o=r==="in"?n.in:n.out,i=0;for(let a of s)for(let d of o){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,c=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>c||e.order>n.order&&u<c)&&(i+=1)}return i}function No(t,e){e.direction==="LR"?ko(t,e):Oo(t,e)}function ko(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.w);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.x=n[s];for(let s of t.layers){let o=0;for(let i of s)i.y=o,o+=i.h+e.nodeGap}er(t,e,"y")}function Oo(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.h);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.y=n[s];for(let s of t.layers){let o=0;for(let i of s)i.x=o,o+=i.w+e.nodeGap}er(t,e,"x")}function er(t,e,n){let r=o=>n==="y"?o.h:o.w,s=e.nodeGap;for(let o=0;o<2;o+=1){let i=o===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let d=new Map;for(let c of a){let p=o===0?c.in:c.out;if(p.length===0)continue;let f=[];for(let l of p){let m=t.nodes.get(o===0?l.fromId:l.toId);if(!m)continue;let b=n==="y"?m.y:m.x;f.push(b+Math.floor(r(m)/2))}if(f.length===0)continue;f.sort((l,m)=>l-m);let h=f[Math.floor(f.length/2)];d.set(c.id,h-Math.floor(r(c)/2))}let u=0;for(let c of a){let p=d.get(c.id),f=n==="y"?c.y:c.x,l=Math.max(p??f,u);n==="y"?c.y=l:c.x=l,u=l+r(c)+s}}}}function Ro(t,e){let n=new Map;for(let u of t.hops){let c=n.get(u.chainId);c?c.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((c,p)=>c.hopIndex-p.hopIndex);let r=e.direction==="LR",s=u=>r?u.x:u.y,o=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let c=t.layers[u],p=t.layers[u+1],f=0;for(let N of c)f=Math.max(f,s(N)+o(N));let h=Number.POSITIVE_INFINITY;for(let N of p)h=Math.min(h,s(N));let l=Number.isFinite(h)?h-1:f,m=Math.max(1,l-f+1),b=[];for(let N of c)for(let k of N.out)b.push(k);b.sort((N,k)=>{let C=i(t.nodes.get(N.fromId)),S=i(t.nodes.get(k.fromId));if(C!==S)return C-S;let D=i(t.nodes.get(N.toId)),M=i(t.nodes.get(k.toId));return D-M});let g=[],v=new Map;for(let N of b){let k=i(t.nodes.get(N.fromId)),C=i(t.nodes.get(N.toId)),S=Math.min(k,C),D=Math.max(k,C),M=-1;for(let H=0;H<g.length;H+=1){let X=g[H],ne=!0;for(let me of X)if(me.lo<=D&&S<=me.hi){ne=!1;break}if(ne){X.push({lo:S,hi:D}),M=H;break}}M<0&&(g.push([{lo:S,hi:D}]),M=g.length-1),v.set(N,M)}let y=g.length,x=m>=Math.max(3,y+2),E=x?f+1:f,T=x?l-1:l,w=Math.max(1,T-E+1);for(let N of b){let k=v.get(N),C;if(y<=1)C=E+Math.floor(w/2);else{let S=(w-1)/(y-1);C=E+Math.floor(k*S)}a.set(N,Math.max(f,Math.min(l,C)))}}let d=[];for(let[,u]of n){let c=[];for(let f=0;f<u.length;f+=1){let h=u[f],l=t.nodes.get(h.fromId),m=t.nodes.get(h.toId),b=a.get(h),g=l.isVirtual?s(l):s(l)+o(l),v=m.isVirtual?s(m):s(m)-1,y=i(l),x=i(m);f===0&&At(c,r,g,y),y!==x&&(At(c,r,b,y),At(c,r,b,x)),At(c,r,v,x)}let p=u[0];d.push({from:p.chainFrom,to:p.chainTo,points:So(c)})}return d}function At(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function So(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function Ao(t){let e=0,n=0;for(let r of t.layers)for(let s of r)e=Math.max(e,s.x+s.w),n=Math.max(n,s.y+s.h);return{width:e,height:n}}var Mo=24,Co=4,Io=1,Do=3;function tr(t,e){let n=Go(e.direction),r=Math.max(3,e.maxLabelWidth??Mo),s=e.asciiCharset??"unicode",o=Object.keys(t.nodes).sort(),i=new Set(o),a=t.edges.filter(h=>i.has(h.from)&&i.has(h.to)),d=new Map,u=new Map;for(let h of o){let l=Kn(h,r);d.set(h,l),u.set(h,Rt(l)+4)}let c=Zn({nodes:o,edges:a,widthCells:h=>u.get(h)??3,heightCells:()=>Do,layerGap:Co,nodeGap:Io,direction:n}),p=Yn(c,{charset:s,labelOf:h=>d.get(h)??h}),f=e.logger;return f&&f(p),p}function Go(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function nr(t,e,n,r={}){let s=e in t.nodes,o=n in t.nodes;if(!s)return Mt(e,n,"no-such-from");if(!o)return Mt(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=Lo(t,e,r);if(u!=null)return u}let d=Ct(e,t.nodes[e],0,r);return It(e,n,[d])}if(i===0)return Mt(e,n,"no-path");let a=rr(t,e,n,i);return a.found?It(e,n,or(t,a.pathOrder,r)):Mt(e,n,a.truncated?"max-depth-exceeded":"no-path")}function rr(t,e,n,r){let s=new Map,o=[{path:n,depth:0}],i=new Set([n]),a=0,d=!1;for(;a<o.length;){let p=o[a++];if(p.path===e)break;if(r!=null&&p.depth>=r){let m=t.nodes[p.path];m?.deps&&m.deps.length>0&&(d=!0);continue}let f=t.nodes[p.path];if(f==null)continue;let h=f.deps??[],l=new Map;for(let m=0;m<h.length;m++){let b=h[m];if(!b)continue;let g=l.get(b);g==null&&(g=[],l.set(b,g)),g.push(m)}for(let[m,b]of l)i.has(m)||(i.add(m),s.set(m,{from:p.path,depIndices:b}),o.push({path:m,depth:p.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==n;){let p=s.get(c);if(p==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=p.depIndices,u.push({path:p.from}),c=p.from}return{found:!0,pathOrder:u,truncated:!1}}function Lo(t,e,n){let r=t.nodes[e];if(r==null)return null;let s=r.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=Ct(e,r,0,n);a.dep_index=o[0];let d=Ct(e,r,1,n);return It(e,e,[a,d])}let i=null;for(let a=0;a<s.length;a++){let d=s[a];if(!d||d===e)continue;let u=rr(t,d,e,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:It(e,e,or(t,i.pathOrder,n))}function or(t,e,n){return e.map((r,s)=>{let o=t.nodes[r.path],i=Ct(r.path,o,s,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function Ct(t,e,n,r){let s={path:t,type:e.type,hop:n};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=r.annotations?.get(t)??e.annotation;o!=null&&(s.annotation=o);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function It(t,e,n){return sr(t,e,!0,"ok",n)}function Mt(t,e,n){return sr(t,e,!1,n,[])}function sr(t,e,n,r,s){let o=Po(t,e,n,r,s);return{from:t,to:e,found:n,reason:r,steps:s,text:o,toJSON(){return{from:t,to:e,found:n,reason:r,steps:s}}}}function Po(t,e,n,r,s){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let o=[`Causal path: ${t} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(d),"value"in i&&o.push(` value: ${$o(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;o.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return o.join(`
|
|
44
|
-
`)}function
|
|
45
|
-
`)}function ur(t){if(t.version!==
|
|
46
|
-
`);return e.logger?.(o),o}function fr(t,e){let n=cr(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`flowchart ${n}`];for(let i of r){let a=s.get(i);o.push(` ${a}["${
|
|
47
|
-
`)}function
|
|
48
|
-
`)}function Qo(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gt(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let s=t.indexOf("]",n+1);if(s<=n+1){e+="\\[";continue}let o=t.slice(n+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,n=s;continue}e+=Qo(r)}return e+="$",new RegExp(e)}var Xo={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},Zo={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function Lt(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function es(t){return t==="none"?Zo:t==="ansi"||t==null?Xo:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function dr(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function ts(t,e,n){for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s<32||s===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function dn(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(W))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${W}' (path separator)`);if(t===he)throw new Error(`Graph "${e}": ${n} name "${he}" is reserved for meta companion paths`);ts(t,e,n)}function ns(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(W);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function rs(t,e){let n=!1;for(let s of t)if(!e.isMetaPassthrough(s[0])){n=!0;break}return n?t.filter(s=>e.isMetaPassthrough(s[0])):t}function hr(t){for(let e of t._mounts.values())hr(e);for(let e of t._nodes.values())try{e.down([[le]],{internal:!0})}catch{}}var re=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(W))throw new Error(`Graph name must not contain '${W}' (got "${e}")`);if(e===he)throw new Error(`Graph name "${he}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??We,this._traceRing=new lt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=Te(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}add(e,n){let r=e.name,s=n?.name??r;if(s==null||s==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let o=s,i=n?.annotation;if(dn(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:q()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Z&&n._applyVersioning(e)}remove(e){dn(e,this.name,"remove");let n=this._mounts.get(e);if(n){let o={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${W}${he}${W}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...n._collectSubgraphs(`${e}${W}`)),this._mounts.delete(e),n._parent=void 0,hr(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[le]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let n=typeof e=="function"?e:(()=>{let o=Gt(e);return i=>o.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>n(o));for(let o of s){let i=this.remove(o);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let s=e[r++];return{value:[s,n.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(W))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let s=r?.internal===!0;this.node(e).down([[F,n]],{actor:r?.actor,internal:s,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);ie(()=>{for(let[s,o]of r)this.set(s,o,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[ye]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let s=r?.internal===!0;this.node(e).down([[L,n]],{actor:r?.actor,internal:s,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[B]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof Z)for(let c of u._deps){let p=r.get(c.node);p!=null&&a.push([p,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,d]of s)o.set(d,a);let i=[];for(let[a,d]of s)if(d instanceof Z)for(let u of d._deps){let c=o.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,n){if(dn(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let n=ns(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],s=n.slice(1);if(s.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let o=this._nodes.get(r);if(o&&s.length>0&&s[0]===he)return this._resolveMetaChainFromNode(o,s,n.join(W));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${s.join(W)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(s.join(W))}_resolveMetaChainFromNode(e,n,r){let s=e,o=0,i=[...n];for(;o<i.length;){if(i[o]!==he)throw new Error(`Graph "${this.name}": expected ${he} segment in meta path "${r}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${he} in "${r}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);s=d,o+=2}return s}signal(e,n){if(n?.internal!==!0){for(let s of e)if(this.config.messageTier(s[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,s){for(let d of this._mounts.values())d._signalDeliver(e,n,r,s);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=rs(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(c){if(c instanceof ve)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,s)}}}_signalMetaSubtree(e,n,r,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,s)}catch(d){if(d instanceof ve)throw d;o.push(d)}this._signalMetaSubtree(a,n,r,s,o)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,s=kt(e?.detail,e?.fields),o=e?.format==="spec",i=o?kt("minimal"):s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[T,w]of a)d.set(w,T);let u=[];{let T=a.map(([,k])=>k),w=new Set(d.values()),N=0;for(;T.length>0;){let k=T.shift();if(k instanceof Z)for(let C of k._deps){let S=C.node;if(d.has(S))continue;let D=S.name??"",M=D;if(!M||w.has(M))if(D){let H=2;for(;w.has(`${D}#${H}`);)H++;M=`${D}#${H}`}else for(M=`__internal__/${N++}`;w.has(M);)M=`__internal__/${N++}`;d.set(S,M),w.add(M),u.push([M,S]),T.push(S)}}}let c=[...a,...u],p={};for(let[T,w]of c){if(n!=null&&!w.allowsObserve(n))continue;let N=an(w,i),k=w instanceof Z?w._deps.map(M=>d.get(M.node)??M.node.name??""):[],{name:C,...S}=N,D={...S,deps:k};if(!o){let M=this._annotations.get(T);M!=null&&(D.annotation=M)}if(r!=null)if(typeof r=="function"){let M=r;if(!(M.length>=2?M(T,D):M(D)))continue}else{let M=!0;for(let[H,X]of Object.entries(r)){let ne=H==="deps_includes"?"depsIncludes":H==="meta_has"?"metaHas":H;if(ne==="depsIncludes"){if(!D.deps.includes(String(X))){M=!1;break}continue}if(ne==="metaHas"){if(!Object.hasOwn(D.meta??{},String(X))){M=!1;break}continue}if(D[ne]!==X){M=!1;break}}if(!M)continue}p[T]=D}let f=new Set(Object.keys(p)),h=[];for(let[T,w]of c)if(w instanceof Z)for(let N of w._deps){let k=d.get(N.node);k!=null&&h.push([k,T])}h.sort((T,w)=>T[0]<w[0]?-1:T[0]>w[0]?1:T[1]<w[1]?-1:T[1]>w[1]?1:0);let l=h.map(([T,w])=>({from:T,to:w}));(n!=null||r!=null)&&(l=l.filter(T=>f.has(T.from)&&f.has(T.to)));let m=this._collectSubgraphs(""),b=n!=null||r!=null?m.filter(T=>{let w=`${T}${W}`;return[...f].some(N=>N===T||N.startsWith(w))}):m,g=this,v=e,y={name:this.name,nodes:p,edges:l,subgraphs:b,expand(T){let w={...v,format:void 0};return Array.isArray(T)?(w.fields=T,w.detail=void 0):(w.detail=T,w.fields=void 0),g.describe(w)}},x=e??{},E=x.format;return E==="json"?qo(y,x):E==="pretty"?Wo(y,x):E==="mermaid"?fr(y,x):E==="mermaid-url"?Yo(y,x):E==="d2"?Jo(y,x):E==="ascii"?tr(y,x):y}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${r}`;n.push(s),n.push(...this._mounts.get(r)._collectSubgraphs(`${s}${W}`))}return n}resourceProfile(e){return Dt(this,e)}reachable(e,n,r={}){return r.withDetail===!0?cn(this.describe(),e,n,{...r,withDetail:!0}):cn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(s.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return nr(s,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",s=0,o=G(s,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,st(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(b=>{let g=b.type;g!=="data"&&g!=="error"&&g!=="complete"&&g!=="teardown"||u()}),p=[],f=new WeakSet,h=b=>{if(f.has(b)||d)return;f.add(b);let g=b.topology.subscribe(v=>{for(let y of v){if(y[0]!==F)continue;let x=y[1];if(u(),x.kind==="added"&&x.nodeKind==="mount"){let E=b._mounts.get(x.name);E!=null&&h(E)}}});p.push(g);for(let v of b._mounts.keys()){let y=b._mounts.get(v);y!=null&&h(y)}};h(this);let l;try{l=I([o],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,g)=>b===g})}catch(b){c();for(let g of p)g();throw i.dispose(),b}let m=xe(l);return{node:l,dispose(){d=!0,c();for(let b of p)b();p.length=0,i.dispose(),m()}}}_explainReactive(e,n,r){let s=0,o=G(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=i.onEvent(h=>{let l=h.type;l!=="data"&&l!=="error"&&l!=="complete"&&l!=="teardown"||a||d||(a=!0,st(()=>{a=!1,!d&&(s+=1,o.emit(s))}))}),c={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},p;try{p=I([o],()=>this._explainStatic(e,n,c),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(h,l)=>h.found===l.found&&h.reason===l.reason&&h.steps.length===l.steps.length&&os(h.steps,l.steps)})}catch(h){throw u(),i.dispose(),h}let f=xe(p);return{node:p,dispose(){d=!0,u(),i.dispose(),f()}}}_pathsMatching(e){let n=Gt(e),r=[];return this._collectObserveTargets("",r),r.map(([s])=>s).filter(s=>n.test(s))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${W}${r}`;this._mounts.get(r)._collectObserveTargets(s,n)}for(let r of[...this._nodes.keys()].sort()){let s=this._nodes.get(r),o=e===""?r:`${e}${W}${r}`;n.push([o,s]),this._appendMetaObserveTargets(o,s,n)}}_appendMetaObserveTargets(e,n,r){for(let s of Object.keys(n.meta).sort()){let o=n.meta[s],i=`${e}${W}${he}${W}${s}`;r.push([i,o]),this._appendMetaObserveTargets(i,o,r)}}observe(e,n){let r=typeof e=="string",o=dr(r?n:e),i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(r){let c=e,p=this.resolve(c);if(a!=null&&!p.allowsObserve(a))throw new ve({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,p]],o,"one"):{subscribe(f){return p.subscribe(f)},up(f){try{p.up?.(f)}catch(h){if(h instanceof ve)return;throw h}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:c=>{let p=u.map(([f,h])=>h.subscribe(l=>{c(f,l)}));return()=>{for(let f of p)f()}},up:(c,p)=>{try{this.resolve(c).up?.(p)}catch(f){if(f instanceof ve)return;throw f}}}}_buildStructuredObserver(e,n,r){let s=r==="one"?e[0]?.[0]:void 0,o=i=>{if(r==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,o)}_createObserveResult(e,n,r){let s=n.timeline===!0,o=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,c=n.maxEvents,p=c!=null&&c>0?new lt(c):null,f=[],h=new Set,l={},m=new Set,b=0,g=0,v=0,y=0,x=0,E=0,T=!1,w=!1,N=0,k=new Map,C=new Map,S=new Map,D=R=>{p?p.push(R):f.push(R);for(let z of h)z(R)},M=()=>s?{timestamp_ns:q(),in_batch:ot(),batch_id:N}:{},H=(R,z)=>{if(!(!u||!(R instanceof Z)))return R._setInspectorHook(oe=>{if(oe.kind==="dep_message")k.set(R,oe.depIndex);else if(oe.kind==="run"){let ke=oe.batchData.map((V,te)=>V!=null&&V.length>0?V.at(-1):oe.prevData[te]);C.set(R,ke);let se=oe.batchData.map(V=>V!=null?[...V]:void 0);S.set(R,se),i&&D({type:"derived",path:z,dep_values:ke,dep_batches:se,...M()})}})},X=R=>{let z=k.get(R),oe=C.get(R);if(!o||oe==null)return{};let se=(z!=null&&z>=0&&R instanceof Z?R._deps[z]:void 0)?.node,V=se?.v,te=S.get(R);return{trigger_dep_index:z,trigger_dep_name:se?.name,...V!=null?{trigger_version:{id:V.id,version:V.version}}:{},dep_values:[...oe],...te!=null?{dep_batches:te}:{}}},ne=[],me=[];for(let[R,z]of e){let oe=H(z,R);oe&&ne.push(oe),me.push(z.subscribe(ke=>{N++;for(let se of ke){let V=se[0],te=M();if(V===F){l[R]=se[1];let A=z instanceof Z?z.lastMutation?.actor??Ke:Ke;D({type:"data",path:R,data:se[1],actor:A,...te,...X(z)})}else if(a)V===Y?b++:V===Q?g++:V===ye?v++:V===we?y++:V===Ie?x++:V===le?E++:V===B&&!m.has(R)?T=!0:V===L&&(w=!0,m.add(R));else if(V===Y)b++,D({type:"dirty",path:R,...te});else if(V===Q)g++,D({type:"resolved",path:R,...te,...X(z)});else if(V===ye)v++,D({type:"invalidate",path:R,...te});else if(V===we)y++,D({type:"pause",path:R,lockId:se[1],...te});else if(V===Ie)x++,D({type:"resume",path:R,lockId:se[1],...te});else if(V===B)m.has(R)||(T=!0),D({type:"complete",path:R,...te});else if(V===L){w=!0,m.add(R);let A=z instanceof Z?z.lastMutation?.actor??Ke:Ke;D({type:"error",path:R,data:se[1],actor:A,...te})}else V===le&&(E++,D({type:"teardown",path:R,...te}))}}))}let _e=!1,Ae=()=>{if(!_e){_e=!0;for(let R of me)R();for(let R of ne)R();for(let R of Ne)R({value:void 0,done:!0});Ne.length=0}},Ee=[],Ne=[];h.add(R=>{let z=Ne.shift();z?z({value:R,done:!1}):Ee.push(R)});let De={get values(){return l},get dirtyCount(){return b},get resolvedCount(){return g},get invalidateCount(){return v},get pauseCount(){return y},get resumeCount(){return x},get teardownCount(){return E},get events(){return p?p.toArray():[...f]},get anyCompletedCleanly(){return T},get anyErrored(){return w},get completedWithoutErrors(){return T&&!w},onEvent(R){return h.add(R),()=>h.delete(R)},dispose:Ae,expand(R){Ae();let z={...n};return typeof R=="string"?z.detail=R:Object.assign(z,R),r(dr(z))},[Symbol.asyncIterator](){return{next(){return Ee.length>0?Promise.resolve({value:Ee.shift(),done:!1}):_e?Promise.resolve({value:void 0,done:!0}):new Promise(R=>Ne.push(R))},return(){return Ae(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(De,n),De}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let s=n.logger??(l=>console.log(l)),o=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=o==null&&i==null?()=>!0:l=>(o==null||o.has(l))&&(i==null||!i.has(l)),d=es(n.theme),u=r==="stage-log"?q():0,c=l=>l==null?"":n.stageLabels?.[l]??l,p=(l,m)=>l.length>m?`${l.slice(0,m-1)}\u2026`:l,f=l=>l.type==="data"||l.type==="error"?p(Lt(l.data),120):"",h=l=>{if(r==="stage-log"){let w=(q()-u)/1e9,N=c(l.path).padEnd(9);if(l.type==="data"){let k=f(l);return`[${w.toFixed(3)}s] ${N} \u2190${k?` ${k}`:""}`}if(l.type==="error"){let k=f(l);return`[${w.toFixed(3)}s] ${N} \u2717${k?` ${k}`:""}`}return l.type==="complete"?`[${w.toFixed(3)}s] ${N} \u25A0 complete`:`[${w.toFixed(3)}s] ${N} ${l.type}`}if(r==="json")try{return JSON.stringify(l)}catch{return JSON.stringify({type:l.type,path:l.path,data:"[unserializable]"})}let m=d[l.type]??"",b=l.path?`${d.path}${l.path}${d.reset} `:"",g=l.type==="data"||l.type==="error",v=l.type==="pause"||l.type==="resume",y=g?` ${Lt(l.data)}`:v?` ${Lt(l.lockId)}`:"",x=l.type==="data"||l.type==="resolved"||l.type==="derived"?l:void 0,E=x?.trigger_dep_name!=null?` <- ${x.trigger_dep_name}`:x?.trigger_dep_index!=null?` <- #${x.trigger_dep_index}`:"",T=l.in_batch?" [batch]":"";return`${b}${m}${l.type.toUpperCase()}${d.reset}${y}${E}${T}`};e.onEvent(l=>{a(l.type)&&s(h(l),l)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){ar(this._disposers,this.name),this.signal([[le]],{internal:!0}),ar(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),s={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...c}=r.nodes[a];s[a]=c}let o=[...r.subgraphs].sort(),i={...r,version:1,nodes:s,subgraphs:o};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return kn(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??We,{codec:s,codecVersion:o,payload:i}=On(e,r);return s.decode(i,o)}restore(e,n){if(ur(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(o=>Gt(o)),s=n?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let d=this.tryResolve(o)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){n?.onError?.(o,a)}}}}}static fromSnapshot(e,n){ur(e);let r=typeof n=="function"?n:n?.build,s=typeof n=="function"?void 0:n?.factories,o=new t(e.name);if(r)return r(o),o.restore(e),o;for(let h of[...e.subgraphs].sort((l,m)=>{let b=l.split(W).length,g=m.split(W).length;return b!==g?b-g:l<m?-1:l>m?1:0})){let l=h.split(W),m=o;for(let b of l)m._mounts.has(b)||m.mount(b,new t(b)),m=m._mounts.get(b)}let i=s?Object.entries(s).map(([h,l])=>({re:Gt(h),factory:l})):[],a=h=>{for(let l of i)if(l.re.test(h))return l.factory},d=h=>{let l=h.split(W),m=l.pop();if(m==null||m.length===0)throw new Error(`invalid snapshot path "${h}"`);let b=o;for(let g of l){let v=b._mounts.get(g);if(!v)throw new Error(`unknown mount "${g}" in path "${h}"`);b=v}return[b,m]},u=Object.entries(e.nodes).filter(([h])=>!h.includes(`${W}${he}${W}`)).sort((h,l)=>h[0]<l[0]?-1:h[0]>l[0]?1:0),c=new Map(u),p=new Map,f=!0;for(;c.size>0&&f;){f=!1;for(let[h,l]of[...c.entries()]){let m=l?.deps??[];if(!m.every(E=>p.has(E)))continue;let[b,g]=d(h),v={...l?.meta??{}},y=a(h),x;if(l?.type==="state")x=G(l.value,{meta:v});else{if(y==null)continue;x=y(g,{path:h,type:l.type,value:l.value,meta:v,deps:m,resolvedDeps:m.map(E=>p.get(E))})}b.add(x,{name:g}),p.set(h,x),c.delete(h),f=!0}}if(c.size>0){let h=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${h}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let s=(u,c)=>{if(u.disposed)return;let p=zo(c.nodes);if(u.lastSnapshot!=null&&p!==""&&p===u.lastFingerprint)return;let f=u.seq+1,h=gt(),b=u.lastSnapshot==null||f%u.compactEvery===0?{mode:"full",snapshot:c,seq:f,timestamp_ns:h,format_version:Be}:{mode:"diff",diff:mr(u.lastSnapshot,c),seq:f,timestamp_ns:h,format_version:Be};if(u.tier.filter&&!u.tier.filter(this.name,b))return;let g;try{g=u.tier.save(this.name,b)}catch(v){n.onError?.(v,u.tier);return}if(g&&typeof g.then=="function"){let x=(u.savePending??Promise.resolve()).then(()=>g,()=>g).then(()=>{u.disposed||(u.seq=f,u.lastSnapshot=c,u.lastFingerprint=p)},E=>{n.onError?.(E,u.tier)});u.savePending=x.finally(()=>{u.savePending===x&&(u.savePending=void 0)})}else u.seq=f,u.lastSnapshot=c,u.lastFingerprint=p},o=(u,c)=>{try{s(u,c)}catch(p){n.onError?.(p,u.tier)}},i=(u,c)=>{if(!c.some(l=>{let m=this.config.messageTier(l[0]);return m>=3&&m<5}))return;if(n.filter){let l=this.tryResolve(u);if(l==null)return;let m=an(l,kt("standard"));if(!n.filter(u,m))return}let f,h=()=>(f==null&&(f=this.snapshot()),f);for(let l of r)l.disposed||(l.debounceMs===0?o(l,h()):(l.timer==null&&(l.timer=new Ot),l.timer.start(l.debounceMs,()=>{l.disposed||o(l,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(p=>{let f=this.tryResolve(p);return f==null?()=>{}:f.subscribe(h=>i(p,h))});a=()=>{for(let p of c)p()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let s;try{s=await r.load(this.name)}catch(i){n?.(i,r);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===Be&&o.nodes!=null)return this.restore(o),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let s of n){let o;try{o=await s.load(e)}catch(d){r?.onError?.(d,s);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===Be&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let s={path:e,annotation:n,timestamp_ns:q(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(s)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(s=>!e(s)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let s of n)this._traceRing.push(s);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(n.nodes)),o=[...s].filter(v=>!r.has(v)).sort(),i=[...r].filter(v=>!s.has(v)).sort(),a=[],d=[];for(let v of r){if(!s.has(v))continue;let y=e.nodes[v],x=n.nodes[v],E=y.v,T=x.v;E!=null&&T!=null&&E.id===T.id&&E.version!==T.version&&d.push({path:v,id:E.id,from:E.version,to:T.version});let w=E!=null&&T!=null&&E.id===T.id&&E.version===T.version;for(let N of["type","status","sentinel"]){let k=y[N],C=x[N];k!==C&&a.push({path:v,field:N,from:k,to:C})}if(!w)for(let N of["value","meta"]){let k=y[N],C=x[N];Bo(k,C)||a.push({path:v,field:N,from:k,to:C})}}let u=v=>`${v.from} ${v.to}`,c=new Set(e.edges.map(u)),p=new Set(n.edges.map(u)),f=n.edges.filter(v=>!c.has(u(v))),h=e.edges.filter(v=>!p.has(u(v))),l=new Set(e.subgraphs),m=new Set(n.subgraphs),b=[...m].filter(v=>!l.has(v)).sort(),g=[...l].filter(v=>!m.has(v)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:f,edgesRemoved:h,subgraphsAdded:b,subgraphsRemoved:g}}};function mr(t,e){let n=re.diff(t,e),r={};for(let s of n.nodesAdded){let o=e.nodes[s];o!=null&&(r[s]=o)}return{...n,nodesAddedFull:r}}function cn(t,e,n,r={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?s:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=r.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return r.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[y,x]of Object.entries(t.nodes)){if(!y)continue;c.add(y);let E=x.deps??[];i.set(y,E);for(let T of E)T&&(c.add(T),a.has(T)||a.set(T,new Set),a.get(T).add(y))}for(let y of t.edges){if(y==null||typeof y!="object")continue;let x=typeof y.from=="string"?y.from:"",E=typeof y.to=="string"?y.to:"";!x||!E||(c.add(x),c.add(E),u.has(x)||u.set(x,new Set),u.get(x).add(E),d.has(E)||d.set(E,new Set),d.get(E).add(x))}if(!c.has(e))return r.withDetail?s:[];let p=r.both===!0,f=y=>{if(p){let w=i.get(y)??[],N=d.get(y),k=a.get(y),C=u.get(y),S=[...w];return N&&S.push(...N),k&&S.push(...k),C&&S.push(...C),S}if(n==="upstream"){let w=i.get(y)??[],N=d.get(y);return N?[...w,...N]:w}let x=a.get(y),E=u.get(y),T=x?[...x]:[];return E&&T.push(...E),T},h=new Set([e]),l=new Map,m=[{path:e,depth:0}],b=0,g=!1;for(;b<m.length;){let y=m[b++];if(o!=null&&y.depth>=o){f(y.path).length>0&&(g=!0);continue}for(let x of f(y.path))!x||h.has(x)||(h.add(x),l.set(x,y.depth+1),m.push({path:x,depth:y.depth+1}))}let v=[...l.keys()].sort((y,x)=>y<x?-1:y>x?1:0);return r.withDetail?{paths:v,depths:l,truncated:g}:v}function os(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],s=e[n];if(r.path!==s.path||r.type!==s.type||r.status!==s.status||r.hop!==s.hop||r.dep_index!==s.dep_index||r.annotation!==s.annotation||r.value!==s.value||r.lastMutation!==s.lastMutation)return!1;let o=r.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}mt();Ce();at();fe();de();Re();Ce();fe();de();var fn=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),s=Math.min(e,this._size);if(s>=r)return[];let o=r-s;if(this._maxSize===void 0)return this._buf.slice(s,r);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function gr(t){return t.subscribe(()=>{})}var ss=64;function br(t,e={}){let{name:n,maxSize:r,versioning:s,backend:o}=e,i=o??new fn(t,r),a=G(i.toArray(),{name:n,describeKind:"state",equals:(l,m)=>l===m,...s!=null?{versioning:s}:{}});function d(){let l=i.toArray();ie(()=>{a.down([[Y]]),a.down([[F,l]])})}let u=new Map,c=new Map;function p(l,m){return`${l}:${m===void 0?"END":m}`}function f(l){if(l.size<ss)return;let m=l.keys().next();if(m.done)return;let b=l.get(m.value);b!==void 0&&b.dispose(),l.delete(m.value)}function h(l){let m=i.version;try{return l()}finally{i.version!==m&&d()}}return{entries:a,get size(){return i.size},at(l){return i.at(l)},append(l){h(()=>i.append(l))},appendMany(l){l.length!==0&&h(()=>i.appendMany(l))},clear(){h(()=>i.clear())},trimHead(l){h(()=>i.trimHead(l))},tail(l){if(!Number.isInteger(l)||l<0)throw new RangeError(`tail: n must be a non-negative integer (got ${l})`);let m=u.get(l);if(m!==void 0)return u.delete(l),u.set(l,m),m.node;f(u);let b=I([a],([v])=>{let y=v;return l===0||y.length===0?[]:y.slice(Math.max(0,y.length-l))},{initial:i.tail(l),describeKind:"derived"}),g=gr(b);return u.set(l,{node:b,dispose:g}),b},slice(l,m){if(!Number.isInteger(l)||l<0)throw new RangeError(`slice: start must be a non-negative integer (got ${l})`);if(m!==void 0&&(!Number.isInteger(m)||m<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${m})`);let b=p(l,m),g=c.get(b);if(g!==void 0)return c.delete(b),c.set(b,g),g.node;f(c);let v=I([a],([x])=>{let E=x;return m===void 0?E.slice(l):E.slice(l,m)},{initial:i.slice(l,m),describeKind:"derived"}),y=gr(v);return c.set(b,{node:v,dispose:y}),v},disposeTail(l){let m=u.get(l);return m===void 0?!1:(m.dispose(),u.delete(l),!0)},disposeSlice(l,m){let b=p(l,m),g=c.get(b);return g===void 0?!1:(g.dispose(),c.delete(b),!0)},disposeAllViews(){for(let l of u.values())l.dispose();u.clear();for(let l of c.values())l.dispose();c.clear()},dispose(){for(let l of u.values())l.dispose();u.clear();for(let l of c.values())l.dispose();c.clear()}}}fe();Je();function pn(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[Y],[F,n+1]]),!0)}function $e(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function ct(t){return t.relatedTo?.[0]??t.summary}var is=2147483647;function Pt(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function He(t,e){return $e("messaging",t,e)}var hn=class extends re{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=br([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=I([this.events],([r])=>{let s=r;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:He("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(xe(this.latest)),this.hasLatest=I([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:He("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(xe(this.hasLatest)),this.addDisposer(()=>{this.events.down([[B]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}},$t=class extends re{source;cursor;available;topic;constructor(e,n,r={}){super(e,r.graph);let s=Pt(r.cursor??0,"subscription cursor");this.topic=n;let o=n.events;this.source=I([o],([i])=>i,{name:"source",describeKind:"derived",meta:He("subscription_source"),initial:o.cache}),this.add(this.source,{name:"source"}),this.cursor=G(s,{name:"cursor",describeKind:"state",meta:He("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=I([this.source,this.cursor],([i,a])=>{let d=i,u=Math.max(0,Math.trunc(a??0));return d.slice(u)},{name:"available",describeKind:"derived",meta:He("subscription_available"),initial:[]}),this.add(this.available,{name:"available"}),this.addDisposer(xe(this.source)),this.addDisposer(xe(this.available))}ack(e){let n=this.available.cache,r=e===void 0?n.length:Pt(e,"subscription ack count"),s=Math.min(r,n.length);if(s<=0)return this.cursor.cache;let o=this.cursor.cache+s;return this.cursor.emit(o),o}pull(e,n={}){let r=this.available.cache,s=e===void 0?r.length:Pt(e,"subscription pull limit"),o=r.slice(0,s);return n.ack&&o.length>0&&this.ack(o.length),o}},mn=class extends re{_sourceSub;_target;bridgedCount;constructor(e,n,r,s={}){super(e,s.graph),this._sourceSub=as(`${e}-subscription`,n,{cursor:s.cursor}),this._target=r,this.mount("subscription",this._sourceSub),this.bridgedCount=G(0,{name:"bridgedCount",describeKind:"state",meta:He("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"});let o=Math.max(1,Pt(s.maxPerPump??is,"topic bridge maxPerPump")),i=s.map??(d=>d),a=ae([this._sourceSub.available],()=>{let d=this._sourceSub.pull(o,{ack:!0});if(d.length===0)return;let u=0;for(let c of d){let p=i(c);p!==void 0&&(this._target.publish(p),u+=1)}if(u>0){let c=this.bridgedCount.cache;this.bridgedCount.emit(c+u)}},{name:"pump",describeKind:"effect",meta:He("topic_bridge_pump")});this.add(a,{name:"pump"}),this.addDisposer(xe(a))}},gn=class extends re{_topics=new Map;_version=0;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get version(){return this._version}get size(){return this._topics.size}has(e){return this._topics.has(e)}topicNames(){return this._topics.keys()}topic(e,n){let r=this._topics.get(e);if(r===void 0){let s={...this._defaultTopicOptions,...n??{}};r=new hn(e,s),this._topics.set(e,r),this.mount(e,r),this._version+=1}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){ie(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let s=this.topic(n);return new $t(e,s,r)}removeTopic(e){if(!this._topics.has(e))return!1;try{this.remove(e)}finally{this._topics.delete(e),this._version+=1}return!0}};function Ft(t,e){return new gn(t,e)}function as(t,e,n){return new $t(t,e,n)}function bn(t,e,n,r){return new mn(t,e,n,r)}function us(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function ds(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let o=ls(e);return{best:t[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(t.length);for(let d=0;d<t.length;d++)o[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<t.length&&(o[u].sum+=d.score,o[u].count+=1)}let i=t[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<t.length;d++){let u=o[d].count>0?o[d].sum/o[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=t[d])}return{best:i,bestScore:a}}let r=t[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<t.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,r=t[o])}return{best:r,bestScore:s}}function ls(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function yr(t,e,n,r){let s=r.name??"refine-loop",o=new re(s,r.graph),i=us(r.dataset)?r.dataset:G(r.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=G(0,{name:"iteration"});o.add(a,{name:"iteration"});let d=G(n,{name:"strategy",equals:()=>!1});o.add(d,{name:"strategy"});let u=G(null,{name:"lastFeedback"});o.add(u,{name:"lastFeedback"});let c=G([],{name:"prevCandidates"});o.add(c,{name:"prevCandidates"});let p=G(!1,{name:"paused"});o.add(p,{name:"paused"});let f=G("running",{name:"status"});o.add(f,{name:"status"});let h=G([],{name:"history",equals:()=>!1});o.add(h,{name:"history"});let l=G(null,{name:"best"});o.add(l,{name:"best"});let m=G(Number.NEGATIVE_INFINITY,{name:"score"});o.add(m,{name:"score"});let b=G(0,{name:"budget-used"});o.add(b,{name:"budget-used"});let g=Ft("stages");o.mount("stages",g);let v=g.topic("generate"),y=g.topic("evaluate"),x=g.topic("analyze"),E=g.topic("decide"),T=n,w=null,N=[];o.addDisposer(d.subscribe(A=>{for(let $ of A)$[0]===F&&(T=$[1])})),o.addDisposer(u.subscribe(A=>{for(let $ of A)$[0]===F&&(w=$[1])})),o.addDisposer(c.subscribe(A=>{for(let $ of A)$[0]===F&&(N=$[1])}));let k=Se(a,A=>{let $=T,J=A===0||w==null;return ae([],(P,_)=>{let O=!1;try{let j=J?$.seed(t):$.generate(w,N);if(j instanceof Promise)return j.then(K=>{O||_.emit(K)},K=>{O||_.down([[L,K]])}),()=>{O=!0};_.emit(j)}catch(j){O=!0,_.down([[L,j]])}},{describeKind:"producer"})},{name:"candidates"});o.add(k,{name:"candidates"});let C=ue([k],(A,$,J)=>{let P=J.terminalDeps[0];P!==void 0&&P!==!0&&f.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(C,{name:"error-watcher"}),o.addDisposer(C.subscribe(()=>{}));let S=I([k,a],([A,$])=>({iteration:$,candidates:A,timestamp_ns:q()}),{name:"generate-event"});o.add(S,{name:"generate-event"}),o.addDisposer(S.subscribe(()=>{}));let D=ue([S],([A])=>{v.publish(A)},{name:"generate-publish"});o.add(D,{name:"generate-publish"}),o.addDisposer(D.subscribe(()=>{}));let M=ue([k],([A])=>{c.emit(A)},{name:"generate-mirror"});o.add(M,{name:"generate-mirror"}),o.addDisposer(M.subscribe(()=>{}));let H=e(k,i);o.add(H,{name:"scores"});let X=I([H,k,a],([A,$,J])=>({iteration:J,candidates:$,scores:A,timestamp_ns:q()}),{name:"evaluate-event"});o.add(X,{name:"evaluate-event"}),o.addDisposer(X.subscribe(()=>{}));let ne=ue([X],([A])=>{y.publish(A)},{name:"evaluate-publish"});o.add(ne,{name:"evaluate-publish"}),o.addDisposer(ne.subscribe(()=>{}));let me=I([H,k],([A,$])=>T.analyze(A,$),{name:"feedback"});o.add(me,{name:"feedback"});let _e=I([me,k,a],([A,$,J])=>({iteration:J,candidates:$,feedback:A,timestamp_ns:q()}),{name:"analyze-event"});o.add(_e,{name:"analyze-event"}),o.addDisposer(_e.subscribe(()=>{}));let Ae=ue([_e],([A])=>{x.publish(A)},{name:"analyze-publish"});o.add(Ae,{name:"analyze-publish"}),o.addDisposer(Ae.subscribe(()=>{}));let Ee=I([h],([A])=>{let $=A;if(r.patience==null||$.length<=r.patience)return!1;let J=$.slice(-(r.patience+1)),P=J[0].bestScore;return J.slice(1).every(_=>_.bestScore<=P)},{name:"patience-check"});o.add(Ee,{name:"patience-check"});let Ne=I([m],([A])=>r.minScore!=null&&A>=r.minScore,{name:"min-score-check"});o.add(Ne,{name:"min-score-check"});let De=I([h],([A])=>{let $=A;if(r.minDelta==null||$.length<2)return!1;let J=$[$.length-2].bestScore,P=$[$.length-1].bestScore;return Math.abs(P-J)<r.minDelta},{name:"min-delta-check"});o.add(De,{name:"min-delta-check"});let R=I([b],([A])=>r.maxEvaluations!=null&&A>=r.maxEvaluations,{name:"max-evaluations-check"});o.add(R,{name:"max-evaluations-check"});let z=I([a],([A])=>r.maxIterations!=null&&A>=r.maxIterations,{name:"max-iterations-check"});o.add(z,{name:"max-iterations-check"});let oe=I([b],([A])=>r.budget!=null&&A>=r.budget,{name:"budget-exhausted-check"});o.add(oe,{name:"budget-exhausted-check"}),o.addDisposer(Ee.subscribe(()=>{})),o.addDisposer(Ne.subscribe(()=>{})),o.addDisposer(De.subscribe(()=>{})),o.addDisposer(R.subscribe(()=>{})),o.addDisposer(z.subscribe(()=>{})),o.addDisposer(oe.subscribe(()=>{}));let ke=I([Ee,Ne,De,R,z],([A,$,J,P,_])=>A?{converged:!0,reason:"patience"}:$?{converged:!0,reason:"min-score"}:J?{converged:!0,reason:"min-delta"}:P?{converged:!0,reason:"max-evaluations"}:_?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(ke,{name:"converged"}),o.addDisposer(ke.subscribe(()=>{}));let se=-1,V=ue([me,H,k],([A,$,J])=>{let P=a.cache,_=A,O=J,j=$;if(P<=se)return;se=P;let{best:K,bestScore:Oe}=ds(O,j),tt=h.cache,Fe={n:P,candidates:O,scores:j,feedback:_,best:K,bestScore:Oe,timestamp_ns:q()},U=[...tt,Fe],ge=b.cache+O.length,ce="continue",Me,_n=r.budget!=null&&ge>=r.budget,En=p.cache;if(_n)ce="budget",Me="budget";else if(r.minScore!=null&&_.score>=r.minScore)ce="converged",Me="min-score";else if(r.maxIterations!=null&&P>=r.maxIterations)ce="converged",Me="max-iterations";else if(r.maxEvaluations!=null&&ge>=r.maxEvaluations)ce="converged",Me="max-evaluations";else if(r.minDelta!=null&&U.length>=2){let pt=U[U.length-2].bestScore,Bt=U[U.length-1].bestScore;Math.abs(Bt-pt)<r.minDelta&&(ce="converged",Me="min-delta")}else if(r.patience!=null&&U.length>r.patience){let pt=U.slice(-(r.patience+1)),Bt=pt[0].bestScore;pt.slice(1).every(Ir=>Ir.bestScore<=Bt)&&(ce="converged",Me="patience")}ce==="continue"&&En&&(ce="paused"),ie(()=>{l.emit(K),m.emit(_.score),h.emit(U),b.emit(ge),u.emit(_),E.publish({iteration:P,decision:ce,reason:Me,timestamp_ns:q()}),ce==="continue"?a.emit(P+1):f.emit(ce==="converged"?"converged":ce==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(V,{name:"decide-bridge"}),o.addDisposer(V.subscribe(()=>{})),Object.assign(o,{best:l,score:m,status:f,history:h,strategy:d,iteration:a,generate:v,evaluate:y,analyze:x,decide:E,setStrategy(A){d.emit(A)},pause(){p.emit(!0)},resume(){f.cache==="paused"&&ie(()=>{p.emit(!1),f.emit("running"),a.emit(a.cache+1)})}})}function cs(t){let{best:e,score:n,status:r}=t,s=Number.isFinite(n)?n.toFixed(3):String(n),o=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${s}`,artifact:o}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${s}`,artifact:o}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:o}}function yn(t){let e=t.name??"refine-executor",n=t.toOutput??cs;return r=>{let s=Qe(r,i=>i!=null,{name:`${e}/gate-in`}),o=Se(s,i=>{let a=yr(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return I([a.status,a.best,a.score],([d,u,c])=>{let p=d;return p!=="converged"&&p!=="budget"&&p!=="errored"?null:n({best:u,score:c,status:p})},{name:`${e}/output`})},{name:e});return Qe(o,i=>i!=null,{name:`${e}/gate-out`})}}function fs(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function ps(t){let{passCount:e,total:n,meanScore:r,threshold:s,missingArtifact:o}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!o&&n>0&&r>=s,d=o?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${s}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${s}`];return a?{verified:!0,findings:d}:{verified:!1,findings:d,errorClass:"structural"}}function hs(t){return t.artifact??null}function vr(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??ps,s=t.extractArtifact??hs;return o=>{let i=Qe(o,d=>d!=null&&d[0]!=null&&d[1]!=null,{name:`${e}/gate-in`}),a=Se(i,d=>{let[u,c]=d,p=s(u,c);if(p==null)return G(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let f=G([p],{name:`${e}/candidates`}),h=G(t.datasetFor(c),{name:`${e}/dataset`}),l=t.evaluator(f,h);return I([l],([m])=>{let b=m;if(b==null)return null;let g=fs(b),v=b.filter(y=>y.score>=n).length;return r({scores:b,meanScore:g,passCount:v,total:b.length,threshold:n})},{name:`${e}/output`})},{name:e});return Qe(a,d=>d!=null,{name:`${e}/gate-out`})}}function ms(t){let e=t.name??"harness-pair",n=yn({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=vr({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Ge();Re();de();Ce();Ge();fe();de();var vn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let s=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),s=0;try{for(let[o,i]of e)this._store.has(o)&&this._store.delete(o),this._store.set(o,{value:i,expiresAt:r}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=q(),n=0;for(let[r,s]of this._store)this._isExpired(s,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=q(),n=new Map;for(let[r,s]of this._store)this._isExpired(s,e)||n.set(r,s.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return q()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??q())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function Vt(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:s,backend:o,retention:i}=t;if(i&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=o??new vn({maxSize:n,defaultTtl:r}),d=G(a.toMap(),{name:e,describeKind:"state",equals:(f,h)=>f===h,...s!=null?{versioning:s}:{}});function u(){let f=a.toMap();ie(()=>{d.down([[Y]]),d.down([[F,f]])})}function c(){if(!i)return;let f=a.toMap(),h=i.archiveThreshold,l=i.maxSize,m=[];for(let[g,v]of f)m.push({key:g,value:v,score:i.score(g,v)});m.sort((g,v)=>g.score-v.score);let b=new Set;if(h!==void 0)for(let g of m)if(g.score<h)b.add(g.key);else break;if(l!==void 0&&m.length-b.size>l)for(let g of m){if(m.length-b.size<=l)break;b.has(g.key)||b.add(g.key)}if(b.size!==0)for(let g of m)b.has(g.key)&&(i.onArchive?.(g.key,g.value,g.score),a.delete(g.key))}function p(f,h="mutation"){let l=a.version;try{return f()}finally{a.version!==l&&(h==="mutation"&&c(),u())}}return{entries:d,has(f){return p(()=>a.has(f),"read")},get(f){return p(()=>a.get(f),"read")},set(f,h,l){p(()=>a.set(f,h,l?.ttl))},setMany(f,h){p(()=>a.setMany(f,h?.ttl))},delete(f){p(()=>a.delete(f))},deleteMany(f){p(()=>a.deleteMany(f))},clear(){p(()=>a.clear())},pruneExpired(){p(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}function ft(t,e){return $e("ai",t,e)}function Tr(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}fe();de();Je();function xr(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function gs(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function jt(t,e,n,r){let s=r?.format??"text",o=r?.name??"prompt_node",i=I(e,d=>{if(d.some(c=>c==null))return[];let u=typeof n=="string"?n:n(...d);return u?[{role:"user",content:u}]:[]},{name:`${o}::messages`,meta:ft("prompt_node")});return Se(i,d=>!d||d.length===0?G(null):Te(u=>{let c=!1,p=!1,f,h={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let g=zn(r.abort);h.signal=g.signal,f=g.dispose}let l;try{l=t.invoke(d,h)}catch(g){return c=!0,u.down([[L,g]]),()=>{f?.()}}let b=Ye(l).subscribe(g=>{if(!(p||c))for(let v of g){if(c)return;if(v[0]===F){let y=v[1];try{let x=xr(y),E=s==="json"?JSON.parse(Tr(x)):x;u.emit(E)}catch(x){let E=xr(y),T=new Error(`promptNode: failed to parse LLM response as JSON: ${x.message}
|
|
49
|
-
Raw content (first 200 chars): ${gs(E)}`);c=!0,u.down([[L,T]]);return}}else if(v[0]===L){c=!0,u.down([[L,v[1]]]);return}else if(v[0]===B){c=!0,u.down([[B]]);return}else u.down([v])}});return()=>{p=!0,b(),f?.()}},{name:`${o}::call`,meta:ft("prompt_node::call")}),{name:`${o}::output`,meta:r?.meta?{...ft("prompt_node::output"),...r.meta}:ft("prompt_node::output")})}Ce();fe();Re();de();function bs(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=ys(t,e);if(!n)throw new Error("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");return{node:e,path:n}}function ys(t,e){let n=t.describe(),r=`::${he}::`;for(let s of Object.keys(n.nodes).sort())if(!s.includes(r))try{if(t.resolve(s)===e)return s}catch{}}function vs(t,e,n,r){t.add(n,{name:e})}function Ts(t,e){return $e("orchestration",t,e)}function wr(t,e,n,r){let s=r?.maxPending??1/0;if(s<1&&s!==1/0)throw new RangeError("gate: maxPending must be >= 1");let o=r?.startOpen??!1,i=bs(t,n),a=G([],{name:"pending",equals:()=>!1}),d=G(o,{name:"isOpen"}),u=I([a],([T])=>T.length,{name:"count"}),c=G(null,{name:"lastRejected",equals:()=>!1}),p=[],f=!1,h=o,l=d.subscribe(T=>{for(let w of T)w[0]===F&&(h=w[1])});function m(){a.emit([...p])}function b(T){p.push(T),p.length>s&&p.shift(),m()}function g(T){let w=p.splice(0,T);return m(),w}function v(T){if(f)throw new Error(`gate: ${T}() called after gate was torn down`)}let y=ae([i.node],(T,w,N)=>{let k=N.terminalDeps[0];if(k!==void 0){f=!0,p=[],m(),w.down(k===!0?[[B]]:[[L,k]]);return}let C=T[0];if(C==null||C.length===0){w.down([[Q]]);return}for(let S of C)h?w.emit(S):(b(S),w.down([[Q]]))},{name:e,describeKind:"derived",meta:Ts("gate",r?.meta)}),x={node:y,pending:a,count:u,isOpen:d,lastRejected:c,approve(T=1){v("approve");let w=g(T);for(let N of w){if(f)break;y.emit(N)}},reject(T=1){v("reject");let w=[...p],N=Math.min(T,w.length);if(N===0){g(T);return}ie(()=>{for(let k=0;k<N;k++)c.emit(w[k]);g(T)})},modify(T,w=1){v("modify");let N=[...p],k=g(w);for(let C=0;C<k.length&&!f;C++)y.emit(T(k[C],C,N))},open(){v("open"),ie(()=>{d.emit(!0);let T=g(p.length);for(let w of T){if(f)break;y.emit(w)}})},close(){v("close"),d.emit(!1)}};t.addDisposer(u.subscribe(()=>{})),t.addDisposer(l),vs(t,e,y,i.path?[i.path]:[]);let E=new re(`${e}_state`);return E.add(a,{name:"pending"}),E.add(d,{name:"isOpen"}),E.add(u,{name:"count"}),E.add(c,{name:"lastRejected"}),t.mount(`${e}_state`,E),t.addDisposer(c.subscribe(()=>{})),x}function _r(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let s=t*Math.exp(-n*e);return Math.max(r,s)}Ce();fe();de();var Tn=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Er(t,e={}){let{name:n,versioning:r,backend:s}=e,o=s??new Tn(t),i=G(o.toArray(),{name:n,describeKind:"state",equals:(u,c)=>u===c,...r!=null?{versioning:r}:{}});function a(){let u=o.toArray();ie(()=>{i.down([[Y]]),i.down([[F,u]])})}function d(u){let c=o.version;try{return u()}finally{o.version!==c&&a()}}return{items:i,get size(){return o.size},at(u){return o.at(u)},append(u){d(()=>o.append(u))},appendMany(u){d(()=>o.appendMany(u))},insert(u,c){d(()=>o.insert(u,c))},insertMany(u,c){d(()=>o.insertMany(u,c))},pop(u=-1){return d(()=>o.pop(u))},clear(){d(()=>o.clear())},dispose(){}}}function xs(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function ws(t,e){return $e("job_queue",t,e)}var xn=class extends re{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,n={}){super(e,n.graph),this._pending=Er([],{name:"pending"}),this._jobs=Vt({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=I([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:ws("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(xe(this.depth))}enqueue(e,n={}){let r=n.id??`${this.name}-${++this._seq}`;if(this._jobs.get(r)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${r}"`);let s={id:r,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(r,s),this._pending.append(r),r}claim(e=1){let n=xs(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let o=this._pending.pop(0),i=this._jobs.get(o);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(o,a),r.push(a)}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),!0):(this._jobs.delete(e),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.state==="queued"){let s=this.pending.cache.indexOf(e);s>=0&&this._pending.pop(s)}return this._jobs.delete(e),!0}};function Nr(t,e){return new xn(t,e)}Ge();de();function wn(){let t=Vt({name:"strategy-entries"}),e=I([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,p]of d){let f=u.get(c);if(!f||p.attempts!==f.attempts||p.successes!==f.successes)return!1}return!0}});function n(i,a,d){let u=et(i,a),c=t.get(u),p=(c?.attempts??0)+1,f=(c?.successes??0)+(d?1:0);t.set(u,{rootCause:i,intervention:a,attempts:p,successes:f,successRate:f/p})}function r(i,a){return t.get(et(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:n,lookup:r,dispose:o}}function _s(t,e,n,r,s){let o={...Xe,...s?.severityWeights},i=s?.decayRate??Ze,a=s?.effectivenessThreshold??.7,d=s?.effectivenessBoost??15,u=[t,e,n];return r&&u.push(r),I(u,c=>{let p=c[0],f=c[1],h=c[2],l=r?c[3]:0,m=o[p.severity??"medium"],b=(q()-h)/1e9,g=_r(m,b,i,0),v=et(p.rootCause,p.intervention),y=f.get(v);return y&&y.successRate>=a&&(g+=d),g+=l*20,g},{name:"priority-score"})}var kr="intake",Es="triage-output",Or="retry",Rr="verify-results",Sr="__unrouted";function Ar(t,e){let n=dt(e,on,(r,s)=>r.replace("{{item}}",JSON.stringify(s)));return r=>jt(t,[r],n,{name:"execute",format:"json"})}function Mr(t,e){let n=dt(e,sn,(r,s)=>{let[o,i]=s;return r.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return r=>jt(t,[r],s=>s==null?"":n(s),{name:"verify",format:"json"})}var zt=class extends re{queues;jobs;gates;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,s,o,i,a,d){super(e),this.queues=n,this.jobs=r,this.gates=s,this.strategy=o,this.totalRetries=i,this.totalReingestions=a,this.priorityScores=d}get intake(){return this.queues.topic(kr)}get verifyResults(){return this.queues.topic(Rr)}get retry(){return this.queues.topic(Or)}get unrouted(){return this.queues.topic(Sr)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],s=pe.flatMap(i=>r(n(i))),o=[];for(let[i]of this.gates)o.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:s},{label:"GATE",paths:o},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function Ns(t,e){let n=e.adapter,r=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??Nt,i=new Map;for(let _ of pe)i.set(_,{...Et[_],...e.queues?.[_]});let a=Ft(`${t}/queues`,{defaultTopicOptions:{retainedLimit:s}}),d=a.topic(kr),u=a.topic(Es),c=a.topic(Or),p=a.topic(Rr),f=new Map;for(let _ of pe)f.set(_,a.topic(_));let h=a.topic(Sr),l=wn(),m=ut(d.latest,l.node),b=dt(e.triagePrompt,rn,(_,O)=>{let[j,K]=O;return _.replace("{{strategy}}",JSON.stringify(Array.from(K.entries()))).replace("{{item}}",JSON.stringify(j))}),g=jt(n,[m],_=>{let O=_;return!O||!O[0]?"":b(O)},{name:"triage",format:"json"}),v=ut(g,m),x=ue([v],([_])=>{if(_==null)return;let[O,j]=_;if(!O?.route)return;let K=j?.[0],Oe={...O,...K};u.publish(Oe)}).subscribe(()=>{}),E=new Set(pe);for(let _ of pe)bn(`bridge/${_}`,u,f.get(_),{map:O=>O.route===_?O:void 0});bn("bridge/__unrouted",u,h,{map:_=>E.has(_.route)?void 0:_});let T=new Map,w=new Map;for(let _ of pe)T.set(_,Nr(`jobs/${_}`));let N=[];for(let _ of pe){let O=f.get(_),j=T.get(_),K=new WeakSet,Oe=ue([O.events],([tt])=>{let Fe=tt??[];for(let U of Fe){if(K.has(U))continue;K.add(U);let ge=j.enqueue(U);w.set(ct(U),{route:_,id:ge})}},{name:`jobs/${_}-mirror`});N.push(Oe.subscribe(()=>{}))}function k(_){let O=ct(_),j=w.get(O);j&&(T.get(j.route)?.removeById(j.id),w.delete(O))}let C=new re("gates"),S=new Map;for(let _ of pe){let O=i.get(_);if(!O.gated)continue;let j=f.get(_);C.add(j.latest,{name:`${_}/source`});let K=wr(C,`${_}/gate`,`${_}/source`,{maxPending:O.maxPending,startOpen:O.startOpen});S.set(_,K)}let D=[];for(let _ of pe)i.get(_).gated&&S.has(_)?D.push(S.get(_).node):D.push(f.get(_).latest);D.push(c.latest);let M=Bn(...D),X=(e.executor??Ar(n,e.executePrompt))(M),ne=ut(X,M),_e=(e.verifier??Mr(n,e.verifyPrompt))(ne),Ae=ut(_e,ne),Ee=e.maxReingestions??1,Ne=Math.min(e.maxTotalRetries??r*10,100),De=Math.min(e.maxTotalReingestions??Ee*10,100),R=G(0),z=G(0);function oe(_,O,j){let K={item:j,outcome:O?.outcome??"failure",detail:O?.detail??"unknown",artifact:O?.artifact};return{item:j,execution:K,verified:_.verified,findings:_.findings??[],errorClass:_.errorClass}}function ke(_,O){l.record(O.rootCause,O.intervention,!0),p.publish(_),k(O)}function se(_,O){let j=ct(O),K=O.$retries??0,Oe={...O,$retries:K+1,summary:`[RETRY ${K+1}/${r}] ${j} \u2014 Previous attempt failed: ${_.findings.join("; ")}`,relatedTo:[j]};c.publish(Oe)}function V(_,O){l.record(O.rootCause,O.intervention,!1),p.publish(_),k(O);let j=ct(O),K=O.$reingestions??0;K<Ee&&pn(z,De)&&d.publish({source:O.source,summary:`Verification failed for: ${j}`,evidence:_.findings.join(`
|
|
50
|
-
`),affectsAreas:O.affectsAreas,affectsEvalTasks:O.affectsEvalTasks,severity:O.severity??"high",relatedTo:[
|
|
42
|
+
}`;function dt(t,e,n){if(typeof t=="function")return t;let r=t??e;return s=>n(r,s)}re();re();Ce();Pe();le();Se();re();vt();Ce();Pe();at();le();at();Se();function Rt(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function yo(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function vo(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function an(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(u=>u.startsWith("meta.")).map(u=>u.slice(5)):null,s=n||e.has("meta")||r!=null&&r.length>0,o="state",i=[];t instanceof Z&&(o=yo(t),i=t._deps.map(u=>u.node.name??""));let a={type:o,deps:i};(n||e.has("status"))&&(a.status=t.status);let d=t instanceof Z?t._guard:void 0;if(s){let u={...vo(t)};if(d!=null&&u.access===void 0&&(u.access=Jt(d)),r!=null&&r.length>0&&!e.has("meta")){let c={};for(let p of r)p in u&&(c[p]=u[p]);a.meta=c}else a.meta=u}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let u={id:t.v.id,version:t.v.version};"cid"in t.v&&(u.cid=t.v.cid,u.prev=t.v.prev),a.v=u}return(n||e.has("guard"))&&d!=null&&(a.guard=Jt(d)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}Se();re();Ke();Bn();var lt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}};Yt();function un(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function kt(t){let e=0;for(let n of t)e+=un(n.codePointAt(0));return e}function Kn(t,e){if(e<=0)return"";let n=0,r="";for(let s of t){let o=un(s.codePointAt(0));if(n+o>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=un(i.codePointAt(0))}return`${r}\u2026`}r+=s,n+=o}return r}var To={horizontal:"\u2500",vertical:"\u2502",cornerTL:"\u250C",cornerTR:"\u2510",cornerBL:"\u2514",cornerBR:"\u2518",tDown:"\u252C",tUp:"\u2534",tRight:"\u251C",tLeft:"\u2524",cross:"\u253C",arrowRight:"\u25B6",arrowDown:"\u25BC",arrowLeft:"\u25C0",arrowUp:"\u25B2",boxTL:"\u250C",boxTR:"\u2510",boxBL:"\u2514",boxBR:"\u2518",boxH:"\u2500",boxV:"\u2502"},xo={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function Yn(t,e){let n=e.charset==="ascii"?xo:To,r=t.width,s=t.height,o=Array.from({length:s},()=>Array.from({length:r},()=>" ")),i=Array.from({length:s},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)_o(o,i,n,a);for(let a of t.boxes)wo(o,i,n,a,e.labelOf(a.id));return o.map(a=>Oo(a.join(""))).join(`
|
|
43
|
+
`)}function wo(t,e,n,r,s){let{x:o,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&Un(t,e,o,i,a,s);return}Fe(t,e,o,i,n.boxTL);for(let c=o+1;c<o+a-1;c+=1)Fe(t,e,c,i,n.boxH);Fe(t,e,o+a-1,i,n.boxTR);for(let c=i+1;c<i+d-1;c+=1){Fe(t,e,o,c,n.boxV);for(let p=o+1;p<o+a-1;p+=1)Jn(t,e,p,c," ","empty");Fe(t,e,o+a-1,c,n.boxV)}Fe(t,e,o,i+d-1,n.boxBL);for(let c=o+1;c<o+a-1;c+=1)Fe(t,e,c,i+d-1,n.boxH);Fe(t,e,o+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);Un(t,e,o+1,u,a-2,s)}function Fe(t,e,n,r,s){Jn(t,e,n,r,s,s===" "?"empty":s==="\u2500"||s==="-"?"boxH":s==="\u2502"||s==="|"?"boxV":"boxCorner")}function Jn(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=s,e[r][n]=o)}function Un(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=n,a=s;for(let d of o){let u=kt(d);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=d,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function _o(t,e,n,r){let s=r.points;if(s.length<2)return;for(let d=0;d+1<s.length;d+=1)Eo(t,e,n,s[d],s[d+1]);for(let d=1;d+1<s.length;d+=1){let u=s[d-1],c=s[d],p=s[d+1],f=No(u,c,p,n);f&&Wn(t,e,c.x,c.y,f,"edgeCorner")}let o=s[s.length-1],i=s[s.length-2],a=Ro(i,o,n);a&&Wn(t,e,o.x,o.y,a,"arrow")}function Eo(t,e,n,r,s){if(!(r.x===s.x&&r.y===s.y)){if(r.y===s.y){let o=r.y,i=Math.min(r.x,s.x),a=Math.max(r.x,s.x);for(let d=i;d<=a;d+=1)qn(t,e,d,o,n,"h")}else if(r.x===s.x){let o=r.x,i=Math.min(r.y,s.y),a=Math.max(r.y,s.y);for(let d=i;d<=a;d+=1)qn(t,e,o,d,n,"v")}}}function qn(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=o==="h"?s.horizontal:s.vertical,e[r][n]=o==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&o==="v"){i[n]=s.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&o==="h"){i[n]=s.cross,e[r][n]="edgeCorner";return}}}function Wn(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=s,e[r][n]=o)}function No(t,e,n,r){let s=t.y===e.y,o=e.y===n.y;if(s===o)return;if(s){let d=t.x<e.x,u=n.y>e.y;return d&&u?r.cornerTR:d&&!u?r.cornerBR:!d&&u?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function Ro(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function Oo(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Zn(t){let e=ko(t);So(e),Ao(e),Mo(e),Io(e,t);let n=Go(e,t),{width:r,height:s}=Po(e),o=[];for(let i of e.layers)for(let a of i)a.isVirtual||o.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:o,edges:n,width:r,height:s}}function ko(t){let e=new Map;for(let s of t.nodes)e.set(s,{id:s,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(s),h:t.heightCells(s),in:[],out:[]});let n=[],r=0;for(let s of t.edges){if(s.from===s.to)continue;let o=e.get(s.from),i=e.get(s.to);if(!o||!i)continue;let a={chainId:r++,chainFrom:s.from,chainTo:s.to,fromId:s.from,toId:s.to,hopIndex:0,chainLen:1};o.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function So(t){let e=new Map;for(let o of t.nodes.values())e.set(o.id,o.in.length);let n=[];for(let o of t.nodes.values())(e.get(o.id)??0)===0&&(o.layer=0,n.push(o));let r=new Set,s=0;for(;s<n.length;){let o=n[s++];if(!r.has(o.id)){r.add(o.id);for(let i of o.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,o.layer+1);let d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let o of t.nodes.values())o.layer<0&&(o.layer=0)}function Ao(t){let e=Math.max(0,...Array.from(t.nodes.values(),o=>o.layer)),n=Array.from({length:e+1},()=>[]);for(let o of t.nodes.values())n[o.layer].push(o);let r=[],s=0;for(let o of t.hops){let i=t.nodes.get(o.fromId),a=t.nodes.get(o.toId),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(p=>p!==o),a.in=a.in.filter(p=>p!==o);continue}if(d===1){o.hopIndex=0,o.chainLen=1,r.push(o);continue}i.out=i.out.filter(p=>p!==o),a.in=a.in.filter(p=>p!==o);let u=i;for(let p=1;p<d;p+=1){let f=`__virt_${s++}__`,h={id:f,isVirtual:!0,layer:i.layer+p,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(f,h),n[h.layer].push(h);let l={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:f,hopIndex:p-1,chainLen:d};u.out.push(l),h.in.push(l),r.push(l),u=h}let c={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(c),a.in.push(c),r.push(c)}for(let o of n)for(let i=0;i<o.length;i+=1)o[i].order=i;t.layers=n,t.hops=r}function Mo(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Qn(t,t.layers[r],"in"),St(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Qn(t,t.layers[r],"out"),St(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let s=1;s<t.layers.length;s+=1){let o=t.layers[s];for(let i=0;i+1<o.length;i+=1){let a=Xn(t,o[i],o[i+1],"in");[o[i],o[i+1]]=[o[i+1],o[i]],St(o),Xn(t,o[i],o[i+1],"in")<a?r=!0:([o[i],o[i+1]]=[o[i+1],o[i]],St(o))}}if(!r)break}}function Qn(t,e,n){let r=new Map;for(let s of e){let o=n==="in"?s.in:s.out;if(o.length===0){r.set(s.id,s.order);continue}let i=0,a=0;for(let d of o){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.order,a+=1)}r.set(s.id,a===0?s.order:i/a)}e.sort((s,o)=>{let i=r.get(s.id),a=r.get(o.id);return i!==a?i-a:s.order-o.order})}function St(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Xn(t,e,n,r){let s=r==="in"?e.in:e.out,o=r==="in"?n.in:n.out,i=0;for(let a of s)for(let d of o){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,c=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>c||e.order>n.order&&u<c)&&(i+=1)}return i}function Io(t,e){e.direction==="LR"?Co(t,e):Do(t,e)}function Co(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.w);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.x=n[s];for(let s of t.layers){let o=0;for(let i of s)i.y=o,o+=i.h+e.nodeGap}er(t,e,"y")}function Do(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.h);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.y=n[s];for(let s of t.layers){let o=0;for(let i of s)i.x=o,o+=i.w+e.nodeGap}er(t,e,"x")}function er(t,e,n){let r=o=>n==="y"?o.h:o.w,s=e.nodeGap;for(let o=0;o<2;o+=1){let i=o===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let d=new Map;for(let c of a){let p=o===0?c.in:c.out;if(p.length===0)continue;let f=[];for(let l of p){let m=t.nodes.get(o===0?l.fromId:l.toId);if(!m)continue;let g=n==="y"?m.y:m.x;f.push(g+Math.floor(r(m)/2))}if(f.length===0)continue;f.sort((l,m)=>l-m);let h=f[Math.floor(f.length/2)];d.set(c.id,h-Math.floor(r(c)/2))}let u=0;for(let c of a){let p=d.get(c.id),f=n==="y"?c.y:c.x,l=Math.max(p??f,u);n==="y"?c.y=l:c.x=l,u=l+r(c)+s}}}}function Go(t,e){let n=new Map;for(let u of t.hops){let c=n.get(u.chainId);c?c.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((c,p)=>c.hopIndex-p.hopIndex);let r=e.direction==="LR",s=u=>r?u.x:u.y,o=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let c=t.layers[u],p=t.layers[u+1],f=0;for(let N of c)f=Math.max(f,s(N)+o(N));let h=Number.POSITIVE_INFINITY;for(let N of p)h=Math.min(h,s(N));let l=Number.isFinite(h)?h-1:f,m=Math.max(1,l-f+1),g=[];for(let N of c)for(let R of N.out)g.push(R);g.sort((N,R)=>{let C=i(t.nodes.get(N.fromId)),S=i(t.nodes.get(R.fromId));if(C!==S)return C-S;let D=i(t.nodes.get(N.toId)),M=i(t.nodes.get(R.toId));return D-M});let b=[],v=new Map;for(let N of g){let R=i(t.nodes.get(N.fromId)),C=i(t.nodes.get(N.toId)),S=Math.min(R,C),D=Math.max(R,C),M=-1;for(let B=0;B<b.length;B+=1){let X=b[B],ne=!0;for(let ge of X)if(ge.lo<=D&&S<=ge.hi){ne=!1;break}if(ne){X.push({lo:S,hi:D}),M=B;break}}M<0&&(b.push([{lo:S,hi:D}]),M=b.length-1),v.set(N,M)}let y=b.length,x=m>=Math.max(3,y+2),E=x?f+1:f,T=x?l-1:l,w=Math.max(1,T-E+1);for(let N of g){let R=v.get(N),C;if(y<=1)C=E+Math.floor(w/2);else{let S=(w-1)/(y-1);C=E+Math.floor(R*S)}a.set(N,Math.max(f,Math.min(l,C)))}}let d=[];for(let[,u]of n){let c=[];for(let f=0;f<u.length;f+=1){let h=u[f],l=t.nodes.get(h.fromId),m=t.nodes.get(h.toId),g=a.get(h),b=l.isVirtual?s(l):s(l)+o(l),v=m.isVirtual?s(m):s(m)-1,y=i(l),x=i(m);f===0&&At(c,r,b,y),y!==x&&(At(c,r,g,y),At(c,r,g,x)),At(c,r,v,x)}let p=u[0];d.push({from:p.chainFrom,to:p.chainTo,points:Lo(c)})}return d}function At(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Lo(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function Po(t){let e=0,n=0;for(let r of t.layers)for(let s of r)e=Math.max(e,s.x+s.w),n=Math.max(n,s.y+s.h);return{width:e,height:n}}var $o=24,Fo=4,Vo=1,jo=3;function tr(t,e){let n=zo(e.direction),r=Math.max(3,e.maxLabelWidth??$o),s=e.asciiCharset??"unicode",o=Object.keys(t.nodes).sort(),i=new Set(o),a=t.edges.filter(h=>i.has(h.from)&&i.has(h.to)),d=new Map,u=new Map;for(let h of o){let l=Kn(h,r);d.set(h,l),u.set(h,kt(l)+4)}let c=Zn({nodes:o,edges:a,widthCells:h=>u.get(h)??3,heightCells:()=>jo,layerGap:Fo,nodeGap:Vo,direction:n}),p=Yn(c,{charset:s,labelOf:h=>d.get(h)??h}),f=e.logger;return f&&f(p),p}function zo(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function nr(t,e,n,r={}){let s=e in t.nodes,o=n in t.nodes;if(!s)return Mt(e,n,"no-such-from");if(!o)return Mt(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=Ho(t,e,r);if(u!=null)return u}let d=It(e,t.nodes[e],0,r);return Ct(e,n,[d])}if(i===0)return Mt(e,n,"no-path");let a=rr(t,e,n,i);return a.found?Ct(e,n,or(t,a.pathOrder,r)):Mt(e,n,a.truncated?"max-depth-exceeded":"no-path")}function rr(t,e,n,r){let s=new Map,o=[{path:n,depth:0}],i=new Set([n]),a=0,d=!1;for(;a<o.length;){let p=o[a++];if(p.path===e)break;if(r!=null&&p.depth>=r){let m=t.nodes[p.path];m?.deps&&m.deps.length>0&&(d=!0);continue}let f=t.nodes[p.path];if(f==null)continue;let h=f.deps??[],l=new Map;for(let m=0;m<h.length;m++){let g=h[m];if(!g)continue;let b=l.get(g);b==null&&(b=[],l.set(g,b)),b.push(m)}for(let[m,g]of l)i.has(m)||(i.add(m),s.set(m,{from:p.path,depIndices:g}),o.push({path:m,depth:p.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==n;){let p=s.get(c);if(p==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=p.depIndices,u.push({path:p.from}),c=p.from}return{found:!0,pathOrder:u,truncated:!1}}function Ho(t,e,n){let r=t.nodes[e];if(r==null)return null;let s=r.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=It(e,r,0,n);a.dep_index=o[0];let d=It(e,r,1,n);return Ct(e,e,[a,d])}let i=null;for(let a=0;a<s.length;a++){let d=s[a];if(!d||d===e)continue;let u=rr(t,d,e,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:Ct(e,e,or(t,i.pathOrder,n))}function or(t,e,n){return e.map((r,s)=>{let o=t.nodes[r.path],i=It(r.path,o,s,n);return r.depIndices!=null&&r.depIndices.length>0&&(i.dep_index=r.depIndices[0],r.depIndices.length>1&&(i.dep_indices=[...r.depIndices])),i})}function It(t,e,n,r){let s={path:t,type:e.type,hop:n};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=r.annotations?.get(t)??e.annotation;o!=null&&(s.annotation=o);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function Ct(t,e,n){return sr(t,e,!0,"ok",n)}function Mt(t,e,n){return sr(t,e,!1,n,[])}function sr(t,e,n,r,s){let o=Bo(t,e,n,r,s);return{from:t,to:e,found:n,reason:r,steps:s,text:o,toJSON(){return{from:t,to:e,found:n,reason:r,steps:s}}}}function Bo(t,e,n,r,s){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let o=[`Causal path: ${t} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(d),"value"in i&&o.push(` value: ${Ko(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;o.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return o.join(`
|
|
44
|
+
`)}function Ko(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}Se();var ee={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},Uo=Symbol.for("sizeof");function ir(t){let e=new WeakSet,n=new WeakSet,r=[t],s=0;for(;r.length>0;){let o=r.pop();s+=qo(o,e,n,r)}return s}function qo(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return ee.number;case"boolean":return ee.boolean;case"string":return ee.string+t.length*2;case"bigint":return ee.bigint+Wo(t);case"symbol":return ee.symbol;case"function":return e.has(t)?0:(e.add(t),ee.function);case"undefined":return 0}let o=t;if(e.has(o))return 0;e.add(o);let i=o[Uo];if(typeof i=="function")try{let u=i.call(o);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(o instanceof Date)return ee.date;if(o instanceof RegExp)return ee.regexp+o.source.length*2;if(o instanceof Error){let u=o.message?o.message.length*2:0,c=o.stack?o.stack.length*2:0;return ee.error+u+c}if(typeof URL<"u"&&o instanceof URL)return ee.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return ee.promise;if(o instanceof WeakMap)return ee.weakmap;if(o instanceof WeakSet)return ee.weakset;if(o instanceof Map){let u=ee.map;for(let[c,p]of o)u+=ee.mapEntry,r.push(c),r.push(p);return u}if(o instanceof Set){let u=ee.set;for(let c of o)u+=ee.setEntry,r.push(c);return u}if(Array.isArray(o)){let u=ee.array+o.length*8;for(let c of o)r.push(c);return u}if(o instanceof ArrayBuffer)return n.has(o)?0:(n.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let u=o;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let a=ee.object,d=Object.keys(o);for(let u of d){a+=ee.string+u.length*2;try{r.push(o[u])}catch{}}return a}function Wo(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function Dt(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),s=[],o=t._collectObserveTargets;typeof o=="function"&&o.call(t,"",s);let i=new Map;for(let[f,h]of s)i.set(f,h);let a=[];for(let[f,h]of Object.entries(r.nodes)){let l=i.get(f),m=l instanceof Z?l:null,g=m?ir(m.cache):0,b=m?m._sinkCount:0,v=h.deps?.length??0,y=h.type==="effect"&&b===0,x=b===0?h.type==="effect"?"orphan-effect":h.type==="derived"?"idle-derived":h.type==="producer"?"idle-producer":null:null;a.push({path:f,type:h.type,status:h.status??"unknown",valueSizeBytes:g,subscriberCount:b,depCount:v,isOrphanEffect:y,orphanKind:x})}let d=a.reduce((f,h)=>f+h.valueSizeBytes,0),u=(f,h)=>[...a].sort(h??((l,m)=>m[f]-l[f])).slice(0,n),c=a.filter(f=>f.orphanKind!=null),p=a.filter(f=>f.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:p}}var W="::",me="__meta__",Ue=1;function ar(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let s=t.values().next();if(s.done)return;let o=s.value;t.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Yo(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
|
|
45
|
+
`)}function ur(t){if(t.version!==Ue)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${Ue})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Jo(t,e){let n=new WeakMap,r=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=n.get(s);if(i==null&&(i=new WeakSet,n.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,d=o.constructor;if(a!==d)return!1;if(s instanceof Date)return s.getTime()===o.getTime();if(s instanceof RegExp)return s.source===o.source&&s.flags===o.flags;if(Array.isArray(s)){let f=o;if(s.length!==f.length)return!1;for(let h=0;h<s.length;h++)if(!r(s[h],f[h]))return!1;return!0}if(s instanceof Map){let f=o;if(s.size!==f.size)return!1;for(let[h,l]of s)if(!f.has(h)||!r(l,f.get(h)))return!1;return!0}if(s instanceof Set){let f=o;if(s.size!==f.size)return!1;for(let h of s){let l=!1;for(let m of f)if(r(h,m)){l=!0;break}if(!l)return!1}return!0}if(ArrayBuffer.isView(s)){let f=s,h=o;if(f.length!==h.length)return!1;for(let l=0;l<f.length;l++)if(f[l]!==h[l])return!1;return!0}let u=Object.keys(s),c=Object.keys(o);if(u.length!==c.length)return!1;let p=new Set(c);for(let f of u)if(!p.has(f)||!r(s[f],o[f]))return!1;return!0};return r(t,e)}function ln(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(ln);let e=t,n=Object.keys(e).sort(),r={};for(let s of n)r[s]=ln(e[s]);return r}function Qo(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Xo(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Zo(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function lr(t){let e=new Set,n=[];function r(s,o){let i=`${s}\0${o}`;e.has(i)||(e.add(i),n.push([s,o]))}for(let[s,o]of Object.entries(t.nodes)){let i=o.deps;if(i)for(let a of i)r(a,s)}for(let s of t.edges)r(s.from,s.to);return n}function cr(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function es(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:s,...o}=t,i={...o,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(ln(i),null,e.indent??2);return e.logger?.(a),a}function ts(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,s=[];s.push(`Graph ${t.name}`),s.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];s.push(`- ${i} (${a.type}/${a.status}): ${Lt(a.value)}`)}if(n){s.push("Edges:");for(let i of t.edges)s.push(`- ${i.from} -> ${i.to}`)}if(r){s.push("Subgraphs:");for(let i of t.subgraphs)s.push(`- ${i}`)}let o=s.join(`
|
|
46
|
+
`);return e.logger?.(o),o}function fr(t,e){let n=cr(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`flowchart ${n}`];for(let i of r){let a=s.get(i);o.push(` ${a}["${Qo(i)}"]`)}for(let[i,a]of lr(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(` ${d} --> ${u}`)}return o.join(`
|
|
47
|
+
`)}function ns(t,e){let n=fr(t,e);return pr(n)}function pr(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,o=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(o),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function rs(t,e){let n=cr(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`direction: ${Zo(n)}`];for(let i of r){let a=s.get(i);o.push(`${a}: "${Xo(i)}"`)}for(let[i,a]of lr(t)){let d=s.get(i),u=s.get(a);!d||!u||o.push(`${d} -> ${u}`)}return o.join(`
|
|
48
|
+
`)}function os(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gt(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let s=t.indexOf("]",n+1);if(s<=n+1){e+="\\[";continue}let o=t.slice(n+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,n=s;continue}e+=os(r)}return e+="$",new RegExp(e)}var ss={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},is={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function Lt(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function as(t){return t==="none"?is:t==="ansi"||t==null?ss:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function dr(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function us(t,e,n){for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s<32||s===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function dn(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(W))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${W}' (path separator)`);if(t===me)throw new Error(`Graph "${e}": ${n} name "${me}" is reserved for meta companion paths`);us(t,e,n)}function ds(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(W);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function ls(t,e){let n=!1;for(let s of t)if(!e.isMetaPassthrough(s[0])){n=!0;break}return n?t.filter(s=>e.isMetaPassthrough(s[0])):t}function hr(t){for(let e of t._mounts.values())hr(e);for(let e of t._nodes.values())try{e.down([[fe]],{internal:!0})}catch{}}var oe=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(W))throw new Error(`Graph name must not contain '${W}' (got "${e}")`);if(e===me)throw new Error(`Graph name "${me}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Qe,this._traceRing=new lt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=de(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}add(e,n){let r=e.name,s=n?.name??r;if(s==null||s==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let o=s,i=n?.annotation;if(dn(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:q()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Z&&n._applyVersioning(e)}remove(e){dn(e,this.name,"remove");let n=this._mounts.get(e);if(n){let o={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${W}${me}${W}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...n._collectSubgraphs(`${e}${W}`)),this._mounts.delete(e),n._parent=void 0,hr(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[fe]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let n=typeof e=="function"?e:(()=>{let o=Gt(e);return i=>o.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>n(o));for(let o of s){let i=this.remove(o);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let s=e[r++];return{value:[s,n.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(W))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let s=r?.internal===!0;this.node(e).down([[G,n]],{actor:r?.actor,internal:s,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);ae(()=>{for(let[s,o]of r)this.set(s,o,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[ve]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let s=r?.internal===!0;this.node(e).down([[L,n]],{actor:r?.actor,internal:s,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[$]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof Z)for(let c of u._deps){let p=r.get(c.node);p!=null&&a.push([p,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,d]of s)o.set(d,a);let i=[];for(let[a,d]of s)if(d instanceof Z)for(let u of d._deps){let c=o.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,n){if(dn(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let n=ds(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],s=n.slice(1);if(s.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let o=this._nodes.get(r);if(o&&s.length>0&&s[0]===me)return this._resolveMetaChainFromNode(o,s,n.join(W));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${s.join(W)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(s.join(W))}_resolveMetaChainFromNode(e,n,r){let s=e,o=0,i=[...n];for(;o<i.length;){if(i[o]!==me)throw new Error(`Graph "${this.name}": expected ${me} segment in meta path "${r}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${me} in "${r}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);s=d,o+=2}return s}signal(e,n){if(n?.internal!==!0){for(let s of e)if(this.config.messageTier(s[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,s){for(let d of this._mounts.values())d._signalDeliver(e,n,r,s);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=ls(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(c){if(c instanceof Te)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,s)}}}_signalMetaSubtree(e,n,r,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,s)}catch(d){if(d instanceof Te)throw d;o.push(d)}this._signalMetaSubtree(a,n,r,s,o)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,s=Rt(e?.detail,e?.fields),o=e?.format==="spec",i=o?Rt("minimal"):s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[T,w]of a)d.set(w,T);let u=[];{let T=a.map(([,R])=>R),w=new Set(d.values()),N=0;for(;T.length>0;){let R=T.shift();if(R instanceof Z)for(let C of R._deps){let S=C.node;if(d.has(S))continue;let D=S.name??"",M=D;if(!M||w.has(M))if(D){let B=2;for(;w.has(`${D}#${B}`);)B++;M=`${D}#${B}`}else for(M=`__internal__/${N++}`;w.has(M);)M=`__internal__/${N++}`;d.set(S,M),w.add(M),u.push([M,S]),T.push(S)}}}let c=[...a,...u],p={};for(let[T,w]of c){if(n!=null&&!w.allowsObserve(n))continue;let N=an(w,i),R=w instanceof Z?w._deps.map(M=>d.get(M.node)??M.node.name??""):[],{name:C,...S}=N,D={...S,deps:R};if(!o){let M=this._annotations.get(T);M!=null&&(D.annotation=M)}if(r!=null)if(typeof r=="function"){let M=r;if(!(M.length>=2?M(T,D):M(D)))continue}else{let M=!0;for(let[B,X]of Object.entries(r)){let ne=B==="deps_includes"?"depsIncludes":B==="meta_has"?"metaHas":B;if(ne==="depsIncludes"){if(!D.deps.includes(String(X))){M=!1;break}continue}if(ne==="metaHas"){if(!Object.hasOwn(D.meta??{},String(X))){M=!1;break}continue}if(D[ne]!==X){M=!1;break}}if(!M)continue}p[T]=D}let f=new Set(Object.keys(p)),h=[];for(let[T,w]of c)if(w instanceof Z)for(let N of w._deps){let R=d.get(N.node);R!=null&&h.push([R,T])}h.sort((T,w)=>T[0]<w[0]?-1:T[0]>w[0]?1:T[1]<w[1]?-1:T[1]>w[1]?1:0);let l=h.map(([T,w])=>({from:T,to:w}));(n!=null||r!=null)&&(l=l.filter(T=>f.has(T.from)&&f.has(T.to)));let m=this._collectSubgraphs(""),g=n!=null||r!=null?m.filter(T=>{let w=`${T}${W}`;return[...f].some(N=>N===T||N.startsWith(w))}):m,b=this,v=e,y={name:this.name,nodes:p,edges:l,subgraphs:g,expand(T){let w={...v,format:void 0};return Array.isArray(T)?(w.fields=T,w.detail=void 0):(w.detail=T,w.fields=void 0),b.describe(w)}},x=e??{},E=x.format;return E==="json"?es(y,x):E==="pretty"?ts(y,x):E==="mermaid"?fr(y,x):E==="mermaid-url"?ns(y,x):E==="d2"?rs(y,x):E==="ascii"?tr(y,x):y}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${r}`;n.push(s),n.push(...this._mounts.get(r)._collectSubgraphs(`${s}${W}`))}return n}resourceProfile(e){return Dt(this,e)}reachable(e,n,r={}){return r.withDetail===!0?cn(this.describe(),e,n,{...r,withDetail:!0}):cn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(s.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return nr(s,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",s=0,o=P(s,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,st(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(g=>{let b=g.type;b!=="data"&&b!=="error"&&b!=="complete"&&b!=="teardown"||u()}),p=[],f=new WeakSet,h=g=>{if(f.has(g)||d)return;f.add(g);let b=g.topology.subscribe(v=>{for(let y of v){if(y[0]!==G)continue;let x=y[1];if(u(),x.kind==="added"&&x.nodeKind==="mount"){let E=g._mounts.get(x.name);E!=null&&h(E)}}});p.push(b);for(let v of g._mounts.keys()){let y=g._mounts.get(v);y!=null&&h(y)}};h(this);let l;try{l=I([o],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(g,b)=>g===b})}catch(g){c();for(let b of p)b();throw i.dispose(),g}let m=xe(l);return{node:l,dispose(){d=!0,c();for(let g of p)g();p.length=0,i.dispose(),m()}}}_explainReactive(e,n,r){let s=0,o=P(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=i.onEvent(h=>{let l=h.type;l!=="data"&&l!=="error"&&l!=="complete"&&l!=="teardown"||a||d||(a=!0,st(()=>{a=!1,!d&&(s+=1,o.emit(s))}))}),c={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},p;try{p=I([o],()=>this._explainStatic(e,n,c),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(h,l)=>h.found===l.found&&h.reason===l.reason&&h.steps.length===l.steps.length&&cs(h.steps,l.steps)})}catch(h){throw u(),i.dispose(),h}let f=xe(p);return{node:p,dispose(){d=!0,u(),i.dispose(),f()}}}_pathsMatching(e){let n=Gt(e),r=[];return this._collectObserveTargets("",r),r.map(([s])=>s).filter(s=>n.test(s))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${W}${r}`;this._mounts.get(r)._collectObserveTargets(s,n)}for(let r of[...this._nodes.keys()].sort()){let s=this._nodes.get(r),o=e===""?r:`${e}${W}${r}`;n.push([o,s]),this._appendMetaObserveTargets(o,s,n)}}_appendMetaObserveTargets(e,n,r){for(let s of Object.keys(n.meta).sort()){let o=n.meta[s],i=`${e}${W}${me}${W}${s}`;r.push([i,o]),this._appendMetaObserveTargets(i,o,r)}}observe(e,n){let r=typeof e=="string",o=dr(r?n:e),i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(r){let c=e,p=this.resolve(c);if(a!=null&&!p.allowsObserve(a))throw new Te({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,p]],o,"one"):{subscribe(f){return p.subscribe(f)},up(f){try{p.up?.(f)}catch(h){if(h instanceof Te)return;throw h}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:c=>{let p=u.map(([f,h])=>h.subscribe(l=>{c(f,l)}));return()=>{for(let f of p)f()}},up:(c,p)=>{try{this.resolve(c).up?.(p)}catch(f){if(f instanceof Te)return;throw f}}}}_buildStructuredObserver(e,n,r){let s=r==="one"?e[0]?.[0]:void 0,o=i=>{if(r==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,o)}_createObserveResult(e,n,r){let s=n.timeline===!0,o=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,c=n.maxEvents,p=c!=null&&c>0?new lt(c):null,f=[],h=new Set,l={},m=new Set,g=0,b=0,v=0,y=0,x=0,E=0,T=!1,w=!1,N=0,R=new Map,C=new Map,S=new Map,D=k=>{p?p.push(k):f.push(k);for(let H of h)H(k)},M=()=>s?{timestamp_ns:q(),in_batch:ot(),batch_id:N}:{},B=(k,H)=>{if(!(!u||!(k instanceof Z)))return k._setInspectorHook(se=>{if(se.kind==="dep_message")R.set(k,se.depIndex);else if(se.kind==="run"){let Oe=se.batchData.map((j,te)=>j!=null&&j.length>0?j.at(-1):se.prevData[te]);C.set(k,Oe);let ie=se.batchData.map(j=>j!=null?[...j]:void 0);S.set(k,ie),i&&D({type:"derived",path:H,dep_values:Oe,dep_batches:ie,...M()})}})},X=k=>{let H=R.get(k),se=C.get(k);if(!o||se==null)return{};let ie=(H!=null&&H>=0&&k instanceof Z?k._deps[H]:void 0)?.node,j=ie?.v,te=S.get(k);return{trigger_dep_index:H,trigger_dep_name:ie?.name,...j!=null?{trigger_version:{id:j.id,version:j.version}}:{},dep_values:[...se],...te!=null?{dep_batches:te}:{}}},ne=[],ge=[];for(let[k,H]of e){let se=B(H,k);se&&ne.push(se),ge.push(H.subscribe(Oe=>{N++;for(let ie of Oe){let j=ie[0],te=M();if(j===G){l[k]=ie[1];let A=H instanceof Z?H.lastMutation?.actor??We:We;D({type:"data",path:k,data:ie[1],actor:A,...te,...X(H)})}else if(a)j===Y?g++:j===Q?b++:j===ve?v++:j===_e?y++:j===Ie?x++:j===fe?E++:j===$&&!m.has(k)?T=!0:j===L&&(w=!0,m.add(k));else if(j===Y)g++,D({type:"dirty",path:k,...te});else if(j===Q)b++,D({type:"resolved",path:k,...te,...X(H)});else if(j===ve)v++,D({type:"invalidate",path:k,...te});else if(j===_e)y++,D({type:"pause",path:k,lockId:ie[1],...te});else if(j===Ie)x++,D({type:"resume",path:k,lockId:ie[1],...te});else if(j===$)m.has(k)||(T=!0),D({type:"complete",path:k,...te});else if(j===L){w=!0,m.add(k);let A=H instanceof Z?H.lastMutation?.actor??We:We;D({type:"error",path:k,data:ie[1],actor:A,...te})}else j===fe&&(E++,D({type:"teardown",path:k,...te}))}}))}let Ee=!1,Ae=()=>{if(!Ee){Ee=!0;for(let k of ge)k();for(let k of ne)k();for(let k of Re)k({value:void 0,done:!0});Re.length=0}},Ne=[],Re=[];h.add(k=>{let H=Re.shift();H?H({value:k,done:!1}):Ne.push(k)});let Ge={get values(){return l},get dirtyCount(){return g},get resolvedCount(){return b},get invalidateCount(){return v},get pauseCount(){return y},get resumeCount(){return x},get teardownCount(){return E},get events(){return p?p.toArray():[...f]},get anyCompletedCleanly(){return T},get anyErrored(){return w},get completedWithoutErrors(){return T&&!w},onEvent(k){return h.add(k),()=>h.delete(k)},dispose:Ae,expand(k){Ae();let H={...n};return typeof k=="string"?H.detail=k:Object.assign(H,k),r(dr(H))},[Symbol.asyncIterator](){return{next(){return Ne.length>0?Promise.resolve({value:Ne.shift(),done:!1}):Ee?Promise.resolve({value:void 0,done:!0}):new Promise(k=>Re.push(k))},return(){return Ae(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(Ge,n),Ge}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let s=n.logger??(l=>console.log(l)),o=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=o==null&&i==null?()=>!0:l=>(o==null||o.has(l))&&(i==null||!i.has(l)),d=as(n.theme),u=r==="stage-log"?q():0,c=l=>l==null?"":n.stageLabels?.[l]??l,p=(l,m)=>l.length>m?`${l.slice(0,m-1)}\u2026`:l,f=l=>l.type==="data"||l.type==="error"?p(Lt(l.data),120):"",h=l=>{if(r==="stage-log"){let w=(q()-u)/1e9,N=c(l.path).padEnd(9);if(l.type==="data"){let R=f(l);return`[${w.toFixed(3)}s] ${N} \u2190${R?` ${R}`:""}`}if(l.type==="error"){let R=f(l);return`[${w.toFixed(3)}s] ${N} \u2717${R?` ${R}`:""}`}return l.type==="complete"?`[${w.toFixed(3)}s] ${N} \u25A0 complete`:`[${w.toFixed(3)}s] ${N} ${l.type}`}if(r==="json")try{return JSON.stringify(l)}catch{return JSON.stringify({type:l.type,path:l.path,data:"[unserializable]"})}let m=d[l.type]??"",g=l.path?`${d.path}${l.path}${d.reset} `:"",b=l.type==="data"||l.type==="error",v=l.type==="pause"||l.type==="resume",y=b?` ${Lt(l.data)}`:v?` ${Lt(l.lockId)}`:"",x=l.type==="data"||l.type==="resolved"||l.type==="derived"?l:void 0,E=x?.trigger_dep_name!=null?` <- ${x.trigger_dep_name}`:x?.trigger_dep_index!=null?` <- #${x.trigger_dep_index}`:"",T=l.in_batch?" [batch]":"";return`${g}${m}${l.type.toUpperCase()}${d.reset}${y}${E}${T}`};e.onEvent(l=>{a(l.type)&&s(h(l),l)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){ar(this._disposers,this.name),this.signal([[fe]],{internal:!0}),ar(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),s={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...c}=r.nodes[a];s[a]=c}let o=[...r.subgraphs].sort(),i={...r,version:1,nodes:s,subgraphs:o};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Sn(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Qe,{codec:s,codecVersion:o,payload:i}=An(e,r);return s.decode(i,o)}restore(e,n){if(ur(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(o=>Gt(o)),s=n?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let d=this.tryResolve(o)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){n?.onError?.(o,a)}}}}}static fromSnapshot(e,n){ur(e);let r=typeof n=="function"?n:n?.build,s=typeof n=="function"?void 0:n?.factories,o=new t(e.name);if(r)return r(o),o.restore(e),o;for(let h of[...e.subgraphs].sort((l,m)=>{let g=l.split(W).length,b=m.split(W).length;return g!==b?g-b:l<m?-1:l>m?1:0})){let l=h.split(W),m=o;for(let g of l)m._mounts.has(g)||m.mount(g,new t(g)),m=m._mounts.get(g)}let i=s?Object.entries(s).map(([h,l])=>({re:Gt(h),factory:l})):[],a=h=>{for(let l of i)if(l.re.test(h))return l.factory},d=h=>{let l=h.split(W),m=l.pop();if(m==null||m.length===0)throw new Error(`invalid snapshot path "${h}"`);let g=o;for(let b of l){let v=g._mounts.get(b);if(!v)throw new Error(`unknown mount "${b}" in path "${h}"`);g=v}return[g,m]},u=Object.entries(e.nodes).filter(([h])=>!h.includes(`${W}${me}${W}`)).sort((h,l)=>h[0]<l[0]?-1:h[0]>l[0]?1:0),c=new Map(u),p=new Map,f=!0;for(;c.size>0&&f;){f=!1;for(let[h,l]of[...c.entries()]){let m=l?.deps??[];if(!m.every(E=>p.has(E)))continue;let[g,b]=d(h),v={...l?.meta??{}},y=a(h),x;if(l?.type==="state")x=P(l.value,{meta:v});else{if(y==null)continue;x=y(b,{path:h,type:l.type,value:l.value,meta:v,deps:m,resolvedDeps:m.map(E=>p.get(E))})}g.add(x,{name:b}),p.set(h,x),c.delete(h),f=!0}}if(c.size>0){let h=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${h}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let s=(u,c)=>{if(u.disposed)return;let p=Yo(c.nodes);if(u.lastSnapshot!=null&&p!==""&&p===u.lastFingerprint)return;let f=u.seq+1,h=Tt(),g=u.lastSnapshot==null||f%u.compactEvery===0?{mode:"full",snapshot:c,seq:f,timestamp_ns:h,format_version:Ue}:{mode:"diff",diff:mr(u.lastSnapshot,c),seq:f,timestamp_ns:h,format_version:Ue};if(u.tier.filter&&!u.tier.filter(this.name,g))return;let b;try{b=u.tier.save(this.name,g)}catch(v){n.onError?.(v,u.tier);return}if(b&&typeof b.then=="function"){let x=(u.savePending??Promise.resolve()).then(()=>b,()=>b).then(()=>{u.disposed||(u.seq=f,u.lastSnapshot=c,u.lastFingerprint=p)},E=>{n.onError?.(E,u.tier)});u.savePending=x.finally(()=>{u.savePending===x&&(u.savePending=void 0)})}else u.seq=f,u.lastSnapshot=c,u.lastFingerprint=p},o=(u,c)=>{try{s(u,c)}catch(p){n.onError?.(p,u.tier)}},i=(u,c)=>{if(!c.some(l=>{let m=this.config.messageTier(l[0]);return m>=3&&m<5}))return;if(n.filter){let l=this.tryResolve(u);if(l==null)return;let m=an(l,Rt("standard"));if(!n.filter(u,m))return}let f,h=()=>(f==null&&(f=this.snapshot()),f);for(let l of r)l.disposed||(l.debounceMs===0?o(l,h()):(l.timer==null&&(l.timer=new Ot),l.timer.start(l.debounceMs,()=>{l.disposed||o(l,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(p=>{let f=this.tryResolve(p);return f==null?()=>{}:f.subscribe(h=>i(p,h))});a=()=>{for(let p of c)p()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let s;try{s=await r.load(this.name)}catch(i){n?.(i,r);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===Ue&&o.nodes!=null)return this.restore(o),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let s of n){let o;try{o=await s.load(e)}catch(d){r?.onError?.(d,s);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===Ue&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let s={path:e,annotation:n,timestamp_ns:q(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(s)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(s=>!e(s)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let s of n)this._traceRing.push(s);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(n.nodes)),o=[...s].filter(v=>!r.has(v)).sort(),i=[...r].filter(v=>!s.has(v)).sort(),a=[],d=[];for(let v of r){if(!s.has(v))continue;let y=e.nodes[v],x=n.nodes[v],E=y.v,T=x.v;E!=null&&T!=null&&E.id===T.id&&E.version!==T.version&&d.push({path:v,id:E.id,from:E.version,to:T.version});let w=E!=null&&T!=null&&E.id===T.id&&E.version===T.version;for(let N of["type","status","sentinel"]){let R=y[N],C=x[N];R!==C&&a.push({path:v,field:N,from:R,to:C})}if(!w)for(let N of["value","meta"]){let R=y[N],C=x[N];Jo(R,C)||a.push({path:v,field:N,from:R,to:C})}}let u=v=>`${v.from} ${v.to}`,c=new Set(e.edges.map(u)),p=new Set(n.edges.map(u)),f=n.edges.filter(v=>!c.has(u(v))),h=e.edges.filter(v=>!p.has(u(v))),l=new Set(e.subgraphs),m=new Set(n.subgraphs),g=[...m].filter(v=>!l.has(v)).sort(),b=[...l].filter(v=>!m.has(v)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:f,edgesRemoved:h,subgraphsAdded:g,subgraphsRemoved:b}}};function mr(t,e){let n=oe.diff(t,e),r={};for(let s of n.nodesAdded){let o=e.nodes[s];o!=null&&(r[s]=o)}return{...n,nodesAddedFull:r}}function cn(t,e,n,r={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?s:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=r.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return r.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[y,x]of Object.entries(t.nodes)){if(!y)continue;c.add(y);let E=x.deps??[];i.set(y,E);for(let T of E)T&&(c.add(T),a.has(T)||a.set(T,new Set),a.get(T).add(y))}for(let y of t.edges){if(y==null||typeof y!="object")continue;let x=typeof y.from=="string"?y.from:"",E=typeof y.to=="string"?y.to:"";!x||!E||(c.add(x),c.add(E),u.has(x)||u.set(x,new Set),u.get(x).add(E),d.has(E)||d.set(E,new Set),d.get(E).add(x))}if(!c.has(e))return r.withDetail?s:[];let p=r.both===!0,f=y=>{if(p){let w=i.get(y)??[],N=d.get(y),R=a.get(y),C=u.get(y),S=[...w];return N&&S.push(...N),R&&S.push(...R),C&&S.push(...C),S}if(n==="upstream"){let w=i.get(y)??[],N=d.get(y);return N?[...w,...N]:w}let x=a.get(y),E=u.get(y),T=x?[...x]:[];return E&&T.push(...E),T},h=new Set([e]),l=new Map,m=[{path:e,depth:0}],g=0,b=!1;for(;g<m.length;){let y=m[g++];if(o!=null&&y.depth>=o){f(y.path).length>0&&(b=!0);continue}for(let x of f(y.path))!x||h.has(x)||(h.add(x),l.set(x,y.depth+1),m.push({path:x,depth:y.depth+1}))}let v=[...l.keys()].sort((y,x)=>y<x?-1:y>x?1:0);return r.withDetail?{paths:v,depths:l,truncated:b}:v}function cs(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],s=e[n];if(r.path!==s.path||r.type!==s.type||r.status!==s.status||r.hop!==s.hop||r.dep_index!==s.dep_index||r.annotation!==s.annotation||r.value!==s.value||r.lastMutation!==s.lastMutation)return!1;let o=r.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}vt();Ce();at();le();re();Se();Ce();le();re();var fn=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),s=Math.min(e,this._size);if(s>=r)return[];let o=r-s;if(this._maxSize===void 0)return this._buf.slice(s,r);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function gr(t){return t.subscribe(()=>{})}var fs=64;function br(t,e={}){let{name:n,maxSize:r,versioning:s,backend:o}=e,i=o??new fn(t,r),a=P(i.toArray(),{name:n,describeKind:"state",equals:(l,m)=>l===m,...s!=null?{versioning:s}:{}});function d(){let l=i.toArray();ae(()=>{a.down([[Y]]),a.down([[G,l]])})}let u=new Map,c=new Map;function p(l,m){return`${l}:${m===void 0?"END":m}`}function f(l){if(l.size<fs)return;let m=l.keys().next();if(m.done)return;let g=l.get(m.value);g!==void 0&&g.dispose(),l.delete(m.value)}function h(l){let m=i.version;try{return l()}finally{i.version!==m&&d()}}return{entries:a,get size(){return i.size},at(l){return i.at(l)},append(l){h(()=>i.append(l))},appendMany(l){l.length!==0&&h(()=>i.appendMany(l))},clear(){h(()=>i.clear())},trimHead(l){h(()=>i.trimHead(l))},tail(l){if(!Number.isInteger(l)||l<0)throw new RangeError(`tail: n must be a non-negative integer (got ${l})`);let m=u.get(l);if(m!==void 0)return u.delete(l),u.set(l,m),m.node;f(u);let g=I([a],([v])=>{let y=v;return l===0||y.length===0?[]:y.slice(Math.max(0,y.length-l))},{initial:i.tail(l),describeKind:"derived"}),b=gr(g);return u.set(l,{node:g,dispose:b}),g},slice(l,m){if(!Number.isInteger(l)||l<0)throw new RangeError(`slice: start must be a non-negative integer (got ${l})`);if(m!==void 0&&(!Number.isInteger(m)||m<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${m})`);let g=p(l,m),b=c.get(g);if(b!==void 0)return c.delete(g),c.set(g,b),b.node;f(c);let v=I([a],([x])=>{let E=x;return m===void 0?E.slice(l):E.slice(l,m)},{initial:i.slice(l,m),describeKind:"derived"}),y=gr(v);return c.set(g,{node:v,dispose:y}),v},disposeTail(l){let m=u.get(l);return m===void 0?!1:(m.dispose(),u.delete(l),!0)},disposeSlice(l,m){let g=p(l,m),b=c.get(g);return b===void 0?!1:(b.dispose(),c.delete(g),!0)},disposeAllViews(){for(let l of u.values())l.dispose();u.clear();for(let l of c.values())l.dispose();c.clear()},dispose(){for(let l of u.values())l.dispose();u.clear();for(let l of c.values())l.dispose();c.clear()}}}le();Ke();function pn(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[Y],[G,n+1]]),!0)}function Ve(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function ct(t){return t.relatedTo?.[0]??t.summary}var ps=2147483647;function Pt(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function qe(t,e){return Ve("messaging",t,e)}var hn=class extends oe{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=br([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=I([this.events],([r])=>{let s=r;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:qe("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(xe(this.latest)),this.hasLatest=I([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:qe("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(xe(this.hasLatest)),this.addDisposer(()=>{this.events.down([[$]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}},$t=class extends oe{source;cursor;available;topic;constructor(e,n,r={}){super(e,r.graph);let s=Pt(r.cursor??0,"subscription cursor");this.topic=n;let o=n.events;this.source=I([o],([i])=>i,{name:"source",describeKind:"derived",meta:qe("subscription_source"),initial:o.cache}),this.add(this.source,{name:"source"}),this.cursor=P(s,{name:"cursor",describeKind:"state",meta:qe("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=I([this.source,this.cursor],([i,a])=>{let d=i,u=Math.max(0,Math.trunc(a??0));return d.slice(u)},{name:"available",describeKind:"derived",meta:qe("subscription_available"),initial:[]}),this.add(this.available,{name:"available"}),this.addDisposer(xe(this.source)),this.addDisposer(xe(this.available))}ack(e){let n=this.available.cache,r=e===void 0?n.length:Pt(e,"subscription ack count"),s=Math.min(r,n.length);if(s<=0)return this.cursor.cache;let o=this.cursor.cache+s;return this.cursor.emit(o),o}pull(e,n={}){let r=this.available.cache,s=e===void 0?r.length:Pt(e,"subscription pull limit"),o=r.slice(0,s);return n.ack&&o.length>0&&this.ack(o.length),o}},mn=class extends oe{_sourceSub;_target;bridgedCount;constructor(e,n,r,s={}){super(e,s.graph),this._sourceSub=hs(`${e}-subscription`,n,{cursor:s.cursor}),this._target=r,this.mount("subscription",this._sourceSub),this.bridgedCount=P(0,{name:"bridgedCount",describeKind:"state",meta:qe("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"});let o=Math.max(1,Pt(s.maxPerPump??ps,"topic bridge maxPerPump")),i=s.map??(d=>d),a=ue([this._sourceSub.available],()=>{let d=this._sourceSub.pull(o,{ack:!0});if(d.length===0)return;let u=0;for(let c of d){let p=i(c);p!==void 0&&(this._target.publish(p),u+=1)}if(u>0){let c=this.bridgedCount.cache;this.bridgedCount.emit(c+u)}},{name:"pump",describeKind:"effect",meta:qe("topic_bridge_pump")});this.add(a,{name:"pump"}),this.addDisposer(xe(a))}},gn=class extends oe{_topics=new Map;_version=0;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get version(){return this._version}get size(){return this._topics.size}has(e){return this._topics.has(e)}topicNames(){return this._topics.keys()}topic(e,n){let r=this._topics.get(e);if(r===void 0){let s={...this._defaultTopicOptions,...n??{}};r=new hn(e,s),this._topics.set(e,r),this.mount(e,r),this._version+=1}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){ae(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let s=this.topic(n);return new $t(e,s,r)}removeTopic(e){if(!this._topics.has(e))return!1;try{this.remove(e)}finally{this._topics.delete(e),this._version+=1}return!0}};function Ft(t,e){return new gn(t,e)}function hs(t,e,n){return new $t(t,e,n)}function bn(t,e,n,r){return new mn(t,e,n,r)}function ms(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function gs(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let o=bs(e);return{best:t[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(t.length);for(let d=0;d<t.length;d++)o[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<t.length&&(o[u].sum+=d.score,o[u].count+=1)}let i=t[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<t.length;d++){let u=o[d].count>0?o[d].sum/o[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=t[d])}return{best:i,bestScore:a}}let r=t[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<t.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,r=t[o])}return{best:r,bestScore:s}}function bs(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function yr(t,e,n,r){let s=r.name??"refine-loop",o=new oe(s,r.graph),i=ms(r.dataset)?r.dataset:P(r.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=P(0,{name:"iteration"});o.add(a,{name:"iteration"});let d=P(n,{name:"strategy",equals:()=>!1});o.add(d,{name:"strategy"});let u=P(null,{name:"lastFeedback"});o.add(u,{name:"lastFeedback"});let c=P([],{name:"prevCandidates"});o.add(c,{name:"prevCandidates"});let p=P(!1,{name:"paused"});o.add(p,{name:"paused"});let f=P("running",{name:"status"});o.add(f,{name:"status"});let h=P([],{name:"history",equals:()=>!1});o.add(h,{name:"history"});let l=P(null,{name:"best"});o.add(l,{name:"best"});let m=P(Number.NEGATIVE_INFINITY,{name:"score"});o.add(m,{name:"score"});let g=P(0,{name:"budget-used"});o.add(g,{name:"budget-used"});let b=Ft("stages");o.mount("stages",b);let v=b.topic("generate"),y=b.topic("evaluate"),x=b.topic("analyze"),E=b.topic("decide"),T=n,w=null,N=[];o.addDisposer(d.subscribe(A=>{for(let V of A)V[0]===G&&(T=V[1])})),o.addDisposer(u.subscribe(A=>{for(let V of A)V[0]===G&&(w=V[1])})),o.addDisposer(c.subscribe(A=>{for(let V of A)V[0]===G&&(N=V[1])}));let R=we(a,A=>{let V=T,J=A===0||w==null;return ue([],(F,_)=>{let O=!1;try{let z=J?V.seed(t):V.generate(w,N);if(z instanceof Promise)return z.then(K=>{O||_.emit(K)},K=>{O||_.down([[L,K]])}),()=>{O=!0};_.emit(z)}catch(z){O=!0,_.down([[L,z]])}},{describeKind:"producer"})},{name:"candidates"});o.add(R,{name:"candidates"});let C=ce([R],(A,V,J)=>{let F=J.terminalDeps[0];F!==void 0&&F!==!0&&f.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(C,{name:"error-watcher"}),o.addDisposer(C.subscribe(()=>{}));let S=I([R,a],([A,V])=>({iteration:V,candidates:A,timestamp_ns:q()}),{name:"generate-event"});o.add(S,{name:"generate-event"}),o.addDisposer(S.subscribe(()=>{}));let D=ce([S],([A])=>{v.publish(A)},{name:"generate-publish"});o.add(D,{name:"generate-publish"}),o.addDisposer(D.subscribe(()=>{}));let M=ce([R],([A])=>{c.emit(A)},{name:"generate-mirror"});o.add(M,{name:"generate-mirror"}),o.addDisposer(M.subscribe(()=>{}));let B=e(R,i);o.add(B,{name:"scores"});let X=I([B,R,a],([A,V,J])=>({iteration:J,candidates:V,scores:A,timestamp_ns:q()}),{name:"evaluate-event"});o.add(X,{name:"evaluate-event"}),o.addDisposer(X.subscribe(()=>{}));let ne=ce([X],([A])=>{y.publish(A)},{name:"evaluate-publish"});o.add(ne,{name:"evaluate-publish"}),o.addDisposer(ne.subscribe(()=>{}));let ge=I([B,R],([A,V])=>T.analyze(A,V),{name:"feedback"});o.add(ge,{name:"feedback"});let Ee=I([ge,R,a],([A,V,J])=>({iteration:J,candidates:V,feedback:A,timestamp_ns:q()}),{name:"analyze-event"});o.add(Ee,{name:"analyze-event"}),o.addDisposer(Ee.subscribe(()=>{}));let Ae=ce([Ee],([A])=>{x.publish(A)},{name:"analyze-publish"});o.add(Ae,{name:"analyze-publish"}),o.addDisposer(Ae.subscribe(()=>{}));let Ne=I([h],([A])=>{let V=A;if(r.patience==null||V.length<=r.patience)return!1;let J=V.slice(-(r.patience+1)),F=J[0].bestScore;return J.slice(1).every(_=>_.bestScore<=F)},{name:"patience-check"});o.add(Ne,{name:"patience-check"});let Re=I([m],([A])=>r.minScore!=null&&A>=r.minScore,{name:"min-score-check"});o.add(Re,{name:"min-score-check"});let Ge=I([h],([A])=>{let V=A;if(r.minDelta==null||V.length<2)return!1;let J=V[V.length-2].bestScore,F=V[V.length-1].bestScore;return Math.abs(F-J)<r.minDelta},{name:"min-delta-check"});o.add(Ge,{name:"min-delta-check"});let k=I([g],([A])=>r.maxEvaluations!=null&&A>=r.maxEvaluations,{name:"max-evaluations-check"});o.add(k,{name:"max-evaluations-check"});let H=I([a],([A])=>r.maxIterations!=null&&A>=r.maxIterations,{name:"max-iterations-check"});o.add(H,{name:"max-iterations-check"});let se=I([g],([A])=>r.budget!=null&&A>=r.budget,{name:"budget-exhausted-check"});o.add(se,{name:"budget-exhausted-check"}),o.addDisposer(Ne.subscribe(()=>{})),o.addDisposer(Re.subscribe(()=>{})),o.addDisposer(Ge.subscribe(()=>{})),o.addDisposer(k.subscribe(()=>{})),o.addDisposer(H.subscribe(()=>{})),o.addDisposer(se.subscribe(()=>{}));let Oe=I([Ne,Re,Ge,k,H],([A,V,J,F,_])=>A?{converged:!0,reason:"patience"}:V?{converged:!0,reason:"min-score"}:J?{converged:!0,reason:"min-delta"}:F?{converged:!0,reason:"max-evaluations"}:_?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(Oe,{name:"converged"}),o.addDisposer(Oe.subscribe(()=>{}));let ie=-1,j=ce([ge,B,R],([A,V,J])=>{let F=a.cache,_=A,O=J,z=V;if(F<=ie)return;ie=F;let{best:K,bestScore:ke}=gs(O,z),tt=h.cache,je={n:F,candidates:O,scores:z,feedback:_,best:K,bestScore:ke,timestamp_ns:q()},U=[...tt,je],be=g.cache+O.length,pe="continue",Me,_n=r.budget!=null&&be>=r.budget,En=p.cache;if(_n)pe="budget",Me="budget";else if(r.minScore!=null&&_.score>=r.minScore)pe="converged",Me="min-score";else if(r.maxIterations!=null&&F>=r.maxIterations)pe="converged",Me="max-iterations";else if(r.maxEvaluations!=null&&be>=r.maxEvaluations)pe="converged",Me="max-evaluations";else if(r.minDelta!=null&&U.length>=2){let pt=U[U.length-2].bestScore,Ht=U[U.length-1].bestScore;Math.abs(Ht-pt)<r.minDelta&&(pe="converged",Me="min-delta")}else if(r.patience!=null&&U.length>r.patience){let pt=U.slice(-(r.patience+1)),Ht=pt[0].bestScore;pt.slice(1).every(Dr=>Dr.bestScore<=Ht)&&(pe="converged",Me="patience")}pe==="continue"&&En&&(pe="paused"),ae(()=>{l.emit(K),m.emit(_.score),h.emit(U),g.emit(be),u.emit(_),E.publish({iteration:F,decision:pe,reason:Me,timestamp_ns:q()}),pe==="continue"?a.emit(F+1):f.emit(pe==="converged"?"converged":pe==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(j,{name:"decide-bridge"}),o.addDisposer(j.subscribe(()=>{})),Object.assign(o,{best:l,score:m,status:f,history:h,strategy:d,iteration:a,generate:v,evaluate:y,analyze:x,decide:E,setStrategy(A){d.emit(A)},pause(){p.emit(!0)},resume(){f.cache==="paused"&&ae(()=>{p.emit(!1),f.emit("running"),a.emit(a.cache+1)})}})}function ys(t){let{best:e,score:n,status:r}=t,s=Number.isFinite(n)?n.toFixed(3):String(n),o=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${s}`,artifact:o}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${s}`,artifact:o}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:o}}function yn(t){let e=t.name??"refine-executor",n=t.toOutput??ys;return r=>{let s=De(r,i=>i!=null,{name:`${e}/gate-in`}),o=we(s,i=>{let a=yr(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return I([a.status,a.best,a.score],([d,u,c])=>{let p=d;return p!=="converged"&&p!=="budget"&&p!=="errored"?null:n({best:u,score:c,status:p})},{name:`${e}/output`})},{name:e});return De(o,i=>i!=null,{name:`${e}/gate-out`})}}function vs(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Ts(t){let{passCount:e,total:n,meanScore:r,threshold:s,missingArtifact:o}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!o&&n>0&&r>=s,d=o?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${s}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${s}`];return a?{verified:!0,findings:d}:{verified:!1,findings:d,errorClass:"structural"}}function xs(t){return t.artifact??null}function vr(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Ts,s=t.extractArtifact??xs;return o=>{let i=De(o,d=>d!=null&&d[0]!=null&&d[1]!=null,{name:`${e}/gate-in`}),a=we(i,d=>{let[u,c]=d,p=s(u,c);if(p==null)return P(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let f=P([p],{name:`${e}/candidates`}),h=P(t.datasetFor(c),{name:`${e}/dataset`}),l=t.evaluator(f,h);return I([l],([m])=>{let g=m;if(g==null)return null;let b=vs(g),v=g.filter(y=>y.score>=n).length;return r({scores:g,meanScore:b,passCount:v,total:g.length,threshold:n})},{name:`${e}/output`})},{name:e});return De(a,d=>d!=null,{name:`${e}/gate-out`})}}function ws(t){let e=t.name??"harness-pair",n=yn({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=vr({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Pe();Se();re();Ce();Pe();le();re();var vn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let s=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),s=0;try{for(let[o,i]of e)this._store.has(o)&&this._store.delete(o),this._store.set(o,{value:i,expiresAt:r}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=q(),n=0;for(let[r,s]of this._store)this._isExpired(s,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=q(),n=new Map;for(let[r,s]of this._store)this._isExpired(s,e)||n.set(r,s.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return q()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??q())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function Vt(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:s,backend:o,retention:i}=t;if(i&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=o??new vn({maxSize:n,defaultTtl:r}),d=P(a.toMap(),{name:e,describeKind:"state",equals:(f,h)=>f===h,...s!=null?{versioning:s}:{}});function u(){let f=a.toMap();ae(()=>{d.down([[Y]]),d.down([[G,f]])})}function c(){if(!i)return;let f=a.toMap(),h=i.archiveThreshold,l=i.maxSize,m=[];for(let[b,v]of f)m.push({key:b,value:v,score:i.score(b,v)});m.sort((b,v)=>b.score-v.score);let g=new Set;if(h!==void 0)for(let b of m)if(b.score<h)g.add(b.key);else break;if(l!==void 0&&m.length-g.size>l)for(let b of m){if(m.length-g.size<=l)break;g.has(b.key)||g.add(b.key)}if(g.size!==0)for(let b of m)g.has(b.key)&&(i.onArchive?.(b.key,b.value,b.score),a.delete(b.key))}function p(f,h="mutation"){let l=a.version;try{return f()}finally{a.version!==l&&(h==="mutation"&&c(),u())}}return{entries:d,has(f){return p(()=>a.has(f),"read")},get(f){return p(()=>a.get(f),"read")},set(f,h,l){p(()=>a.set(f,h,l?.ttl))},setMany(f,h){p(()=>a.setMany(f,h?.ttl))},delete(f){p(()=>a.delete(f))},deleteMany(f){p(()=>a.deleteMany(f))},clear(){p(()=>a.clear())},pruneExpired(){p(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}function ft(t,e){return Ve("ai",t,e)}function Tr(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}le();re();Ke();function xr(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function _s(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function jt(t,e,n,r){let s=r?.format??"text",o=r?.name??"prompt_node",i=I(e,d=>{if(d.some(c=>c==null))return[];let u=typeof n=="string"?n:n(...d);return u?[{role:"user",content:u}]:[]},{name:`${o}::messages`,meta:ft("prompt_node")});return we(i,d=>!d||d.length===0?P(null):de(u=>{let c=!1,p=!1,f,h={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let b=zn(r.abort);h.signal=b.signal,f=b.dispose}let l;try{l=t.invoke(d,h)}catch(b){return c=!0,u.down([[L,b]]),()=>{f?.()}}let g=$e(l).subscribe(b=>{if(!(p||c))for(let v of b){if(c)return;if(v[0]===G){let y=v[1];try{let x=xr(y),E=s==="json"?JSON.parse(Tr(x)):x;u.emit(E)}catch(x){let E=xr(y),T=new Error(`promptNode: failed to parse LLM response as JSON: ${x.message}
|
|
49
|
+
Raw content (first 200 chars): ${_s(E)}`);c=!0,u.down([[L,T]]);return}}else if(v[0]===L){c=!0,u.down([[L,v[1]]]);return}else if(v[0]===$){c=!0,u.down([[$]]);return}else u.down([v])}});return()=>{p=!0,g(),f?.()}},{name:`${o}::call`,meta:ft("prompt_node::call")}),{name:`${o}::output`,meta:r?.meta?{...ft("prompt_node::output"),...r.meta}:ft("prompt_node::output")})}Ce();le();Se();re();function Es(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=wr(t,e);if(!n)throw new Error("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");return{node:e,path:n}}function wr(t,e){let n=t.describe(),r=`::${me}::`;for(let s of Object.keys(n.nodes).sort())if(!s.includes(r))try{if(t.resolve(s)===e)return s}catch{}}function Ns(t,e,n,r){t.add(n,{name:e})}function Rs(t,e){return Ve("orchestration",t,e)}function _r(t,e,n,r){let s=r?.maxPending??1/0;if(s<1&&s!==1/0)throw new RangeError("gate: maxPending must be >= 1");let o=r?.startOpen??!1;typeof n!="string"&&!wr(t,n)&&t.add(n,{name:`${e}/source`});let i=Es(t,n),a=P([],{name:"pending",equals:()=>!1}),d=P(o,{name:"isOpen"}),u=I([a],([T])=>T.length,{name:"count"}),c=P(null,{name:"lastRejected",equals:()=>!1}),p=[],f=!1,h=o,l=d.subscribe(T=>{for(let w of T)w[0]===G&&(h=w[1])});function m(){a.emit([...p])}function g(T){p.push(T),p.length>s&&p.shift(),m()}function b(T){let w=p.splice(0,T);return m(),w}function v(T){if(f)throw new Error(`gate: ${T}() called after gate was torn down`)}let y=ue([i.node],(T,w,N)=>{let R=N.terminalDeps[0];if(R!==void 0){f=!0,p=[],m(),w.down(R===!0?[[$]]:[[L,R]]);return}let C=T[0];if(C==null||C.length===0){w.down([[Q]]);return}for(let S of C)h?w.emit(S):(g(S),w.down([[Q]]))},{name:e,describeKind:"derived",meta:Rs("gate",r?.meta)}),x={node:y,pending:a,count:u,isOpen:d,lastRejected:c,approve(T=1){v("approve");let w=b(T);for(let N of w){if(f)break;y.emit(N)}},reject(T=1){v("reject"),ae(()=>{let w=[...p],N=Math.min(T,w.length);for(let R=0;R<N;R++)c.emit(w[R]);b(T)})},modify(T,w=1){v("modify");let N=[...p],R=b(w);for(let C=0;C<R.length&&!f;C++)y.emit(T(R[C],C,N))},open(){v("open"),ae(()=>{d.emit(!0);let T=b(p.length);for(let w of T){if(f)break;y.emit(w)}})},close(){v("close"),d.emit(!1)}};t.addDisposer(u.subscribe(()=>{})),t.addDisposer(l),Ns(t,e,y,i.path?[i.path]:[]);let E=new oe(`${e}_state`);return E.add(a,{name:"pending"}),E.add(d,{name:"isOpen"}),E.add(u,{name:"count"}),E.add(c,{name:"lastRejected"}),t.mount(`${e}_state`,E),t.addDisposer(c.subscribe(()=>{})),x}function Er(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let s=t*Math.exp(-n*e);return Math.max(r,s)}Ce();le();re();var Tn=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Nr(t,e={}){let{name:n,versioning:r,backend:s}=e,o=s??new Tn(t),i=P(o.toArray(),{name:n,describeKind:"state",equals:(u,c)=>u===c,...r!=null?{versioning:r}:{}});function a(){let u=o.toArray();ae(()=>{i.down([[Y]]),i.down([[G,u]])})}function d(u){let c=o.version;try{return u()}finally{o.version!==c&&a()}}return{items:i,get size(){return o.size},at(u){return o.at(u)},append(u){d(()=>o.append(u))},appendMany(u){d(()=>o.appendMany(u))},insert(u,c){d(()=>o.insert(u,c))},insertMany(u,c){d(()=>o.insertMany(u,c))},pop(u=-1){return d(()=>o.pop(u))},clear(){d(()=>o.clear())},dispose(){}}}function Os(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function ks(t,e){return Ve("job_queue",t,e)}var xn=class extends oe{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,n={}){super(e,n.graph),this._pending=Nr([],{name:"pending"}),this._jobs=Vt({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=I([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:ks("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(xe(this.depth))}enqueue(e,n={}){let r=n.id??`${this.name}-${++this._seq}`;if(this._jobs.get(r)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${r}"`);let s={id:r,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(r,s),this._pending.append(r),r}claim(e=1){let n=Os(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let o=this._pending.pop(0),i=this._jobs.get(o);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(o,a),r.push(a)}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),!0):(this._jobs.delete(e),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.state==="queued"){let s=this.pending.cache.indexOf(e);s>=0&&this._pending.pop(s)}return this._jobs.delete(e),!0}};function Rr(t,e){return new xn(t,e)}Pe();re();function wn(){let t=Vt({name:"strategy-entries"}),e=I([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,p]of d){let f=u.get(c);if(!f||p.attempts!==f.attempts||p.successes!==f.successes)return!1}return!0}});function n(i,a,d){let u=et(i,a),c=t.get(u),p=(c?.attempts??0)+1,f=(c?.successes??0)+(d?1:0);t.set(u,{rootCause:i,intervention:a,attempts:p,successes:f,successRate:f/p})}function r(i,a){return t.get(et(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:n,lookup:r,dispose:o}}function Ss(t,e,n,r,s){let o={...Xe,...s?.severityWeights},i=s?.decayRate??Ze,a=s?.effectivenessThreshold??.7,d=s?.effectivenessBoost??15,u=[t,e,n];return r&&u.push(r),I(u,c=>{let p=c[0],f=c[1],h=c[2],l=r?c[3]:0,m=o[p.severity??"medium"],g=(q()-h)/1e9,b=Er(m,g,i,0),v=et(p.rootCause,p.intervention),y=f.get(v);return y&&y.successRate>=a&&(b+=d),b+=l*20,b},{name:"priority-score"})}var Or="intake",As="triage-output",kr="retry",Sr="verify-results",Ar="__unrouted";function Mr(t,e){let n=dt(e,on,(r,s)=>r.replace("{{item}}",JSON.stringify(s)));return r=>jt(t,[r],n,{name:"execute",format:"json"})}function Ir(t,e){let n=dt(e,sn,(r,s)=>{let[o,i]=s;return r.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return r=>jt(t,[r],s=>s==null?"":n(s),{name:"verify",format:"json"})}var zt=class extends oe{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,s,o,i,a,d,u){super(e),this.queues=n,this.queueTopics=r,this.jobs=s,this.gates=o,this.strategy=i,this.totalRetries=a,this.totalReingestions=d,this.priorityScores=u}get intake(){return this.queues.topic(Or)}get verifyResults(){return this.queues.topic(Sr)}get retry(){return this.queues.topic(kr)}get unrouted(){return this.queues.topic(Ar)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],s=he.flatMap(i=>r(n(i))),o=[];for(let[i]of this.gates)o.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:s},{label:"GATE",paths:o},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function Ms(t,e){let n=e.adapter,r=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??Nt,i=new Map;for(let _ of he)i.set(_,{...Et[_],...e.queues?.[_]});let a=Ft(`${t}/queues`,{defaultTopicOptions:{retainedLimit:s}}),d=a.topic(Or),u=a.topic(As),c=a.topic(kr),p=a.topic(Sr),f=new Map;for(let _ of he)f.set(_,a.topic(_));let h=a.topic(Ar),l=wn(),m=ut(d.latest,l.node),g=dt(e.triagePrompt,rn,(_,O)=>{let[z,K]=O;return _.replace("{{strategy}}",JSON.stringify(Array.from(K.entries()))).replace("{{item}}",JSON.stringify(z))}),b=jt(n,[m],_=>{let O=_;return!O||!O[0]?"":g(O)},{name:"triage",format:"json"}),v=ut(b,m),x=ce([v],([_])=>{if(_==null)return;let[O,z]=_;if(!O?.route)return;let K=z?.[0],ke={...O,...K};u.publish(ke)}).subscribe(()=>{}),E=new Set(he);for(let _ of he)bn(`bridge/${_}`,u,f.get(_),{map:O=>O.route===_?O:void 0});bn("bridge/__unrouted",u,h,{map:_=>E.has(_.route)?void 0:_});let T=new Map,w=new Map;for(let _ of he)T.set(_,Rr(`jobs/${_}`));let N=[];for(let _ of he){let O=f.get(_),z=T.get(_),K=new WeakSet,ke=ce([O.events],([tt])=>{let je=tt??[];for(let U of je){if(K.has(U))continue;K.add(U);let be=z.enqueue(U);w.set(ct(U),{route:_,id:be})}},{name:`jobs/${_}-mirror`});N.push(ke.subscribe(()=>{}))}function R(_){let O=ct(_),z=w.get(O);z&&(T.get(z.route)?.removeById(z.id),w.delete(O))}let C=new oe("gates"),S=new Map;for(let _ of he){let O=i.get(_);if(!O.gated)continue;let z=f.get(_),K=_r(C,`${_}/gate`,z.latest,{maxPending:O.maxPending,startOpen:O.startOpen});S.set(_,K)}let D=[];for(let _ of he)i.get(_).gated&&S.has(_)?D.push(S.get(_).node):D.push(f.get(_).latest);D.push(c.latest);let M=Hn(...D),X=(e.executor??Mr(n,e.executePrompt))(M),ne=ut(X,M),Ee=(e.verifier??Ir(n,e.verifyPrompt))(ne),Ae=ut(Ee,ne),Ne=e.maxReingestions??1,Re=Math.min(e.maxTotalRetries??r*10,100),Ge=Math.min(e.maxTotalReingestions??Ne*10,100),k=P(0),H=P(0);function se(_,O,z){let K={item:z,outcome:O?.outcome??"failure",detail:O?.detail??"unknown",artifact:O?.artifact};return{item:z,execution:K,verified:_.verified,findings:_.findings??[],errorClass:_.errorClass}}function Oe(_,O){l.record(O.rootCause,O.intervention,!0),p.publish(_),R(O)}function ie(_,O){let z=ct(O),K=O.$retries??0,ke={...O,$retries:K+1,summary:`[RETRY ${K+1}/${r}] ${z} \u2014 Previous attempt failed: ${_.findings.join("; ")}`,relatedTo:[z]};c.publish(ke)}function j(_,O){l.record(O.rootCause,O.intervention,!1),p.publish(_),R(O);let z=ct(O),K=O.$reingestions??0;K<Ne&&pn(H,Ge)&&d.publish({source:O.source,summary:`Verification failed for: ${z}`,evidence:_.findings.join(`
|
|
50
|
+
`),affectsAreas:O.affectsAreas,affectsEvalTasks:O.affectsEvalTasks,severity:O.severity??"high",relatedTo:[z],$reingestions:K+1})}let te=ue([Ae],(_,O)=>{let z=_[0];if(z==null||z.length===0)return;let K=z[z.length-1];if(K==null)return;let[ke,tt]=K,[je,U]=tt??[null,null];if(!ke||!U)return;if(je==null){j({item:U,execution:{item:U,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},U);return}let be=se(ke,je,U);if(be.verified){Oe(be,U);return}let pe=be.errorClass??o({item:U,outcome:je.outcome,detail:be.findings.join("; ")}),Me=U.$retries??0;pe==="self-correctable"&&Me<r&&pn(k,Re)?ie(be,U):j(be,U)}),A=te.subscribe(()=>{}),V=I([te],()=>null,{name:"reflect",equals:()=>!1}),J;e.priority&&(J=Is(f,l,e));let F=new zt(t,a,f,T,S,l,k,H,J);F.addDisposer(x),F.addDisposer(A),F.addDisposer(l.dispose);for(let _ of N)F.addDisposer(_);if(F.add(b,{name:"triage"}),F.add(M,{name:"execute-input"}),F.add(X,{name:"execute"}),F.add(ne,{name:"execute-context"}),F.add(Ee,{name:"verify"}),F.add(Ae,{name:"verify-context"}),F.add(te,{name:"verify-dispatch"}),F.add(V,{name:"reflect"}),F.add(l.node,{name:"strategy"}),F.addDisposer(V.subscribe(()=>{})),J)for(let[_,O]of J)F.add(O,{name:`priority/${_}`}),F.addDisposer(O.subscribe(()=>{}));F.mount("queues",a),F.mount("gates",C);for(let[_,O]of T)F.mount(`jobs/${_}`,O);return F}function Is(t,e,n){if(!n.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let r=n.lastInteractionNs,s=n.priority??{},o={...Xe,...s.severityWeights},i=s.decayRate??Ze,a=s.effectivenessThreshold??.7,d=s.effectivenessBoost??15,u=new Map;for(let[c,p]of t){let f=I([p.latest,e.node,r],h=>{let l=h[0];if(l==null)return 0;let m=o[l.severity??"medium"]??40,g=(q()-h[2])/1e9,b=m*Math.exp(-i*Math.max(0,g)),v=`${l.rootCause}\u2192${l.intervention}`,x=h[1]?.get(v);return x&&x.successRate>=a&&(b+=d),b},{name:`priority/${c}`});u.set(c,f)}return u}function Cs(t,e){let n=Dt(t,e),r={};for(let s of he){let o=t.queues.has(s)?t.queues.topic(s):null;r[s]=o?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}Pe();function Ds(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let s of r)e[s]=n;return e}function Gs(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",s=q(),o=[],i=[],a=Ds(t);function d(){return(q()-s)/1e9}function u(c,p,f){let h={elapsed:d(),stage:c,type:p};r!=="summary"&&(h.summary=Ls(f)),r==="full"&&(h.data=f),i.push(h)}for(let[c,p]of Object.entries(a))try{let f=t.observe(c,{format:"stage-log",stageLabels:a,logger:n?h=>n(h):()=>{},includeTypes:["data","error","complete"]});f.onEvent(h=>{h.type==="data"?u(p,"data",h.data):h.type==="error"?u(p,"error",h.data):h.type==="complete"&&u(p,"complete",void 0)}),o.push(f)}catch(f){let h=f instanceof Error?f.message:String(f);u(p,"error",`observe-unavailable: ${c} \u2014 ${h}`),n&&n(`[${d().toFixed(3)}s] ${p.padEnd(9)} \u2717 observe-unavailable: ${h}`)}return{get events(){return i},dispose(){for(let c of o)c.dispose();o.length=0}}}function Ls(t){if(t==null)return"null";if(typeof t=="string")return Cr(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Cr(e,120)}catch{return String(t)}}function Cr(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}0&&(module.exports={DEFAULT_DECAY_RATE,DEFAULT_EXECUTE_PROMPT,DEFAULT_QUEUE_CONFIGS,DEFAULT_SEVERITY_WEIGHTS,DEFAULT_TRIAGE_PROMPT,DEFAULT_VERIFY_PROMPT,HarnessGraph,QUEUE_NAMES,actuatorExecutor,affectedTaskFilter,autoSolidify,beforeAfterCompare,codeChangeBridge,createIntakeBridge,defaultErrorClassifier,defaultLlmExecutor,defaultLlmVerifier,evalIntakeBridge,evalSource,evalVerifier,harnessEvalPair,harnessLoop,harnessProfile,harnessTrace,notifyEffect,priorityScore,refineExecutor,resolvePromptFn,strategyKey,strategyModel});
|