@graphrefly/graphrefly 0.40.0 → 0.41.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.
Files changed (87) hide show
  1. package/dist/{chunk-6XVD5TZV.js → chunk-2W553JJC.js} +1 -1
  2. package/dist/{chunk-WL6LFPJB.js → chunk-33N4TU3X.js} +1 -1
  3. package/dist/{chunk-RZJDIV2G.js → chunk-4MKL6Q3K.js} +1 -1
  4. package/dist/chunk-5B3JDG5F.js +1 -0
  5. package/dist/{chunk-K2Z7UENB.js → chunk-5QSXEMXG.js} +1 -1
  6. package/dist/{chunk-ECQRP2UT.js → chunk-5TEFC2ZX.js} +1 -1
  7. package/dist/{chunk-SVFKHUCW.js → chunk-5TOPVRN6.js} +1 -1
  8. package/dist/{chunk-XJLYLLIJ.js → chunk-5VEZLQFN.js} +1 -1
  9. package/dist/{chunk-32N3JALT.js → chunk-7PQLZMOG.js} +1 -1
  10. package/dist/{chunk-2QXRYP7Q.js → chunk-AI7QC7J6.js} +1 -1
  11. package/dist/{chunk-FHRBBHJN.js → chunk-AK5RHMC5.js} +1 -1
  12. package/dist/{chunk-B7LCDQEV.js → chunk-CGNOWGV6.js} +1 -1
  13. package/dist/{chunk-LCGAVGGV.js → chunk-CYOSWFT2.js} +1 -1
  14. package/dist/{chunk-VMF23LGB.js → chunk-EC2WNSZ7.js} +1 -1
  15. package/dist/{chunk-UWA6D7UF.js → chunk-ELAASRBT.js} +1 -1
  16. package/dist/{chunk-Z4F3DOWS.js → chunk-F7VUYPP6.js} +1 -1
  17. package/dist/{chunk-LYM4PBMV.js → chunk-G3M3IMEV.js} +1 -1
  18. package/dist/{chunk-SSCGRYJ2.js → chunk-GI4Q7PNY.js} +1 -1
  19. package/dist/{chunk-7Q4ZD3YW.js → chunk-H5SCWHWP.js} +1 -1
  20. package/dist/{chunk-6I726LZU.js → chunk-KNVCCBIU.js} +1 -1
  21. package/dist/{chunk-CKFQS2CJ.js → chunk-L77I47VU.js} +1 -1
  22. package/dist/{chunk-I2DEVPMU.js → chunk-M3FQSXEW.js} +1 -1
  23. package/dist/{chunk-WUT362QV.js → chunk-OLIKJUKI.js} +1 -1
  24. package/dist/{chunk-QSK3RRII.js → chunk-OV5AA6HJ.js} +1 -1
  25. package/dist/{chunk-2BX4NB34.js → chunk-POXANAJ6.js} +1 -1
  26. package/dist/chunk-RSMEXK53.js +43 -0
  27. package/dist/{chunk-MNZIKXK4.js → chunk-SC27WTSG.js} +1 -1
  28. package/dist/{chunk-YXDRGKXP.js → chunk-TT4C7DXW.js} +1 -1
  29. package/dist/{chunk-2DMKW2AD.js → chunk-UISPDFJ3.js} +1 -1
  30. package/dist/{chunk-J63M5U46.js → chunk-URJ2VFNC.js} +1 -1
  31. package/dist/{chunk-XW4YDF6G.js → chunk-VV62MIG4.js} +1 -1
  32. package/dist/{chunk-756D5TFD.js → chunk-VXPLLA4P.js} +1 -1
  33. package/dist/{chunk-PPUYQ66A.js → chunk-WZYB3JQS.js} +1 -1
  34. package/dist/{chunk-6VWBPSSY.js → chunk-X7QKTXXC.js} +1 -1
  35. package/dist/{chunk-JKBOIJ22.js → chunk-YQRN4CIV.js} +1 -1
  36. package/dist/chunk-Z6X7B6A4.js +61 -0
  37. package/dist/{chunk-N43XM7BM.js → chunk-ZAJ7J7TO.js} +1 -1
  38. package/dist/compat/index.js +1 -1
  39. package/dist/compat/nestjs/index.js +1 -1
  40. package/dist/compat/zustand/index.js +1 -1
  41. package/dist/extra/index.js +1 -1
  42. package/dist/extra/node.js +1 -1
  43. package/dist/extra/operators.js +1 -1
  44. package/dist/extra/reactive.js +1 -1
  45. package/dist/extra/sources.js +1 -1
  46. package/dist/graph/index.js +1 -1
  47. package/dist/{index-IUCY0OFN.d.ts → index-CG33HeBW.d.ts} +17 -2
  48. package/dist/{index-BTHOTC0Q.d.cts → index-DGD4_fj6.d.cts} +17 -2
  49. package/dist/{index-D1IEZUsj.d.ts → index-DfOK_oL5.d.ts} +204 -199
  50. package/dist/{index-DJ_MPOJ5.d.cts → index-DuRsN9ae.d.cts} +204 -199
  51. package/dist/index.cjs +46 -46
  52. package/dist/index.d.cts +2 -2
  53. package/dist/index.d.ts +2 -2
  54. package/dist/index.js +1 -1
  55. package/dist/patterns/ai/browser.js +1 -1
  56. package/dist/patterns/ai/index.cjs +11 -11
  57. package/dist/patterns/ai/index.js +1 -1
  58. package/dist/patterns/ai/node.js +1 -1
  59. package/dist/patterns/audit/index.js +1 -1
  60. package/dist/patterns/cqrs/index.js +1 -1
  61. package/dist/patterns/demo-shell/index.js +1 -1
  62. package/dist/patterns/domain-templates/index.js +1 -1
  63. package/dist/patterns/graphspec/index.js +1 -1
  64. package/dist/patterns/guarded-execution/index.js +1 -1
  65. package/dist/patterns/harness/index.cjs +8 -8
  66. package/dist/patterns/harness/index.d.cts +4 -4
  67. package/dist/patterns/harness/index.d.ts +4 -4
  68. package/dist/patterns/harness/index.js +1 -1
  69. package/dist/patterns/job-queue/index.cjs +3 -3
  70. package/dist/patterns/job-queue/index.d.cts +1 -1
  71. package/dist/patterns/job-queue/index.d.ts +1 -1
  72. package/dist/patterns/job-queue/index.js +1 -1
  73. package/dist/patterns/lens/index.js +1 -1
  74. package/dist/patterns/memory/index.js +1 -1
  75. package/dist/patterns/messaging/index.js +1 -1
  76. package/dist/patterns/orchestration/index.js +1 -1
  77. package/dist/patterns/process/index.js +1 -1
  78. package/dist/patterns/reactive-layout/index.js +1 -1
  79. package/dist/patterns/reduction/index.js +1 -1
  80. package/dist/patterns/refine-loop/index.js +1 -1
  81. package/dist/patterns/resilient-pipeline/index.js +1 -1
  82. package/dist/patterns/surface/index.js +1 -1
  83. package/dist/{resilience-S33JV6XC.js → resilience-JISHQD2F.js} +1 -1
  84. package/package.json +1 -1
  85. package/dist/chunk-INQFTVZA.js +0 -61
  86. package/dist/chunk-OSZ22J7O.js +0 -1
  87. package/dist/chunk-YKD7WUYJ.js +0 -43
@@ -1,4 +1,4 @@
1
- "use strict";var Yt=Object.defineProperty;var Vr=Object.getOwnPropertyDescriptor;var jr=Object.getOwnPropertyNames;var zr=Object.prototype.hasOwnProperty;var me=(r,e)=>()=>(r&&(e=r(r=0)),e);var Br=(r,e)=>{for(var t in e)Yt(r,t,{get:e[t],enumerable:!0})},qr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jr(e))!zr.call(r,s)&&s!==t&&Yt(r,s,{get:()=>e[s],enumerable:!(n=Vr(e,s))||n.enumerable});return r};var Hr=r=>qr(Yt({},"__esModule",{value:!0}),r);var Pe,C,ee,Q,xe,Ae,Le,ue,j,G,He,Et,Pn,kt,Ln,Fn,Rt,Qt,Xt,Zt,Ot,ge=me(()=>{"use strict";Pe=Symbol.for("graphrefly/START"),C=Symbol.for("graphrefly/DATA"),ee=Symbol.for("graphrefly/DIRTY"),Q=Symbol.for("graphrefly/RESOLVED"),xe=Symbol.for("graphrefly/INVALIDATE"),Ae=Symbol.for("graphrefly/PAUSE"),Le=Symbol.for("graphrefly/RESUME"),ue=Symbol.for("graphrefly/TEARDOWN"),j=Symbol.for("graphrefly/COMPLETE"),G=Symbol.for("graphrefly/ERROR"),He=Object.freeze([ee]),Et=Object.freeze([Q]),Pn=Object.freeze([xe]),kt=Object.freeze([Pe]),Ln=Object.freeze([j]),Fn=Object.freeze([ue]),Rt=Object.freeze([He]),Qt=Object.freeze([Et]),Xt=Object.freeze([Pn]),Zt=Object.freeze([Ln]),Ot=Object.freeze([Fn])});function Vn(r,e){let t=new TextEncoder().encode(r.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${r.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let n=r.version;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`encodeEnvelope: codec.version ${n} out of u16 range (expected integer 0\u201365535)`);let s=2+t.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++]=en,o[i++]=t.length,o.set(t,i),i+=t.length,o[i++]=n>>>8&255,o[i++]=n&255,o.set(e,i),o}function jn(r,e){if(r.length<$n)throw new Error(`decodeEnvelope: bytes too short (${r.length} < ${$n})`);let t=0,n=r[t++];if(n!==en)throw new Error(`decodeEnvelope: unsupported envelope version ${n} (expected ${en})`);let s=r[t++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+s+2>r.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+s+2} bytes, have ${r.length})`);let o=new TextDecoder().decode(r.subarray(t,t+s));t+=s;let i=(r[t]<<8|r[t+1])>>>0;t+=2;let a=r.subarray(t),u=e.lookupCodec(o);if(u==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:u,codecVersion:i,payload:a}}function zn(r){r.registerCodec(Ur)}var Ur,en,$n,tn=me(()=>{"use strict";Ur={name:"json",version:1,contentType:"application/json",encode(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)},decode(r,e){let t=new TextDecoder().decode(r);return JSON.parse(t)}},en=1,$n=4});function St(r){if(r==null)return Ye;let{type:e,id:t,...n}=r;return{type:e??"system",id:t??"",...n}}var Ye,At=me(()=>{"use strict";Ye={type:"system",id:""}});function ft(){return Qe>0||ct}function Bn(){return Qe>0}function Ze(r){Qe>0?lt.push(r):r()}function te(r){Qe+=1;let e=!1;try{r()}catch(t){throw e=!0,t}finally{if(Qe-=1,Qe===0)if(e){if(!ct){let t=lt.splice(0);for(let n of t)try{n()}catch{}Ue.length=0,Ke.length=0,Xe.length=0}}else Kr()}}function Kr(){let r=!ct;r&&(ct=!0);let e=[],t=0;try{for(;Ue.length>0||Ke.length>0||Xe.length>0||r&&lt.length>0;){if(r&&lt.length>0){let o=lt.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(t+=1,t>1e3)throw Ue.length=0,Ke.length=0,Xe.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(Ue.length>0?Ue:Ke.length>0?Ke:Xe).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{r&&(ct=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function pt(r,e,t){if(e.length===0)return;if(e.length===1){let d=t(e[0][0]);if(d<3||!ft()){r(e);return}(d>=5?Xe:d===4?Ke:Ue).push(()=>r(e));return}let n=e.length,s=n,o=n,i=n,a=0;for(;a<n&&t(e[a][0])<3;)a++;for(s=a;a<n&&t(e[a][0])===3;)a++;for(o=a;a<n&&t(e[a][0])===4;)a++;i=a;let u=ft();if(s>0){let d=e.slice(0,s);r(d)}if(o>s){let d=e.slice(s,o);u?Ue.push(()=>r(d)):r(d)}if(i>o){let d=e.slice(o,i);u?Ke.push(()=>r(d)):r(d)}if(n>i){let d=e.slice(i,n);u?Xe.push(()=>r(d)):r(d)}}var Qe,ct,Ue,Ke,Xe,lt,Ie=me(()=>{"use strict";Qe=0,ct=!1,Ue=[],Ke=[],Xe=[],lt=[]});function K(){return Math.trunc(performance.now()*1e6)}function ve(){return Date.now()*1e6}var Ne=me(()=>{"use strict"});function qn(r){r.registerMessageType(Pe,{tier:0,wireCrossing:!1}),r.registerMessageType(ee,{tier:1,wireCrossing:!1}),r.registerMessageType(xe,{tier:1,wireCrossing:!1,metaPassthrough:!1}),r.registerMessageType(Ae,{tier:2,wireCrossing:!1}),r.registerMessageType(Le,{tier:2,wireCrossing:!1}),r.registerMessageType(C,{tier:3,wireCrossing:!0}),r.registerMessageType(Q,{tier:3,wireCrossing:!0}),r.registerMessageType(j,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(G,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(ue,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Dt,Hn=me(()=>{"use strict";ge();Dt=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=t=>{let n=this._messageTypes.get(t);return n!=null?n.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,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.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 Un(r){return Array.isArray(r)?[...r]:[r]}function Wr(r,e){return r.has(e)||r.has("*")}function Kn(r){let e=[];return r((s,o)=>{e.push({kind:"allow",actions:new Set(Un(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(Un(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let u of e)Wr(u.actions,o)&&u.where(s)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function nn(r){let e=Jr.filter(t=>r({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}var Ee,Jr,et=me(()=>{"use strict";Ee=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`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}};Jr=["human","llm","wallet","system"]});function rn(r){if(r===void 0)return null;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`Cannot hash non-finite number: ${r}`);if(Number.isInteger(r)&&!Number.isSafeInteger(r))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${r}. Cross-language cid parity is not guaranteed for unsafe integers.`);return r}if(typeof r=="string"||typeof r=="boolean"||r===null)return r;if(Array.isArray(r))return r.map(rn);if(typeof r=="object"&&r!==null){let e={};for(let t of Object.keys(r).sort())e[t]=rn(r[t]);return e}return null}function Xr(r){let e=Qr.encode(r),t=e.length,n=t*8,s=t+9+63&-64,o=new Uint8Array(s);o.set(e),o[t]=128;let i=new DataView(o.buffer);i.setUint32(s-4,n>>>0,!1),i.setUint32(s-8,Math.floor(n/4294967296)>>>0,!1);let a=1779033703,u=3144134277,d=1013904242,c=2773480762,p=1359893119,l=2600822924,h=528734635,f=1541459225,g=new Uint32Array(64),m=(y,v)=>y>>>v|y<<32-v;for(let y=0;y<s;y+=64){for(let N=0;N<16;N++)g[N]=i.getUint32(y+N*4,!1);for(let N=16;N<64;N++){let P=g[N-15],B=g[N-2],z=m(P,7)^m(P,18)^P>>>3,le=m(B,17)^m(B,19)^B>>>10;g[N]=g[N-16]+z+g[N-7]+le>>>0}let v=a,_=u,w=d,R=c,b=p,x=l,O=h,S=f;for(let N=0;N<64;N++){let P=m(b,6)^m(b,11)^m(b,25),B=b&x^~b&O,z=S+P+B+Yr[N]+g[N]>>>0,le=m(v,2)^m(v,13)^m(v,22),ae=v&_^v&w^_&w,Oe=le+ae>>>0;S=O,O=x,x=b,b=R+z>>>0,R=w,w=_,_=v,v=z+Oe>>>0}a=a+v>>>0,u=u+_>>>0,d=d+w>>>0,c=c+R>>>0,p=p+b>>>0,l=l+x>>>0,h=h+O>>>0,f=f+S>>>0}let T=y=>y.toString(16).padStart(8,"0");return T(a)+T(u)+T(d)+T(c)+T(p)+T(l)+T(h)+T(f)}function on(r){let e=rn(r??null),t=JSON.stringify(e);return Xr(t).slice(0,16)}function Zr(){let r=globalThis.crypto;if(r?.randomUUID)return r.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function sn(r,e,t){let n=t?.id??Zr();if(r===0)return{id:n,version:0};let o=(t?.hash??on)(e);return{id:n,version:0,cid:o,prev:null}}function Wn(r,e,t){r.version+=1,"cid"in r&&(r.prev=r.cid,r.cid=t(e))}var Yr,Qr,Jn=me(()=>{"use strict";Yr=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]),Qr=new TextEncoder});function Xn(r){return{node:r,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function an(r){r.prevData=void 0,r.dirty=!1,r.involvedThisWave=!1,r.dataBatch.length=0,r.terminal=void 0}function Ct(r){return r.length===0?r:typeof r[0]=="symbol"?[r]:r}function ne(r,e,t){let n=Zn(r)?r:[],s=typeof r=="function"?r:typeof e=="function"?e:void 0,o={};return Zn(r)?o=(un(e)?e:t)??{}:un(r)?o=r:o=(un(e)?e:t)??{},new re(n,s,o)}var Yn,Qn,eo,to,tt,re,Zn,un,De=me(()=>{"use strict";tn();At();Ie();Ne();Hn();et();ge();Jn();Yn=()=>{},Qn=100;eo=(r,e,t,n)=>{t.direction==="down-in"&&r._onDepMessage(t.depIndex,e)},to=(r,e,t,n)=>{let s=r;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[kt]:[kt,[C,o]];s._status==="dirty"&&i.push(He),pt(e,i,s._config.tierOf)},tt=new Dt({onMessage:eo,onSubscribe:to});qn(tt);zn(tt);re=class r{_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,t,n){this._config=n.config??tt,this._config.onMessage,this._optsName=n.name,this._describeKind=n.describeKind,this._equals=n.equals??Object.is,this._resubscribable=n.resubscribable??!1,this._resetOnTeardown=n.resetOnTeardown??!1,this._autoComplete=n.completeWhenDepsComplete??!0,this._autoError=n.errorWhenDepsError??!0,this._pausable=n.pausable??!0,this._guard=n.guard,this._fn=t,this._partial=n.partial??!1,this._cached=n.initial!==void 0?n.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=n.versioningHash??this._config.defaultHashFn??on;let s=n.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?sn(s,this._cached===void 0?void 0:this._cached,{id:n.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Xn);let o={};for(let[a,u]of Object.entries(n.meta??{})){let d={initial:u,name:`${n.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};n.guard!=null&&(d.guard=n.guard),o[a]=new r([],void 0,d)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[C,a]])},down(a){i._emit(Ct(a))},up(a){i._emitUp(Ct(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,t){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 n=this._versioningLevel;if(n!=null&&e<=n)return;let s=t?.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??t?.id,u=i?.version??0,d=sn(e,o,{id:a,hash:s});d.version=u,this._versioning=d,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 t=St(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let n of this._extraGuards)if(!n(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,n=e?.actor!=null;if(!t&&!n)return;let s=St(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new Ee({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new Ee({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:ve()}}down(e,t){let n=Ct(e);n.length!==0&&(this._checkGuard(t),this._emit(n))}emit(e,t){this._checkGuard(t),this._emit([[C,e]])}up(e,t){if(this._deps.length===0)return;let n=Ct(e);if(n.length===0)return;this._checkGuard(t);let s=t??{internal:!0};this._validateUpTiers(n);for(let o of this._deps)o.node.up?.(n,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let n of e){let s=t(n[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,t){if(t!=null&&this._guard!=null){let u=St(t);if(!this._guard(u,"observe"))throw new Ee({actor:u,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 u of this._deps)an(u);if(this._partial===!1){for(let u of this._deps)if(u.prevData!==void 0||u.dataBatch.length!==0||u.terminal!==void 0||u.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(u){throw this._sinkCount-=1,u}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(u){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw u}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[t]=this._sinks;this._sinks=t}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,t=0;try{for(let n=0;n<e;n++){let s=n,o=this._deps[n];o.unsub=Yn,o.unsub=o.node.subscribe(i=>{if(o.unsub===null)return;let a=this._config.tierOf,u=!1;for(let d of i)a(d[0])>=3&&(u=!0),this._config.onMessage(this,d,{direction:"down-in",depIndex:s},this._actions);u&&this._maybeRunFnOnSettlement()}),t++}}catch(n){this._deps[t].unsub=null;for(let s=0;s<t;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}an(o)}}throw this._dirtyDepCount=0,n}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let t=this._deps.length,n=Xn(e);if(this._deps.push(n),this._sinks==null)return t;n.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rt),n.unsub=Yn;try{n.unsub=e.subscribe(s=>{if(n.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:t},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw n.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(n){this._emit([[G,this._wrapFnError("cleanup threw",n)]])}else if(t!=null&&typeof t=="object"){let n=t.deactivate;if(typeof n=="function")try{n()}catch(s){this._emit([[G,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let n of this._deps){if(n.unsub!=null){let s=n.unsub;n.unsub=null;try{s()}catch{}}an(n)}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,t){let n=this._deps[e],s=t[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:t};for(let i of this._inspectorHooks)i(o)}if(s!==Pe){if(s===ee){this._depDirtied(n);return}if(s===xe){if(this._depInvalidated(n),this._cached===void 0)return;this._emit(Xt);return}if(s===Ae||s===Le){this._emit([t]);return}if(s===ue){this._emit(Ot);return}if(s===C)this._depSettledAsData(n,t[1]);else if(s===Q)this._depSettledAsResolved(n);else if(s===j)this._depSettledAsTerminal(n,!0);else if(s===G)this._depSettledAsTerminal(n,t[1]);else{this._emit([t]);return}if(!this._fn){(s===C||s===Q)&&this._emit([t]),(s===j||s===G)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rt))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,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 t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.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(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[G,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(Zt)}_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([[G,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([[G,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let t=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),n=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=t[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:n,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:t,prevData:n};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(t,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([[G,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Qn?(this._rerunDepth=0,this._emit([[G,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Qn} \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,t){let n=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${n}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[He,e[0]]:e;let n=!0,s=!1,o=!1,i=-1;for(let u of e){let d=t(u[0]);d<i&&(n=!1),d===3&&(s=!0),u[0]===ee&&(o=!0),i=d}let a=e;if(!n){let u=e.map((d,c)=>({m:d,i:c,tier:t(d[0])}));u.sort((d,c)=>d.tier-c.tier||d.i-c.i),a=u.map(d=>d.m)}if(s&&!o&&this._status!=="dirty"){let u=0;for(;u<a.length&&t(a[u][0])===0;)u++;return u===0?[He,...a]:[...a.slice(0,u),He,...a.slice(u)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let u=e[a];if(u[0]===G&&u[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 t=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(u=>u[0]===ue||u[0]===xe);if(a.length===0)return;t=a}t=this._frameBatch(t);let s=null;for(let a=0;a<t.length;a++){let u=t[a],d=u[0];if(d!==Ae&&d!==Le){s?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${d===Ae?"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=u[1];if(d===Ae)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 l=this._pauseBuffer;this._pauseBuffer=[],this._emit(l)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(u):s==null&&(s=t.slice(0,a))}if(s!=null){if(s.length===0)return;t=s}if(this._hasMeta&&t.some(a=>a[0]===ue))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Ot)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(t);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,u=[];for(let d of o)a(d[0])===3?this._pauseBuffer.push(d):u.push(d);u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[G,i]])}_updateState(e){let t=this._config.tierOf,n,s,o=-1,i=0;for(let c of e)t(c[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===C){u=c;break}}for(let c=0;c<e.length;c++){let p=e[c],l=p[0];if(l===C){if(p.length>=2){let h=!1;if(a&&this._cached!==void 0)try{h=this._equals(this._cached,p[1])}catch(f){s=this._wrapFnError("equals threw",f),o=c;break}if(h){n==null&&(n=e.slice(0,c)),n.push(Et),this._status="resolved";continue}this._cached=p[1],this._versioning!=null&&(u<0||c===u)&&Wn(this._versioning,p[1],this._hashFn)}this._status="settled",n?.push(p)}else if(n?.push(p),l===ee)this._status="dirty";else if(l===Q)this._status="resolved";else if(l===j){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(l===G){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(l===xe){if(this._cached!==void 0){let f=this._config.rigorRecorder;if(f!=null)try{f.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 f=h.invalidate;if(typeof f=="function")try{f()}catch{}}}else l===ue&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let d=o>=0?n??e.slice(0,o):n??e;return s!=null?{finalMessages:d,equalsError:s}:{finalMessages:d}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let n of t)n(e)};_dispatchOrAccumulate(e){if(Bn()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Ze(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}pt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);pt(this._deliverToSinks,t,this._config.tierOf)}},Zn=r=>Array.isArray(r),un=r=>typeof r=="object"&&r!=null&&!Array.isArray(r)});function L(r,e){return ne([],{...e,initial:r})}function de(r,e){return ne((n,s,o)=>r(s,o)??void 0,{describeKind:"producer",...e})}function I(r,e,t){return ne(r,(s,o,i)=>{let a=s.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);o.emit(e(a,i))},{describeKind:"derived",...t})}function be(r,e,t){return ne(r,(s,o,i)=>{let a=s.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);return e(a,o,i)??void 0},{describeKind:"effect",...t})}var oe=me(()=>{"use strict";De()});function cn(r,e){if(e!=null&&e.length>0)return new Set(e);switch(r){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function no(r){return r._describeKind!=null?r._describeKind:r._deps.length>0?"derived":r._fn!=null?"producer":"state"}function ht(r){let e=new WeakSet,t={};for(let[n,s]of er(r))t[n]=dn(s,e);return t}function dn(r,e){if(r==null)return r;let t=typeof r;if(t==="boolean"||t==="number"||t==="string")return r;if(t==="function")return"<function>";if(Array.isArray(r))return e.has(r)?"<cycle>":(e.add(r),r.map(n=>dn(n,e)));if(t==="object"){let n=r;if(e.has(n))return"<cycle>";e.add(n);try{if(typeof n.subscribe=="function"&&"cache"in n)return"<Node>"}catch{return"<unserializable>"}let s={};for(let[o,i]of er(n))s[o]=dn(i,e);return s}return"<unserializable>"}function er(r){let e=[],t;try{t=Object.keys(r)}catch{return e}for(let n of t)try{e.push([n,r[n]])}catch{e.push([n,"<unserializable>"])}return e}function nt(r,e){let t={factory:r};return e!==void 0&&(t.factoryArgs=e),t}function ro(r){let e={};for(let[t,n]of Object.entries(r.meta))try{e[t]=n.cache}catch{}return e}function ln(r,e,t){let n=e==null,s=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||s!=null&&s.length>0,i="state",a=[];r instanceof re&&(i=no(r),a=r._deps.map(c=>c.node.name??""));let u={type:i,deps:a};(n||e.has("status"))&&(u.status=r.status);let d=r instanceof re?r._guard:void 0;if(o){let c={...ro(r)};if(d!=null&&c.access===void 0&&(c.access=nn(d)),s!=null&&s.length>0&&!e.has("meta")){let p={};for(let l of s)l in c&&(p[l]=c[l]);u.meta=p}else u.meta=c}if(r.name!=null&&(u.name=r.name),(n||e.has("value"))&&(!t||i==="state")){r.status==="sentinel"&&(u.sentinel=!0);try{u.value=r.cache}catch{}}if((n||e.has("v"))&&r.v!=null){let c={id:r.v.id,version:r.v.version};"cid"in r.v&&(c.cid=r.v.cid,c.prev=r.v.prev),u.v=c}return(n||e.has("guard"))&&d!=null&&(u.guard=nn(d)),(n||e.has("lastMutation"))&&r.lastMutation!=null&&(u.lastMutation=r.lastMutation),u}var mt=me(()=>{"use strict";et();De()});function fn(r){return{describeKind:"producer",...r}}function tr(r,e){return de(t=>{let n=!1;try{for(let s of r){if(n)return;t.emit(s)}n||t.down([[j]])}catch(s){n||t.down([[G,s]])}return()=>{n=!0}},fn(e))}function oo(r){return r!=null&&typeof r.then=="function"}function so(r,e){let{signal:t,...n}=e??{};return de(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[G,t.reason]]))};if(t?.aborted){i();return}return t?.addEventListener("abort",i,{once:!0}),Promise.resolve(r).then(a=>{o||(o=!0,t?.removeEventListener("abort",i),s.emit(a),s.down([[j]]))},a=>{o||(o=!0,t?.removeEventListener("abort",i),s.down([[G,a]]))}),()=>{o=!0,t?.removeEventListener("abort",i)}},fn(n))}function io(r,e){let{signal:t,...n}=e??{};return de(s=>{let o=new AbortController,i=()=>o.abort(t?.reason);t?.aborted?o.abort(t.reason):t?.addEventListener("abort",i,{once:!0});let a=t??o.signal,u=!1,d=r[Symbol.asyncIterator](),c=()=>{u||a.aborted||Promise.resolve(d.next()).then(p=>{if(!(u||a.aborted)){if(p.done){s.down([[j]]);return}s.emit(p.value),c()}},p=>{!u&&!a.aborted&&s.down([[G,p]])})};return c(),()=>{u=!0,t?.removeEventListener("abort",i),o.abort(),Promise.resolve(d.return?.()).catch(()=>{})}},fn(n))}function ao(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"}function Fe(r,e){if(ao(r))return r;if(oo(r))return so(r,e);if(r!=null){let t=r;if(typeof t[Symbol.asyncIterator]=="function")return io(r,e);if(typeof t[Symbol.iterator]=="function")return tr(r,e)}return uo(r)}function uo(...r){return tr(r,void 0)}function nr(r,e){let t=new AbortController,n=e?.reason??new Error("cancelled via nodeSignal"),s,o=!1,i=()=>{s?(s(),s=void 0):o=!0};return s=r.subscribe(a=>{if(!t.signal.aborted)for(let u of a){if(u[0]===C&&u[1]===!0){t.abort(n),i();return}if(u[0]===G){t.abort(u[1]),i();return}if(u[0]===j){i();return}}}),o&&(s?.(),s=void 0),{signal:t.signal,dispose:()=>{s&&(s(),s=void 0)}}}function ye(r){return r.subscribe(()=>{})}var rr=me(()=>{"use strict";ge();oe()});var $e=me(()=>{"use strict";rr()});var Pt,ar=me(()=>{"use strict";Pt=class{_timer;_gen=0;start(e,t){this.cancel(),this._gen+=1;let n=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,n===this._gen&&t()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var yt,ur=me(()=>{"use strict";yt=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 t=(this.head+this._size)%this.capacity;this.buf[t]=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 t=e<0?this._size+e:e;if(!(t<0||t>=this._size))return this.buf[(this.head+t)%this.capacity]}toArray(){let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this.buf[(this.head+t)%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}}});function ze(r,e,t){return{[r]:!0,[`${r}_type`]:e,...t??{}}}var vt=me(()=>{"use strict"});var gs={};Br(gs,{DEFAULT_DECAY_RATE:()=>ot,DEFAULT_EXECUTE_PROMPT:()=>hn,DEFAULT_QUEUE_CONFIGS:()=>It,DEFAULT_SEVERITY_WEIGHTS:()=>rt,DEFAULT_TRIAGE_PROMPT:()=>pn,DEFAULT_VERIFY_PROMPT:()=>mn,HarnessGraph:()=>Wt,QUEUE_NAMES:()=>_e,actuatorExecutor:()=>sr,affectedTaskFilter:()=>wo,autoSolidify:()=>bo,beforeAfterCompare:()=>_o,codeChangeBridge:()=>xo,createIntakeBridge:()=>yo,defaultErrorClassifier:()=>Gt,defaultLlmExecutor:()=>Pr,defaultLlmVerifier:()=>Lr,dispatchActuator:()=>go,effectivenessTracker:()=>ko,evalIntakeBridge:()=>vo,evalSource:()=>To,evalVerifier:()=>xr,harnessEvalPair:()=>ns,harnessLoop:()=>cs,harnessProfile:()=>fs,harnessTrace:()=>hs,notifyEffect:()=>No,priorityScore:()=>us,refineExecutor:()=>On,resolvePromptFn:()=>bt,strategyKey:()=>st,strategyModel:()=>Mn});module.exports=Hr(gs);ge();oe();ge();mt();De();oe();$e();function Mt(r){return{describeKind:"derived",...r}}function co(r){return{describeKind:"derived",partial:!0,...r}}function Ve(r,e,t){return ne([r],(n,s)=>{let o=n[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]])},{...Mt(t),meta:{...nt("filter"),...t?.meta??{}}})}function gt(r,e,t){return ne([r,e],(n,s,o)=>{let i=n[0],a=n[1],u=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 d of i)s.emit([d,u])}else s.down([[Q]])},{...co(t),meta:{...nt("withLatestFrom"),...t?.meta??{}}})}function or(...r){return r.length===0?de(e=>{e.down([[j]])},{...Mt(),meta:{...nt("merge")}}):de(e=>{let t=r.length,n=0,s=[];for(let o of r){let i=o.subscribe(a=>{for(let u of a)u[0]===C?e.emit(u[1]):u[0]===j?(n+=1,n>=t&&e.down([[j]])):u[0]===G&&e.down([u])});s.push(i)}return()=>{for(let o of s)o()}},{...Mt(),meta:{...nt("merge")}})}function lo(r,e,t){let n,s=!1,o=()=>{s||(s=!0,t())};return n=r.subscribe(i=>{let a=!1,u=!1;for(let d of i)d[0]!==Pe&&(d[0]===C?e.emit(d[1]):d[0]===j?a=!0:d[0]===G?(u=!0,e.down([d])):(d[0]===ee||d[0]===Q)&&e.down([d]));u?(n?.(),n=void 0,o()):a&&o()}),()=>{n?.(),n=void 0}}function ke(r,e,t){let n,s=!1;function o(){n?.(),n=void 0}return ne([r],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){o();return}if(u.terminalDeps[0]===!0){s=!0,n||a.down([[j]]);return}let d=i[0];if(!(d==null||d.length===0))return o(),n=lo(Fe(e(d[d.length-1])),a,()=>{o(),s&&a.down([[j]])}),{deactivate:()=>{o(),s=!1}}},{...Mt(t),completeWhenDepsComplete:!1,meta:{...nt("switchMap"),...t?.meta??{}}})}$e();function fo(r,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${mo(e.summary)}`,artifact:r}}function po(r,e){let t=r instanceof Error?r.message:String(r);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${t}`}}function ho(r){return`actuator skipped ${r.intervention} (shouldApply returned false)`}function mo(r,e=80){return r.length<=e?r:`${r.slice(0,e-1)}\u2026`}function sr(r){let e=r.name??"actuator-executor",t=r.toOutput??fo,n=r.onError??po,s=r.skipDetail??ho;return o=>{let i=Ve(o,u=>u!=null,{name:`${e}/gate-in`}),a=ke(i,u=>r.shouldApply&&!r.shouldApply(u)?de(d=>(d.down([[C,{outcome:"failure",detail:s(u)}],[j]]),()=>{}),{name:`${e}/skip`}):de(d=>{let c=new AbortController,p=!1,l=null,h=g=>{p||(p=!0,d.down([[C,g],[j]]),l?.(),l=null)},f;try{let g=r.apply(u,{signal:c.signal});f=Fe(g,{signal:c.signal})}catch(g){return h(n(g,u)),()=>{c.abort()}}return l=f.subscribe(g=>{for(let m of g){if(p)return;if(m[0]===C){h(t(m[1],u));return}if(m[0]===G){h(n(m[1],u));return}if(m[0]===j){h(n(new Error("actuator inner completed without emitting DATA"),u));return}}}),p&&l&&(l(),l=null),()=>{c.abort(),l?.(),l=null}},{name:`${e}/inner`}),{name:e});return Ve(a,u=>u!=null,{name:`${e}/gate-out`})}}function go(r){let e=r.name??"dispatch-actuator",t=r.default??null,n=t!=null;return sr({apply:(s,o)=>{let i=Object.hasOwn(r.routes,s.intervention)?r.routes[s.intervention]:t;if(!i)throw new Error(`dispatchActuator: no route for intervention '${s.intervention}'`);return i(s,o)},shouldApply:s=>Object.hasOwn(r.routes,s.intervention)||n,skipDetail:s=>`no route for intervention '${s.intervention}'`,name:e})}ge();oe();function bo(r){let e=r.name??"auto-solidify",t=r.extract??(s=>s.execution.artifact??null),n=r.predicate??(()=>!0);return de(s=>{let o=null,i=!1,a=()=>{i||(i=!0,o?.(),o=null)},u=d=>{i||(s.down([[G,d]]),a())};return o=r.verifyResults.subscribe(d=>{if(!i)for(let c of d){if(i)return;if(c[0]!==C){if(c[0]===j){s.down([[j]]),a();return}continue}let p=c[1];if(p==null||!p.verified)continue;let l;try{l=n(p)}catch(f){u(f);return}if(!l)continue;let h;try{h=t(p)}catch(f){u(f);return}if(h!=null){try{r.write(h,p)}catch(f){u(f);return}s.down([[C,h]])}}}),i&&o&&(o(),o=null),()=>{a()}},{name:e})}oe();$e();function yo(r,e,t,n){return be([r],([s])=>{if(s==null)return;let o=t(s);for(let i of o)e.publish(i)},{name:n?.name??"intake-bridge"})}function vo(r,e,t){let n=t?.defaultSeverity??"medium";return be([r],([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(u=>u.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:n});continue}if(a.judge_scores)for(let u of a.judge_scores)u.pass||e.publish({source:"eval",summary:`${a.task_id}: ${u.claim} (model: ${i.model})`,evidence:u.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:n})}},{name:t?.name??"eval-intake-bridge"})}function To(r,e){return ke(r,()=>Fe(e()))}function _o(r,e){return I([r,e],([t,n])=>{let s=t,o=n,i=new Map(s.tasks.map(l=>[l.task_id,l])),a=new Map(o.tasks.map(l=>[l.task_id,l])),u=new Set([...i.keys(),...a.keys()]),d=[],c=[],p=[];for(let l of u){let h=i.get(l),f=a.get(l),g=h?.valid??!1,m=f?.valid??!1,T=h?.judge_scores?h.judge_scores.filter(_=>_.pass).length:void 0,y=f?.judge_scores?f.judge_scores.filter(_=>_.pass).length:void 0,v=T!==void 0&&y!==void 0?y-T:void 0;d.push({taskId:l,before:g,after:m,scoreDiff:v}),g&&!m&&c.push(l),!g&&m&&p.push(l)}return{newFailures:c,resolved:p,taskDeltas:d,overallImproved:p.length>c.length}},{name:"eval-delta"})}function wo(r,e){let t=e==null?null:Array.isArray(e)?L(e):e,n=[r];return t&&n.push(t),I(n,s=>{let o=s[0],i=t?new Set(s[1]):null,a=new Set;for(let u of o)for(let d of u.affectsEvalTasks??[])(i==null||i.has(d))&&a.add(d);return[...a].sort()},{name:"affected-task-filter"})}function xo(r,e,t,n){let s=n?.defaultSeverity??"high";function o(a){let u=[];for(let d of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${d.rule} in ${d.file}:${d.line}`,evidence:d.message,affectsAreas:[d.file],severity:s});for(let d of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${d.testId}`,evidence:d.message,affectsAreas:[d.file],affectsEvalTasks:[d.testId],severity:s});return u}let i=t??o;return be([r],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:n?.name??"code-change-bridge"})}function No(r,e,t){return be([r.latest],([n])=>{n!=null&&e(n)},{name:t?.name??"notify-effect"})}var _e=["auto-fix","needs-decision","investigation","backlog"],It={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},rt={critical:100,high:70,medium:40,low:10},ot=Math.LN2/(168*3600);function st(r,e){return`${r}\u2192${e}`}var Eo=/\b(parse|json|config|validation|syntax)\b/i,Gt=r=>Eo.test(r.detail)?"self-correctable":"structural",pn=`You are a triage classifier for a reactive collaboration harness.
1
+ "use strict";var Zt=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Ur=Object.getOwnPropertyNames;var Kr=Object.prototype.hasOwnProperty;var _e=(r,e)=>()=>(r&&(e=r(r=0)),e);var Wr=(r,e)=>{for(var t in e)Zt(r,t,{get:e[t],enumerable:!0})},Jr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ur(e))!Kr.call(r,s)&&s!==t&&Zt(r,s,{get:()=>e[s],enumerable:!(n=qr(e,s))||n.enumerable});return r};var Yr=r=>Jr(Zt({},"__esModule",{value:!0}),r);var $e,D,Q,W,Re,De,Ve,pe,$,I,Be,Et,jn,kt,zn,Hn,Rt,en,tn,nn,Ot,be=_e(()=>{"use strict";$e=Symbol.for("graphrefly/START"),D=Symbol.for("graphrefly/DATA"),Q=Symbol.for("graphrefly/DIRTY"),W=Symbol.for("graphrefly/RESOLVED"),Re=Symbol.for("graphrefly/INVALIDATE"),De=Symbol.for("graphrefly/PAUSE"),Ve=Symbol.for("graphrefly/RESUME"),pe=Symbol.for("graphrefly/TEARDOWN"),$=Symbol.for("graphrefly/COMPLETE"),I=Symbol.for("graphrefly/ERROR"),Be=Object.freeze([Q]),Et=Object.freeze([W]),jn=Object.freeze([Re]),kt=Object.freeze([$e]),zn=Object.freeze([$]),Hn=Object.freeze([pe]),Rt=Object.freeze([Be]),en=Object.freeze([Et]),tn=Object.freeze([jn]),nn=Object.freeze([zn]),Ot=Object.freeze([Hn])});function qn(r,e){let t=new TextEncoder().encode(r.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${r.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let n=r.version;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`encodeEnvelope: codec.version ${n} out of u16 range (expected integer 0\u201365535)`);let s=2+t.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++]=rn,o[i++]=t.length,o.set(t,i),i+=t.length,o[i++]=n>>>8&255,o[i++]=n&255,o.set(e,i),o}function Un(r,e){if(r.length<Bn)throw new Error(`decodeEnvelope: bytes too short (${r.length} < ${Bn})`);let t=0,n=r[t++];if(n!==rn)throw new Error(`decodeEnvelope: unsupported envelope version ${n} (expected ${rn})`);let s=r[t++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+s+2>r.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+s+2} bytes, have ${r.length})`);let o=new TextDecoder().decode(r.subarray(t,t+s));t+=s;let i=(r[t]<<8|r[t+1])>>>0;t+=2;let a=r.subarray(t),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 Kn(r){r.registerCodec(Qr)}var Qr,rn,Bn,on=_e(()=>{"use strict";Qr={name:"json",version:1,contentType:"application/json",encode(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)},decode(r,e){let t=new TextDecoder().decode(r);return JSON.parse(t)}},rn=1,Bn=4});function St(r){if(r==null)return Qe;let{type:e,id:t,...n}=r;return{type:e??"system",id:t??"",...n}}var Qe,At=_e(()=>{"use strict";Qe={type:"system",id:""}});function ht(){return Xe>0||ft}function Wn(){return Xe>0}function et(r){Xe>0?pt.push(r):r()}function U(r){Xe+=1;let e=!1;try{r()}catch(t){throw e=!0,t}finally{if(Xe-=1,Xe===0)if(e){if(!ft){let t=pt.splice(0);for(let n of t)try{n()}catch{}qe.length=0,Ue.length=0,Ze.length=0}}else Xr()}}function Xr(){let r=!ft;r&&(ft=!0);let e=[],t=0;try{for(;qe.length>0||Ue.length>0||Ze.length>0||r&&pt.length>0;){if(r&&pt.length>0){let o=pt.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(t+=1,t>1e3)throw qe.length=0,Ue.length=0,Ze.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(qe.length>0?qe:Ue.length>0?Ue:Ze).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{r&&(ft=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function mt(r,e,t){if(e.length===0)return;if(e.length===1){let u=t(e[0][0]);if(u<3||!ht()){r(e);return}(u>=5?Ze:u===4?Ue:qe).push(()=>r(e));return}let n=e.length,s=n,o=n,i=n,a=0;for(;a<n&&t(e[a][0])<3;)a++;for(s=a;a<n&&t(e[a][0])===3;)a++;for(o=a;a<n&&t(e[a][0])===4;)a++;i=a;let d=ht();if(s>0){let u=e.slice(0,s);r(u)}if(o>s){let u=e.slice(s,o);d?qe.push(()=>r(u)):r(u)}if(i>o){let u=e.slice(o,i);d?Ue.push(()=>r(u)):r(u)}if(n>i){let u=e.slice(i,n);d?Ze.push(()=>r(u)):r(u)}}var Xe,ft,qe,Ue,Ze,pt,Me=_e(()=>{"use strict";Xe=0,ft=!1,qe=[],Ue=[],Ze=[],pt=[]});function K(){return Math.trunc(performance.now()*1e6)}function xe(){return Date.now()*1e6}var Oe=_e(()=>{"use strict"});function Jn(r){r.registerMessageType($e,{tier:0,wireCrossing:!1}),r.registerMessageType(Q,{tier:1,wireCrossing:!1}),r.registerMessageType(Re,{tier:1,wireCrossing:!1,metaPassthrough:!1}),r.registerMessageType(De,{tier:2,wireCrossing:!1}),r.registerMessageType(Ve,{tier:2,wireCrossing:!1}),r.registerMessageType(D,{tier:3,wireCrossing:!0}),r.registerMessageType(W,{tier:3,wireCrossing:!0}),r.registerMessageType($,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(pe,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Ct,Yn=_e(()=>{"use strict";be();Ct=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=t=>{let n=this._messageTypes.get(t);return n!=null?n.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,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.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 Qn(r){return Array.isArray(r)?[...r]:[r]}function Zr(r,e){return r.has(e)||r.has("*")}function Xn(r){let e=[];return r((s,o)=>{e.push({kind:"allow",actions:new Set(Qn(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(Qn(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let d of e)Zr(d.actions,o)&&d.where(s)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function sn(r){let e=eo.filter(t=>r({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}var Se,eo,tt=_e(()=>{"use strict";Se=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`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}};eo=["human","llm","wallet","system"]});function an(r){if(r===void 0)return null;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`Cannot hash non-finite number: ${r}`);if(Number.isInteger(r)&&!Number.isSafeInteger(r))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${r}. Cross-language cid parity is not guaranteed for unsafe integers.`);return r}if(typeof r=="string"||typeof r=="boolean"||r===null)return r;if(Array.isArray(r))return r.map(an);if(typeof r=="object"&&r!==null){let e={};for(let t of Object.keys(r).sort())e[t]=an(r[t]);return e}return null}function ro(r){let e=no.encode(r),t=e.length,n=t*8,s=t+9+63&-64,o=new Uint8Array(s);o.set(e),o[t]=128;let i=new DataView(o.buffer);i.setUint32(s-4,n>>>0,!1),i.setUint32(s-8,Math.floor(n/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,p=1359893119,l=2600822924,h=528734635,f=1541459225,b=new Uint32Array(64),m=(v,g)=>v>>>g|v<<32-g;for(let v=0;v<s;v+=64){for(let N=0;N<16;N++)b[N]=i.getUint32(v+N*4,!1);for(let N=16;N<64;N++){let P=b[N-15],H=b[N-2],F=m(P,7)^m(P,18)^P>>>3,ye=m(H,17)^m(H,19)^H>>>10;b[N]=b[N-16]+F+b[N-7]+ye>>>0}let g=a,_=d,w=u,E=c,y=p,x=l,k=h,S=f;for(let N=0;N<64;N++){let P=m(y,6)^m(y,11)^m(y,25),H=y&x^~y&k,F=S+P+H+to[N]+b[N]>>>0,ye=m(g,2)^m(g,13)^m(g,22),ve=g&_^g&w^_&w,ke=ye+ve>>>0;S=k,k=x,x=y,y=E+F>>>0,E=w,w=_,_=g,g=F+ke>>>0}a=a+g>>>0,d=d+_>>>0,u=u+w>>>0,c=c+E>>>0,p=p+y>>>0,l=l+x>>>0,h=h+k>>>0,f=f+S>>>0}let T=v=>v.toString(16).padStart(8,"0");return T(a)+T(d)+T(u)+T(c)+T(p)+T(l)+T(h)+T(f)}function un(r){let e=an(r??null),t=JSON.stringify(e);return ro(t).slice(0,16)}function oo(){let r=globalThis.crypto;if(r?.randomUUID)return r.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function dn(r,e,t){let n=t?.id??oo();if(r===0)return{id:n,version:0};let o=(t?.hash??un)(e);return{id:n,version:0,cid:o,prev:null}}function Zn(r,e,t){r.version+=1,"cid"in r&&(r.prev=r.cid,r.cid=t(e))}var to,no,er=_e(()=>{"use strict";to=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]),no=new TextEncoder});function rr(r){return{node:r,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function cn(r){r.prevData=void 0,r.dirty=!1,r.involvedThisWave=!1,r.dataBatch.length=0,r.terminal=void 0}function Dt(r){return r.length===0?r:typeof r[0]=="symbol"?[r]:r}function ee(r,e,t){let n=or(r)?r:[],s=typeof r=="function"?r:typeof e=="function"?e:void 0,o={};return or(r)?o=(ln(e)?e:t)??{}:ln(r)?o=r:o=(ln(e)?e:t)??{},new oe(n,s,o)}var tr,nr,so,io,nt,oe,or,ln,Ie=_e(()=>{"use strict";on();At();Me();Oe();Yn();tt();be();er();tr=()=>{},nr=100;so=(r,e,t,n)=>{t.direction==="down-in"&&r._onDepMessage(t.depIndex,e)},io=(r,e,t,n)=>{let s=r;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[kt]:[kt,[D,o]];s._status==="dirty"&&i.push(Be),mt(e,i,s._config.tierOf)},nt=new Ct({onMessage:so,onSubscribe:io});Jn(nt);Kn(nt);oe=class r{_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,t,n){this._config=n.config??nt,this._config.onMessage,this._optsName=n.name,this._describeKind=n.describeKind,this._equals=n.equals??Object.is,this._resubscribable=n.resubscribable??!1,this._resetOnTeardown=n.resetOnTeardown??!1,this._autoComplete=n.completeWhenDepsComplete??!0,this._autoError=n.errorWhenDepsError??!0,this._pausable=n.pausable??!0,this._guard=n.guard,this._fn=t,this._partial=n.partial??!1,this._cached=n.initial!==void 0?n.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=n.versioningHash??this._config.defaultHashFn??un;let s=n.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?dn(s,this._cached===void 0?void 0:this._cached,{id:n.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(rr);let o={};for(let[a,d]of Object.entries(n.meta??{})){let u={initial:d,name:`${n.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};n.guard!=null&&(u.guard=n.guard),o[a]=new r([],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([[D,a]])},down(a){i._emit(Dt(a))},up(a){i._emitUp(Dt(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,t){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 n=this._versioningLevel;if(n!=null&&e<=n)return;let s=t?.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??t?.id,d=i?.version??0,u=dn(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 t=St(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let n of this._extraGuards)if(!n(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,n=e?.actor!=null;if(!t&&!n)return;let s=St(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new Se({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new Se({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:xe()}}down(e,t){let n=Dt(e);n.length!==0&&(this._checkGuard(t),this._emit(n))}emit(e,t){this._checkGuard(t),this._emit([[D,e]])}up(e,t){if(this._deps.length===0)return;let n=Dt(e);if(n.length===0)return;this._checkGuard(t);let s=t??{internal:!0};this._validateUpTiers(n);for(let o of this._deps)o.node.up?.(n,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let n of e){let s=t(n[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,t){if(t!=null&&this._guard!=null){let d=St(t);if(!this._guard(d,"observe"))throw new Se({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)cn(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[t]=this._sinks;this._sinks=t}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,t=0;try{for(let n=0;n<e;n++){let s=n,o=this._deps[n];o.unsub=tr,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()}),t++}}catch(n){this._deps[t].unsub=null;for(let s=0;s<t;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}cn(o)}}throw this._dirtyDepCount=0,n}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let t=this._deps.length,n=rr(e);if(this._deps.push(n),this._sinks==null)return t;n.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rt),n.unsub=tr;try{n.unsub=e.subscribe(s=>{if(n.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:t},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw n.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(n){this._emit([[I,this._wrapFnError("cleanup threw",n)]])}else if(t!=null&&typeof t=="object"){let n=t.deactivate;if(typeof n=="function")try{n()}catch(s){this._emit([[I,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let n of this._deps){if(n.unsub!=null){let s=n.unsub;n.unsub=null;try{s()}catch{}}cn(n)}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,t){let n=this._deps[e],s=t[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:t};for(let i of this._inspectorHooks)i(o)}if(s!==$e){if(s===Q){this._depDirtied(n);return}if(s===Re){if(this._depInvalidated(n),this._cached===void 0)return;this._emit(tn);return}if(s===De||s===Ve){this._emit([t]);return}if(s===pe){this._emit(Ot);return}if(s===D)this._depSettledAsData(n,t[1]);else if(s===W)this._depSettledAsResolved(n);else if(s===$)this._depSettledAsTerminal(n,!0);else if(s===I)this._depSettledAsTerminal(n,t[1]);else{this._emit([t]);return}if(!this._fn){(s===D||s===W)&&this._emit([t]),(s===$||s===I)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Rt))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,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 t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(en),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[I,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(nn)}_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([[I,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([[I,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let t=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),n=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=t[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:n,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:t,prevData:n};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(t,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([[I,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>nr?(this._rerunDepth=0,this._emit([[I,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${nr} \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,t){let n=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${n}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[Be,e[0]]:e;let n=!0,s=!1,o=!1,i=-1;for(let d of e){let u=t(d[0]);u<i&&(n=!1),u===3&&(s=!0),d[0]===Q&&(o=!0),i=u}let a=e;if(!n){let d=e.map((u,c)=>({m:u,i:c,tier:t(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&&t(a[d][0])===0;)d++;return d===0?[Be,...a]:[...a.slice(0,d),Be,...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]===I&&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 t=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===pe||d[0]===Re);if(a.length===0)return;t=a}t=this._frameBatch(t);let s=null;for(let a=0;a<t.length;a++){let d=t[a],u=d[0];if(u!==De&&u!==Ve){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===De?"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===De)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 l=this._pauseBuffer;this._pauseBuffer=[],this._emit(l)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(d):s==null&&(s=t.slice(0,a))}if(s!=null){if(s.length===0)return;t=s}if(this._hasMeta&&t.some(a=>a[0]===pe))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Ot)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(t);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([[I,i]])}_updateState(e){let t=this._config.tierOf,n,s,o=-1,i=0;for(let c of e)t(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]===D){d=c;break}}for(let c=0;c<e.length;c++){let p=e[c],l=p[0];if(l===D){if(p.length>=2){let h=!1;if(a&&this._cached!==void 0)try{h=this._equals(this._cached,p[1])}catch(f){s=this._wrapFnError("equals threw",f),o=c;break}if(h){n==null&&(n=e.slice(0,c)),n.push(Et),this._status="resolved";continue}this._cached=p[1],this._versioning!=null&&(d<0||c===d)&&Zn(this._versioning,p[1],this._hashFn)}this._status="settled",n?.push(p)}else if(n?.push(p),l===Q)this._status="dirty";else if(l===W)this._status="resolved";else if(l===$){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(l===I){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(l===Re){if(this._cached!==void 0){let f=this._config.rigorRecorder;if(f!=null)try{f.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 f=h.invalidate;if(typeof f=="function")try{f()}catch{}}}else l===pe&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?n??e.slice(0,o):n??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 t=[...this._sinks];for(let n of t)n(e)};_dispatchOrAccumulate(e){if(Wn()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],et(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}mt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);mt(this._deliverToSinks,t,this._config.tierOf)}},or=r=>Array.isArray(r),ln=r=>typeof r=="object"&&r!=null&&!Array.isArray(r)});function V(r,e){return ee([],{...e,initial:r})}function ue(r,e){return ee((n,s,o)=>r(s,o)??void 0,{describeKind:"producer",...e})}function G(r,e,t){return ee(r,(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",...t})}function he(r,e,t){return ee(r,(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",...t})}var te=_e(()=>{"use strict";Ie()});function fn(r){return{describeKind:"producer",...r}}function sr(r,e){return ue(t=>{let n=!1;try{for(let s of r){if(n)return;t.emit(s)}n||t.down([[$]])}catch(s){n||t.down([[I,s]])}return()=>{n=!0}},fn(e))}function ao(r){return r!=null&&typeof r.then=="function"}function uo(r,e){let{signal:t,...n}=e??{};return ue(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[I,t.reason]]))};if(t?.aborted){i();return}return t?.addEventListener("abort",i,{once:!0}),Promise.resolve(r).then(a=>{o||(o=!0,t?.removeEventListener("abort",i),s.emit(a),s.down([[$]]))},a=>{o||(o=!0,t?.removeEventListener("abort",i),s.down([[I,a]]))}),()=>{o=!0,t?.removeEventListener("abort",i)}},fn(n))}function co(r,e){let{signal:t,...n}=e??{};return ue(s=>{let o=new AbortController,i=()=>o.abort(t?.reason);t?.aborted?o.abort(t.reason):t?.addEventListener("abort",i,{once:!0});let a=t??o.signal,d=!1,u=r[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([[I,p]])})};return c(),()=>{d=!0,t?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},fn(n))}function lo(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"}function Ae(r,e){if(lo(r))return r;if(ao(r))return uo(r,e);if(r!=null){let t=r;if(typeof t[Symbol.asyncIterator]=="function")return co(r,e);if(typeof t[Symbol.iterator]=="function")return sr(r,e)}return fo(r)}function fo(...r){return sr(r,void 0)}function ir(r,e){let t=new AbortController,n=e?.reason??new Error("cancelled via nodeSignal"),s,o=!1,i=()=>{s?(s(),s=void 0):o=!0};return s=r.subscribe(a=>{if(!t.signal.aborted)for(let d of a){if(d[0]===D&&d[1]===!0){t.abort(n),i();return}if(d[0]===I){t.abort(d[1]),i();return}if(d[0]===$){i();return}}}),o&&(s?.(),s=void 0),{signal:t.signal,dispose:()=>{s&&(s(),s=void 0)}}}function de(r){return r.subscribe(()=>{})}var ar=_e(()=>{"use strict";be();te()});var Pe=_e(()=>{"use strict";ar()});function Mt(r,e){if(e!=null&&e.length>0)return new Set(e);switch(r){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function vo(r){return r._describeKind!=null?r._describeKind:r._deps.length>0?"derived":r._fn!=null?"producer":"state"}function Ke(r){let e=new WeakSet,t={};for(let[n,s]of dr(r))t[n]=pn(s,e);return t}function pn(r,e){if(r==null)return r;let t=typeof r;if(t==="boolean"||t==="number"||t==="string")return r;if(t==="function")return"<function>";if(Array.isArray(r))return e.has(r)?"<cycle>":(e.add(r),r.map(n=>pn(n,e)));if(t==="object"){let n=r;if(e.has(n))return"<cycle>";e.add(n);try{if(typeof n.subscribe=="function"&&"cache"in n)return"<Node>"}catch{return"<unserializable>"}let s={};for(let[o,i]of dr(n))s[o]=pn(i,e);return s}return"<unserializable>"}function dr(r){let e=[],t;try{t=Object.keys(r)}catch{return e}for(let n of t)try{e.push([n,r[n]])}catch{e.push([n,"<unserializable>"])}return e}function We(r,e){let t={factory:r};return e!==void 0&&(t.factoryArgs=e),t}function To(r){let e={};for(let[t,n]of Object.entries(r.meta))try{e[t]=n.cache}catch{}return e}function hn(r,e,t){let n=e==null,s=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||s!=null&&s.length>0,i="state",a=[];r instanceof oe&&(i=vo(r),a=r._deps.map(c=>c.node.name??""));let d={type:i,deps:a};(n||e.has("status"))&&(d.status=r.status);let u=r instanceof oe?r._guard:void 0;if(o){let c={...To(r)};if(u!=null&&c.access===void 0&&(c.access=sn(u)),s!=null&&s.length>0&&!e.has("meta")){let p={};for(let l of s)l in c&&(p[l]=c[l]);d.meta=p}else d.meta=c}if(r.name!=null&&(d.name=r.name),(n||e.has("value"))&&(!t||i==="state")){r.status==="sentinel"&&(d.sentinel=!0);try{d.value=r.cache}catch{}}if((n||e.has("v"))&&r.v!=null){let c={id:r.v.id,version:r.v.version};"cid"in r.v&&(c.cid=r.v.cid,c.prev=r.v.prev),d.v=c}return(n||e.has("guard"))&&u!=null&&(d.guard=sn(u)),(n||e.has("lastMutation"))&&r.lastMutation!=null&&(d.lastMutation=r.lastMutation),d}var rt=_e(()=>{"use strict";tt();Ie()});var Ft,fr=_e(()=>{"use strict";Ft=class{_timer;_gen=0;start(e,t){this.cancel(),this._gen+=1;let n=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,n===this._gen&&t()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var bt,pr=_e(()=>{"use strict";bt=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 t=(this.head+this._size)%this.capacity;this.buf[t]=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 t=e<0?this._size+e:e;if(!(t<0||t>=this._size))return this.buf[(this.head+t)%this.capacity]}toArray(){let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this.buf[(this.head+t)%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}}});function ze(r,e,t){return{[r]:!0,[`${r}_type`]:e,...t??{}}}var yt=_e(()=>{"use strict"});var _s={};Wr(_s,{DEFAULT_DECAY_RATE:()=>it,DEFAULT_EXECUTE_PROMPT:()=>bn,DEFAULT_QUEUE_CONFIGS:()=>Pt,DEFAULT_SEVERITY_WEIGHTS:()=>st,DEFAULT_TRIAGE_PROMPT:()=>gn,DEFAULT_VERIFY_PROMPT:()=>yn,HarnessGraph:()=>Jt,QUEUE_NAMES:()=>Ne,actuatorExecutor:()=>ur,affectedTaskFilter:()=>Ro,autoSolidify:()=>yo,beforeAfterCompare:()=>ko,codeChangeBridge:()=>Oo,createIntakeBridge:()=>xo,defaultErrorClassifier:()=>Lt,defaultLlmExecutor:()=>jr,defaultLlmVerifier:()=>zr,dispatchActuator:()=>bo,effectivenessTracker:()=>Co,evalIntakeBridge:()=>No,evalSource:()=>Eo,evalVerifier:()=>Or,harnessEvalPair:()=>as,harnessLoop:()=>ms,harnessProfile:()=>bs,harnessTrace:()=>vs,notifyEffect:()=>So,priorityScore:()=>ps,refineExecutor:()=>Cn,resolvePromptFn:()=>gt,strategyKey:()=>at,strategyModel:()=>Vn});module.exports=Yr(_s);be();te();Pe();function po(r,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${go(e.summary)}`,artifact:r}}function ho(r,e){let t=r instanceof Error?r.message:String(r);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${t}`}}function mo(r){return`actuator skipped ${r.intervention} (shouldApply returned false)`}function go(r,e=80){return r.length<=e?r:`${r.slice(0,e-1)}\u2026`}function ur(r){let e=r.name??"actuator-executor",t=r.toOutput??po,n=r.onError??ho,s=r.skipDetail??mo;return o=>{let i=o.payload.item;return r.shouldApply&&!r.shouldApply(i)?{...o.payload,execution:{item:i,outcome:"failure",detail:s(i)}}:ue(a=>{let d=new AbortController,u=!1,c=null,p=h=>{u||(u=!0,a.down([[D,{...o.payload,execution:{item:i,...h}}],[$]]),c?.(),c=null)},l;try{let h=r.apply(i,{signal:d.signal});l=Ae(h,{signal:d.signal})}catch(h){return p(n(h,i)),()=>{d.abort()}}return c=l.subscribe(h=>{for(let f of h){if(u)return;if(f[0]===D){p(t(f[1],i));return}if(f[0]===I){p(n(f[1],i));return}if(f[0]===$){p(n(new Error("actuator inner completed without emitting DATA"),i));return}}}),u&&c&&(c(),c=null),()=>{d.abort(),c?.(),c=null}},{name:`${e}/inner`})}}function bo(r){let e=r.name??"dispatch-actuator",t=r.default??null,n=t!=null;return ur({apply:(s,o)=>{let i=Object.hasOwn(r.routes,s.intervention)?r.routes[s.intervention]:t;if(!i)throw new Error(`dispatchActuator: no route for intervention '${s.intervention}'`);return i(s,o)},shouldApply:s=>Object.hasOwn(r.routes,s.intervention)||n,skipDetail:s=>`no route for intervention '${s.intervention}'`,name:e})}be();te();function yo(r){let e=r.name??"auto-solidify",t=r.extract??(s=>s.execution.artifact??null),n=r.predicate??(()=>!0);return ue(s=>{let o=null,i=!1,a=()=>{i||(i=!0,o?.(),o=null)},d=u=>{i||(s.down([[I,u]]),a())};return o=r.verifyResults.subscribe(u=>{if(!i)for(let c of u){if(i)return;if(c[0]!==D){if(c[0]===$){s.down([[$]]),a();return}continue}let p=c[1];if(p==null||!p.verified)continue;let l;try{l=n(p)}catch(f){d(f);return}if(!l)continue;let h;try{h=t(p)}catch(f){d(f);return}if(h!=null){try{r.write(h,p)}catch(f){d(f);return}s.down([[D,h]])}}}),i&&o&&(o(),o=null),()=>{a()}},{name:e})}te();be();rt();Ie();te();Pe();function It(r){return{describeKind:"derived",...r}}function _o(r){return{describeKind:"derived",partial:!0,...r}}function Gt(r,e,t){return ee([r],(n,s)=>{let o=n[0];if(o==null||o.length===0){s.down([[W]]);return}let i=!1;for(let a of o)e(a)&&(s.emit(a),i=!0);i||s.down([[W]])},{...It(t),meta:{...We("filter"),...t?.meta??{}}})}function mn(r,e,t){return ee([r,e],(n,s,o)=>{let i=n[0],a=n[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([[W]]);return}for(let u of i)s.emit([u,d])}else s.down([[W]])},{..._o(t),meta:{...We("withLatestFrom"),...t?.meta??{}}})}function cr(...r){return r.length===0?ue(e=>{e.down([[$]])},{...It(),meta:{...We("merge")}}):ue(e=>{let t=r.length,n=0,s=[];for(let o of r){let i=o.subscribe(a=>{for(let d of a)d[0]===D?e.emit(d[1]):d[0]===$?(n+=1,n>=t&&e.down([[$]])):d[0]===I&&e.down([d])});s.push(i)}return()=>{for(let o of s)o()}},{...It(),meta:{...We("merge")}})}function wo(r,e,t){let n,s=!1,o=()=>{s||(s=!0,t())};return n=r.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==$e&&(u[0]===D?e.emit(u[1]):u[0]===$?a=!0:u[0]===I?(d=!0,e.down([u])):(u[0]===Q||u[0]===W)&&e.down([u]));d?(n?.(),n=void 0,o()):a&&o()}),()=>{n?.(),n=void 0}}function ot(r,e,t){let n,s=!1;function o(){n?.(),n=void 0}return ee([r],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){o();return}if(d.terminalDeps[0]===!0){s=!0,n||a.down([[$]]);return}let u=i[0];if(!(u==null||u.length===0))return o(),n=wo(Ae(e(u[u.length-1])),a,()=>{o(),s&&a.down([[$]])}),{deactivate:()=>{o(),s=!1}}},{...It(t),completeWhenDepsComplete:!1,meta:{...We("switchMap"),...t?.meta??{}}})}Pe();function xo(r,e,t,n){return he([r],([s])=>{if(s==null)return;let o=t(s);for(let i of o)e.publish(i)},{name:n?.name??"intake-bridge"})}function No(r,e,t){let n=t?.defaultSeverity??"medium";return he([r],([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:n});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:n})}},{name:t?.name??"eval-intake-bridge"})}function Eo(r,e){return ot(r,()=>Ae(e()))}function ko(r,e){return G([r,e],([t,n])=>{let s=t,o=n,i=new Map(s.tasks.map(l=>[l.task_id,l])),a=new Map(o.tasks.map(l=>[l.task_id,l])),d=new Set([...i.keys(),...a.keys()]),u=[],c=[],p=[];for(let l of d){let h=i.get(l),f=a.get(l),b=h?.valid??!1,m=f?.valid??!1,T=h?.judge_scores?h.judge_scores.filter(_=>_.pass).length:void 0,v=f?.judge_scores?f.judge_scores.filter(_=>_.pass).length:void 0,g=T!==void 0&&v!==void 0?v-T:void 0;u.push({taskId:l,before:b,after:m,scoreDiff:g}),b&&!m&&c.push(l),!b&&m&&p.push(l)}return{newFailures:c,resolved:p,taskDeltas:u,overallImproved:p.length>c.length}},{name:"eval-delta"})}function Ro(r,e){let t=e==null?null:Array.isArray(e)?V(e):e,n=[r];return t&&n.push(t),G(n,s=>{let o=s[0],i=t?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 Oo(r,e,t,n){let s=n?.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=t??o;return he([r],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:n?.name??"code-change-bridge"})}function So(r,e,t){return he([r.latest],([n])=>{n!=null&&e(n)},{name:t?.name??"notify-effect"})}var Ne=["auto-fix","needs-decision","investigation","backlog"],Pt={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},st={critical:100,high:70,medium:40,low:10},it=Math.LN2/(168*3600);function at(r,e){return`${r}\u2192${e}`}var Ao=/\b(parse|json|config|validation|syntax)\b/i,Lt=r=>Ao.test(r.detail)?"self-correctable":"structural",gn=`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
  {
@@ -13,7 +13,7 @@ Strategy model (past effectiveness):
13
13
  {{strategy}}
14
14
 
15
15
  Intake item:
16
- {{item}}`,hn=`You are an implementation agent.
16
+ {{item}}`,bn=`You are an implementation agent.
17
17
 
18
18
  Given a triaged issue with root cause and intervention type, produce a fix.
19
19
 
@@ -24,7 +24,7 @@ Output JSON:
24
24
  {
25
25
  "outcome": "success" | "failure" | "partial",
26
26
  "detail": "<description of what was done or what failed>"
27
- }`,mn=`You are a QA reviewer.
27
+ }`,yn=`You are a QA reviewer.
28
28
 
29
29
  Given an execution result, verify whether the fix is correct.
30
30
 
@@ -39,8 +39,8 @@ Output JSON:
39
39
  "verified": true/false,
40
40
  "findings": ["<finding1>", ...],
41
41
  "errorClass": "self-correctable" | "structural" // only if verified=false
42
- }`;function bt(r,e,t){if(typeof r=="function")return r;let n=r??e;return s=>t(n,s)}oe();Ie();Ne();ge();oe();var gn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:t,defaultTtl:n}=e;if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(n!==void 0&&n<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=t,this._defaultTtl=n}get version(){return this._version}get size(){return this._store.size}has(e){let t=this._store.get(e);return t===void 0?!1:this._isExpired(t)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,t),!0)}get(e){let t=this._store.get(e);if(t!==void 0){if(this._isExpired(t)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,t),t.value}}set(e,t,n){let s=this._resolveExpiresAt(n);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:t,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(e,t){let n=this._resolveExpiresAt(t),s=0;try{for(let[o,i]of e)this._store.has(o)&&this._store.delete(o),this._store.set(o,{value:i,expiresAt:n}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let t=this._store.delete(e);return t&&(this._version+=1),t}deleteMany(e){let t=0;try{for(let n of e)this._store.delete(n)&&(t+=1)}finally{t>0&&(this._version+=1)}return t}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=K(),t=0;for(let[n,s]of this._store)this._isExpired(s,e)&&(this._store.delete(n),t+=1);return t>0&&(this._version+=1),t}toMap(){let e=K(),t=new Map;for(let[n,s]of this._store)this._isExpired(s,e)||t.set(n,s.value);return t}_resolveExpiresAt(e){let t=e??this._defaultTtl;if(t!==void 0){if(!Number.isFinite(t)||t<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${t})`);return K()+t*1e9}}_isExpired(e,t){return e.expiresAt===void 0?!1:(t??K())>=e.expiresAt}_touchLru(e,t){this._store.delete(e),this._store.set(e,t)}_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 it(r={}){let{name:e,maxSize:t,defaultTtl:n,versioning:s,backend:o,retention:i}=r;if(i&&t!==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 gn({maxSize:t,defaultTtl:n}),u=L(a.toMap(),{name:e,describeKind:"state",equals:(l,h)=>l===h,...s!=null?{versioning:s}:{}});function d(){let l=a.toMap();te(()=>{u.down([[ee]]),u.down([[C,l]])})}function c(){if(!i)return;let l=a.toMap(),h=i.archiveThreshold,f=i.maxSize,g=[];for(let[T,y]of l)g.push({key:T,value:y,score:i.score(T,y)});g.sort((T,y)=>T.score-y.score);let m=new Set;if(h!==void 0)for(let T of g)if(T.score<h)m.add(T.key);else break;if(f!==void 0&&g.length-m.size>f)for(let T of g){if(g.length-m.size<=f)break;m.has(T.key)||m.add(T.key)}if(m.size!==0)for(let T of g)m.has(T.key)&&(i.onArchive?.(T.key,T.value,T.score),a.delete(T.key))}function p(l,h="mutation"){let f=a.version;try{return l()}finally{a.version!==f&&(h==="mutation"&&c(),d())}}return{entries:u,has(l){return p(()=>a.has(l),"read")},get(l){return p(()=>a.get(l),"read")},set(l,h,f){p(()=>a.set(l,h,f?.ttl))},setMany(l,h){p(()=>a.setMany(l,h?.ttl))},delete(l){p(()=>a.delete(l))},deleteMany(l){p(()=>a.deleteMany(l))},clear(){p(()=>a.clear())},pruneExpired(){p(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}$e();function ko(r){let e=it({name:r?.name??"effectiveness-entries"}),t=I([e.entries],([i])=>new Map(i),{name:`${r?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,p]of u){let l=d.get(c);if(!l||p.attempts!==l.attempts||p.successes!==l.successes)return!1}return!0}});function n(i,a){let u=e.get(i),d=(u?.attempts??0)+1,c=(u?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:d,successes:c,successRate:c/d})}function s(i){return e.get(i)}let o=ye(t);return{node:t,record:n,lookup:s,dispose:()=>{o(),e.dispose()}}}oe();oe();Ie();Ne();ge();De();oe();At();Ie();Ne();et();ge();mt();De();oe();Ne();function bn(r,e){if(Object.is(r,e))return!0;if(r==null||e==null||typeof r!="object"||typeof e!="object")return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let o=0;o<r.length;o++)if(!bn(r[o],e[o]))return!1;return!0}if(Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;let s=new Set(n);for(let o of t)if(!s.has(o)||!bn(r[o],e[o]))return!1;return!0}function ir(r,e){return`${r}\0${e}`}function yn(r,e){let t=[],n=new Set(r.subgraphs),s=new Set(e.subgraphs),o=[];for(let m of s)n.has(m)||o.push(m);o.sort();for(let m of o)t.push({type:"subgraph-mounted",path:m});let i=new Set(Object.keys(r.nodes)),a=new Set(Object.keys(e.nodes)),u=[];for(let m of a)i.has(m)||u.push(m);u.sort();for(let m of u)t.push({type:"node-added",path:m,node:{...e.nodes[m]}});let d=[];for(let m of a){if(!i.has(m))continue;let T=r.nodes[m]?.meta,y=e.nodes[m]?.meta;T==null&&y==null||bn(T??{},y??{})||d.push(m)}d.sort();for(let m of d)t.push({type:"node-meta-changed",path:m,prevMeta:r.nodes[m]?.meta??{},nextMeta:e.nodes[m]?.meta??{}});let c=new Map;for(let m of r.edges)c.set(ir(m.from,m.to),m);let p=new Map;for(let m of e.edges)p.set(ir(m.from,m.to),m);let l=[];for(let[m,T]of p)c.has(m)||l.push(T);l.sort((m,T)=>m.from<T.from?-1:m.from>T.from?1:m.to<T.to?-1:m.to>T.to?1:0);for(let m of l)t.push({type:"edge-added",from:m.from,to:m.to});let h=[];for(let[m,T]of c)p.has(m)||h.push(T);h.sort((m,T)=>m.from<T.from?-1:m.from>T.from?1:m.to<T.to?-1:m.to>T.to?1:0);for(let m of h)t.push({type:"edge-removed",from:m.from,to:m.to});let f=[];for(let m of i)a.has(m)||f.push(m);f.sort();for(let m of f)t.push({type:"node-removed",path:m});let g=[];for(let m of n)s.has(m)||g.push(m);g.sort();for(let m of g)t.push({type:"subgraph-unmounted",path:m});return{events:t,flushedAt_ns:K()}}$e();ar();ur();tn();function dr(r,e,t,n={}){let s=e in r.nodes,o=t in r.nodes;if(!s)return Lt(e,t,"no-such-from");if(!o)return Lt(e,t,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===t){if(n.findCycle===!0){let d=Ro(r,e,n);if(d!=null)return d}let u=Ft(e,r.nodes[e],0,n);return $t(e,t,[u])}if(i===0)return Lt(e,t,"no-path");let a=cr(r,e,t,i);return a.found?$t(e,t,lr(r,a.pathOrder,n)):Lt(e,t,a.truncated?"max-depth-exceeded":"no-path")}function cr(r,e,t,n){let s=new Map,o=[{path:t,depth:0}],i=new Set([t]),a=0,u=!1;for(;a<o.length;){let p=o[a++];if(p.path===e)break;if(n!=null&&p.depth>=n){let g=r.nodes[p.path];g?.deps&&g.deps.length>0&&(u=!0);continue}let l=r.nodes[p.path];if(l==null)continue;let h=l.deps??[],f=new Map;for(let g=0;g<h.length;g++){let m=h[g];if(!m)continue;let T=f.get(m);T==null&&(T=[],f.set(m,T)),T.push(g)}for(let[g,m]of f)i.has(g)||(i.add(g),s.set(g,{from:p.path,depIndices:m}),o.push({path:g,depth:p.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:u};let d=[{path:e}],c=e;for(;c!==t;){let p=s.get(c);if(p==null)return{found:!1,pathOrder:[],truncated:!1};d[d.length-1].depIndices=p.depIndices,d.push({path:p.from}),c=p.from}return{found:!0,pathOrder:d,truncated:!1}}function Ro(r,e,t){let n=r.nodes[e];if(n==null)return null;let s=n.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=Ft(e,n,0,t);a.dep_index=o[0];let u=Ft(e,n,1,t);return $t(e,e,[a,u])}let i=null;for(let a=0;a<s.length;a++){let u=s[a];if(!u||u===e)continue;let d=cr(r,u,e,t.maxDepth);d.found&&(i==null||d.pathOrder.length<i.pathOrder.length)&&(i=d,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...d.pathOrder],truncated:!1})}return i==null?null:$t(e,e,lr(r,i.pathOrder,t))}function lr(r,e,t){return e.map((n,s)=>{let o=r.nodes[n.path],i=Ft(n.path,o,s,t);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function Ft(r,e,t,n){let s={path:r,type:e.type,hop:t};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=n.annotations?.get(r)??e.annotation;o!=null&&(s.annotation=o);let i=n.lastMutations?.get(r)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function $t(r,e,t){return fr(r,e,!0,"ok",t)}function Lt(r,e,t){return fr(r,e,!1,t,[])}function fr(r,e,t,n,s){let o=Oo(r,e,t,n,s);return{from:r,to:e,found:t,reason:n,steps:s,text:o,toJSON(){return{from:r,to:e,found:t,reason:n,steps:s}}}}function Oo(r,e,t,n,s){if(!t)switch(n){case"no-such-from":return`explainPath: no node named "${r}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${r}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${r}" to "${e}"`}let o=[`Causal path: ${r} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let u=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(u),"value"in i&&o.push(` value: ${So(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let d=i.lastMutation.actor;o.push(` actor: ${d.type}${d.id?`:${d.id}`:""}`)}}return o.join(`
43
- `)}function So(r){if(r===void 0)return"<sentinel>";if(r===null)return"null";if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(r)}}De();var se={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},Ao=Symbol.for("sizeof");function pr(r){let e=new WeakSet,t=new WeakSet,n=[r],s=0;for(;n.length>0;){let o=n.pop();s+=Do(o,e,t,n)}return s}function Do(r,e,t,n){if(r==null)return 0;switch(typeof r){case"number":return se.number;case"boolean":return se.boolean;case"string":return se.string+r.length*2;case"bigint":return se.bigint+Co(r);case"symbol":return se.symbol;case"function":return e.has(r)?0:(e.add(r),se.function);case"undefined":return 0}let o=r;if(e.has(o))return 0;e.add(o);let i=o[Ao];if(typeof i=="function")try{let d=i.call(o);if(typeof d=="number"&&Number.isFinite(d))return d}catch{}if(o instanceof Date)return se.date;if(o instanceof RegExp)return se.regexp+o.source.length*2;if(o instanceof Error){let d=o.message?o.message.length*2:0,c=o.stack?o.stack.length*2:0;return se.error+d+c}if(typeof URL<"u"&&o instanceof URL)return se.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return se.promise;if(o instanceof WeakMap)return se.weakmap;if(o instanceof WeakSet)return se.weakset;if(o instanceof Map){let d=se.map;for(let[c,p]of o)d+=se.mapEntry,n.push(c),n.push(p);return d}if(o instanceof Set){let d=se.set;for(let c of o)d+=se.setEntry,n.push(c);return d}if(Array.isArray(o)){let d=se.array+o.length*8;for(let c of o)n.push(c);return d}if(o instanceof ArrayBuffer)return t.has(o)?0:(t.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let d=o;return t.has(d.buffer)?48:(t.add(d.buffer),d.buffer.byteLength+48)}let a=se.object,u=Object.keys(o);for(let d of u){a+=se.string+d.length*2;try{n.push(o[d])}catch{}}return a}function Co(r){let e=r<0n?-r:r;if(e===0n)return 0;let t=e.toString(2).length;return Math.ceil(t/32)*8}function Vt(r,e){let t=e?.topN??10,n=r.describe({detail:"standard"}),s=[],o=r._collectObserveTargets;typeof o=="function"&&o.call(r,"",s);let i=new Map;for(let[l,h]of s)i.set(l,h);let a=[];for(let[l,h]of Object.entries(n.nodes)){let f=i.get(l),g=f instanceof re?f:null,m=g?pr(g.cache):0,T=g?g._sinkCount:0,y=h.deps?.length??0,v=h.type==="effect"&&T===0,_=T===0?h.type==="effect"?"orphan-effect":h.type==="derived"?"idle-derived":h.type==="producer"?"idle-producer":null:null;a.push({path:l,type:h.type,status:h.status??"unknown",valueSizeBytes:m,subscriberCount:T,depCount:y,isOrphanEffect:v,orphanKind:_})}let u=a.reduce((l,h)=>l+h.valueSizeBytes,0),d=(l,h)=>[...a].sort(h??((f,g)=>g[l]-f[l])).slice(0,t),c=a.filter(l=>l.orphanKind!=null),p=a.filter(l=>l.isOrphanEffect);return{nodeCount:a.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:a,totalValueSizeBytes:u,hotspots:{byValueSize:d("valueSizeBytes"),bySubscriberCount:d("subscriberCount"),byDepCount:d("depCount")},orphans:c,orphanEffects:p}}var X="::",Re="__meta__",We=1;function hr(r,e){let t=Math.max(16,r.size*4),n=0;for(;r.size>0;){if(n++>=t){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${t}); ${r.size} disposer(s) discarded`),r.clear();return}let s=r.values().next();if(s.done)return;let o=s.value;r.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function vr(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function Mo(r){if(r!=null)return vr(r)?r.cache:r}function Je(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function je(r){return Je(r)?r.cache??"":r}function mr(r){return Je(r)?r.cache??0:r}function gr(r){return Je(r)?r.cache??!1:r}function Io(r){let e=[];for(let t of Object.keys(r).sort()){let n=r[t].v;n!=null&&e.push(`${t} ${n.id} ${n.version}`)}return e.join(`
44
- `)}function br(r){if(r.version!==We)throw new Error(`unsupported snapshot version ${String(r.version)} (expected ${We})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in r))throw new Error(`snapshot missing required key "${e}"`);if(typeof r.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof r.nodes!="object"||r.nodes===null||Array.isArray(r.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(r.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(r.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Go(r,e){let t=new WeakMap,n=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=t.get(s);if(i==null&&(i=new WeakSet,t.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,u=o.constructor;if(a!==u)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 l=o;if(s.length!==l.length)return!1;for(let h=0;h<s.length;h++)if(!n(s[h],l[h]))return!1;return!0}if(s instanceof Map){let l=o;if(s.size!==l.size)return!1;for(let[h,f]of s)if(!l.has(h)||!n(f,l.get(h)))return!1;return!0}if(s instanceof Set){let l=o;if(s.size!==l.size)return!1;for(let h of s){let f=!1;for(let g of l)if(n(h,g)){f=!0;break}if(!f)return!1}return!0}if(ArrayBuffer.isView(s)){let l=s,h=o;if(l.length!==h.length)return!1;for(let f=0;f<l.length;f++)if(l[f]!==h[f])return!1;return!0}let d=Object.keys(s),c=Object.keys(o);if(d.length!==c.length)return!1;let p=new Set(c);for(let l of d)if(!p.has(l)||!n(s[l],o[l]))return!1;return!0};return n(r,e)}function Po(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jt(r){let e="^";for(let t=0;t<r.length;t+=1){let n=r[t];if(n==="*"){e+=".*";continue}if(n==="?"){e+=".";continue}if(n==="["){let s=r.indexOf("]",t+1);if(s<=t+1){e+="\\[";continue}let o=r.slice(t+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,t=s;continue}e+=Po(n)}return e+="$",new RegExp(e)}var Lo={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"},Fo={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function vn(r){if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||r==null)return String(r);try{return JSON.stringify(r)}catch{return"[unserializable]"}}function $o(r){return r==="none"?Fo:r==="ansi"||r==null?Lo:{data:r.data??"",dirty:r.dirty??"",resolved:r.resolved??"",invalidate:r.invalidate??"",pause:r.pause??"",resume:r.resume??"",complete:r.complete??"",error:r.error??"",teardown:r.teardown??"",derived:r.derived??"",path:r.path??"",reset:r.reset??""}}function yr(r){if(r==null)return{};let e=r.detail;return e==="full"?{...r,structured:r.structured??!0,timeline:r.timeline??!0,causal:r.causal??!0,derived:r.derived??!0}:e==="minimal"?{...r,structured:r.structured??!0}:r.format==="stage-log"?{...r,structured:r.structured??!0,timeline:r.timeline??!0}:r}function Vo(r,e,t){for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);if(s<32||s===127)throw new Error(`Graph "${e}": ${t} "${r}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function Tn(r,e,t){if(r==="")throw new Error(`Graph "${e}": ${t} name must be non-empty`);if(r.includes(X))throw new Error(`Graph "${e}": ${t} "${r}" must not contain '${X}' (path separator)`);if(r===Re)throw new Error(`Graph "${e}": ${t} name "${Re}" is reserved for meta companion paths`);Vo(r,e,t)}function jo(r,e){if(r==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let t=r.split(X);for(let n of t)if(n==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return t}function zo(r,e){let t=!1;for(let s of r)if(!e.isMetaPassthrough(s[0])){t=!0;break}return t?r.filter(s=>e.isMetaPassthrough(s[0])):r}function Tr(r){for(let e of r._mounts.values())Tr(e);for(let e of r._nodes.values())try{e.down([[ue]],{internal:!0})}catch{}}var ce=class r{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;_factory;_factoryArgs;constructor(e,t){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(X))throw new Error(`Graph name must not contain '${X}' (got "${e}")`);if(e===Re)throw new Error(`Graph name "${Re}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??tt,this._traceRing=new yt(t?.traceCapacity??1e3),t?.versioning!=null&&this.setVersioning(t.versioning),typeof t?.factory=="string"&&(this._factory=t.factory,t.factoryArgs!==void 0&&(this._factoryArgs=t.factoryArgs))}tagFactory(e,t){return this._factory=e,this._factoryArgs=t,this}ancestors(e=!0){let t=[],n=e?this:this._parent;for(;n!=null;)t.push(n),n=n._parent;return t}get topology(){return this._topology==null&&(this._topology=de(e=>{let t=n=>{e.emit(n)};return this._topologyEmitters.add(t),()=>{this._topologyEmitters.delete(t)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let t of this._topologyEmitters)t(e)}nameOf(e){return this._nodeToName.get(e)}add(e,t){let n=e.name,s=t?.name??n;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=t?.annotation;if(Tn(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:K()})),e}setVersioning(e){if(e!=null)for(let t of this._nodes.values())t instanceof re&&t._applyVersioning(e)}remove(e){Tn(e,this.name,"remove");let t=this._mounts.get(e);if(t){let o={kind:"mount",nodes:[],mounts:[]},i=[];t._collectObserveTargets("",i);for(let[a,u]of i)a.includes(`${X}${Re}${X}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...t._collectSubgraphs(`${e}${X}`)),this._mounts.delete(e),t._parent=void 0,Tr(t),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(n),n.down([[ue]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let t=typeof e=="function"?e:(()=>{let o=jt(e);return i=>o.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>t(o));for(let o of s){let i=this.remove(o);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),t=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=e.length)return{value:void 0,done:!0};let s=e[n++];return{value:[s,t.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(X))return this.resolve(e);let t=this._nodes.get(e);if(!t)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return t}get(e){return this.node(e).cache}set(e,t,n){let s=n?.internal===!0;this.node(e).down([[C,t]],{actor:n?.actor,internal:s,delivery:"write"})}setAll(e,t){let n=Symbol.iterator in e?e:Object.entries(e);te(()=>{for(let[s,o]of n)this.set(s,o,t)})}invalidate(e,t){let n=t?.internal===!0;this.node(e).down([[xe]],{actor:t?.actor,internal:n,delivery:"write"})}error(e,t,n){let s=n?.internal===!0;this.node(e).down([[G,t]],{actor:n?.actor,internal:s,delivery:"write"})}complete(e,t){let n=t?.internal===!0;this.node(e).down([[j]],{actor:t?.actor,internal:n,delivery:"write"})}edges(e){let t=e?.recursive===!0,n=new Map;if(!t){for(let[u,d]of this._nodes)n.set(d,u);let a=[];for(let[u,d]of this._nodes)if(d instanceof re)for(let c of d._deps){let p=n.get(c.node);p!=null&&a.push([p,u])}return a.sort((u,d)=>u[0]<d[0]?-1:u[0]>d[0]?1:u[1]<d[1]?-1:u[1]>d[1]?1:0),a}let s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,u]of s)o.set(u,a);let i=[];for(let[a,u]of s)if(u instanceof re)for(let d of u._deps){let c=o.get(d.node);c!=null&&i.push([c,a])}return i.sort((a,u)=>a[0]<u[0]?-1:a[0]>u[0]?1:a[1]<u[1]?-1:a[1]>u[1]?1:0),i}mount(e,t){if(t===void 0){let s=new r(e);return this.mount(e,s)}if(typeof t=="function"){let s=new r(e);return t(s),this.mount(e,s)}let n=t;if(Tn(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 s=this;s!=null;s=s._parent)if(s===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 t=jo(e,this.name);return this._resolveFromSegments(t)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let t=e;if(t[0]===this.name&&(t=t.slice(1),t.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=t[0],s=t.slice(1);if(s.length===0){let a=this._nodes.get(n);if(a)return a;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let o=this._nodes.get(n);if(o&&s.length>0&&s[0]===Re)return this._resolveMetaChainFromNode(o,s,t.join(X));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${s.join(X)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(s.join(X))}_resolveMetaChainFromNode(e,t,n){let s=e,o=0,i=[...t];for(;o<i.length;){if(i[o]!==Re)throw new Error(`Graph "${this.name}": expected ${Re} segment in meta path "${n}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Re} in "${n}"`);let a=i[o+1],u=s.meta[a];if(!u)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${n}"`);s=u,o+=2}return s}signal(e,t){if(t?.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 n=[];if(this._signalDeliver(e,t??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(e,t,n,s){for(let u of this._mounts.values())u._signalDeliver(e,t,n,s);let i=t.internal===!0?{internal:!0}:{actor:t.actor,delivery:"signal"},a=zo(e,this.config);for(let u of[...this._nodes.keys()].sort()){let d=this._nodes.get(u);if(!n.has(d)){n.add(d);try{d.down(e,i)}catch(c){if(c instanceof Ee)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(d,a,n,i,s)}}}_signalMetaSubtree(e,t,n,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!n.has(a)){n.add(a);try{a.down(t,s)}catch(u){if(u instanceof Ee)throw u;o.push(u)}this._signalMetaSubtree(a,t,n,s,o)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let t=Mo(e?.actor),n=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let s=cn(e?.detail,e?.fields),o=e?.detail==="spec",i=s,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[_,w]of a)u.set(w,_);let d=[];{let _=a.map(([,b])=>b),w=new Set(u.values()),R=0;for(;_.length>0;){let b=_.shift();if(b instanceof re)for(let x of b._deps){let O=x.node;if(u.has(O))continue;let S=O.name??"",N=S;if(!N||w.has(N))if(S){let P=2;for(;w.has(`${S}#${P}`);)P++;N=`${S}#${P}`}else for(N=`__internal__/${R++}`;w.has(N);)N=`__internal__/${R++}`;u.set(O,N),w.add(N),d.push([N,O]),_.push(O)}}}let c=[...a,...d],p={};for(let[_,w]of c){if(t!=null&&!w.allowsObserve(t))continue;let R=ln(w,i,o),b=w instanceof re?w._deps.map(N=>u.get(N.node)??N.node.name??""):[],{name:x,...O}=R,S={...O,deps:b};if(!o){let N=this._annotations.get(_);N!=null&&(S.annotation=N)}if(n!=null)if(typeof n=="function"){let N=n;if(!(N.length>=2?N(_,S):N(S)))continue}else{let N=!0;for(let[P,B]of Object.entries(n)){let z=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(z==="depsIncludes"){if(!S.deps.includes(String(B))){N=!1;break}continue}if(z==="metaHas"){if(!Object.hasOwn(S.meta??{},String(B))){N=!1;break}continue}if(S[z]!==B){N=!1;break}}if(!N)continue}p[_]=S}let l=new Set(Object.keys(p)),h=[];for(let[_,w]of c)if(w instanceof re)for(let R of w._deps){let b=u.get(R.node);b!=null&&h.push([b,_])}h.sort((_,w)=>_[0]<w[0]?-1:_[0]>w[0]?1:_[1]<w[1]?-1:_[1]>w[1]?1:0);let f=h.map(([_,w])=>({from:_,to:w}));(t!=null||n!=null)&&(f=f.filter(_=>l.has(_.from)&&l.has(_.to)));let g=this._collectSubgraphs(""),m=t!=null||n!=null?g.filter(_=>{let w=`${_}${X}`;return[...l].some(R=>R===_||R.startsWith(w))}):g,T=this,y=e;return{name:this.name,nodes:p,edges:f,subgraphs:m,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(_){let w={...y};return Array.isArray(_)?(w.fields=_,w.detail=void 0):(w.detail=_,w.fields=void 0),T.describe(w)}}}_collectSubgraphs(e){let t=[];for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${n}`;t.push(s),t.push(...this._mounts.get(n)._collectSubgraphs(`${s}${X}`))}return t}resourceProfile(e){return Vt(this,e)}reachable(e,t,n={}){return n.withDetail===!0?_n(this.describe(),e,t,{...n,withDetail:!0}):_n(this.describe(),e,t,n)}explain(e,t,n){return n?.reactive===!0?this._explainReactive(e,t,n):this._explainStatic(je(e),je(t),{...n?.maxDepth!==void 0?{maxDepth:mr(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:gr(n.findCycle)}:{}})}_explainStatic(e,t,n){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,u]of Object.entries(s.nodes))u.lastMutation!=null&&i.set(a,u.lastMutation);return dr(s,e,t,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let t={...e,reactive:!1},n=e.reactiveName??"describe",s=0,o=L(s,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=()=>{a||u||(a=!0,Ze(()=>{a=!1,!u&&(s+=1,o.emit(s))}))},c=i.onEvent(y=>{let v=y.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||d()}),p=[],l=new WeakSet,h=y=>{if(l.has(y)||u)return;l.add(y);let v=y.topology.subscribe(_=>{for(let w of _){if(w[0]!==C)continue;let R=w[1];if(d(),R.kind==="added"&&R.nodeKind==="mount"){let b=y._mounts.get(R.name);b!=null&&h(b)}}});p.push(v);for(let _ of y._mounts.keys()){let w=y._mounts.get(_);w!=null&&h(w)}};h(this);let f,g=e.actor;vr(g)&&(f=g.subscribe(y=>{let v=!1,_=!1;for(let w of y){let R=w[0];R===C?v=!0:(R===j||R===G||R===ue)&&(_=!0)}v&&d(),_&&(f?.(),f=void 0,d())}));let m;try{m=I([o],()=>this.describe(t),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(y,v)=>y===v})}catch(y){c(),f?.();for(let v of p)v();throw i.dispose(),y}let T=ye(m);return{node:m,dispose(){u=!0,c(),f?.();for(let y of p)y();p.length=0,i.dispose(),T()}}}_describeReactiveDiff(e){let t={...e,reactive:!1},n=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},o=this.describe(t),i=yn(s,o),a=L(i,{name:n,meta:{domain:"audit",kind:"describe-diff"},equals:(l,h)=>l===h}),u=this._describeReactive({...e,reactiveName:void 0}),d=!1,c=u.node.subscribe(l=>{if(!d)for(let h of l){if(h[0]!==C)continue;let f=h[1],g=yn(o,f);o=f,g.events.length!==0&&a.emit(g)}}),p=ye(a);return{node:a,dispose(){d=!0,c(),u.dispose(),a.down([[ue,"describe-diff disposed"]]),p()}}}_explainReactive(e,t,n){let s=0,o=L(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=()=>{a||u||(a=!0,Ze(()=>{a=!1,!u&&(s+=1,o.emit(s))}))},c=i.onEvent(y=>{let v=y.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||d()}),p=[];e!=null&&Je(e)&&p.push(e),t!=null&&Je(t)&&p.push(t),n?.maxDepth!=null&&Je(n.maxDepth)&&p.push(n.maxDepth),n?.findCycle!=null&&Je(n.findCycle)&&p.push(n.findCycle);let l=()=>{for(let y of p)if(y.cache===void 0)return!1;return!0},h=()=>{let y=je(e),v=je(t);return{from:y,to:v,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:y,to:v,found:!1,reason:"pending",steps:[]})}},f;try{f=I([o],()=>{if(!l())return h();let y=je(e),v=je(t),_={...n?.maxDepth!==void 0?{maxDepth:mr(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:gr(n.findCycle)}:{}};return this._explainStatic(y,v,_)},{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:je(e),to:je(t)},equals:(y,v)=>y.found===v.found&&y.reason===v.reason&&y.steps.length===v.steps.length&&Bo(y.steps,v.steps)})}catch(y){throw c(),i.dispose(),y}let g=ye(f),m=[],T=y=>{let v;return v=y.subscribe(_=>{let w=!1,R=!1;for(let b of _){let x=b[0];x===C?w=!0:(x===j||x===G||x===ue)&&(R=!0)}(w||R)&&d(),R&&v&&(v(),v=void 0)}),()=>{v&&(v(),v=void 0)}};for(let y of p)m.push(T(y));return{node:f,dispose(){u=!0,c();for(let y of m)y?.();m.length=0,i.dispose(),g()}}}_pathsMatching(e){let t=jt(e),n=[];return this._collectObserveTargets("",n),n.map(([s])=>s).filter(s=>t.test(s))}_collectObserveTargets(e,t){for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${X}${n}`;this._mounts.get(n)._collectObserveTargets(s,t)}for(let n of[...this._nodes.keys()].sort()){let s=this._nodes.get(n),o=e===""?n:`${e}${X}${n}`;t.push([o,s]),this._appendMetaObserveTargets(o,s,t)}}_appendMetaObserveTargets(e,t,n){for(let s of Object.keys(t.meta).sort()){let o=t.meta[s],i=`${e}${X}${Re}${X}${s}`;n.push([i,o]),this._appendMetaObserveTargets(i,o,n)}}observe(e,t){let n=typeof e=="string",o=yr(n?t:e);if(o.reactive===!0)return this._observeReactive(n?e:void 0,o);let 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(n){let c=e,p=this.resolve(c);if(a!=null&&!p.allowsObserve(a))throw new Ee({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,p]],o,"one"):{subscribe(l){return p.subscribe(l)},up(l){try{p.up?.(l)}catch(h){if(h instanceof Ee)return;throw h}}}}let u=[];this._collectObserveTargets("",u),u.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0);let d=a==null?u:u.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(d,o,"all"):{subscribe:c=>{let p=d.map(([l,h])=>h.subscribe(f=>{c(l,f)}));return()=>{for(let l of p)l()}},up:(c,p)=>{try{this.resolve(c).up?.(p)}catch(l){if(l instanceof Ee)return;throw l}}}}_observeReactive(e,t){let n=t.tiers,s=n!=null?new Set(n):null,o=t.reactiveName??"observe";return de(i=>{let a=[],u=!1,d=!1,c=()=>{if(a.length===0||d)return;let g={events:a.slice(),flushedAt_ns:K()};a.length=0,i.emit(g)},p={...t,reactive:!1,structured:!0,timeline:!0},l=e!=null?this.observe(e,p):this.observe(p),h=g=>{d||(a.push(g),!u&&(u=!0,Ze(()=>{u=!1,c()})))};for(let g of l.events)h(g);let f=l.onEvent(h);return()=>{d=!0,f(),l.dispose()}},{name:o,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,t,n){let s=n==="one"?e[0]?.[0]:void 0,o=i=>{if(n==="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 u=i.actor,d=u==null?a:a.filter(([,c])=>c.allowsObserve(u));return this._buildStructuredObserver(d,i,"all")};return this._createObserveResult(e,t,o)}_createObserveResult(e,t,n){let s=t.timeline===!0,o=t.causal===!0,i=t.derived===!0,a=t.detail==="minimal",u=this.config.inspectorEnabled,d=(o||i)&&u,c=t.maxEvents,p=c!=null&&c>0?new yt(c):null,l=[],h=new Set,f=t.tiers!=null?new Set(t.tiers):null,g={},m=new Set,T=0,y=0,v=0,_=0,w=0,R=0,b=!1,x=!1,O=0,S=new Map,N=new Map,P=new Map,B=A=>{if(!(f!=null&&!f.has(A.type))){p?p.push(A):l.push(A);for(let U of h)U(A)}},z=A=>f==null||f.has(A),le=()=>s?{timestamp_ns:K(),in_batch:ft(),batch_id:O}:{},ae=(A,U)=>{if(!(!d||!(A instanceof re)))return A._setInspectorHook(pe=>{if(pe.kind==="dep_message")S.set(A,pe.depIndex);else if(pe.kind==="run"){let Se=pe.batchData.map((E,M)=>E!=null&&E.length>0?E.at(-1):pe.prevData[M]);N.set(A,Se);let he=pe.batchData.map(E=>E!=null?[...E]:void 0);P.set(A,he),i&&B({type:"derived",path:U,dep_values:Se,dep_batches:he,...le()})}})},Oe=A=>{let U=S.get(A),pe=N.get(A);if(!o||pe==null)return{};let he=(U!=null&&U>=0&&A instanceof re?A._deps[U]:void 0)?.node,E=he?.v,M=P.get(A);return{trigger_dep_index:U,trigger_dep_name:he?.name,...E!=null?{trigger_version:{id:E.id,version:E.version}}:{},dep_values:[...pe],...M!=null?{dep_batches:M}:{}}},Ce=[],$=[];for(let[A,U]of e){let pe=ae(U,A);pe&&Ce.push(pe),$.push(U.subscribe(Se=>{O++;for(let he of Se){let E=he[0],M=le();if(E===C){g[A]=he[1];let J=U instanceof re?U.lastMutation?.actor??Ye:Ye;B({type:"data",path:A,data:he[1],actor:J,...M,...Oe(U)})}else if(a)E===ee?z("dirty")&&T++:E===Q?z("resolved")&&y++:E===xe?z("invalidate")&&v++:E===Ae?z("pause")&&_++:E===Le?z("resume")&&w++:E===ue?z("teardown")&&R++:E===j&&!m.has(A)?z("complete")&&(b=!0):E===G&&z("error")&&(x=!0,m.add(A));else if(E===ee)z("dirty")&&T++,B({type:"dirty",path:A,...M});else if(E===Q)z("resolved")&&y++,B({type:"resolved",path:A,...M,...Oe(U)});else if(E===xe)z("invalidate")&&v++,B({type:"invalidate",path:A,...M});else if(E===Ae)z("pause")&&_++,B({type:"pause",path:A,lockId:he[1],...M});else if(E===Le)z("resume")&&w++,B({type:"resume",path:A,lockId:he[1],...M});else if(E===j)z("complete")&&!m.has(A)&&(b=!0),B({type:"complete",path:A,...M});else if(E===G){z("error")&&(x=!0,m.add(A));let J=U instanceof re?U.lastMutation?.actor??Ye:Ye;B({type:"error",path:A,data:he[1],actor:J,...M})}else E===ue&&(z("teardown")&&R++,B({type:"teardown",path:A,...M}))}}))}let V=!1,F=()=>{if(!V){V=!0;for(let A of $)A();for(let A of Ce)A();for(let A of Z)A({value:void 0,done:!0});Z.length=0}},ie=[],Z=[];h.add(A=>{let U=Z.shift();U?U({value:A,done:!1}):ie.push(A)});let fe={get values(){return g},get dirtyCount(){return T},get resolvedCount(){return y},get invalidateCount(){return v},get pauseCount(){return _},get resumeCount(){return w},get teardownCount(){return R},get events(){return p?p.toArray():[...l]},get anyCompletedCleanly(){return b},get anyErrored(){return x},get completedWithoutErrors(){return b&&!x},onEvent(A){return h.add(A),()=>h.delete(A)},dispose:F,expand(A){F();let U={...t};return typeof A=="string"?U.detail=A:Object.assign(U,A),n(yr(U))},[Symbol.asyncIterator](){return{next(){return ie.length>0?Promise.resolve({value:ie.shift(),done:!1}):V?Promise.resolve({value:void 0,done:!0}):new Promise(A=>Z.push(A))},return(){return F(),Promise.resolve({value:void 0,done:!0})}}}};return t.format!=null&&this._attachFormatLogger(fe,t),fe}_attachFormatLogger(e,t){let n=t.format;if(n==null)return;let s=t.logger??(f=>console.log(f)),o=t.includeTypes?new Set(t.includeTypes):null,i=t.excludeTypes?new Set(t.excludeTypes):null,a=o==null&&i==null?()=>!0:f=>(o==null||o.has(f))&&(i==null||!i.has(f)),u=$o(t.theme),d=n==="stage-log"?K():0,c=f=>f==null?"":t.stageLabels?.[f]??f,p=(f,g)=>f.length>g?`${f.slice(0,g-1)}\u2026`:f,l=f=>f.type==="data"||f.type==="error"?p(vn(f.data),120):"",h=f=>{if(n==="stage-log"){let b=(K()-d)/1e9,x=c(f.path).padEnd(9);if(f.type==="data"){let O=l(f);return`[${b.toFixed(3)}s] ${x} \u2190${O?` ${O}`:""}`}if(f.type==="error"){let O=l(f);return`[${b.toFixed(3)}s] ${x} \u2717${O?` ${O}`:""}`}return f.type==="complete"?`[${b.toFixed(3)}s] ${x} \u25A0 complete`:`[${b.toFixed(3)}s] ${x} ${f.type}`}if(n==="json")try{return JSON.stringify(f)}catch{return JSON.stringify({type:f.type,path:f.path,data:"[unserializable]"})}let g=u[f.type]??"",m=f.path?`${u.path}${f.path}${u.reset} `:"",T=f.type==="data"||f.type==="error",y=f.type==="pause"||f.type==="resume",v=T?` ${vn(f.data)}`:y?` ${vn(f.lockId)}`:"",_=f.type==="data"||f.type==="resolved"||f.type==="derived"?f:void 0,w=_?.trigger_dep_name!=null?` <- ${_.trigger_dep_name}`:_?.trigger_dep_index!=null?` <- #${_.trigger_dep_index}`:"",R=f.in_batch?" [batch]":"";return`${m}${g}${f.type.toUpperCase()}${u.reset}${v}${w}${R}`};e.onEvent(f=>{a(f.type)&&s(h(f),f)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){hr(this._disposers,this.name),this.signal([[ue]],{internal:!0}),hr(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:t,...n}=this.describe({detail:"full"}),s={};for(let a of Object.keys(n.nodes).sort()){let{lastMutation:u,guard:d,...c}=n.nodes[a];s[a]=c}let o=[...n.subgraphs].sort(),i={...n,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 Vn(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??tt,{codec:s,codecVersion:o,payload:i}=jn(e,n);return s.decode(i,o)}restore(e,t){if(br(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let n=t?.only==null?null:(Array.isArray(t.only)?t.only:[t.only]).map(o=>jt(o)),s=t?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(n!==null&&!n.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&&t?.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 u=this.tryResolve(o)?.v;if(u!=null&&u.id===i.v.id&&u.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){t?.onError?.(o,a)}}}}}static fromSnapshot(e,t){br(e);let n=typeof t=="function"?t:t?.build,s=typeof t=="function"?void 0:t?.factories,o=new r(e.name);if(n)return n(o),o.restore(e),o;for(let h of[...e.subgraphs].sort((f,g)=>{let m=f.split(X).length,T=g.split(X).length;return m!==T?m-T:f<g?-1:f>g?1:0})){let f=h.split(X),g=o;for(let m of f)g._mounts.has(m)||g.mount(m,new r(m)),g=g._mounts.get(m)}let i=s?Object.entries(s).map(([h,f])=>({re:jt(h),factory:f})):[],a=h=>{for(let f of i)if(f.re.test(h))return f.factory},u=h=>{let f=h.split(X),g=f.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${h}"`);let m=o;for(let T of f){let y=m._mounts.get(T);if(!y)throw new Error(`unknown mount "${T}" in path "${h}"`);m=y}return[m,g]},d=Object.entries(e.nodes).filter(([h])=>!h.includes(`${X}${Re}${X}`)).sort((h,f)=>h[0]<f[0]?-1:h[0]>f[0]?1:0),c=new Map(d),p=new Map,l=!0;for(;c.size>0&&l;){l=!1;for(let[h,f]of[...c.entries()]){let g=f?.deps??[];if(!g.every(w=>p.has(w)))continue;let[m,T]=u(h),y={...f?.meta??{}},v=a(h),_;if(f?.type==="state")_=L(f.value,{meta:y});else{if(v==null)continue;_=v(T,{path:h,type:f.type,value:f.value,meta:y,deps:g,resolvedDeps:g.map(w=>p.get(w))})}m.add(_,{name:T}),p.set(h,_),c.delete(h),l=!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()}attachSnapshotStorage(e,t={}){let n=e.map(d=>({tier:d,debounceMs:Math.max(0,d.debounceMs??0),compactEvery:Math.max(1,d.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));t.autoRestore===!0&&this._cascadeRestore(e,t.onError);let s=(d,c)=>{if(d.disposed)return;let p=Io(c.nodes);if(d.lastSnapshot!=null&&p!==""&&p===d.lastFingerprint)return;let l=d.seq+1,h=ve(),m=d.lastSnapshot==null||l%d.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:l,timestamp_ns:h,format_version:We}:{name:this.name,mode:"diff",diff:_r(d.lastSnapshot,c),seq:l,timestamp_ns:h,format_version:We};if(d.tier.filter&&!d.tier.filter(m))return;let T;try{T=d.tier.save(m)}catch(y){t.onError?.(y,d.tier);return}if(T&&typeof T.then=="function"){let _=(d.savePending??Promise.resolve()).then(()=>T,()=>T).then(()=>{d.disposed||(d.seq=l,d.lastSnapshot=c,d.lastFingerprint=p)},w=>{t.onError?.(w,d.tier)});d.savePending=_.finally(()=>{d.savePending===_&&(d.savePending=void 0)})}else d.seq=l,d.lastSnapshot=c,d.lastFingerprint=p},o=(d,c)=>{try{s(d,c)}catch(p){t.onError?.(p,d.tier)}},i=(d,c)=>{if(!c.some(f=>{let g=this.config.messageTier(f[0]);return g>=3&&g<5}))return;if(t.filter){let f=this.tryResolve(d);if(f==null)return;let g=ln(f,cn("standard"));if(!t.filter(d,g))return}let l,h=()=>(l==null&&(l=this.snapshot()),l);for(let f of n)f.disposed||(f.debounceMs===0?o(f,h()):(f.timer==null&&(f.timer=new Pt),f.timer.start(f.debounceMs,()=>{f.disposed||o(f,this.snapshot())})))},a;if(t.paths!=null){let c=(typeof t.paths=="string"?this._pathsMatching(t.paths):t.paths).map(p=>{let l=this.tryResolve(p);return l==null?()=>{}:l.subscribe(h=>i(p,h))});a=()=>{for(let p of c)p()}}else a=this.observe().subscribe((d,c)=>i(d,c));let u=()=>{a();for(let d of n)d.disposed=!0,d.timer?.cancel();this._storageDisposers.delete(u)};return this._storageDisposers.add(u),{dispose:u}}async _cascadeRestore(e,t){for(let n of e){let s;try{s=await n.load?.()}catch(i){t?.(i,n);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===We&&o.nodes!=null)return this.restore(o),!0}catch(i){t?.(i,n)}}return!1}static async fromStorage(e,t,n){for(let s of t){let o;try{o=await s.load?.()}catch(u){n?.onError?.(u,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===We&&i.nodes!=null?i:void 0;if(a!=null)try{return r.fromSnapshot(a,n)}catch(u){n?.onError?.(u,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${t.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,t,n){if(e!=null&&t!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,t),this.config.inspectorEnabled){let s={path:e,annotation:t,timestamp_ns:K(),...n?.actor!=null?{actor:n.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 t=this._traceRing.toArray().filter(s=>!e(s)),n=this._traceRing.size-t.length;this._traceRing.clear();for(let s of t)this._traceRing.push(s);return n}static diff(e,t){let n=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(t.nodes)),o=[...s].filter(y=>!n.has(y)).sort(),i=[...n].filter(y=>!s.has(y)).sort(),a=[],u=[];for(let y of n){if(!s.has(y))continue;let v=e.nodes[y],_=t.nodes[y],w=v.v,R=_.v;w!=null&&R!=null&&w.id===R.id&&w.version!==R.version&&u.push({path:y,id:w.id,from:w.version,to:R.version});let b=w!=null&&R!=null&&w.id===R.id&&w.version===R.version;for(let x of["type","status","sentinel"]){let O=v[x],S=_[x];O!==S&&a.push({path:y,field:x,from:O,to:S})}if(!b)for(let x of["value","meta"]){let O=v[x],S=_[x];Go(O,S)||a.push({path:y,field:x,from:O,to:S})}}let d=y=>`${y.from} ${y.to}`,c=new Set(e.edges.map(d)),p=new Set(t.edges.map(d)),l=t.edges.filter(y=>!c.has(d(y))),h=e.edges.filter(y=>!p.has(d(y))),f=new Set(e.subgraphs),g=new Set(t.subgraphs),m=[...g].filter(y=>!f.has(y)).sort(),T=[...f].filter(y=>!g.has(y)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:u,edgesAdded:l,edgesRemoved:h,subgraphsAdded:m,subgraphsRemoved:T}}};function _r(r,e){let t=ce.diff(r,e),n={};for(let s of t.nodesAdded){let o=e.nodes[s];o!=null&&(n[s]=o)}return{...t,nodesAddedFull:n}}function _n(r,e,t,n={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return n.withDetail?s:[];if(!n.both&&t!=="upstream"&&t!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=n.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return n.withDetail?s:[];let i=new Map,a=new Map,u=new Map,d=new Map,c=new Set;for(let[v,_]of Object.entries(r.nodes)){if(!v)continue;c.add(v);let w=_.deps??[];i.set(v,w);for(let R of w)R&&(c.add(R),a.has(R)||a.set(R,new Set),a.get(R).add(v))}for(let v of r.edges){if(v==null||typeof v!="object")continue;let _=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!_||!w||(c.add(_),c.add(w),d.has(_)||d.set(_,new Set),d.get(_).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(_))}if(!c.has(e))return n.withDetail?s:[];let p=n.both===!0,l=v=>{if(p){let b=i.get(v)??[],x=u.get(v),O=a.get(v),S=d.get(v),N=[...b];return x&&N.push(...x),O&&N.push(...O),S&&N.push(...S),N}if(t==="upstream"){let b=i.get(v)??[],x=u.get(v);return x?[...b,...x]:b}let _=a.get(v),w=d.get(v),R=_?[..._]:[];return w&&R.push(...w),R},h=new Set([e]),f=new Map,g=[{path:e,depth:0}],m=0,T=!1;for(;m<g.length;){let v=g[m++];if(o!=null&&v.depth>=o){l(v.path).length>0&&(T=!0);continue}for(let _ of l(v.path))!_||h.has(_)||(h.add(_),f.set(_,v.depth+1),g.push({path:_,depth:v.depth+1}))}let y=[...f.keys()].sort((v,_)=>v<_?-1:v>_?1:0);return n.withDetail?{paths:y,depths:f,truncated:T}:y}function Bo(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],s=e[t];if(n.path!==s.path||n.type!==s.type||n.status!==s.status||n.hop!==s.hop||n.dep_index!==s.dep_index||n.annotation!==s.annotation||n.value!==s.value||n.lastMutation!==s.lastMutation)return!1;let o=n.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}At();Ie();et();ge();oe();De();vt();Ie();ge();De();oe();var wn=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=t,t!==void 0){if(this._buf=new Array(t),e&&e.length>0){let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}}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 t=e>=0?e:this._size+e;if(!(t<0||t>=this._size))return this._maxSize!==void 0?this._buf[(this._head+t)%this._maxSize]:this._buf[t]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let n=t;n<e.length;n++)this._rawAppend(e[n]);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 t=0;t<e;t++)this._buf[(this._head+t)%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 t=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,t);else{for(let n=0;n<t;n++)this._buf[(this._head+n)%this._maxSize]=void 0;this._head=(this._head+t)%this._maxSize}return this._size-=t,this._version+=1,t}slice(e,t){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${t})`);let n=t===void 0?this._size:Math.min(Math.max(t,0),this._size),s=Math.min(e,this._size);if(s>=n)return[];let o=n-s;if(this._maxSize===void 0)return this._buf.slice(s,n);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 t=Math.min(e,this._size);return this.slice(this._size-t,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this._buf[(this._head+t)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let t=0;t<e.length;t++)this._buf.push(e[t]);this._size=this._buf.length}else{let t=this._maxSize;for(let o=0;o<t;o++)this._buf[o]=void 0;this._head=0;let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}this._version+=1}_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 Tt(r){return r.subscribe(()=>{})}var qo=64;function zt(r,e={}){let{name:t,maxSize:n,versioning:s,guard:o,backend:i}=e,a=i??new wn(r,n),u=L(a.toArray(),{name:t,describeKind:"state",equals:(b,x)=>b===x,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function d(){let b=a.toArray();te(()=>{u.down([[ee]],{internal:!0}),u.down([[C,b]],{internal:!0})})}let c=new Map,p=new Map,l=new Map;function h(b,x){return`${b}:${x===void 0?"END":x}`}function f(b){if(b.size<qo)return;let x=b.keys().next();if(x.done)return;let O=b.get(x.value);O!==void 0&&O.dispose(),b.delete(x.value)}function g(b){let x=a.version;try{return b()}finally{a.version!==x&&d()}}function m(b){if(!Number.isInteger(b)||b<0)throw new RangeError(`tail: n must be a non-negative integer (got ${b})`);let x=c.get(b);if(x!==void 0)return c.delete(b),c.set(b,x),x.node;f(c);let O=I([u],([N])=>{let P=N;return b===0||P.length===0?[]:P.slice(Math.max(0,P.length-b))},{initial:a.tail(b),describeKind:"derived"}),S=Tt(O);return c.set(b,{node:O,dispose:S}),O}function T(b,x){if(!Number.isInteger(b)||b<0)throw new RangeError(`slice: start must be a non-negative integer (got ${b})`);if(x!==void 0&&(!Number.isInteger(x)||x<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${x})`);let O=h(b,x),S=p.get(O);if(S!==void 0)return p.delete(O),p.set(O,S),S.node;f(p);let N=I([u],([B])=>{let z=B;return x===void 0?z.slice(b):z.slice(b,x)},{initial:a.slice(b,x),describeKind:"derived"}),P=Tt(N);return p.set(O,{node:N,dispose:P}),N}function y(b){let x=l.get(b);if(x!==void 0)return x.node;let O=I([u,b],([N,P])=>{let B=N,z=Math.max(0,Math.trunc(P??0));return B.slice(z)},{initial:[],describeKind:"derived"}),S=Tt(O);return l.set(b,{node:O,dispose:S}),O}let v,_;function w(){v===void 0&&(v=ne([u],(b,x,O)=>{let S=b[0],P=S!=null&&S.length>0?S.at(-1):O.prevData[0];if(P==null||P.length===0){x.down([[Q]]);return}x.emit(P[P.length-1])},{name:t!=null?`${t}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),_=I([u],([b])=>b.length>0,{name:t!=null?`${t}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),Tt(v),Tt(_))}let R={entries:u,get size(){return a.size},at(b){return a.at(b)},append(b){g(()=>a.append(b))},appendMany(b){b.length!==0&&g(()=>a.appendMany(b))},clear(){g(()=>a.clear())},trimHead(b){g(()=>a.trimHead(b))},withLatest(){return w(),u},get lastValue(){return w(),v},get hasLatest(){return w(),_},view(b){switch(b.kind){case"tail":return m(b.n);case"slice":return T(b.start,b.stop);case"fromCursor":return y(b.cursor)}},attach(b){let x=b.subscribe(O=>{for(let S of O)S[0]===C&&R.append(S[1])});return()=>x()},attachStorage(b){if(b.length===0)return()=>{};let x=new Map;for(let S of b)x.set(S,a.size);(async()=>{for(let S of b)if(typeof S.loadEntries=="function")try{let N=await Promise.resolve(S.loadEntries());N.entries.length>0&&a.size===0&&(a.restore(N.entries),x.set(S,N.entries.length),d());break}catch{}})();let O=u.subscribe(S=>{for(let N of S){if(N[0]!==C)continue;let P=N[1];for(let B of b){let z=x.get(B)??0;if(P.length<z){try{let ae=B.appendEntries(P);ae instanceof Promise&&ae.catch(()=>{})}catch{}x.set(B,P.length);continue}if(P.length===z)continue;let le=P.slice(z);x.set(B,P.length);try{let ae=B.appendEntries(le);ae instanceof Promise&&ae.catch(()=>{})}catch{}}}});return()=>O()},disposeAllViews(){for(let b of c.values())b.dispose();c.clear();for(let b of p.values())b.dispose();p.clear();for(let b of l.values())b.dispose();l.clear()},dispose(){for(let b of c.values())b.dispose();c.clear();for(let b of p.values())b.dispose();p.clear();for(let b of l.values())b.dispose();l.clear()}};return R}$e();var Ho=256;function at(r,e){if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`${e} must be a non-negative integer`);return r}function Be(r,e){return ze("messaging",r,e)}var Uo=1024,xn=class extends ce{_log;events;latest;hasLatest;constructor(e,t={}){super(e,t.graph),this._log=zt([],{name:"events",maxSize:t.retainedLimit??Uo}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=I([this.events],([n])=>{let s=n;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:Be("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(ye(this.latest)),this.hasLatest=I([this.events],([n])=>n.length>0,{name:"hasLatest",describeKind:"derived",meta:Be("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(ye(this.hasLatest)),this.addDisposer(()=>{this.events.down([[j]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},Bt=class extends ce{cursor;available;topic;_disposed=!1;constructor(e,t,n={}){super(e,n.graph),this.topic=t;let s;if(n.from!==void 0?n.from==="retained"?s=0:n.from==="now"?s=t.events.cache.length:s=at(n.from,"subscription from"):s=at(n.cursor??0,"subscription cursor"),this.cursor=L(s,{name:"cursor",describeKind:"state",meta:Be("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=t._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(ye(this.available)),n.advanceOn!==void 0){let o=n.advanceOn,i=!1,a=ne([o],()=>{if(!i){i=!0;return}if(this._disposed)return;let u=this.available.cache;if(u.length===0)return;let d=this.cursor.cache+u.length;this.cursor.emit(d)},{name:"advancePump",describeKind:"effect",meta:Be("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(ye(a))}}ack(e){if(this._disposed)return this.cursor.cache;let t=this.available.cache,n=e===void 0?t.length:at(e,"subscription ack count"),s=Math.min(n,t.length);if(s<=0)return this.cursor.cache;let o=this.cursor.cache+s;return this.cursor.emit(o),o}pull(e){if(this._disposed)return[];let t=this.available.cache,n=e===void 0?t.length:at(e,"subscription pull limit");return t.slice(0,n)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let t=this.available.cache,n=e===void 0?t.length:at(e,"subscription pullAndAck limit"),s=t.slice(0,n);if(s.length===0)return{items:s,cursor:this.cursor.cache};let o=this.cursor.cache+s.length;return this.cursor.emit(o),{items:s,cursor:o}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[j]]),this.destroy())}},Nn=class extends ce{_sourceSub;bridgedCount;output;constructor(e,t,n,s={}){super(e,s.graph),this._sourceSub=Wo(`${e}-subscription`,t,{cursor:s.cursor}),this.mount("subscription",this._sourceSub);let o=Math.max(1,at(s.maxPerPump??Ho,"topic bridge maxPerPump")),i=s.map??(l=>l);this.output=I([this._sourceSub.available],([l])=>{let h=l,f=[],g=Math.min(h.length,o);for(let m=0;m<g;m++){let T=i(h[m]);T!==void 0&&f.push(T)}return f},{name:"output",describeKind:"derived",meta:Be("topic_bridge_output",{targetRef:n.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(ye(this.output)),this.bridgedCount=L(0,{name:"bridgedCount",describeKind:"state",meta:Be("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(ye(this.bridgedCount));let a=this.output,u=this._sourceSub,d=this.bridgedCount,c=ne([a],()=>{let l=a.cache;if(l.length===0)return;let h=u.available.cache.length,f=Math.min(h,o);if(f>0){u.ack(f);let g=d.cache??0;d.emit(g+l.length)}},{name:"ackPump",describeKind:"effect",meta:Be("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(ye(c));let p=Ko(this.output,n);this.addDisposer(p)}};function Ko(r,e){return r.subscribe(t=>{for(let n of t){if(n[0]!==C)continue;let s=n[1];s.length!==0&&te(()=>{for(let o of s)e.publish(o)})}})}var En=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,t){this._map.set(e,t)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},kn=class extends ce{_registry;version;_defaultTopicOptions;constructor(e,t={}){super(e,t.graph);let n=L(0,{name:"version",describeKind:"state",meta:Be("hub_version")});this.add(n,{name:"version"}),this.version=n,this._registry=new En(n),this._defaultTopicOptions={...t.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,t){let n=this._registry.get(e);if(n===void 0){let s={...this._defaultTopicOptions,...t??{}};n=new xn(e,s),this._registry.set(e,n),this.mount(e,n);let o=this.version.cache??0;this.version.emit(o+1)}return n}publish(e,t){this.topic(e).publish(t)}publishMany(e){te(()=>{for(let[t,n]of e)this.topic(t).publish(n)})}subscribe(e,t,n){let s=this.topic(t);return new Bt(e,s,n)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let t=this.version.cache??0;this.version.emit(t+1)}return!0}};function qt(r,e){return new kn(r,e)}function Wo(r,e,t){return new Bt(r,e,t)}function Rn(r,e,t,n){return new Nn(r,e,t,n)}function Jo(r){if(typeof r!="object"||r===null)return!1;let e=r;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function Yo(r,e){if(r.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(r.length===1){let o=Qo(e);return{best:r[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(r.length);for(let u=0;u<r.length;u++)o[u]={sum:0,count:0};for(let u of e){let d=u.candidateIndex;typeof d=="number"&&d>=0&&d<r.length&&(o[d].sum+=u.score,o[d].count+=1)}let i=r[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let u=1;u<r.length;u++){let d=o[u].count>0?o[u].sum/o[u].count:Number.NEGATIVE_INFINITY;d>a&&(a=d,i=r[u])}return{best:i,bestScore:a}}let n=r[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<r.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,n=r[o])}return{best:n,bestScore:s}}function Qo(r){if(r.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let t of r)e+=t.score;return e/r.length}function wr(r,e,t,n){let s=n.name??"refine-loop",o=new ce(s,n.graph),i=Jo(n.dataset)?n.dataset:L(n.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=L(0,{name:"iteration"});o.add(a,{name:"iteration"});let u=L(t,{name:"strategy",equals:()=>!1});o.add(u,{name:"strategy"});let d=L(null,{name:"lastFeedback"});o.add(d,{name:"lastFeedback"});let c=L([],{name:"prevCandidates"});o.add(c,{name:"prevCandidates"});let p=L(!1,{name:"paused"});o.add(p,{name:"paused"});let l=L("running",{name:"status"});o.add(l,{name:"status"});let h=L([],{name:"history",equals:()=>!1});o.add(h,{name:"history"});let f=L(null,{name:"best"});o.add(f,{name:"best"});let g=L(Number.NEGATIVE_INFINITY,{name:"score"});o.add(g,{name:"score"});let m=L(0,{name:"budget-used"});o.add(m,{name:"budget-used"});let T=qt("stages");o.mount("stages",T);let y=T.topic("generate"),v=T.topic("evaluate"),_=T.topic("analyze"),w=T.topic("decide"),R=t,b=null,x=[];o.addDisposer(u.subscribe(E=>{for(let M of E)M[0]===C&&(R=M[1])})),o.addDisposer(d.subscribe(E=>{for(let M of E)M[0]===C&&(b=M[1])})),o.addDisposer(c.subscribe(E=>{for(let M of E)M[0]===C&&(x=M[1])}));let O=ke(a,E=>{let M=R,J=E===0||b==null;return ne([],(q,k)=>{let D=!1;try{let H=J?M.seed(r):M.generate(b,x);if(H instanceof Promise)return H.then(W=>{D||k.emit(W)},W=>{D||k.down([[G,W]])}),()=>{D=!0};k.emit(H)}catch(H){D=!0,k.down([[G,H]])}},{describeKind:"producer"})},{name:"candidates"});o.add(O,{name:"candidates"});let S=be([O],(E,M,J)=>{let q=J.terminalDeps[0];q!==void 0&&q!==!0&&l.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(S,{name:"error-watcher"}),o.addDisposer(S.subscribe(()=>{}));let N=I([O,a],([E,M])=>({iteration:M,candidates:E,timestamp_ns:K()}),{name:"generate-event"});o.add(N,{name:"generate-event"}),o.addDisposer(N.subscribe(()=>{}));let P=be([N],([E])=>{y.publish(E)},{name:"generate-publish"});o.add(P,{name:"generate-publish"}),o.addDisposer(P.subscribe(()=>{}));let B=be([O],([E])=>{c.emit(E)},{name:"generate-mirror"});o.add(B,{name:"generate-mirror"}),o.addDisposer(B.subscribe(()=>{}));let z=e(O,i);o.add(z,{name:"scores"});let le=I([z,O,a],([E,M,J])=>({iteration:J,candidates:M,scores:E,timestamp_ns:K()}),{name:"evaluate-event"});o.add(le,{name:"evaluate-event"}),o.addDisposer(le.subscribe(()=>{}));let ae=be([le],([E])=>{v.publish(E)},{name:"evaluate-publish"});o.add(ae,{name:"evaluate-publish"}),o.addDisposer(ae.subscribe(()=>{}));let Oe=I([z,O],([E,M])=>R.analyze(E,M),{name:"feedback"});o.add(Oe,{name:"feedback"});let Ce=I([Oe,O,a],([E,M,J])=>({iteration:J,candidates:M,feedback:E,timestamp_ns:K()}),{name:"analyze-event"});o.add(Ce,{name:"analyze-event"}),o.addDisposer(Ce.subscribe(()=>{}));let $=be([Ce],([E])=>{_.publish(E)},{name:"analyze-publish"});o.add($,{name:"analyze-publish"}),o.addDisposer($.subscribe(()=>{}));let V=I([h],([E])=>{let M=E;if(n.patience==null||M.length<=n.patience)return!1;let J=M.slice(-(n.patience+1)),q=J[0].bestScore;return J.slice(1).every(k=>k.bestScore<=q)},{name:"patience-check"});o.add(V,{name:"patience-check"});let F=I([g],([E])=>n.minScore!=null&&E>=n.minScore,{name:"min-score-check"});o.add(F,{name:"min-score-check"});let ie=I([h],([E])=>{let M=E;if(n.minDelta==null||M.length<2)return!1;let J=M[M.length-2].bestScore,q=M[M.length-1].bestScore;return Math.abs(q-J)<n.minDelta},{name:"min-delta-check"});o.add(ie,{name:"min-delta-check"});let Z=I([m],([E])=>n.maxEvaluations!=null&&E>=n.maxEvaluations,{name:"max-evaluations-check"});o.add(Z,{name:"max-evaluations-check"});let fe=I([a],([E])=>n.maxIterations!=null&&E>=n.maxIterations,{name:"max-iterations-check"});o.add(fe,{name:"max-iterations-check"});let A=I([m],([E])=>n.budget!=null&&E>=n.budget,{name:"budget-exhausted-check"});o.add(A,{name:"budget-exhausted-check"}),o.addDisposer(V.subscribe(()=>{})),o.addDisposer(F.subscribe(()=>{})),o.addDisposer(ie.subscribe(()=>{})),o.addDisposer(Z.subscribe(()=>{})),o.addDisposer(fe.subscribe(()=>{})),o.addDisposer(A.subscribe(()=>{}));let U=I([V,F,ie,Z,fe],([E,M,J,q,k])=>E?{converged:!0,reason:"patience"}:M?{converged:!0,reason:"min-score"}:J?{converged:!0,reason:"min-delta"}:q?{converged:!0,reason:"max-evaluations"}:k?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(U,{name:"converged"}),o.addDisposer(U.subscribe(()=>{}));let pe=-1,Se=be([Oe,z,O],([E,M,J])=>{let q=a.cache,k=E,D=J,H=M;if(q<=pe)return;pe=q;let{best:W,bestScore:Me}=Yo(D,H),dt=h.cache,qe={n:q,candidates:D,scores:H,feedback:k,best:W,bestScore:Me,timestamp_ns:K()},Y=[...dt,qe],we=m.cache+D.length,Te="continue",Ge,In=n.budget!=null&&we>=n.budget,Gn=p.cache;if(In)Te="budget",Ge="budget";else if(n.minScore!=null&&k.score>=n.minScore)Te="converged",Ge="min-score";else if(n.maxIterations!=null&&q>=n.maxIterations)Te="converged",Ge="max-iterations";else if(n.maxEvaluations!=null&&we>=n.maxEvaluations)Te="converged",Ge="max-evaluations";else if(n.minDelta!=null&&Y.length>=2){let Nt=Y[Y.length-2].bestScore,Jt=Y[Y.length-1].bestScore;Math.abs(Jt-Nt)<n.minDelta&&(Te="converged",Ge="min-delta")}else if(n.patience!=null&&Y.length>n.patience){let Nt=Y.slice(-(n.patience+1)),Jt=Nt[0].bestScore;Nt.slice(1).every($r=>$r.bestScore<=Jt)&&(Te="converged",Ge="patience")}Te==="continue"&&Gn&&(Te="paused"),te(()=>{f.emit(W),g.emit(k.score),h.emit(Y),m.emit(we),d.emit(k),w.publish({iteration:q,decision:Te,reason:Ge,timestamp_ns:K()}),Te==="continue"?a.emit(q+1):l.emit(Te==="converged"?"converged":Te==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(Se,{name:"decide-bridge"}),o.addDisposer(Se.subscribe(()=>{})),Object.assign(o,{best:f,score:g,status:l,history:h,strategy:u,iteration:a,generate:y,evaluate:v,analyze:_,decide:w,setStrategy(E){u.emit(E)},pause(){p.emit(!0)},resume(){l.cache==="paused"&&te(()=>{p.emit(!1),l.emit("running"),a.emit(a.cache+1)})}})}function Xo(r){let{best:e,score:t,status:n}=r,s=Number.isFinite(t)?t.toFixed(3):String(t),o=e??void 0;return n==="converged"?{outcome:"success",detail:`refineLoop converged at score ${s}`,artifact:o}:n==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${s}`,artifact:o}:{outcome:"failure",detail:`refineLoop errored (status=${n})`,artifact:o}}function On(r){let e=r.name??"refine-executor",t=r.toOutput??Xo;return n=>{let s=Ve(n,i=>i!=null,{name:`${e}/gate-in`}),o=ke(s,i=>{let a=wr(r.seedFrom(i),r.evaluator,r.strategy,{...r.refine,dataset:r.datasetFor(i),name:`${e}/inner`});return I([a.status,a.best,a.score],([u,d,c])=>{let p=u;return p!=="converged"&&p!=="budget"&&p!=="errored"?null:t({best:d,score:c,status:p})},{name:`${e}/output`})},{name:e});return Ve(o,i=>i!=null,{name:`${e}/gate-out`})}}function Zo(r){if(r.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let t of r)e+=t.score;return e/r.length}function es(r){let{passCount:e,total:t,meanScore:n,threshold:s,missingArtifact:o}=r,i=Number.isFinite(n)?n.toFixed(3):String(n),a=!o&&t>0&&n>=s,u=o?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${t} eval tasks passed; mean score ${i} \u2265 ${s}`]:t===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${t} eval tasks passed; mean score ${i} < threshold ${s}`];return a?{verified:!0,findings:u}:{verified:!1,findings:u,errorClass:"structural"}}function ts(r){return r.artifact??null}function xr(r){let e=r.name??"eval-verifier",t=r.threshold??.5,n=r.toOutput??es,s=r.extractArtifact??ts;return o=>{let i=Ve(o,u=>u!=null&&u[0]!=null&&u[1]!=null,{name:`${e}/gate-in`}),a=ke(i,u=>{let[d,c]=u,p=s(d,c);if(p==null)return L(n({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:t,missingArtifact:!0}));let l=L([p],{name:`${e}/candidates`}),h=L(r.datasetFor(c),{name:`${e}/dataset`}),f=r.evaluator(l,h);return I([f],([g])=>{let m=g;if(m==null)return null;let T=Zo(m),y=m.filter(v=>v.score>=t).length;return n({scores:m,meanScore:T,passCount:y,total:m.length,threshold:t})},{name:`${e}/output`})},{name:e});return Ve(a,u=>u!=null,{name:`${e}/gate-out`})}}function ns(r){let e=r.name??"harness-pair",t=On({name:`${e}-exec`,seedFrom:r.seedFrom,evaluator:r.evaluator,strategy:r.strategy,datasetFor:r.datasetFor,refine:r.refine}),n=xr({name:`${e}-verify`,evaluator:r.evaluator,datasetFor:r.datasetFor,threshold:r.threshold});return{executor:t,verifier:n}}Ne();mt();De();oe();Ie();Ne();et();ge();oe();function Sn(r,e){let t=r.cache??0;return t>=e?!1:(r.down([[ee],[C,t+1]]),!0)}var rs=Kn((r,e)=>{r("observe"),r("signal"),e("write")});function Ht(r){let e=zt([],{name:r.name,maxSize:r.retainedLimit??1024,guard:r.guard??rs,...r.versioning!=null?{versioning:r.versioning}:{}});return e.withLatest(),r.graph&&r.graph.add(e.entries,{name:r.name}),e}function Er(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Er(r[e]);return Object.freeze(r)}function os(r){let e=r.cache,n=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return r.down([[ee],[C,n]]),n}function Nr(r,e,t,n,s,o){let i=e(t,n,s);if(i===void 0)return;let a=o!=null?{...i,handlerVersion:o}:i;r.append(a)}function ut(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(Er):s,i=ve(),a,u,d=!1,c;try{te(()=>{e.seq&&(c=os(e.seq));try{a=r(...o),e.onSuccess&&Nr(e.audit,e.onSuccess,o,a,{t_ns:i,seq:c},e.handlerVersion)}catch(p){throw u=p,d=!0,p}})}catch(p){if(d&&e.onFailure){let l=u instanceof Error?u.name:typeof u;Nr(e.audit,e.onFailure,o,u,{t_ns:i,seq:c,errorType:l},e.handlerVersion)}throw d?u:p}return a}}function kr(r,e,t=0){let n=L(t,{name:e,describeKind:"state"});return r.add(n,{name:e}),n}function _t(r){return r.relatedTo?.[0]??r.summary}vt();function wt(r,e){return ze("ai",r,e)}function Rr(r){let e=r.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:r}ge();oe();$e();function Or(r){return r!=null&&typeof r=="object"&&"content"in r?String(r.content):typeof r=="string"?r:String(r)}function ss(r,e=200){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Ut(r,e,t,n){let s=n?.format??"text",o=n?.name??"prompt_node";n?.tools!==void 0&&s!=="raw"&&console.warn("promptNode: `tools` is set but `format !== 'raw'`. Tool calls in the response will be silently dropped \u2014 set `format: 'raw'` to receive the full LLMResponse with `toolCalls`.");let i=I(e,u=>{if(u.some(c=>c==null))return[];let d=typeof t=="string"?t:t(...u);return d?[{role:"user",content:d}]:[]},{name:`${o}::messages`,meta:wt("prompt_node")});return ke(i,u=>!u||u.length===0?L(null):de(d=>{let c=!1,p=!1,l,h={model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,...n?.tools!==void 0?{tools:n.tools}:{}};if(n?.abort){let T=nr(n.abort);h.signal=T.signal,l=T.dispose}let f;try{f=r.invoke(u,h)}catch(T){return c=!0,d.down([[G,T]]),()=>{l?.()}}let m=Fe(f).subscribe(T=>{if(!(p||c))for(let y of T){if(c)return;if(y[0]===C){let v=y[1];if(s==="raw")d.emit(v);else try{let _=Or(v),w=s==="json"?JSON.parse(Rr(_)):_;d.emit(w)}catch(_){let w=Or(v),R=new Error(`promptNode: failed to parse LLM response as JSON: ${_.message}
45
- Raw content (first 200 chars): ${ss(w)}`);c=!0,d.down([[G,R]]);return}}else if(y[0]===G){c=!0,d.down([[G,y[1]]]);return}else if(y[0]===j){c=!0,d.down([[j]]);return}else d.down([y])}});return()=>{p=!0,m(),l?.()}},{name:`${o}::call`,meta:wt("prompt_node::call")}),{name:`${o}::output`,meta:n?.meta?{...wt("prompt_node::output"),...n.meta}:wt("prompt_node::output")})}Ie();Ne();ge();mt();De();oe();vt();function xt(r,e){return ze("orchestration",r,e)}var Kt=class extends ce{constructor(e,t){super(e,t)}task(e,t,n={}){let s=(n.deps??[]).map(i=>this._resolveStep(i)),o=I(s,t,{name:e,describeKind:"derived",meta:xt("task",n.meta)});return this.add(o,{name:e}),o}classify(e,t,n,s={}){let o=this._resolveStep(t),i=I([o],([a])=>{try{return{tag:n(a),value:a}}catch(u){return{tag:"error",value:a,error:u}}},{name:e,describeKind:"derived",meta:xt("classify",s.meta)});return this.add(i,{name:e}),i}combine(e,t,n={}){let s=Object.keys(t),o=s.map(a=>this._resolveStep(t[a])),i=I(o,a=>{let u={};for(let d=0;d<s.length;d++)u[s[d]]=a[d];return u},{name:e,describeKind:"derived",meta:xt("combine",n.meta)});return this.add(i,{name:e}),i}approvalGate(e,t,n={}){let s=n.maxPending??1e3;if(s<1&&s!==Number.POSITIVE_INFINITY)throw new RangeError("approvalGate: maxPending must be >= 1");let o=n.startOpen??!1;typeof t!="string"&&this.nameOf(t)===void 0&&this.add(t,{name:`${e}/source`});let i=this._resolveStep(t),a=new ce(`${e}_state`),u=L([],{name:"pending",equals:()=>!1}),d=L(o,{name:"isOpen"}),c=I([u],([$])=>$.length,{name:"count"}),p=L(0,{name:"droppedCount"}),l=Ht({name:"decisions",retainedLimit:1024,graph:a});a.add(u,{name:"pending"}),a.add(d,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(p,{name:"droppedCount"}),this.mount(`${e}_state`,a);let h=[],f=!1,g=!1,m=o,T=d.subscribe($=>{for(let V of $)V[0]===C&&(m=V[1])});this.addDisposer(T);function y(){u.emit([...h])}function v($,V,F){l.append({action:$,t_ns:ve(),...V!==void 0?{items:V,count:V.length}:{},...F!==void 0?{unflushed:F}:{},...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}function _($){if(h.push($),h.length>s){let V=h.shift();p.emit(p.cache+1),v("drop",[V])}y()}function w($){let V=h.splice(0,$);return y(),V}let R=ne([i],($,V,F)=>{let ie=F.terminalDeps[0];if(ie!==void 0){f=!0;let fe=h.length;h=[],y(),v("teardown",void 0,fe),V.down(ie===!0?[[j]]:[[G,ie]]);return}let Z=$[0];if(Z==null||Z.length===0){V.down([[Q]]);return}for(let fe of Z)m?V.emit(fe):(_(fe),V.down([[Q]]))},{name:e,describeKind:"derived",meta:xt("approval_gate",n.meta)});if(this.add(R,{name:e}),n.approver!=null){n.approver.cache&&(d.emit(!0),m=!0,n.onceOnly&&(g=!0));let V=n.approver.subscribe(F=>{for(let ie of F){if(ie[0]!==C)continue;let Z=!!ie[1];if(Z&&!m){if(n.onceOnly){if(g)continue;g=!0}te(()=>{d.emit(!0);let fe=w(h.length);v("open",fe);for(let A of fe){if(f)break;R.emit(A)}})}else if(!Z&&m){if(n.onceOnly&&g)continue;te(()=>{d.emit(!1),v("close")})}}});this.addDisposer(V)}let b=$=>{if(f)throw new Error(`approvalGate: ${$}() called after the gate was torn down`)},x=($=1)=>{b("approve");let V=w($);for(let F of V){if(f)break;R.emit(F)}},O=($=1)=>{b("reject"),w($)},S=($,V=1)=>{b("modify");let F=[...h],ie=w(V);for(let Z=0;Z<ie.length&&!f;Z++)R.emit($(ie[Z],Z,F))},N=()=>{b("open"),d.emit(!0);let $=w(h.length);for(let V of $){if(f)break;R.emit(V)}},P=()=>{b("close"),!(n.onceOnly&&g)&&d.emit(!1)},B=ut(x,{audit:l,freeze:!1,onSuccess:($,V,F)=>({action:"approve",count:$[0]??1,t_ns:F.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:($,V,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),z=ut(O,{audit:l,freeze:!1,onSuccess:($,V,F)=>({action:"reject",count:$[0]??1,t_ns:F.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:($,V,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),le=ut(S,{audit:l,freeze:!1,onSuccess:($,V,F)=>({action:"modify",count:$[1]??1,t_ns:F.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:($,V,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),ae=ut(N,{audit:l,freeze:!1,onSuccess:($,V,F)=>({action:"open",t_ns:F.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:($,V,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),Oe=ut(P,{audit:l,freeze:!1,onSuccess:($,V,F)=>({action:"close",t_ns:F.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:($,V,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:R,pending:u,count:c,isOpen:d,droppedCount:p,decisions:l,audit:l,approve:B,reject:z,modify:le,open:ae,close:Oe}}approval(e,t,n,s={}){return this.approvalGate(e,t,{...s,approver:n,maxPending:1})}catch(e,t,n,s={}){let o=this._resolveStep(t),i=s.on??"errored",a=ne([o],(u,d,c)=>{let p=c.terminalDeps[0];if(p!==void 0){let h=p===!0?{kind:"completed"}:{kind:"errored",error:p};if(i==="terminal"||i===h.kind){d.emit(n(h,d));return}d.down(h.kind==="completed"?[[j]]:[[G,h.error]]);return}let l=u[0];if(l==null||l.length===0){d.down([[Q]]);return}for(let h of l)d.emit(h)},{name:e,describeKind:"derived",completeWhenDepsComplete:s.completeWhenDepsComplete??!(i==="completed"||i==="terminal"),errorWhenDepsError:!(i==="errored"||i==="terminal"),meta:xt("catch",s.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function An(r,e){let t=new Kt(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("pipelineGraph",ht(o)),t}var au=Math.LN2/604800;function Sr(r,e,t,n=0){if(!Number.isFinite(r))return n;if(!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)return Math.max(n,r);let s=r*Math.exp(-t*e);return Math.max(n,s)}Ne();vt();Ie();ge();oe();var Dn=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 t=e>=0?e:this._buf.length+e;if(!(t<0||t>=this._buf.length))return this._buf[t]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._buf.length;this._buf.length=t+e.length;for(let n=0;n<e.length;n++)this._buf[t+n]=e[n];this._version+=1}insert(e,t){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,t),this._version+=1}insertMany(e,t){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);t.length!==0&&(this._buf.splice(e,0,...t),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 t=e>=0?e:this._buf.length+e;if(t<0||t>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[n]=this._buf.splice(t,1);return this._version+=1,n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Ar(r,e={}){let{name:t,versioning:n,backend:s}=e,o=s??new Dn(r),i=L(o.toArray(),{name:t,describeKind:"state",equals:(d,c)=>d===c,...n!=null?{versioning:n}:{}});function a(){let d=o.toArray();te(()=>{i.down([[ee]]),i.down([[C,d]])})}function u(d){let c=o.version;try{return d()}finally{o.version!==c&&a()}}return{items:i,get size(){return o.size},at(d){return o.at(d)},append(d){u(()=>o.append(d))},appendMany(d){u(()=>o.appendMany(d))},insert(d,c){u(()=>o.insert(d,c))},insertMany(d,c){u(()=>o.insertMany(d,c))},pop(d=-1){return u(()=>o.pop(d))},clear(){u(()=>o.clear())},dispose(){}}}$e();function is(r,e){if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`${e} must be a non-negative integer`);return r}function as(r,e){return ze("job_queue",r,e)}var Cn=class extends ce{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,t={}){super(e,t.graph),this._pending=Ar([],{name:"pending"}),this._jobs=it({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],([n])=>n.length,{name:"depth",describeKind:"derived",meta:as("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(ye(this.depth)),this.events=Ht({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=kr(this,"seq",0)}_bumpSeq(){let t=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(t),t}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,t={}){let n=this._bumpSeq(),s=t.id??`${this.name}-${n}`;if(this._jobs.get(s)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${s}"`);let o={id:s,payload:e,attempts:0,metadata:Object.freeze({...t.metadata??{}}),state:"queued"};return this._jobs.set(s,o),this._pending.append(s),this.events.append({action:"enqueue",id:s,payload:e,t_ns:ve(),seq:n}),s}claim(e=1){let t=is(e,"job queue claim limit");if(t===0)return[];let n=[];for(;n.length<t&&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),n.push(a),this.events.append({action:"claim",id:o,attempts:a.attempts,t_ns:ve(),seq:this._bumpSeq()})}return n}ack(e){let t=this._jobs.get(e);return!t||t.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:t.attempts,t_ns:ve(),seq:this._bumpSeq()}),!0)}nack(e,t={}){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:t.requeue??!0?(this._jobs.set(e,{...n,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:n.attempts,t_ns:ve(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:n.attempts,t_ns:ve(),seq:this._bumpSeq()}),!0)}removeById(e){let t=this._jobs.get(e);if(!t)return!1;if(t.state==="queued"){let s=this.pending.cache.indexOf(e);s>=0&&this._pending.pop(s)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:t.attempts,t_ns:ve(),seq:this._bumpSeq()}),!0}consumeFrom(e,t){return e.subscribe(n=>{for(let s of n){if(s[0]!==C)continue;let o=s[1];this.enqueue(o,t?{metadata:t.metadata}:void 0)}})}};function Dr(r,e){return new Cn(r,e)}Ne();oe();function Mn(){let r=it({name:"strategy-entries"}),e=I([r.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,p]of u){let l=d.get(c);if(!l||p.attempts!==l.attempts||p.successes!==l.successes)return!1}return!0}});function t(i,a,u){let d=st(i,a),c=r.get(d),p=(c?.attempts??0)+1,l=(c?.successes??0)+(u?1:0);r.set(d,{rootCause:i,intervention:a,attempts:p,successes:l,successRate:l/p})}function n(i,a){return r.get(st(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:t,lookup:n,dispose:o}}function us(r,e,t,n,s){let o={...rt,...s?.severityWeights},i=s?.decayRate??ot,a=s?.effectivenessThreshold??.7,u=s?.effectivenessBoost??15,d=[r,e,t];return n&&d.push(n),I(d,c=>{let p=c[0],l=c[1],h=c[2],f=n?c[3]:0,g=o[p.severity??"medium"],m=(K()-h)/1e9,T=Sr(g,m,i,0),y=st(p.rootCause,p.intervention),v=l.get(y);return v&&v.successRate>=a&&(T+=u),T+=f*20,T},{name:"priority-score"})}var Cr="intake",ds="triage-output",Mr="retry",Ir="verify-results",Gr="__unrouted";function Pr(r,e){let t=bt(e,hn,(n,s)=>n.replace("{{item}}",JSON.stringify(s)));return n=>Ut(r,[n],t,{name:"execute",format:"json"})}function Lr(r,e){let t=bt(e,mn,(n,s)=>{let[o,i]=s;return n.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return n=>Ut(r,[n],s=>s==null?"":t(s),{name:"verify",format:"json"})}var Wt=class extends ce{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,t,n,s,o,i,a,u,d){super(e),this.queues=t,this.queueTopics=n,this.jobs=s,this.gates=o,this.strategy=i,this.totalRetries=a,this.totalReingestions=u,this.priorityScores=d}get intake(){return this.queues.topic(Cr)}get verifyResults(){return this.queues.topic(Ir)}get retry(){return this.queues.topic(Mr)}get unrouted(){return this.queues.topic(Gr)}stageNodes(){let e=this.queues,t=i=>e.has(i)?`queues::${i}::latest`:null,n=i=>i==null?[]:[i],s=_e.flatMap(i=>n(t(i))),o=[];for(let[i]of this.gates)o.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:n(t("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:s},{label:"GATE",paths:o},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:n(t("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function cs(r,e){let t=e.adapter,n=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??Gt,i=new Map;for(let k of _e)i.set(k,{...It[k],...e.queues?.[k]});let a=qt(`${r}/queues`,{defaultTopicOptions:{retainedLimit:s}}),u=a.topic(Cr),d=a.topic(ds),c=a.topic(Mr),p=a.topic(Ir),l=new Map;for(let k of _e)l.set(k,a.topic(k));let h=a.topic(Gr),f=Mn(),g=gt(u.latest,f.node),m=bt(e.triagePrompt,pn,(k,D)=>{let[H,W]=D;return k.replace("{{strategy}}",JSON.stringify(Array.from(W.entries()))).replace("{{item}}",JSON.stringify(H))}),T=Ut(t,[g],k=>{let D=k;return!D||!D[0]?"":m(D)},{name:"triage",format:"json"}),y=gt(T,g),_=be([y],([k])=>{if(k==null)return;let[D,H]=k;if(!D?.route)return;let W=H?.[0],Me={...D,...W};d.publish(Me)}).subscribe(()=>{}),w=new Set(_e);for(let k of _e)Rn(`bridge/${k}`,d,l.get(k),{map:D=>D.route===k?D:void 0});Rn("bridge/__unrouted",d,h,{map:k=>w.has(k.route)?void 0:k});let R=new Map,b=new Map;for(let k of _e)R.set(k,Dr(`jobs/${k}`));let x=[];for(let k of _e){let D=l.get(k),H=R.get(k),W=new WeakSet,Me=be([D.events],([dt])=>{let qe=dt??[];for(let Y of qe){if(W.has(Y))continue;W.add(Y);let we=H.enqueue(Y);b.set(_t(Y),{route:k,id:we})}},{name:`jobs/${k}-mirror`});x.push(Me.subscribe(()=>{}))}function O(k){let D=_t(k),H=b.get(D);H&&(R.get(H.route)?.removeById(H.id),b.delete(D))}let S=An("gates"),N=new Map;for(let k of _e){let D=i.get(k);if(!D.gated)continue;let H=l.get(k),W=S.approvalGate(`${k}/gate`,H.latest,{maxPending:D.maxPending,startOpen:D.startOpen});N.set(k,W)}let P=[];for(let k of _e)i.get(k).gated&&N.has(k)?P.push(N.get(k).node):P.push(l.get(k).latest);P.push(c.latest);let B=or(...P),le=(e.executor??Pr(t,e.executePrompt))(B),ae=gt(le,B),Ce=(e.verifier??Lr(t,e.verifyPrompt))(ae),$=gt(Ce,ae),V=e.maxReingestions??1,F=Math.min(e.maxTotalRetries??n*10,100),ie=Math.min(e.maxTotalReingestions??V*10,100),Z=L(0),fe=L(0);function A(k,D,H){let W={item:H,outcome:D?.outcome??"failure",detail:D?.detail??"unknown",artifact:D?.artifact};return{item:H,execution:W,verified:k.verified,findings:k.findings??[],errorClass:k.errorClass}}function U(k,D){f.record(D.rootCause,D.intervention,!0),p.publish(k),O(D)}function pe(k,D){let H=_t(D),W=D.$retries??0,Me={...D,$retries:W+1,summary:`[RETRY ${W+1}/${n}] ${H} \u2014 Previous attempt failed: ${k.findings.join("; ")}`,relatedTo:[H]};c.publish(Me)}function Se(k,D){f.record(D.rootCause,D.intervention,!1),p.publish(k),O(D);let H=_t(D),W=D.$reingestions??0;W<V&&Sn(fe,ie)&&u.publish({source:D.source,summary:`Verification failed for: ${H}`,evidence:k.findings.join(`
46
- `),affectsAreas:D.affectsAreas,affectsEvalTasks:D.affectsEvalTasks,severity:D.severity??"high",relatedTo:[H],$reingestions:W+1})}let he=ne([$],(k,D)=>{let H=k[0];if(H==null||H.length===0)return;let W=H[H.length-1];if(W==null)return;let[Me,dt]=W,[qe,Y]=dt??[null,null];if(!Me||!Y)return;if(qe==null){Se({item:Y,execution:{item:Y,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},Y);return}let we=A(Me,qe,Y);if(we.verified){U(we,Y);return}let Te=we.errorClass??o({item:Y,outcome:qe.outcome,detail:we.findings.join("; ")}),Ge=Y.$retries??0;Te==="self-correctable"&&Ge<n&&Sn(Z,F)?pe(we,Y):Se(we,Y)}),E=he.subscribe(()=>{}),M=I([he],()=>null,{name:"reflect",equals:()=>!1}),J;e.priority&&(J=ls(l,f,e));let q=new Wt(r,a,l,R,N,f,Z,fe,J);q.addDisposer(_),q.addDisposer(E),q.addDisposer(f.dispose);for(let k of x)q.addDisposer(k);if(q.add(T,{name:"triage"}),q.add(B,{name:"execute-input"}),q.add(le,{name:"execute"}),q.add(ae,{name:"execute-context"}),q.add(Ce,{name:"verify"}),q.add($,{name:"verify-context"}),q.add(he,{name:"verify-dispatch"}),q.add(M,{name:"reflect"}),q.add(f.node,{name:"strategy"}),q.addDisposer(M.subscribe(()=>{})),J)for(let[k,D]of J)q.add(D,{name:`priority/${k}`}),q.addDisposer(D.subscribe(()=>{}));q.mount("queues",a),q.mount("gates",S);for(let[k,D]of R)q.mount(`jobs/${k}`,D);return q.tagFactory("harnessLoop",ht(e)),q}function ls(r,e,t){if(!t.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 n=t.lastInteractionNs,s=t.priority??{},o={...rt,...s.severityWeights},i=s.decayRate??ot,a=s.effectivenessThreshold??.7,u=s.effectivenessBoost??15,d=new Map;for(let[c,p]of r){let l=I([p.latest,e.node,n],h=>{let f=h[0];if(f==null)return 0;let g=o[f.severity??"medium"]??40,m=(K()-h[2])/1e9,T=g*Math.exp(-i*Math.max(0,m)),y=`${f.rootCause}\u2192${f.intervention}`,_=h[1]?.get(y);return _&&_.successRate>=a&&(T+=u),T},{name:`priority/${c}`});d.set(c,l)}return d}function fs(r,e){let t=Vt(r,e),n={};for(let s of _e){let o=r.queues.has(s)?r.queues.topic(s):null;n[s]=o?.retained().length??0}return{...t,queueDepths:n,strategyEntries:r.strategy.node.cache?.size??0,totalRetries:r.totalRetries.cache??0,totalReingestions:r.totalReingestions.cache??0}}Ne();function ps(r){let e={};for(let{label:t,paths:n}of r.stageNodes())for(let s of n)e[s]=t;return e}function hs(r,e){let t=e?.logger===null?null:e?.logger??console.log,n=e?.detail??"summary",s=K(),o=[],i=[],a=ps(r);function u(){return(K()-s)/1e9}function d(c,p,l){let h={elapsed:u(),stage:c,type:p};n!=="summary"&&(h.summary=ms(l)),n==="full"&&(h.data=l),i.push(h)}for(let[c,p]of Object.entries(a))try{let l=r.observe(c,{format:"stage-log",stageLabels:a,logger:t?h=>t(h):()=>{},includeTypes:["data","error","complete"]});l.onEvent(h=>{h.type==="data"?d(p,"data",h.data):h.type==="error"?d(p,"error",h.data):h.type==="complete"&&d(p,"complete",void 0)}),o.push(l)}catch(l){let h=l instanceof Error?l.message:String(l);d(p,"error",`observe-unavailable: ${c} \u2014 ${h}`),t&&t(`[${u().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 ms(r){if(r==null)return"null";if(typeof r=="string")return Fr(r,80);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return Fr(e,120)}catch{return String(r)}}function Fr(r,e){return r.length>e?`${r.slice(0,e-1)}\u2026`:r}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,dispatchActuator,effectivenessTracker,evalIntakeBridge,evalSource,evalVerifier,harnessEvalPair,harnessLoop,harnessProfile,harnessTrace,notifyEffect,priorityScore,refineExecutor,resolvePromptFn,strategyKey,strategyModel});
42
+ }`;function gt(r,e,t){if(typeof r=="function")return r;let n=r??e;return s=>t(n,s)}te();Me();Oe();be();te();var vn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:t,defaultTtl:n}=e;if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(n!==void 0&&n<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=t,this._defaultTtl=n}get version(){return this._version}get size(){return this._store.size}has(e){let t=this._store.get(e);return t===void 0?!1:this._isExpired(t)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,t),!0)}get(e){let t=this._store.get(e);if(t!==void 0){if(this._isExpired(t)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,t),t.value}}set(e,t,n){let s=this._resolveExpiresAt(n);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:t,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(e,t){let n=this._resolveExpiresAt(t),s=0;try{for(let[o,i]of e)this._store.has(o)&&this._store.delete(o),this._store.set(o,{value:i,expiresAt:n}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let t=this._store.delete(e);return t&&(this._version+=1),t}deleteMany(e){let t=0;try{for(let n of e)this._store.delete(n)&&(t+=1)}finally{t>0&&(this._version+=1)}return t}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=K(),t=0;for(let[n,s]of this._store)this._isExpired(s,e)&&(this._store.delete(n),t+=1);return t>0&&(this._version+=1),t}toMap(){let e=K(),t=new Map;for(let[n,s]of this._store)this._isExpired(s,e)||t.set(n,s.value);return t}_resolveExpiresAt(e){let t=e??this._defaultTtl;if(t!==void 0){if(!Number.isFinite(t)||t<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${t})`);return K()+t*1e9}}_isExpired(e,t){return e.expiresAt===void 0?!1:(t??K())>=e.expiresAt}_touchLru(e,t){this._store.delete(e),this._store.set(e,t)}_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 ut(r={}){let{name:e,maxSize:t,defaultTtl:n,versioning:s,backend:o,retention:i}=r;if(i&&t!==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:t,defaultTtl:n}),d=V(a.toMap(),{name:e,describeKind:"state",equals:(l,h)=>l===h,...s!=null?{versioning:s}:{}});function u(){let l=a.toMap();U(()=>{d.down([[Q]]),d.down([[D,l]])})}function c(){if(!i)return;let l=a.toMap(),h=i.archiveThreshold,f=i.maxSize,b=[];for(let[T,v]of l)b.push({key:T,value:v,score:i.score(T,v)});b.sort((T,v)=>T.score-v.score);let m=new Set;if(h!==void 0)for(let T of b)if(T.score<h)m.add(T.key);else break;if(f!==void 0&&b.length-m.size>f)for(let T of b){if(b.length-m.size<=f)break;m.has(T.key)||m.add(T.key)}if(m.size!==0)for(let T of b)m.has(T.key)&&(i.onArchive?.(T.key,T.value,T.score),a.delete(T.key))}function p(l,h="mutation"){let f=a.version;try{return l()}finally{a.version!==f&&(h==="mutation"&&c(),u())}}return{entries:d,has(l){return p(()=>a.has(l),"read")},get(l){return p(()=>a.get(l),"read")},set(l,h,f){p(()=>a.set(l,h,f?.ttl))},setMany(l,h){p(()=>a.setMany(l,h?.ttl))},delete(l){p(()=>a.delete(l))},deleteMany(l){p(()=>a.deleteMany(l))},clear(){p(()=>a.clear())},pruneExpired(){p(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}Pe();function Co(r){let e=ut({name:r?.name??"effectiveness-entries"}),t=G([e.entries],([i])=>new Map(i),{name:`${r?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,p]of d){let l=u.get(c);if(!l||p.attempts!==l.attempts||p.successes!==l.successes)return!1}return!0}});function n(i,a){let d=e.get(i),u=(d?.attempts??0)+1,c=(d?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:u,successes:c,successRate:c/u})}function s(i){return e.get(i)}let o=de(t);return{node:t,record:n,lookup:s,dispose:()=>{o(),e.dispose()}}}Me();te();te();Me();Oe();be();Ie();te();At();Me();Oe();tt();be();rt();Ie();te();Oe();function Tn(r,e){if(Object.is(r,e))return!0;if(r==null||e==null||typeof r!="object"||typeof e!="object")return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let o=0;o<r.length;o++)if(!Tn(r[o],e[o]))return!1;return!0}if(Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;let s=new Set(n);for(let o of t)if(!s.has(o)||!Tn(r[o],e[o]))return!1;return!0}function lr(r,e){return`${r}\0${e}`}function _n(r,e){let t=[],n=new Set(r.subgraphs),s=new Set(e.subgraphs),o=[];for(let m of s)n.has(m)||o.push(m);o.sort();for(let m of o)t.push({type:"subgraph-mounted",path:m});let i=new Set(Object.keys(r.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let m of a)i.has(m)||d.push(m);d.sort();for(let m of d)t.push({type:"node-added",path:m,node:{...e.nodes[m]}});let u=[];for(let m of a){if(!i.has(m))continue;let T=r.nodes[m]?.meta,v=e.nodes[m]?.meta;T==null&&v==null||Tn(T??{},v??{})||u.push(m)}u.sort();for(let m of u)t.push({type:"node-meta-changed",path:m,prevMeta:r.nodes[m]?.meta??{},nextMeta:e.nodes[m]?.meta??{}});let c=new Map;for(let m of r.edges)c.set(lr(m.from,m.to),m);let p=new Map;for(let m of e.edges)p.set(lr(m.from,m.to),m);let l=[];for(let[m,T]of p)c.has(m)||l.push(T);l.sort((m,T)=>m.from<T.from?-1:m.from>T.from?1:m.to<T.to?-1:m.to>T.to?1:0);for(let m of l)t.push({type:"edge-added",from:m.from,to:m.to});let h=[];for(let[m,T]of c)p.has(m)||h.push(T);h.sort((m,T)=>m.from<T.from?-1:m.from>T.from?1:m.to<T.to?-1:m.to>T.to?1:0);for(let m of h)t.push({type:"edge-removed",from:m.from,to:m.to});let f=[];for(let m of i)a.has(m)||f.push(m);f.sort();for(let m of f)t.push({type:"node-removed",path:m});let b=[];for(let m of n)s.has(m)||b.push(m);b.sort();for(let m of b)t.push({type:"subgraph-unmounted",path:m});return{events:t,flushedAt_ns:K()}}Pe();fr();pr();on();function hr(r,e,t,n={}){let s=e in r.nodes,o=t in r.nodes;if(!s)return $t(e,t,"no-such-from");if(!o)return $t(e,t,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===t){if(n.findCycle===!0){let u=Do(r,e,n);if(u!=null)return u}let d=Vt(e,r.nodes[e],0,n);return jt(e,t,[d])}if(i===0)return $t(e,t,"no-path");let a=mr(r,e,t,i);return a.found?jt(e,t,gr(r,a.pathOrder,n)):$t(e,t,a.truncated?"max-depth-exceeded":"no-path")}function mr(r,e,t,n){let s=new Map,o=[{path:t,depth:0}],i=new Set([t]),a=0,d=!1;for(;a<o.length;){let p=o[a++];if(p.path===e)break;if(n!=null&&p.depth>=n){let b=r.nodes[p.path];b?.deps&&b.deps.length>0&&(d=!0);continue}let l=r.nodes[p.path];if(l==null)continue;let h=l.deps??[],f=new Map;for(let b=0;b<h.length;b++){let m=h[b];if(!m)continue;let T=f.get(m);T==null&&(T=[],f.set(m,T)),T.push(b)}for(let[b,m]of f)i.has(b)||(i.add(b),s.set(b,{from:p.path,depIndices:m}),o.push({path:b,depth:p.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==t;){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 Do(r,e,t){let n=r.nodes[e];if(n==null)return null;let s=n.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=Vt(e,n,0,t);a.dep_index=o[0];let d=Vt(e,n,1,t);return jt(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=mr(r,d,e,t.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:jt(e,e,gr(r,i.pathOrder,t))}function gr(r,e,t){return e.map((n,s)=>{let o=r.nodes[n.path],i=Vt(n.path,o,s,t);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function Vt(r,e,t,n){let s={path:r,type:e.type,hop:t};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=n.annotations?.get(r)??e.annotation;o!=null&&(s.annotation=o);let i=n.lastMutations?.get(r)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function jt(r,e,t){return br(r,e,!0,"ok",t)}function $t(r,e,t){return br(r,e,!1,t,[])}function br(r,e,t,n,s){let o=Mo(r,e,t,n,s);return{from:r,to:e,found:t,reason:n,steps:s,text:o,toJSON(){return{from:r,to:e,found:t,reason:n,steps:s}}}}function Mo(r,e,t,n,s){if(!t)switch(n){case"no-such-from":return`explainPath: no node named "${r}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${r}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${r}" to "${e}"`}let o=[`Causal path: ${r} \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: ${Io(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(`
43
+ `)}function Io(r){if(r===void 0)return"<sentinel>";if(r===null)return"null";if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(r)}}Ie();var se={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},Go=Symbol.for("sizeof");function yr(r){let e=new WeakSet,t=new WeakSet,n=[r],s=0;for(;n.length>0;){let o=n.pop();s+=Po(o,e,t,n)}return s}function Po(r,e,t,n){if(r==null)return 0;switch(typeof r){case"number":return se.number;case"boolean":return se.boolean;case"string":return se.string+r.length*2;case"bigint":return se.bigint+Lo(r);case"symbol":return se.symbol;case"function":return e.has(r)?0:(e.add(r),se.function);case"undefined":return 0}let o=r;if(e.has(o))return 0;e.add(o);let i=o[Go];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 se.date;if(o instanceof RegExp)return se.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 se.error+u+c}if(typeof URL<"u"&&o instanceof URL)return se.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return se.promise;if(o instanceof WeakMap)return se.weakmap;if(o instanceof WeakSet)return se.weakset;if(o instanceof Map){let u=se.map;for(let[c,p]of o)u+=se.mapEntry,n.push(c),n.push(p);return u}if(o instanceof Set){let u=se.set;for(let c of o)u+=se.setEntry,n.push(c);return u}if(Array.isArray(o)){let u=se.array+o.length*8;for(let c of o)n.push(c);return u}if(o instanceof ArrayBuffer)return t.has(o)?0:(t.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let u=o;return t.has(u.buffer)?48:(t.add(u.buffer),u.buffer.byteLength+48)}let a=se.object,d=Object.keys(o);for(let u of d){a+=se.string+u.length*2;try{n.push(o[u])}catch{}}return a}function Lo(r){let e=r<0n?-r:r;if(e===0n)return 0;let t=e.toString(2).length;return Math.ceil(t/32)*8}function zt(r,e){let t=e?.topN??10,n=r.describe({detail:"standard"}),s=[],o=r._collectObserveTargets;typeof o=="function"&&o.call(r,"",s);let i=new Map;for(let[l,h]of s)i.set(l,h);let a=[];for(let[l,h]of Object.entries(n.nodes)){let f=i.get(l),b=f instanceof oe?f:null,m=b?yr(b.cache):0,T=b?b._sinkCount:0,v=h.deps?.length??0,g=h.type==="effect"&&T===0,_=T===0?h.type==="effect"?"orphan-effect":h.type==="derived"?"idle-derived":h.type==="producer"?"idle-producer":null:null;a.push({path:l,type:h.type,status:h.status??"unknown",valueSizeBytes:m,subscriberCount:T,depCount:v,isOrphanEffect:g,orphanKind:_})}let d=a.reduce((l,h)=>l+h.valueSizeBytes,0),u=(l,h)=>[...a].sort(h??((f,b)=>b[l]-f[l])).slice(0,t),c=a.filter(l=>l.orphanKind!=null),p=a.filter(l=>l.isOrphanEffect);return{nodeCount:a.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:p}}var J="::",Ce="__meta__",Je=1;function vr(r,e){let t=Math.max(16,r.size*4),n=0;for(;r.size>0;){if(n++>=t){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${t}); ${r.size} disposer(s) discarded`),r.clear();return}let s=r.values().next();if(s.done)return;let o=s.value;r.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Nr(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function Fo(r){if(r!=null)return Nr(r)?r.cache:r}function Ye(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function je(r){return Ye(r)?r.cache??"":r}function Tr(r){return Ye(r)?r.cache??0:r}function _r(r){return Ye(r)?r.cache??!1:r}function $o(r){let e=[];for(let t of Object.keys(r).sort()){let n=r[t].v;n!=null&&e.push(`${t} ${n.id} ${n.version}`)}return e.join(`
44
+ `)}function wr(r){if(r.version!==Je)throw new Error(`unsupported snapshot version ${String(r.version)} (expected ${Je})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in r))throw new Error(`snapshot missing required key "${e}"`);if(typeof r.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof r.nodes!="object"||r.nodes===null||Array.isArray(r.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(r.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(r.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Vo(r,e){let t=new WeakMap,n=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=t.get(s);if(i==null&&(i=new WeakSet,t.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 l=o;if(s.length!==l.length)return!1;for(let h=0;h<s.length;h++)if(!n(s[h],l[h]))return!1;return!0}if(s instanceof Map){let l=o;if(s.size!==l.size)return!1;for(let[h,f]of s)if(!l.has(h)||!n(f,l.get(h)))return!1;return!0}if(s instanceof Set){let l=o;if(s.size!==l.size)return!1;for(let h of s){let f=!1;for(let b of l)if(n(h,b)){f=!0;break}if(!f)return!1}return!0}if(ArrayBuffer.isView(s)){let l=s,h=o;if(l.length!==h.length)return!1;for(let f=0;f<l.length;f++)if(l[f]!==h[f])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 l of u)if(!p.has(l)||!n(s[l],o[l]))return!1;return!0};return n(r,e)}function jo(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ht(r){let e="^";for(let t=0;t<r.length;t+=1){let n=r[t];if(n==="*"){e+=".*";continue}if(n==="?"){e+=".";continue}if(n==="["){let s=r.indexOf("]",t+1);if(s<=t+1){e+="\\[";continue}let o=r.slice(t+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,t=s;continue}e+=jo(n)}return e+="$",new RegExp(e)}var zo={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"},Ho={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function wn(r){if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||r==null)return String(r);try{return JSON.stringify(r)}catch{return"[unserializable]"}}function Bo(r){return r==="none"?Ho:r==="ansi"||r==null?zo:{data:r.data??"",dirty:r.dirty??"",resolved:r.resolved??"",invalidate:r.invalidate??"",pause:r.pause??"",resume:r.resume??"",complete:r.complete??"",error:r.error??"",teardown:r.teardown??"",derived:r.derived??"",path:r.path??"",reset:r.reset??""}}function xr(r){if(r==null)return{};let e=r.detail;return e==="full"?{...r,structured:r.structured??!0,timeline:r.timeline??!0,causal:r.causal??!0,derived:r.derived??!0}:e==="minimal"?{...r,structured:r.structured??!0}:r.format==="stage-log"?{...r,structured:r.structured??!0,timeline:r.timeline??!0}:r}function qo(r,e,t){for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);if(s<32||s===127)throw new Error(`Graph "${e}": ${t} "${r}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function xn(r,e,t){if(r==="")throw new Error(`Graph "${e}": ${t} name must be non-empty`);if(r.includes(J))throw new Error(`Graph "${e}": ${t} "${r}" must not contain '${J}' (path separator)`);if(r===Ce)throw new Error(`Graph "${e}": ${t} name "${Ce}" is reserved for meta companion paths`);qo(r,e,t)}function Uo(r,e){if(r==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let t=r.split(J);for(let n of t)if(n==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return t}function Ko(r,e){let t=!1;for(let s of r)if(!e.isMetaPassthrough(s[0])){t=!0;break}return t?r.filter(s=>e.isMetaPassthrough(s[0])):r}function Er(r){for(let e of r._mounts.values())Er(e);for(let e of r._nodes.values())try{e.down([[pe]],{internal:!0})}catch{}}var ce=class r{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;_factory;_factoryArgs;constructor(e,t){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(J))throw new Error(`Graph name must not contain '${J}' (got "${e}")`);if(e===Ce)throw new Error(`Graph name "${Ce}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??nt,this._traceRing=new bt(t?.traceCapacity??1e3),t?.versioning!=null&&this.setVersioning(t.versioning),typeof t?.factory=="string"&&(this._factory=t.factory,t.factoryArgs!==void 0&&(this._factoryArgs=t.factoryArgs))}tagFactory(e,t){return this._factory=e,this._factoryArgs=t,this}ancestors(e=!0){let t=[],n=e?this:this._parent;for(;n!=null;)t.push(n),n=n._parent;return t}get topology(){return this._topology==null&&(this._topology=ue(e=>{let t=n=>{e.emit(n)};return this._topologyEmitters.add(t),()=>{this._topologyEmitters.delete(t)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let t of this._topologyEmitters)t(e)}nameOf(e){return this._nodeToName.get(e)}add(e,t){let n=e.name,s=t?.name??n;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=t?.annotation;if(xn(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:K()})),e}setVersioning(e){if(e!=null)for(let t of this._nodes.values())t instanceof oe&&t._applyVersioning(e)}remove(e){xn(e,this.name,"remove");let t=this._mounts.get(e);if(t){let o={kind:"mount",nodes:[],mounts:[]},i=[];t._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${J}${Ce}${J}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...t._collectSubgraphs(`${e}${J}`)),this._mounts.delete(e),t._parent=void 0,Er(t),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(n),n.down([[pe]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let t=typeof e=="function"?e:(()=>{let o=Ht(e);return i=>o.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>t(o));for(let o of s){let i=this.remove(o);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),t=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=e.length)return{value:void 0,done:!0};let s=e[n++];return{value:[s,t.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(J))return this.resolve(e);let t=this._nodes.get(e);if(!t)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return t}get(e){return this.node(e).cache}set(e,t,n){let s=n?.internal===!0;this.node(e).down([[D,t]],{actor:n?.actor,internal:s,delivery:"write"})}setAll(e,t){let n=Symbol.iterator in e?e:Object.entries(e);U(()=>{for(let[s,o]of n)this.set(s,o,t)})}invalidate(e,t){let n=t?.internal===!0;this.node(e).down([[Re]],{actor:t?.actor,internal:n,delivery:"write"})}error(e,t,n){let s=n?.internal===!0;this.node(e).down([[I,t]],{actor:n?.actor,internal:s,delivery:"write"})}complete(e,t){let n=t?.internal===!0;this.node(e).down([[$]],{actor:t?.actor,internal:n,delivery:"write"})}edges(e){let t=e?.recursive===!0,n=new Map;if(!t){for(let[d,u]of this._nodes)n.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof oe)for(let c of u._deps){let p=n.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 oe)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,t){if(t===void 0){let s=new r(e);return this.mount(e,s)}if(typeof t=="function"){let s=new r(e);return t(s),this.mount(e,s)}let n=t;if(xn(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 s=this;s!=null;s=s._parent)if(s===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 t=Uo(e,this.name);return this._resolveFromSegments(t)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let t=e;if(t[0]===this.name&&(t=t.slice(1),t.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=t[0],s=t.slice(1);if(s.length===0){let a=this._nodes.get(n);if(a)return a;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let o=this._nodes.get(n);if(o&&s.length>0&&s[0]===Ce)return this._resolveMetaChainFromNode(o,s,t.join(J));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${s.join(J)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(s.join(J))}_resolveMetaChainFromNode(e,t,n){let s=e,o=0,i=[...t];for(;o<i.length;){if(i[o]!==Ce)throw new Error(`Graph "${this.name}": expected ${Ce} segment in meta path "${n}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Ce} in "${n}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${n}"`);s=d,o+=2}return s}signal(e,t){if(t?.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 n=[];if(this._signalDeliver(e,t??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(e,t,n,s){for(let d of this._mounts.values())d._signalDeliver(e,t,n,s);let i=t.internal===!0?{internal:!0}:{actor:t.actor,delivery:"signal"},a=Ko(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!n.has(u)){n.add(u);try{u.down(e,i)}catch(c){if(c instanceof Se)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,n,i,s)}}}_signalMetaSubtree(e,t,n,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!n.has(a)){n.add(a);try{a.down(t,s)}catch(d){if(d instanceof Se)throw d;o.push(d)}this._signalMetaSubtree(a,t,n,s,o)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let t=Fo(e?.actor),n=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let s=Mt(e?.detail,e?.fields),o=e?.detail==="spec",i=s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[_,w]of a)d.set(w,_);let u=[];{let _=a.map(([,y])=>y),w=new Set(d.values()),E=0;for(;_.length>0;){let y=_.shift();if(y instanceof oe)for(let x of y._deps){let k=x.node;if(d.has(k))continue;let S=k.name??"",N=S;if(!N||w.has(N))if(S){let P=2;for(;w.has(`${S}#${P}`);)P++;N=`${S}#${P}`}else for(N=`__internal__/${E++}`;w.has(N);)N=`__internal__/${E++}`;d.set(k,N),w.add(N),u.push([N,k]),_.push(k)}}}let c=[...a,...u],p={};for(let[_,w]of c){if(t!=null&&!w.allowsObserve(t))continue;let E=hn(w,i,o),y=w instanceof oe?w._deps.map(N=>d.get(N.node)??N.node.name??""):[],{name:x,...k}=E,S={...k,deps:y};if(!o){let N=this._annotations.get(_);N!=null&&(S.annotation=N)}if(n!=null)if(typeof n=="function"){let N=n;if(!(N.length>=2?N(_,S):N(S)))continue}else{let N=!0;for(let[P,H]of Object.entries(n)){let F=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(F==="depsIncludes"){if(!S.deps.includes(String(H))){N=!1;break}continue}if(F==="metaHas"){if(!Object.hasOwn(S.meta??{},String(H))){N=!1;break}continue}if(S[F]!==H){N=!1;break}}if(!N)continue}p[_]=S}let l=new Set(Object.keys(p)),h=[];for(let[_,w]of c)if(w instanceof oe)for(let E of w._deps){let y=d.get(E.node);y!=null&&h.push([y,_])}h.sort((_,w)=>_[0]<w[0]?-1:_[0]>w[0]?1:_[1]<w[1]?-1:_[1]>w[1]?1:0);let f=h.map(([_,w])=>({from:_,to:w}));(t!=null||n!=null)&&(f=f.filter(_=>l.has(_.from)&&l.has(_.to)));let b=this._collectSubgraphs(""),m=t!=null||n!=null?b.filter(_=>{let w=`${_}${J}`;return[...l].some(E=>E===_||E.startsWith(w))}):b,T=this,v=e;return{name:this.name,nodes:p,edges:f,subgraphs:m,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(_){let w={...v};return Array.isArray(_)?(w.fields=_,w.detail=void 0):(w.detail=_,w.fields=void 0),T.describe(w)}}}_collectSubgraphs(e){let t=[];for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${n}`;t.push(s),t.push(...this._mounts.get(n)._collectSubgraphs(`${s}${J}`))}return t}resourceProfile(e){return zt(this,e)}reachable(e,t,n={}){return n.withDetail===!0?Nn(this.describe(),e,t,{...n,withDetail:!0}):Nn(this.describe(),e,t,n)}explain(e,t,n){return n?.reactive===!0?this._explainReactive(e,t,n):this._explainStatic(je(e),je(t),{...n?.maxDepth!==void 0?{maxDepth:Tr(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:_r(n.findCycle)}:{}})}_explainStatic(e,t,n){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 hr(s,e,t,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let t={...e,reactive:!1},n=e.reactiveName??"describe",s=0,o=V(s,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,et(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let g=v.type;g!=="data"&&g!=="error"&&g!=="complete"&&g!=="teardown"||u()}),p=[],l=new WeakSet,h=v=>{if(l.has(v)||d)return;l.add(v);let g=v.topology.subscribe(_=>{for(let w of _){if(w[0]!==D)continue;let E=w[1];if(u(),E.kind==="added"&&E.nodeKind==="mount"){let y=v._mounts.get(E.name);y!=null&&h(y)}}});p.push(g);for(let _ of v._mounts.keys()){let w=v._mounts.get(_);w!=null&&h(w)}};h(this);let f,b=e.actor;Nr(b)&&(f=b.subscribe(v=>{let g=!1,_=!1;for(let w of v){let E=w[0];E===D?g=!0:(E===$||E===I||E===pe)&&(_=!0)}g&&u(),_&&(f?.(),f=void 0,u())}));let m;try{m=G([o],()=>this.describe(t),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(v,g)=>v===g})}catch(v){c(),f?.();for(let g of p)g();throw i.dispose(),v}let T=de(m);return{node:m,dispose(){d=!0,c(),f?.();for(let v of p)v();p.length=0,i.dispose(),T()}}}_describeReactiveDiff(e){let t={...e,reactive:!1},n=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},o=this.describe(t),i=_n(s,o),a=V(i,{name:n,meta:{domain:"audit",kind:"describe-diff"},equals:(l,h)=>l===h}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(l=>{if(!u)for(let h of l){if(h[0]!==D)continue;let f=h[1],b=_n(o,f);o=f,b.events.length!==0&&a.emit(b)}}),p=de(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[pe,"describe-diff disposed"]]),p()}}}_explainReactive(e,t,n){let s=0,o=V(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,et(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let g=v.type;g!=="data"&&g!=="error"&&g!=="complete"&&g!=="teardown"||u()}),p=[];e!=null&&Ye(e)&&p.push(e),t!=null&&Ye(t)&&p.push(t),n?.maxDepth!=null&&Ye(n.maxDepth)&&p.push(n.maxDepth),n?.findCycle!=null&&Ye(n.findCycle)&&p.push(n.findCycle);let l=()=>{for(let v of p)if(v.cache===void 0)return!1;return!0},h=()=>{let v=je(e),g=je(t);return{from:v,to:g,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:v,to:g,found:!1,reason:"pending",steps:[]})}},f;try{f=G([o],()=>{if(!l())return h();let v=je(e),g=je(t),_={...n?.maxDepth!==void 0?{maxDepth:Tr(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:_r(n.findCycle)}:{}};return this._explainStatic(v,g,_)},{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:je(e),to:je(t)},equals:(v,g)=>v.found===g.found&&v.reason===g.reason&&v.steps.length===g.steps.length&&Wo(v.steps,g.steps)})}catch(v){throw c(),i.dispose(),v}let b=de(f),m=[],T=v=>{let g;return g=v.subscribe(_=>{let w=!1,E=!1;for(let y of _){let x=y[0];x===D?w=!0:(x===$||x===I||x===pe)&&(E=!0)}(w||E)&&u(),E&&g&&(g(),g=void 0)}),()=>{g&&(g(),g=void 0)}};for(let v of p)m.push(T(v));return{node:f,dispose(){d=!0,c();for(let v of m)v?.();m.length=0,i.dispose(),b()}}}_pathsMatching(e){let t=Ht(e),n=[];return this._collectObserveTargets("",n),n.map(([s])=>s).filter(s=>t.test(s))}_collectObserveTargets(e,t){for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${J}${n}`;this._mounts.get(n)._collectObserveTargets(s,t)}for(let n of[...this._nodes.keys()].sort()){let s=this._nodes.get(n),o=e===""?n:`${e}${J}${n}`;t.push([o,s]),this._appendMetaObserveTargets(o,s,t)}}_appendMetaObserveTargets(e,t,n){for(let s of Object.keys(t.meta).sort()){let o=t.meta[s],i=`${e}${J}${Ce}${J}${s}`;n.push([i,o]),this._appendMetaObserveTargets(i,o,n)}}observe(e,t){let n=typeof e=="string",o=xr(n?t:e);if(o.reactive===!0)return this._observeReactive(n?e:void 0,o);let 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(n){let c=e,p=this.resolve(c);if(a!=null&&!p.allowsObserve(a))throw new Se({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,p]],o,"one"):{subscribe(l){return p.subscribe(l)},up(l){try{p.up?.(l)}catch(h){if(h instanceof Se)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(([l,h])=>h.subscribe(f=>{c(l,f)}));return()=>{for(let l of p)l()}},up:(c,p)=>{try{this.resolve(c).up?.(p)}catch(l){if(l instanceof Se)return;throw l}}}}_observeReactive(e,t){let n=t.tiers,s=n!=null?new Set(n):null,o=t.reactiveName??"observe";return ue(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let b={events:a.slice(),flushedAt_ns:K()};a.length=0,i.emit(b)},p={...t,reactive:!1,structured:!0,timeline:!0},l=e!=null?this.observe(e,p):this.observe(p),h=b=>{u||(a.push(b),!d&&(d=!0,et(()=>{d=!1,c()})))};for(let b of l.events)h(b);let f=l.onEvent(h);return()=>{u=!0,f(),l.dispose()}},{name:o,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,t,n){let s=n==="one"?e[0]?.[0]:void 0,o=i=>{if(n==="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,t,o)}_createObserveResult(e,t,n){let s=t.timeline===!0,o=t.causal===!0,i=t.derived===!0,a=t.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,c=t.maxEvents,p=c!=null&&c>0?new bt(c):null,l=[],h=new Set,f=t.tiers!=null?new Set(t.tiers):null,b={},m=new Set,T=0,v=0,g=0,_=0,w=0,E=0,y=!1,x=!1,k=0,S=new Map,N=new Map,P=new Map,H=C=>{if(!(f!=null&&!f.has(C.type))){p?p.push(C):l.push(C);for(let q of h)q(C)}},F=C=>f==null||f.has(C),ye=()=>s?{timestamp_ns:K(),in_batch:ht(),batch_id:k}:{},ve=(C,q)=>{if(!(!u||!(C instanceof oe)))return C._setInspectorHook(ge=>{if(ge.kind==="dep_message")S.set(C,ge.depIndex);else if(ge.kind==="run"){let Ge=ge.batchData.map((R,M)=>R!=null&&R.length>0?R.at(-1):ge.prevData[M]);N.set(C,Ge);let we=ge.batchData.map(R=>R!=null?[...R]:void 0);P.set(C,we),i&&H({type:"derived",path:q,dep_values:Ge,dep_batches:we,...ye()})}})},ke=C=>{let q=S.get(C),ge=N.get(C);if(!o||ge==null)return{};let we=(q!=null&&q>=0&&C instanceof oe?C._deps[q]:void 0)?.node,R=we?.v,M=P.get(C);return{trigger_dep_index:q,trigger_dep_name:we?.name,...R!=null?{trigger_version:{id:R.id,version:R.version}}:{},dep_values:[...ge],...M!=null?{dep_batches:M}:{}}},Ee=[],j=[];for(let[C,q]of e){let ge=ve(q,C);ge&&Ee.push(ge),j.push(q.subscribe(Ge=>{k++;for(let we of Ge){let R=we[0],M=ye();if(R===D){b[C]=we[1];let Z=q instanceof oe?q.lastMutation?.actor??Qe:Qe;H({type:"data",path:C,data:we[1],actor:Z,...M,...ke(q)})}else if(a)R===Q?F("dirty")&&T++:R===W?F("resolved")&&v++:R===Re?F("invalidate")&&g++:R===De?F("pause")&&_++:R===Ve?F("resume")&&w++:R===pe?F("teardown")&&E++:R===$&&!m.has(C)?F("complete")&&(y=!0):R===I&&F("error")&&(x=!0,m.add(C));else if(R===Q)F("dirty")&&T++,H({type:"dirty",path:C,...M});else if(R===W)F("resolved")&&v++,H({type:"resolved",path:C,...M,...ke(q)});else if(R===Re)F("invalidate")&&g++,H({type:"invalidate",path:C,...M});else if(R===De)F("pause")&&_++,H({type:"pause",path:C,lockId:we[1],...M});else if(R===Ve)F("resume")&&w++,H({type:"resume",path:C,lockId:we[1],...M});else if(R===$)F("complete")&&!m.has(C)&&(y=!0),H({type:"complete",path:C,...M});else if(R===I){F("error")&&(x=!0,m.add(C));let Z=q instanceof oe?q.lastMutation?.actor??Qe:Qe;H({type:"error",path:C,data:we[1],actor:Z,...M})}else R===pe&&(F("teardown")&&E++,H({type:"teardown",path:C,...M}))}}))}let z=!1,L=()=>{if(!z){z=!0;for(let C of j)C();for(let C of Ee)C();for(let C of X)C({value:void 0,done:!0});X.length=0}},ie=[],X=[];h.add(C=>{let q=X.shift();q?q({value:C,done:!1}):ie.push(C)});let me={get values(){return b},get dirtyCount(){return T},get resolvedCount(){return v},get invalidateCount(){return g},get pauseCount(){return _},get resumeCount(){return w},get teardownCount(){return E},get events(){return p?p.toArray():[...l]},get anyCompletedCleanly(){return y},get anyErrored(){return x},get completedWithoutErrors(){return y&&!x},onEvent(C){return h.add(C),()=>h.delete(C)},dispose:L,expand(C){L();let q={...t};return typeof C=="string"?q.detail=C:Object.assign(q,C),n(xr(q))},[Symbol.asyncIterator](){return{next(){return ie.length>0?Promise.resolve({value:ie.shift(),done:!1}):z?Promise.resolve({value:void 0,done:!0}):new Promise(C=>X.push(C))},return(){return L(),Promise.resolve({value:void 0,done:!0})}}}};return t.format!=null&&this._attachFormatLogger(me,t),me}_attachFormatLogger(e,t){let n=t.format;if(n==null)return;let s=t.logger??(f=>console.log(f)),o=t.includeTypes?new Set(t.includeTypes):null,i=t.excludeTypes?new Set(t.excludeTypes):null,a=o==null&&i==null?()=>!0:f=>(o==null||o.has(f))&&(i==null||!i.has(f)),d=Bo(t.theme),u=n==="stage-log"?K():0,c=f=>f==null?"":t.stageLabels?.[f]??f,p=(f,b)=>f.length>b?`${f.slice(0,b-1)}\u2026`:f,l=f=>f.type==="data"||f.type==="error"?p(wn(f.data),120):"",h=f=>{if(n==="stage-log"){let y=(K()-u)/1e9,x=c(f.path).padEnd(9);if(f.type==="data"){let k=l(f);return`[${y.toFixed(3)}s] ${x} \u2190${k?` ${k}`:""}`}if(f.type==="error"){let k=l(f);return`[${y.toFixed(3)}s] ${x} \u2717${k?` ${k}`:""}`}return f.type==="complete"?`[${y.toFixed(3)}s] ${x} \u25A0 complete`:`[${y.toFixed(3)}s] ${x} ${f.type}`}if(n==="json")try{return JSON.stringify(f)}catch{return JSON.stringify({type:f.type,path:f.path,data:"[unserializable]"})}let b=d[f.type]??"",m=f.path?`${d.path}${f.path}${d.reset} `:"",T=f.type==="data"||f.type==="error",v=f.type==="pause"||f.type==="resume",g=T?` ${wn(f.data)}`:v?` ${wn(f.lockId)}`:"",_=f.type==="data"||f.type==="resolved"||f.type==="derived"?f:void 0,w=_?.trigger_dep_name!=null?` <- ${_.trigger_dep_name}`:_?.trigger_dep_index!=null?` <- #${_.trigger_dep_index}`:"",E=f.in_batch?" [batch]":"";return`${m}${b}${f.type.toUpperCase()}${d.reset}${g}${w}${E}`};e.onEvent(f=>{a(f.type)&&s(h(f),f)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){vr(this._disposers,this.name),this.signal([[pe]],{internal:!0}),vr(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:t,...n}=this.describe({detail:"full"}),s={};for(let a of Object.keys(n.nodes).sort()){let{lastMutation:d,guard:u,...c}=n.nodes[a];s[a]=c}let o=[...n.subgraphs].sort(),i={...n,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 qn(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??nt,{codec:s,codecVersion:o,payload:i}=Un(e,n);return s.decode(i,o)}restore(e,t){if(wr(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let n=t?.only==null?null:(Array.isArray(t.only)?t.only:[t.only]).map(o=>Ht(o)),s=t?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(n!==null&&!n.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&&t?.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){t?.onError?.(o,a)}}}}}static fromSnapshot(e,t){wr(e);let n=typeof t=="function"?t:t?.build,s=typeof t=="function"?void 0:t?.factories,o=new r(e.name);if(n)return n(o),o.restore(e),o;for(let h of[...e.subgraphs].sort((f,b)=>{let m=f.split(J).length,T=b.split(J).length;return m!==T?m-T:f<b?-1:f>b?1:0})){let f=h.split(J),b=o;for(let m of f)b._mounts.has(m)||b.mount(m,new r(m)),b=b._mounts.get(m)}let i=s?Object.entries(s).map(([h,f])=>({re:Ht(h),factory:f})):[],a=h=>{for(let f of i)if(f.re.test(h))return f.factory},d=h=>{let f=h.split(J),b=f.pop();if(b==null||b.length===0)throw new Error(`invalid snapshot path "${h}"`);let m=o;for(let T of f){let v=m._mounts.get(T);if(!v)throw new Error(`unknown mount "${T}" in path "${h}"`);m=v}return[m,b]},u=Object.entries(e.nodes).filter(([h])=>!h.includes(`${J}${Ce}${J}`)).sort((h,f)=>h[0]<f[0]?-1:h[0]>f[0]?1:0),c=new Map(u),p=new Map,l=!0;for(;c.size>0&&l;){l=!1;for(let[h,f]of[...c.entries()]){let b=f?.deps??[];if(!b.every(w=>p.has(w)))continue;let[m,T]=d(h),v={...f?.meta??{}},g=a(h),_;if(f?.type==="state")_=V(f.value,{meta:v});else{if(g==null)continue;_=g(T,{path:h,type:f.type,value:f.value,meta:v,deps:b,resolvedDeps:b.map(w=>p.get(w))})}m.add(_,{name:T}),p.set(h,_),c.delete(h),l=!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()}attachSnapshotStorage(e,t={}){let n=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}));t.autoRestore===!0&&this._cascadeRestore(e,t.onError);let s=(u,c)=>{if(u.disposed)return;let p=$o(c.nodes);if(u.lastSnapshot!=null&&p!==""&&p===u.lastFingerprint)return;let l=u.seq+1,h=xe(),m=u.lastSnapshot==null||l%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:l,timestamp_ns:h,format_version:Je}:{name:this.name,mode:"diff",diff:kr(u.lastSnapshot,c),seq:l,timestamp_ns:h,format_version:Je};if(u.tier.filter&&!u.tier.filter(m))return;let T;try{T=u.tier.save(m)}catch(v){t.onError?.(v,u.tier);return}if(T&&typeof T.then=="function"){let _=(u.savePending??Promise.resolve()).then(()=>T,()=>T).then(()=>{u.disposed||(u.seq=l,u.lastSnapshot=c,u.lastFingerprint=p)},w=>{t.onError?.(w,u.tier)});u.savePending=_.finally(()=>{u.savePending===_&&(u.savePending=void 0)})}else u.seq=l,u.lastSnapshot=c,u.lastFingerprint=p},o=(u,c)=>{try{s(u,c)}catch(p){t.onError?.(p,u.tier)}},i=(u,c)=>{if(!c.some(f=>{let b=this.config.messageTier(f[0]);return b>=3&&b<5}))return;if(t.filter){let f=this.tryResolve(u);if(f==null)return;let b=hn(f,Mt("standard"));if(!t.filter(u,b))return}let l,h=()=>(l==null&&(l=this.snapshot()),l);for(let f of n)f.disposed||(f.debounceMs===0?o(f,h()):(f.timer==null&&(f.timer=new Ft),f.timer.start(f.debounceMs,()=>{f.disposed||o(f,this.snapshot())})))},a;if(t.paths!=null){let c=(typeof t.paths=="string"?this._pathsMatching(t.paths):t.paths).map(p=>{let l=this.tryResolve(p);return l==null?()=>{}:l.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 n)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,t){for(let n of e){let s;try{s=await n.load?.()}catch(i){t?.(i,n);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===Je&&o.nodes!=null)return this.restore(o),!0}catch(i){t?.(i,n)}}return!1}static async fromStorage(e,t,n){for(let s of t){let o;try{o=await s.load?.()}catch(d){n?.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===Je&&i.nodes!=null?i:void 0;if(a!=null)try{return r.fromSnapshot(a,n)}catch(d){n?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${t.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,t,n){if(e!=null&&t!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,t),this.config.inspectorEnabled){let s={path:e,annotation:t,timestamp_ns:K(),...n?.actor!=null?{actor:n.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 t=this._traceRing.toArray().filter(s=>!e(s)),n=this._traceRing.size-t.length;this._traceRing.clear();for(let s of t)this._traceRing.push(s);return n}static diff(e,t){let n=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(t.nodes)),o=[...s].filter(v=>!n.has(v)).sort(),i=[...n].filter(v=>!s.has(v)).sort(),a=[],d=[];for(let v of n){if(!s.has(v))continue;let g=e.nodes[v],_=t.nodes[v],w=g.v,E=_.v;w!=null&&E!=null&&w.id===E.id&&w.version!==E.version&&d.push({path:v,id:w.id,from:w.version,to:E.version});let y=w!=null&&E!=null&&w.id===E.id&&w.version===E.version;for(let x of["type","status","sentinel"]){let k=g[x],S=_[x];k!==S&&a.push({path:v,field:x,from:k,to:S})}if(!y)for(let x of["value","meta"]){let k=g[x],S=_[x];Vo(k,S)||a.push({path:v,field:x,from:k,to:S})}}let u=v=>`${v.from} ${v.to}`,c=new Set(e.edges.map(u)),p=new Set(t.edges.map(u)),l=t.edges.filter(v=>!c.has(u(v))),h=e.edges.filter(v=>!p.has(u(v))),f=new Set(e.subgraphs),b=new Set(t.subgraphs),m=[...b].filter(v=>!f.has(v)).sort(),T=[...f].filter(v=>!b.has(v)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:l,edgesRemoved:h,subgraphsAdded:m,subgraphsRemoved:T}}};function kr(r,e){let t=ce.diff(r,e),n={};for(let s of t.nodesAdded){let o=e.nodes[s];o!=null&&(n[s]=o)}return{...t,nodesAddedFull:n}}function Nn(r,e,t,n={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return n.withDetail?s:[];if(!n.both&&t!=="upstream"&&t!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=n.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return n.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[g,_]of Object.entries(r.nodes)){if(!g)continue;c.add(g);let w=_.deps??[];i.set(g,w);for(let E of w)E&&(c.add(E),a.has(E)||a.set(E,new Set),a.get(E).add(g))}for(let g of r.edges){if(g==null||typeof g!="object")continue;let _=typeof g.from=="string"?g.from:"",w=typeof g.to=="string"?g.to:"";!_||!w||(c.add(_),c.add(w),u.has(_)||u.set(_,new Set),u.get(_).add(w),d.has(w)||d.set(w,new Set),d.get(w).add(_))}if(!c.has(e))return n.withDetail?s:[];let p=n.both===!0,l=g=>{if(p){let y=i.get(g)??[],x=d.get(g),k=a.get(g),S=u.get(g),N=[...y];return x&&N.push(...x),k&&N.push(...k),S&&N.push(...S),N}if(t==="upstream"){let y=i.get(g)??[],x=d.get(g);return x?[...y,...x]:y}let _=a.get(g),w=u.get(g),E=_?[..._]:[];return w&&E.push(...w),E},h=new Set([e]),f=new Map,b=[{path:e,depth:0}],m=0,T=!1;for(;m<b.length;){let g=b[m++];if(o!=null&&g.depth>=o){l(g.path).length>0&&(T=!0);continue}for(let _ of l(g.path))!_||h.has(_)||(h.add(_),f.set(_,g.depth+1),b.push({path:_,depth:g.depth+1}))}let v=[...f.keys()].sort((g,_)=>g<_?-1:g>_?1:0);return n.withDetail?{paths:v,depths:f,truncated:T}:v}function Wo(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],s=e[t];if(n.path!==s.path||n.type!==s.type||n.status!==s.status||n.hop!==s.hop||n.dep_index!==s.dep_index||n.annotation!==s.annotation||n.value!==s.value||n.lastMutation!==s.lastMutation)return!1;let o=n.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}At();Me();tt();be();rt();te();Ie();yt();Me();be();Ie();te();var En=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=t,t!==void 0){if(this._buf=new Array(t),e&&e.length>0){let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}}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 t=e>=0?e:this._size+e;if(!(t<0||t>=this._size))return this._maxSize!==void 0?this._buf[(this._head+t)%this._maxSize]:this._buf[t]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let n=t;n<e.length;n++)this._rawAppend(e[n]);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 t=0;t<e;t++)this._buf[(this._head+t)%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 t=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,t);else{for(let n=0;n<t;n++)this._buf[(this._head+n)%this._maxSize]=void 0;this._head=(this._head+t)%this._maxSize}return this._size-=t,this._version+=1,t}slice(e,t){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${t})`);let n=t===void 0?this._size:Math.min(Math.max(t,0),this._size),s=Math.min(e,this._size);if(s>=n)return[];let o=n-s;if(this._maxSize===void 0)return this._buf.slice(s,n);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 t=Math.min(e,this._size);return this.slice(this._size-t,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this._buf[(this._head+t)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let t=0;t<e.length;t++)this._buf.push(e[t]);this._size=this._buf.length}else{let t=this._maxSize;for(let o=0;o<t;o++)this._buf[o]=void 0;this._head=0;let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}this._version+=1}_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 vt(r){return r.subscribe(()=>{})}var Jo=64;function dt(r,e={}){let{name:t,maxSize:n,versioning:s,guard:o,backend:i}=e,a=i??new En(r,n),d=V(a.toArray(),{name:t,describeKind:"state",equals:(y,x)=>y===x,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let y=a.toArray();U(()=>{d.down([[Q]],{internal:!0}),d.down([[D,y]],{internal:!0})})}let c=new Map,p=new Map,l=new Map;function h(y,x){return`${y}:${x===void 0?"END":x}`}function f(y){if(y.size<Jo)return;let x=y.keys().next();if(x.done)return;let k=y.get(x.value);k!==void 0&&k.dispose(),y.delete(x.value)}function b(y){let x=a.version;try{return y()}finally{a.version!==x&&u()}}function m(y){if(!Number.isInteger(y)||y<0)throw new RangeError(`tail: n must be a non-negative integer (got ${y})`);let x=c.get(y);if(x!==void 0)return c.delete(y),c.set(y,x),x.node;f(c);let k=G([d],([N])=>{let P=N;return y===0||P.length===0?[]:P.slice(Math.max(0,P.length-y))},{initial:a.tail(y),describeKind:"derived"}),S=vt(k);return c.set(y,{node:k,dispose:S}),k}function T(y,x){if(!Number.isInteger(y)||y<0)throw new RangeError(`slice: start must be a non-negative integer (got ${y})`);if(x!==void 0&&(!Number.isInteger(x)||x<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${x})`);let k=h(y,x),S=p.get(k);if(S!==void 0)return p.delete(k),p.set(k,S),S.node;f(p);let N=G([d],([H])=>{let F=H;return x===void 0?F.slice(y):F.slice(y,x)},{initial:a.slice(y,x),describeKind:"derived"}),P=vt(N);return p.set(k,{node:N,dispose:P}),N}function v(y){let x=l.get(y);if(x!==void 0)return x.node;let k=G([d,y],([N,P])=>{let H=N,F=Math.max(0,Math.trunc(P??0));return H.slice(F)},{initial:[],describeKind:"derived"}),S=vt(k);return l.set(y,{node:k,dispose:S}),k}let g,_;function w(){g===void 0&&(g=ee([d],(y,x,k)=>{let S=y[0],P=S!=null&&S.length>0?S.at(-1):k.prevData[0];if(P==null||P.length===0){x.down([[W]]);return}x.emit(P[P.length-1])},{name:t!=null?`${t}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),_=G([d],([y])=>y.length>0,{name:t!=null?`${t}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),vt(g),vt(_))}let E={entries:d,get size(){return a.size},at(y){return a.at(y)},append(y){b(()=>a.append(y))},appendMany(y){y.length!==0&&b(()=>a.appendMany(y))},clear(){b(()=>a.clear())},trimHead(y){b(()=>a.trimHead(y))},withLatest(){return w(),d},get lastValue(){return w(),g},get hasLatest(){return w(),_},view(y){switch(y.kind){case"tail":return m(y.n);case"slice":return T(y.start,y.stop);case"fromCursor":return v(y.cursor)}},attach(y){let x=y.subscribe(k=>{for(let S of k)S[0]===D&&E.append(S[1])});return()=>x()},attachStorage(y){if(y.length===0)return()=>{};let x=new Map;for(let S of y)x.set(S,a.size);(async()=>{for(let S of y)if(typeof S.loadEntries=="function")try{let N=await Promise.resolve(S.loadEntries());N.entries.length>0&&a.size===0&&(a.restore(N.entries),x.set(S,N.entries.length),u());break}catch{}})();let k=d.subscribe(S=>{for(let N of S){if(N[0]!==D)continue;let P=N[1];for(let H of y){let F=x.get(H)??0;if(P.length<F){try{let ve=H.appendEntries(P);ve instanceof Promise&&ve.catch(()=>{})}catch{}x.set(H,P.length);continue}if(P.length===F)continue;let ye=P.slice(F);x.set(H,P.length);try{let ve=H.appendEntries(ye);ve instanceof Promise&&ve.catch(()=>{})}catch{}}}});return()=>k()},disposeAllViews(){for(let y of c.values())y.dispose();c.clear();for(let y of p.values())y.dispose();p.clear();for(let y of l.values())y.dispose();l.clear()},dispose(){for(let y of c.values())y.dispose();c.clear();for(let y of p.values())y.dispose();p.clear();for(let y of l.values())y.dispose();l.clear()}};return E}Pe();var Yo=256;function ct(r,e){if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`${e} must be a non-negative integer`);return r}function He(r,e){return ze("messaging",r,e)}var Qo=1024,kn=class extends ce{_log;events;latest;hasLatest;constructor(e,t={}){super(e,t.graph),this._log=dt([],{name:"events",maxSize:t.retainedLimit??Qo}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=G([this.events],([n])=>{let s=n;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(de(this.latest)),this.hasLatest=G([this.events],([n])=>n.length>0,{name:"hasLatest",describeKind:"derived",meta:He("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(de(this.hasLatest)),this.addDisposer(()=>{this.events.down([[$]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},Bt=class extends ce{cursor;available;topic;_disposed=!1;constructor(e,t,n={}){super(e,n.graph),this.topic=t;let s;if(n.from!==void 0?n.from==="retained"?s=0:n.from==="now"?s=t.events.cache.length:s=ct(n.from,"subscription from"):s=ct(n.cursor??0,"subscription cursor"),this.cursor=V(s,{name:"cursor",describeKind:"state",meta:He("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=t._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(de(this.available)),n.advanceOn!==void 0){let o=n.advanceOn,i=!1,a=ee([o],()=>{if(!i){i=!0;return}if(this._disposed)return;let d=this.available.cache;if(d.length===0)return;let u=this.cursor.cache+d.length;this.cursor.emit(u)},{name:"advancePump",describeKind:"effect",meta:He("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(de(a))}}ack(e){if(this._disposed)return this.cursor.cache;let t=this.available.cache,n=e===void 0?t.length:ct(e,"subscription ack count"),s=Math.min(n,t.length);if(s<=0)return this.cursor.cache;let o=this.cursor.cache+s;return this.cursor.emit(o),o}pull(e){if(this._disposed)return[];let t=this.available.cache,n=e===void 0?t.length:ct(e,"subscription pull limit");return t.slice(0,n)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let t=this.available.cache,n=e===void 0?t.length:ct(e,"subscription pullAndAck limit"),s=t.slice(0,n);if(s.length===0)return{items:s,cursor:this.cursor.cache};let o=this.cursor.cache+s.length;return this.cursor.emit(o),{items:s,cursor:o}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[$]]),this.destroy())}},Rn=class extends ce{_sourceSub;bridgedCount;output;constructor(e,t,n,s={}){super(e,s.graph),this._sourceSub=Zo(`${e}-subscription`,t,{cursor:s.cursor}),this.mount("subscription",this._sourceSub);let o=Math.max(1,ct(s.maxPerPump??Yo,"topic bridge maxPerPump")),i=s.map??(l=>l);this.output=G([this._sourceSub.available],([l])=>{let h=l,f=[],b=Math.min(h.length,o);for(let m=0;m<b;m++){let T=i(h[m]);T!==void 0&&f.push(T)}return f},{name:"output",describeKind:"derived",meta:He("topic_bridge_output",{targetRef:n.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(de(this.output)),this.bridgedCount=V(0,{name:"bridgedCount",describeKind:"state",meta:He("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(de(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,c=ee([a],()=>{let l=a.cache;if(l.length===0)return;let h=d.available.cache.length,f=Math.min(h,o);if(f>0){d.ack(f);let b=u.cache??0;u.emit(b+l.length)}},{name:"ackPump",describeKind:"effect",meta:He("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(de(c));let p=Xo(this.output,n);this.addDisposer(p)}};function Xo(r,e){return r.subscribe(t=>{for(let n of t){if(n[0]!==D)continue;let s=n[1];s.length!==0&&U(()=>{for(let o of s)e.publish(o)})}})}var On=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,t){this._map.set(e,t)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},Sn=class extends ce{_registry;version;_defaultTopicOptions;constructor(e,t={}){super(e,t.graph);let n=V(0,{name:"version",describeKind:"state",meta:He("hub_version")});this.add(n,{name:"version"}),this.version=n,this._registry=new On(n),this._defaultTopicOptions={...t.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,t){let n=this._registry.get(e);if(n===void 0){let s={...this._defaultTopicOptions,...t??{}};n=new kn(e,s),this._registry.set(e,n),this.mount(e,n);let o=this.version.cache??0;this.version.emit(o+1)}return n}publish(e,t){this.topic(e).publish(t)}publishMany(e){U(()=>{for(let[t,n]of e)this.topic(t).publish(n)})}subscribe(e,t,n){let s=this.topic(t);return new Bt(e,s,n)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let t=this.version.cache??0;this.version.emit(t+1)}return!0}};function qt(r,e){return new Sn(r,e)}function Zo(r,e,t){return new Bt(r,e,t)}function An(r,e,t,n){return new Rn(r,e,t,n)}function es(r){if(typeof r!="object"||r===null)return!1;let e=r;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function ts(r,e){if(r.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(r.length===1){let o=ns(e);return{best:r[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(r.length);for(let d=0;d<r.length;d++)o[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<r.length&&(o[u].sum+=d.score,o[u].count+=1)}let i=r[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<r.length;d++){let u=o[d].count>0?o[d].sum/o[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=r[d])}return{best:i,bestScore:a}}let n=r[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<r.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,n=r[o])}return{best:n,bestScore:s}}function ns(r){if(r.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let t of r)e+=t.score;return e/r.length}function Rr(r,e,t,n){let s=n.name??"refine-loop",o=new ce(s,n.graph),i=es(n.dataset)?n.dataset:V(n.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=V(0,{name:"iteration"});o.add(a,{name:"iteration"});let d=V(t,{name:"strategy",equals:()=>!1});o.add(d,{name:"strategy"});let u=V(null,{name:"lastFeedback"});o.add(u,{name:"lastFeedback"});let c=V([],{name:"prevCandidates"});o.add(c,{name:"prevCandidates"});let p=V(!1,{name:"paused"});o.add(p,{name:"paused"});let l=V("running",{name:"status"});o.add(l,{name:"status"});let h=V([],{name:"history",equals:()=>!1});o.add(h,{name:"history"});let f=V(null,{name:"best"});o.add(f,{name:"best"});let b=V(Number.NEGATIVE_INFINITY,{name:"score"});o.add(b,{name:"score"});let m=V(0,{name:"budget-used"});o.add(m,{name:"budget-used"});let T=qt("stages");o.mount("stages",T);let v=T.topic("generate"),g=T.topic("evaluate"),_=T.topic("analyze"),w=T.topic("decide"),E=t,y=null,x=[];o.addDisposer(d.subscribe(R=>{for(let M of R)M[0]===D&&(E=M[1])})),o.addDisposer(u.subscribe(R=>{for(let M of R)M[0]===D&&(y=M[1])})),o.addDisposer(c.subscribe(R=>{for(let M of R)M[0]===D&&(x=M[1])}));let k=ot(a,R=>{let M=E,Z=R===0||y==null;return ee([],(ae,le)=>{let B=!1;try{let O=Z?M.seed(r):M.generate(y,x);if(O instanceof Promise)return O.then(A=>{B||le.emit(A)},A=>{B||le.down([[I,A]])}),()=>{B=!0};le.emit(O)}catch(O){B=!0,le.down([[I,O]])}},{describeKind:"producer"})},{name:"candidates"});o.add(k,{name:"candidates"});let S=he([k],(R,M,Z)=>{let ae=Z.terminalDeps[0];ae!==void 0&&ae!==!0&&l.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(S,{name:"error-watcher"}),o.addDisposer(S.subscribe(()=>{}));let N=G([k,a],([R,M])=>({iteration:M,candidates:R,timestamp_ns:K()}),{name:"generate-event"});o.add(N,{name:"generate-event"}),o.addDisposer(N.subscribe(()=>{}));let P=he([N],([R])=>{v.publish(R)},{name:"generate-publish"});o.add(P,{name:"generate-publish"}),o.addDisposer(P.subscribe(()=>{}));let H=he([k],([R])=>{c.emit(R)},{name:"generate-mirror"});o.add(H,{name:"generate-mirror"}),o.addDisposer(H.subscribe(()=>{}));let F=e(k,i);o.add(F,{name:"scores"});let ye=G([F,k,a],([R,M,Z])=>({iteration:Z,candidates:M,scores:R,timestamp_ns:K()}),{name:"evaluate-event"});o.add(ye,{name:"evaluate-event"}),o.addDisposer(ye.subscribe(()=>{}));let ve=he([ye],([R])=>{g.publish(R)},{name:"evaluate-publish"});o.add(ve,{name:"evaluate-publish"}),o.addDisposer(ve.subscribe(()=>{}));let ke=G([F,k],([R,M])=>E.analyze(R,M),{name:"feedback"});o.add(ke,{name:"feedback"});let Ee=G([ke,k,a],([R,M,Z])=>({iteration:Z,candidates:M,feedback:R,timestamp_ns:K()}),{name:"analyze-event"});o.add(Ee,{name:"analyze-event"}),o.addDisposer(Ee.subscribe(()=>{}));let j=he([Ee],([R])=>{_.publish(R)},{name:"analyze-publish"});o.add(j,{name:"analyze-publish"}),o.addDisposer(j.subscribe(()=>{}));let z=G([h],([R])=>{let M=R;if(n.patience==null||M.length<=n.patience)return!1;let Z=M.slice(-(n.patience+1)),ae=Z[0].bestScore;return Z.slice(1).every(le=>le.bestScore<=ae)},{name:"patience-check"});o.add(z,{name:"patience-check"});let L=G([b],([R])=>n.minScore!=null&&R>=n.minScore,{name:"min-score-check"});o.add(L,{name:"min-score-check"});let ie=G([h],([R])=>{let M=R;if(n.minDelta==null||M.length<2)return!1;let Z=M[M.length-2].bestScore,ae=M[M.length-1].bestScore;return Math.abs(ae-Z)<n.minDelta},{name:"min-delta-check"});o.add(ie,{name:"min-delta-check"});let X=G([m],([R])=>n.maxEvaluations!=null&&R>=n.maxEvaluations,{name:"max-evaluations-check"});o.add(X,{name:"max-evaluations-check"});let me=G([a],([R])=>n.maxIterations!=null&&R>=n.maxIterations,{name:"max-iterations-check"});o.add(me,{name:"max-iterations-check"});let C=G([m],([R])=>n.budget!=null&&R>=n.budget,{name:"budget-exhausted-check"});o.add(C,{name:"budget-exhausted-check"}),o.addDisposer(z.subscribe(()=>{})),o.addDisposer(L.subscribe(()=>{})),o.addDisposer(ie.subscribe(()=>{})),o.addDisposer(X.subscribe(()=>{})),o.addDisposer(me.subscribe(()=>{})),o.addDisposer(C.subscribe(()=>{}));let q=G([z,L,ie,X,me],([R,M,Z,ae,le])=>R?{converged:!0,reason:"patience"}:M?{converged:!0,reason:"min-score"}:Z?{converged:!0,reason:"min-delta"}:ae?{converged:!0,reason:"max-evaluations"}:le?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(q,{name:"converged"}),o.addDisposer(q.subscribe(()=>{}));let ge=-1,Ge=he([ke,F,k],([R,M,Z])=>{let ae=a.cache,le=R,B=Z,O=M;if(ae<=ge)return;ge=ae;let{best:A,bestScore:Y}=ts(B,O),ne=h.cache,Le={n:ae,candidates:B,scores:O,feedback:le,best:A,bestScore:Y,timestamp_ns:K()},fe=[...ne,Le],Fe=m.cache+B.length,re="continue",Te,Yt=n.budget!=null&&Fe>=n.budget,Qt=p.cache;if(Yt)re="budget",Te="budget";else if(n.minScore!=null&&le.score>=n.minScore)re="converged",Te="min-score";else if(n.maxIterations!=null&&ae>=n.maxIterations)re="converged",Te="max-iterations";else if(n.maxEvaluations!=null&&Fe>=n.maxEvaluations)re="converged",Te="max-evaluations";else if(n.minDelta!=null&&fe.length>=2){let Nt=fe[fe.length-2].bestScore,Xt=fe[fe.length-1].bestScore;Math.abs(Xt-Nt)<n.minDelta&&(re="converged",Te="min-delta")}else if(n.patience!=null&&fe.length>n.patience){let Nt=fe.slice(-(n.patience+1)),Xt=Nt[0].bestScore;Nt.slice(1).every(Br=>Br.bestScore<=Xt)&&(re="converged",Te="patience")}re==="continue"&&Qt&&(re="paused"),U(()=>{f.emit(A),b.emit(le.score),h.emit(fe),m.emit(Fe),u.emit(le),w.publish({iteration:ae,decision:re,reason:Te,timestamp_ns:K()}),re==="continue"?a.emit(ae+1):l.emit(re==="converged"?"converged":re==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(Ge,{name:"decide-bridge"}),o.addDisposer(Ge.subscribe(()=>{})),Object.assign(o,{best:f,score:b,status:l,history:h,strategy:d,iteration:a,generate:v,evaluate:g,analyze:_,decide:w,setStrategy(R){d.emit(R)},pause(){p.emit(!0)},resume(){l.cache==="paused"&&U(()=>{p.emit(!1),l.emit("running"),a.emit(a.cache+1)})}})}function rs(r){let{best:e,score:t,status:n}=r,s=Number.isFinite(t)?t.toFixed(3):String(t),o=e??void 0;return n==="converged"?{outcome:"success",detail:`refineLoop converged at score ${s}`,artifact:o}:n==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${s}`,artifact:o}:{outcome:"failure",detail:`refineLoop errored (status=${n})`,artifact:o}}function Cn(r){let e=r.name??"refine-executor",t=r.toOutput??rs;return n=>{let s=n.payload.item,o=Rr(r.seedFrom(s),r.evaluator,r.strategy,{...r.refine,dataset:r.datasetFor(s),name:`${e}/inner`}),i=G([o.status,o.best,o.score],([a,d,u])=>{let c=a;if(c!=="converged"&&c!=="budget"&&c!=="errored")return null;let p=t({best:d,score:u,status:c});return{...n.payload,execution:{item:s,...p}}},{name:`${e}/output`});return Gt(i,a=>a!=null,{name:`${e}/gate-out`})}}function os(r){if(r.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let t of r)e+=t.score;return e/r.length}function ss(r){let{passCount:e,total:t,meanScore:n,threshold:s,missingArtifact:o}=r,i=Number.isFinite(n)?n.toFixed(3):String(n),a=!o&&t>0&&n>=s,d=o?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${t} eval tasks passed; mean score ${i} \u2265 ${s}`]:t===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${t} eval tasks passed; mean score ${i} < threshold ${s}`];return a?{verified:!0,findings:d}:{verified:!1,findings:d,errorClass:"structural"}}function is(r){return r.artifact??null}function Or(r){let e=r.name??"eval-verifier",t=r.threshold??.5,n=r.toOutput??ss,s=r.extractArtifact??is;return o=>{let{item:i,execution:a}=o.payload;if(a==null)return{...o.payload,verify:{verified:!1,findings:["evalVerifier: prior execute stage produced no execution"],errorClass:"structural"}};let d=s(a,i);if(d==null)return{...o.payload,verify:n({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:t,missingArtifact:!0})};let u=V([d],{name:`${e}/candidates`}),c=V(r.datasetFor(i),{name:`${e}/dataset`}),p;U(()=>{p=r.evaluator(u,c)});let l=G([p],([h])=>{let f=h;if(f==null)return null;let b=os(f),m=f.filter(T=>T.score>=t).length;return{...o.payload,verify:n({scores:f,meanScore:b,passCount:m,total:f.length,threshold:t})}},{name:`${e}/output`});return Gt(l,h=>h!=null,{name:`${e}/gate-out`})}}function as(r){let e=r.name??"harness-pair",t=Cn({name:`${e}-exec`,seedFrom:r.seedFrom,evaluator:r.evaluator,strategy:r.strategy,datasetFor:r.datasetFor,refine:r.refine}),n=Or({name:`${e}-verify`,evaluator:r.evaluator,datasetFor:r.datasetFor,threshold:r.threshold});return{executor:t,verifier:n}}Oe();rt();te();Me();Oe();tt();be();te();function Dn(r,e){let t=r.cache??0;return t>=e?!1:(r.down([[Q],[D,t+1]]),!0)}var us=Xn((r,e)=>{r("observe"),r("signal"),e("write")});function Ut(r){let e=dt([],{name:r.name,maxSize:r.retainedLimit??1024,guard:r.guard??us,...r.versioning!=null?{versioning:r.versioning}:{}});return e.withLatest(),r.graph&&r.graph.add(e.entries,{name:r.name}),e}function Ar(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Ar(r[e]);return Object.freeze(r)}function ds(r){let e=r.cache,n=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return r.down([[Q],[D,n]]),n}function Sr(r,e,t,n,s,o){let i=e(t,n,s);if(i===void 0)return;let a=o!=null?{...i,handlerVersion:o}:i;r.append(a)}function lt(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(Ar):s,i=xe(),a,d,u=!1,c;try{U(()=>{e.seq&&(c=ds(e.seq));try{a=r(...o),e.onSuccess&&Sr(e.audit,e.onSuccess,o,a,{t_ns:i,seq:c},e.handlerVersion)}catch(p){throw d=p,u=!0,p}})}catch(p){if(u&&e.onFailure){let l=d instanceof Error?d.name:typeof d;Sr(e.audit,e.onFailure,o,d,{t_ns:i,seq:c,errorType:l},e.handlerVersion)}throw u?d:p}return a}}function Cr(r,e,t=0){let n=V(t,{name:e,describeKind:"state"});return r.add(n,{name:e}),n}function Tt(r){return r.relatedTo?.[0]??r.summary}be();te();yt();Pe();function _t(r,e){return ze("ai",r,e)}function wt(r){let e=r.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:r}function Mn(r,e,t){return ue(n=>{let s=new AbortController,o=!1,i=null,a=c=>{o||(o=!0,n.down([[D,c],[$]]),i?.(),i=null)},d;try{d=r.invoke(e,{...t.invokeOpts,signal:s.signal})}catch(c){return a(t.onFailure("throw",c)),()=>s.abort()}return i=Ae(d,{signal:s.signal}).subscribe(c=>{for(let p of c){if(o)return;if(p[0]===D){try{a(t.onSuccess(p[1]))}catch(l){a(t.onFailure("onSuccess-threw",l))}return}if(p[0]===I){a(t.onFailure("error",p[1]));return}if(p[0]===$){a(t.onFailure("complete",void 0));return}}}),o&&i&&(i(),i=null),()=>{s.abort(),i?.(),i=null}})}be();te();Pe();function Dr(r){return r!=null&&typeof r=="object"&&"content"in r?String(r.content):typeof r=="string"?r:String(r)}function cs(r,e=200){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Mr(r,e,t,n){let s=n?.format??"text",o=n?.name??"prompt_node";n?.tools!==void 0&&s!=="raw"&&console.warn("promptNode: `tools` is set but `format !== 'raw'`. Tool calls in the response will be silently dropped \u2014 set `format: 'raw'` to receive the full LLMResponse with `toolCalls`.");let i=G(e,d=>{if(d.some(c=>c==null))return[];let u=typeof t=="string"?t:t(...d);return u?[{role:"user",content:u}]:[]},{name:`${o}::messages`,meta:_t("prompt_node")});return ot(i,d=>!d||d.length===0?V(null):ue(u=>{let c=!1,p=!1,l,h={model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,...n?.tools!==void 0?{tools:n.tools}:{}};if(n?.abort){let T=ir(n.abort);h.signal=T.signal,l=T.dispose}let f;try{f=r.invoke(d,h)}catch(T){return c=!0,u.down([[I,T]]),()=>{l?.()}}let m=Ae(f).subscribe(T=>{if(!(p||c))for(let v of T){if(c)return;if(v[0]===D){let g=v[1];if(s==="raw")u.emit(g);else try{let _=Dr(g),w=s==="json"?JSON.parse(wt(_)):_;u.emit(w)}catch(_){let w=Dr(g),E=new Error(`promptNode: failed to parse LLM response as JSON: ${_.message}
45
+ Raw content (first 200 chars): ${cs(w)}`);c=!0,u.down([[I,E]]);return}}else if(v[0]===I){c=!0,u.down([[I,v[1]]]);return}else if(v[0]===$){c=!0,u.down([[$]]);return}else u.down([v])}});return()=>{p=!0,m(),l?.()}},{name:`${o}::call`,meta:_t("prompt_node::call")}),{name:`${o}::output`,meta:n?.meta?{..._t("prompt_node::output"),...n.meta}:_t("prompt_node::output")})}Me();Oe();be();rt();Ie();te();yt();function xt(r,e){return ze("orchestration",r,e)}var Kt=class extends ce{constructor(e,t){super(e,t)}task(e,t,n={}){let s=(n.deps??[]).map(i=>this._resolveStep(i)),o=G(s,t,{name:e,describeKind:"derived",meta:xt("task",n.meta)});return this.add(o,{name:e}),o}classify(e,t,n,s={}){let o=this._resolveStep(t),i=G([o],([a])=>{try{return{tag:n(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:xt("classify",s.meta)});return this.add(i,{name:e}),i}combine(e,t,n={}){let s=Object.keys(t),o=s.map(a=>this._resolveStep(t[a])),i=G(o,a=>{let d={};for(let u=0;u<s.length;u++)d[s[u]]=a[u];return d},{name:e,describeKind:"derived",meta:xt("combine",n.meta)});return this.add(i,{name:e}),i}approvalGate(e,t,n={}){let s=n.maxPending??1e3;if(s<1&&s!==Number.POSITIVE_INFINITY)throw new RangeError("approvalGate: maxPending must be >= 1");let o=n.startOpen??!1;typeof t!="string"&&this.nameOf(t)===void 0&&this.add(t,{name:`${e}/source`});let i=this._resolveStep(t),a=new ce(`${e}_state`),d=V([],{name:"pending",equals:()=>!1}),u=V(o,{name:"isOpen"}),c=G([d],([j])=>j.length,{name:"count"}),p=V(0,{name:"droppedCount"}),l=Ut({name:"decisions",retainedLimit:1024,graph:a});a.add(d,{name:"pending"}),a.add(u,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(p,{name:"droppedCount"}),this.mount(`${e}_state`,a);let h=[],f=!1,b=!1,m=o,T=u.subscribe(j=>{for(let z of j)z[0]===D&&(m=z[1])});this.addDisposer(T);function v(){d.emit([...h])}function g(j,z,L){l.append({action:j,t_ns:xe(),...z!==void 0?{items:z,count:z.length}:{},...L!==void 0?{unflushed:L}:{},...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}function _(j){if(h.push(j),h.length>s){let z=h.shift();p.emit(p.cache+1),g("drop",[z])}v()}function w(j){let z=h.splice(0,j);return v(),z}let E=ee([i],(j,z,L)=>{let ie=L.terminalDeps[0];if(ie!==void 0){f=!0;let me=h.length;h=[],v(),g("teardown",void 0,me),z.down(ie===!0?[[$]]:[[I,ie]]);return}let X=j[0];if(X==null||X.length===0){z.down([[W]]);return}for(let me of X)m?z.emit(me):(_(me),z.down([[W]]))},{name:e,describeKind:"derived",meta:xt("approval_gate",n.meta)});if(this.add(E,{name:e}),n.approver!=null){n.approver.cache&&(u.emit(!0),m=!0,n.onceOnly&&(b=!0));let z=n.approver.subscribe(L=>{for(let ie of L){if(ie[0]!==D)continue;let X=!!ie[1];if(X&&!m){if(n.onceOnly){if(b)continue;b=!0}U(()=>{u.emit(!0);let me=w(h.length);g("open",me);for(let C of me){if(f)break;E.emit(C)}})}else if(!X&&m){if(n.onceOnly&&b)continue;U(()=>{u.emit(!1),g("close")})}}});this.addDisposer(z)}let y=j=>{if(f)throw new Error(`approvalGate: ${j}() called after the gate was torn down`)},x=(j=1)=>{y("approve");let z=w(j);for(let L of z){if(f)break;E.emit(L)}},k=(j=1)=>{y("reject"),w(j)},S=(j,z=1)=>{y("modify");let L=[...h],ie=w(z);for(let X=0;X<ie.length&&!f;X++)E.emit(j(ie[X],X,L))},N=()=>{y("open"),u.emit(!0);let j=w(h.length);for(let z of j){if(f)break;E.emit(z)}},P=()=>{y("close"),!(n.onceOnly&&b)&&u.emit(!1)},H=lt(x,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"approve",count:j[0]??1,t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),F=lt(k,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"reject",count:j[0]??1,t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),ye=lt(S,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"modify",count:j[1]??1,t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),ve=lt(N,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"open",t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})}),ke=lt(P,{audit:l,freeze:!1,onSuccess:(j,z,L)=>({action:"close",t_ns:L.t_ns,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}}),onFailure:(j,z,L)=>({action:"drop",t_ns:L.t_ns,errorType:L.errorType,...n.handlerVersion!=null?{handlerVersion:n.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:E,pending:d,count:c,isOpen:u,droppedCount:p,decisions:l,audit:l,approve:H,reject:F,modify:ye,open:ve,close:ke}}approval(e,t,n,s={}){return this.approvalGate(e,t,{...s,approver:n,maxPending:1})}catch(e,t,n,s={}){let o=this._resolveStep(t),i=s.on??"errored",a=ee([o],(d,u,c)=>{let p=c.terminalDeps[0];if(p!==void 0){let h=p===!0?{kind:"completed"}:{kind:"errored",error:p};if(i==="terminal"||i===h.kind){u.emit(n(h,u));return}u.down(h.kind==="completed"?[[$]]:[[I,h.error]]);return}let l=d[0];if(l==null||l.length===0){u.down([[W]]);return}for(let h of l)u.emit(h)},{name:e,describeKind:"derived",completeWhenDepsComplete:s.completeWhenDepsComplete??!(i==="completed"||i==="terminal"),errorWhenDepsError:!(i==="errored"||i==="terminal"),meta:xt("catch",s.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function In(r,e){let t=new Kt(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("pipelineGraph",Ke(o)),t}var gu=Math.LN2/604800;function Ir(r,e,t,n=0){if(!Number.isFinite(r))return n;if(!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)return Math.max(n,r);let s=r*Math.exp(-t*e);return Math.max(n,s)}Oe();Ie();yt();Me();be();te();var Gn=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 t=e>=0?e:this._buf.length+e;if(!(t<0||t>=this._buf.length))return this._buf[t]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._buf.length;this._buf.length=t+e.length;for(let n=0;n<e.length;n++)this._buf[t+n]=e[n];this._version+=1}insert(e,t){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,t),this._version+=1}insertMany(e,t){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);t.length!==0&&(this._buf.splice(e,0,...t),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 t=e>=0?e:this._buf.length+e;if(t<0||t>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[n]=this._buf.splice(t,1);return this._version+=1,n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Gr(r,e={}){let{name:t,versioning:n,backend:s}=e,o=s??new Gn(r),i=V(o.toArray(),{name:t,describeKind:"state",equals:(u,c)=>u===c,...n!=null?{versioning:n}:{}});function a(){let u=o.toArray();U(()=>{i.down([[Q]]),i.down([[D,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(){}}}Pe();var ls=256,fs=1024;function Pn(r,e){if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`${e} must be a non-negative integer`);return r}function Wt(r,e){return ze("job_queue",r,e)}var Ln=class extends ce{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,t={}){super(e,t.graph),this._pending=Gr([],{name:"pending"}),this._jobs=ut({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=G([this.pending],([n])=>n.length,{name:"depth",describeKind:"derived",meta:Wt("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(de(this.depth)),this.events=Ut({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=Cr(this,"seq",0)}_bumpSeq(){let t=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(t),t}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,t={}){let n=this._bumpSeq(),s=t.id??`${this.name}-${n}`;if(this._jobs.get(s)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${s}"`);let o={id:s,payload:e,attempts:0,metadata:Object.freeze({...t.metadata??{}}),state:"queued"};return this._jobs.set(s,o),this._pending.append(s),this.events.append({action:"enqueue",id:s,payload:e,t_ns:xe(),seq:n}),s}claim(e=1){let t=Pn(e,"job queue claim limit");if(t===0)return[];let n=[];for(;n.length<t&&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),n.push(a),this.events.append({action:"claim",id:o,attempts:a.attempts,t_ns:xe(),seq:this._bumpSeq()})}return n}ack(e){let t=this._jobs.get(e);return!t||t.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:t.attempts,t_ns:xe(),seq:this._bumpSeq()}),!0)}nack(e,t={}){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:t.requeue??!0?(this._jobs.set(e,{...n,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:n.attempts,t_ns:xe(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:n.attempts,t_ns:xe(),seq:this._bumpSeq()}),!0)}removeById(e){let t=this._jobs.get(e);if(!t)return!1;if(t.state==="queued"){let s=this.pending.cache.indexOf(e);s>=0&&this._pending.pop(s)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:t.attempts,t_ns:xe(),seq:this._bumpSeq()}),!0}consumeFrom(e,t){return e.subscribe(n=>{for(let s of n){if(s[0]!==D)continue;let o=s[1];this.enqueue(o,t?{metadata:t.metadata}:void 0)}})}},Fn=class extends ce{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,t={}){super(e,t.graph);let n=t.stages??["incoming","processing","done"],s=[],o=new Map,i=new Map;for(let u of n){let c=typeof u=="string"?u.trim():u.name.trim();typeof u!="string"&&u.work&&o.set(c,u.work),typeof u!="string"&&u.maxPerPump!=null&&i.set(c,Math.max(1,Pn(u.maxPerPump,`job flow stage "${c}" maxPerPump`))),s.push(c)}if(s.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(s).size!==s.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...s]),this._stageWorkFns=o;for(let u of this._stageNames){let c=$n(`${e}-${u}`);this._queues.set(u,c),this.mount(u,c)}this._completed=dt([],{name:"completed",maxSize:fs}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=G([this.completed],([u])=>u.length,{name:"completedCount",describeKind:"derived",meta:Wt("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(de(this.completedCount));let d=Math.max(1,Pn(t.maxPerPump??ls,"job flow maxPerPump"));for(let u=0;u<this._stageNames.length;u+=1){let c=this._stageNames[u],p=this.queue(c),l=u+1<this._stageNames.length?this.queue(this._stageNames[u+1]):null,h=this._stageWorkFns.get(c),f=i.get(c)??d,b=l===null;if(h){let m=ee([p.pending],()=>{let T=0;for(;T<f;){let v=p.claim(1);if(v.length===0)break;let g=v[0];if(!g)break;let w=[...g.metadata.job_flow_path??[],c],E;try{E=h(g)}catch{p.nack(g.id,{requeue:!1}),T+=1;continue}let y=Ae(E),x=!1,k;k=y.subscribe(S=>{if(!x){for(let N of S)if(N[0]===D){x=!0,k?k():Promise.resolve().then(()=>k?.());let P=N[1],H={...g.metadata,job_flow_path:w};if(b){let F={...g,payload:P,metadata:Object.freeze(H)};U(()=>{p.ack(g.id),this._completed.append(F)})}else U(()=>{p.ack(g.id),l.enqueue(P,{metadata:H})});return}else if(N[0]===I){x=!0,k?k():Promise.resolve().then(()=>k?.()),p.nack(g.id,{requeue:!1});return}}}),T+=1}},{name:`pump_${c}`,describeKind:"effect",meta:Wt("job_flow_pump",{stage:c,has_work:!0})});this.add(m,{name:`pump_${c}`}),this.addDisposer(de(m))}else{let m=ee([p.pending],()=>{let T=0;for(;T<f;){let v=p.claim(1);if(v.length===0)break;let g=v[0];if(!g)break;let w=[...g.metadata.job_flow_path??[],c],E={...g.metadata,job_flow_path:w};if(b){let y={...g,metadata:Object.freeze(E)};U(()=>{p.ack(g.id),this._completed.append(y)})}else U(()=>{p.ack(g.id),l.enqueue(g.payload,{metadata:E})});T+=1}},{name:`pump_${c}`,describeKind:"effect",meta:Wt("job_flow_pump",{stage:c,has_work:!1})});this.add(m,{name:`pump_${c}`}),this.addDisposer(de(m))}}}stages(){return this._stageNames}queue(e){let t=this._queues.get(e);if(!t)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return t}enqueue(e,t={}){return this.queue(this._stageNames[0]).enqueue(e,t)}retainedCompleted(){return this.completed.cache}};function $n(r,e){return new Ln(r,e)}function Pr(r,e){let t=new Fn(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("jobFlow",Ke(o)),t}Oe();te();function Vn(){let r=ut({name:"strategy-entries"}),e=G([r.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 l=u.get(c);if(!l||p.attempts!==l.attempts||p.successes!==l.successes)return!1}return!0}});function t(i,a,d){let u=at(i,a),c=r.get(u),p=(c?.attempts??0)+1,l=(c?.successes??0)+(d?1:0);r.set(u,{rootCause:i,intervention:a,attempts:p,successes:l,successRate:l/p})}function n(i,a){return r.get(at(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:t,lookup:n,dispose:o}}function ps(r,e,t,n,s){let o={...st,...s?.severityWeights},i=s?.decayRate??it,a=s?.effectivenessThreshold??.7,d=s?.effectivenessBoost??15,u=[r,e,t];return n&&u.push(n),G(u,c=>{let p=c[0],l=c[1],h=c[2],f=n?c[3]:0,b=o[p.severity??"medium"],m=(K()-h)/1e9,T=Ir(b,m,i,0),v=at(p.rootCause,p.intervention),g=l.get(v);return g&&g.successRate>=a&&(T+=d),T+=f*20,T},{name:"priority-score"})}var Lr="intake",hs="triage-output",Fr="retry",$r="verify-results",Vr="__unrouted";function jr(r,e){let t=gt(e,bn,(n,s)=>n.replace("{{item}}",JSON.stringify(s)));return n=>{let s=n.payload.item,o=[{role:"user",content:t(s)}],i=d=>({...n.payload,execution:{item:s,outcome:"failure",detail:d}}),a=d=>d instanceof Error?d.message:String(d);return Mn(r,o,{onSuccess:d=>{let u;try{u=JSON.parse(wt(String(d.content)))}catch(p){return i(`execute parse error: ${a(p)}`)}if(u==null||typeof u!="object"||Array.isArray(u))return i(`execute parse error: non-object response: ${JSON.stringify(u)}`);let c=u;return{...n.payload,execution:{item:s,outcome:c.outcome??"failure",detail:c.detail??"unknown",artifact:c.artifact}}},onFailure:(d,u)=>i(d==="complete"?"adapter completed without emitting DATA":`executor failed: ${a(u)}`)})}}function zr(r,e){let t=gt(e,yn,(n,s)=>{let[o,i]=s;return n.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return n=>{let{item:s,execution:o}=n.payload;if(o==null)return{...n.payload,verify:{verified:!1,findings:["verifier: prior execute stage produced no execution"],errorClass:"structural"}};let i=[{role:"user",content:t([o,s])}],a=u=>({...n.payload,verify:{verified:!1,findings:[u],errorClass:"self-correctable"}}),d=u=>u instanceof Error?u.message:String(u);return Mn(r,i,{onSuccess:u=>{let c;try{c=JSON.parse(wt(String(u.content)))}catch(l){return a(`verify parse error: ${d(l)}`)}if(c==null||typeof c!="object"||Array.isArray(c))return a(`verify parse error: non-object response: ${JSON.stringify(c)}`);let p=c;return{...n.payload,verify:{verified:p.verified===!0,findings:p.findings??[],errorClass:p.errorClass}}},onFailure:(u,c)=>a(u==="complete"?"verifier completed without emitting DATA":`verifier failed: ${d(c)}`)})}}var Jt=class extends ce{queues;executeFlow;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,t,n,s,o,i,a,d,u,c){super(e),this.queues=t,this.executeFlow=n,this.queueTopics=s,this.jobs=o,this.gates=i,this.strategy=a,this.totalRetries=d,this.totalReingestions=u,this.priorityScores=c}get intake(){return this.queues.topic(Lr)}get verifyResults(){return this.queues.topic($r)}get retry(){return this.queues.topic(Fr)}get unrouted(){return this.queues.topic(Vr)}stageNodes(){let e=this.queues,t=i=>e.has(i)?`queues::${i}::latest`:null,n=i=>i==null?[]:[i],s=Ne.flatMap(i=>n(t(i))),o=[];for(let[i]of this.gates)o.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:n(t("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:s},{label:"GATE",paths:o},{label:"EXECUTE",paths:["executeFlow::execute::events"]},{label:"VERIFY",paths:["executeFlow::verify::events"]},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function ms(r,e){let t=e.adapter,n=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??Lt,i=new Map;for(let O of Ne)i.set(O,{...Pt[O],...e.queues?.[O]});let a=qt(`${r}/queues`,{defaultTopicOptions:{retainedLimit:s}}),d=a.topic(Lr),u=a.topic(hs),c=a.topic(Fr),p=a.topic($r),l=new Map;for(let O of Ne)l.set(O,a.topic(O));let h=a.topic(Vr),f=Vn(),b=mn(d.latest,f.node),m=gt(e.triagePrompt,gn,(O,A)=>{let[Y,ne]=A;return O.replace("{{strategy}}",JSON.stringify(Array.from(ne.entries()))).replace("{{item}}",JSON.stringify(Y))}),T=Mr(t,[b],O=>{let A=O;return!A||!A[0]?"":m(A)},{name:"triage",format:"json"}),v=mn(T,b),_=he([v],([O])=>{if(O==null)return;let[A,Y]=O;if(!A?.route)return;let ne=Y?.[0],Le={...A,...ne};u.publish(Le)}).subscribe(()=>{}),w=new Set(Ne);for(let O of Ne)An(`bridge/${O}`,u,l.get(O),{map:A=>A.route===O?A:void 0});An("bridge/__unrouted",u,h,{map:O=>w.has(O.route)?void 0:O});let E=new Map,y=new Map;for(let O of Ne)E.set(O,$n(`jobs/${O}`));let x=[];for(let O of Ne){let A=l.get(O),Y=E.get(O),ne=new WeakSet,Le=he([A.events],([fe])=>{let Fe=fe??[];for(let re of Fe){if(ne.has(re))continue;ne.add(re);let Te=Y.enqueue(re);y.set(Tt(re),{route:O,id:Te})}},{name:`jobs/${O}-mirror`});x.push(Le.subscribe(()=>{}))}function k(O){let A=Tt(O),Y=y.get(A);Y&&(E.get(Y.route)?.removeById(Y.id),y.delete(A))}let S=In("gates"),N=new Map;for(let O of Ne){let A=i.get(O);if(!A.gated)continue;let Y=l.get(O),ne=S.approvalGate(`${O}/gate`,Y.latest,{maxPending:A.maxPending,startOpen:A.startOpen});N.set(O,ne)}let P=[];for(let O of Ne)i.get(O).gated&&N.has(O)?P.push(N.get(O).node):P.push(l.get(O).latest);P.push(c.latest);let H=cr(...P),F=e.executor??jr(t,e.executePrompt),ye=e.verifier??zr(t,e.verifyPrompt),ve=e.executeMaxPerPump??Number.MAX_SAFE_INTEGER,ke=e.verifyMaxPerPump??Number.MAX_SAFE_INTEGER,Ee=Pr(`${r}/executeFlow`,{stages:[{name:"execute",work:O=>F(O),maxPerPump:ve},{name:"verify",work:O=>ye(O),maxPerPump:ke}]}),j=he([H],([O])=>{O!=null&&Ee.enqueue({item:O})},{name:"execute-enqueue"}),z=j.subscribe(()=>{}),L=e.maxReingestions??1,ie=Math.min(e.maxTotalRetries??n*10,100),X=Math.min(e.maxTotalReingestions??L*10,100),me=V(0),C=V(0);function q(O,A,Y){return{item:Y,execution:O,verified:A.verified,findings:A.findings??[],errorClass:A.errorClass}}function ge(O,A){f.record(A.rootCause,A.intervention,!0),p.publish(O),k(A)}function Ge(O,A){let Y=Tt(A),ne=A.$retries??0,Le={...A,$retries:ne+1,summary:`[RETRY ${ne+1}/${n}] ${Y} \u2014 Previous attempt failed: ${O.findings.join("; ")}`,relatedTo:[Y]};c.publish(Le)}function we(O,A){f.record(A.rootCause,A.intervention,!1),p.publish(O),k(A);let Y=Tt(A),ne=A.$reingestions??0;ne<L&&Dn(C,X)&&d.publish({source:A.source,summary:`Verification failed for: ${Y}`,evidence:O.findings.join(`
46
+ `),affectsAreas:A.affectsAreas,affectsEvalTasks:A.affectsEvalTasks,severity:A.severity??"high",relatedTo:[Y],$reingestions:ne+1})}let R=0,M=he([Ee.completed],([O])=>{let A=O??[];R>A.length&&(R=A.length);let Y=R;R=A.length;for(let ne=Y;ne<A.length;ne++){let Le=A[ne],{item:fe,execution:Fe,verify:re}=Le.payload;if(Fe==null||re==null){k(fe);continue}let Te=q(Fe,re,fe);if(Te.verified){ge(Te,fe);continue}let Yt=Te.errorClass??o({item:fe,outcome:Fe.outcome,detail:Te.findings.join("; ")}),Qt=fe.$retries??0;Yt==="self-correctable"&&Qt<n&&Dn(me,ie)?Ge(Te,fe):we(Te,fe)}},{name:"verify-dispatch"}),Z=M.subscribe(()=>{}),ae=G([Ee.completed],()=>null,{name:"reflect",equals:()=>!1}),le;e.priority&&(le=gs(l,f,e));let B=new Jt(r,a,Ee,l,E,N,f,me,C,le);B.addDisposer(_),B.addDisposer(z),B.addDisposer(Z),B.addDisposer(f.dispose);for(let O of x)B.addDisposer(O);if(B.add(b,{name:"triage-input"}),B.add(T,{name:"triage"}),B.add(v,{name:"router-input"}),B.add(H,{name:"execute-input"}),B.add(j,{name:"execute-enqueue"}),B.add(M,{name:"verify-dispatch"}),B.add(ae,{name:"reflect"}),B.add(f.node,{name:"strategy"}),B.addDisposer(ae.subscribe(()=>{})),le)for(let[O,A]of le)B.add(A,{name:`priority/${O}`}),B.addDisposer(A.subscribe(()=>{}));B.mount("queues",a),B.mount("gates",S),B.mount("executeFlow",Ee);for(let[O,A]of E)B.mount(`jobs/${O}`,A);return B.tagFactory("harnessLoop",Ke(e)),B}function gs(r,e,t){if(!t.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 n=t.lastInteractionNs,s=t.priority??{},o={...st,...s.severityWeights},i=s.decayRate??it,a=s.effectivenessThreshold??.7,d=s.effectivenessBoost??15,u=new Map;for(let[c,p]of r){let l=G([p.latest,e.node,n],h=>{let f=h[0];if(f==null)return 0;let b=o[f.severity??"medium"]??40,m=(K()-h[2])/1e9,T=b*Math.exp(-i*Math.max(0,m)),v=`${f.rootCause}\u2192${f.intervention}`,_=h[1]?.get(v);return _&&_.successRate>=a&&(T+=d),T},{name:`priority/${c}`});u.set(c,l)}return u}function bs(r,e){let t=zt(r,e),n={};for(let s of Ne){let o=r.queues.has(s)?r.queues.topic(s):null;n[s]=o?.retained().length??0}return{...t,queueDepths:n,strategyEntries:r.strategy.node.cache?.size??0,totalRetries:r.totalRetries.cache??0,totalReingestions:r.totalReingestions.cache??0}}Oe();function ys(r){let e={};for(let{label:t,paths:n}of r.stageNodes())for(let s of n)e[s]=t;return e}function vs(r,e){let t=e?.logger===null?null:e?.logger??console.log,n=e?.detail??"summary",s=K(),o=[],i=[],a=ys(r);function d(){return(K()-s)/1e9}function u(c,p,l){let h={elapsed:d(),stage:c,type:p};n!=="summary"&&(h.summary=Ts(l)),n==="full"&&(h.data=l),i.push(h)}for(let[c,p]of Object.entries(a))try{let l=r.observe(c,{format:"stage-log",stageLabels:a,logger:t?h=>t(h):()=>{},includeTypes:["data","error","complete"]});l.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(l)}catch(l){let h=l instanceof Error?l.message:String(l);u(p,"error",`observe-unavailable: ${c} \u2014 ${h}`),t&&t(`[${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 Ts(r){if(r==null)return"null";if(typeof r=="string")return Hr(r,80);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return Hr(e,120)}catch{return String(r)}}function Hr(r,e){return r.length>e?`${r.slice(0,e-1)}\u2026`:r}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,dispatchActuator,effectivenessTracker,evalIntakeBridge,evalSource,evalVerifier,harnessEvalPair,harnessLoop,harnessProfile,harnessTrace,notifyEffect,priorityScore,refineExecutor,resolvePromptFn,strategyKey,strategyModel});