@ibgib/space-gib 0.0.34 → 0.0.36

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 (54) hide show
  1. package/dist/client/bootstrap.mjs +1 -1
  2. package/dist/client/{chunk-25PXC4HP.mjs → chunk-5DTAUY3E.mjs} +1586 -464
  3. package/dist/client/chunk-J7X3XTAI.mjs +53 -0
  4. package/dist/client/css/activity-bar.css +21 -3
  5. package/dist/client/css/layout.css +126 -5
  6. package/dist/client/css/tutorial.css +327 -0
  7. package/dist/client/index.html +6 -0
  8. package/dist/client/index.mjs +22 -45
  9. package/dist/client/privacy.html +22 -22
  10. package/dist/client/script.mjs +1 -1
  11. package/dist/client/style.css +1 -0
  12. package/dist/server/server.mjs +3 -3
  13. package/package.json +6 -6
  14. package/src/client/AUTO-GENERATED-version.mts +1 -1
  15. package/src/client/cosmos/seed-cosmos-workspace.mts +20 -6
  16. package/src/client/css/activity-bar.css +21 -3
  17. package/src/client/css/layout.css +126 -5
  18. package/src/client/css/tutorial.css +327 -0
  19. package/src/client/dev-tools/vcs-workspace.mts +4 -4
  20. package/src/client/index.html +6 -0
  21. package/src/client/privacy.html +22 -22
  22. package/src/client/style.css +1 -0
  23. package/src/client/ui/component/changes/changes.css +413 -0
  24. package/src/client/ui/component/changes/changes.html +37 -0
  25. package/src/client/ui/component/changes/changes.mts +766 -0
  26. package/src/client/ui/component/changes/index.mts +9 -0
  27. package/src/client/ui/component/chat-view/chat-view.html +6 -58
  28. package/src/client/ui/component/chat-view/chat-view.mts +13 -26
  29. package/src/client/ui/component/clone/clone.mts +67 -39
  30. package/src/client/ui/component/code-editor/code-editor.css +91 -9
  31. package/src/client/ui/component/code-editor/code-editor.html +58 -45
  32. package/src/client/ui/component/code-editor/code-editor.mts +265 -49
  33. package/src/client/ui/component/cosmos-navigator/cosmos-navigator.css +1 -1
  34. package/src/client/ui/component/cosmos-navigator/cosmos-navigator.html +5 -10
  35. package/src/client/ui/component/cosmos-navigator/cosmos-navigator.mts +328 -64
  36. package/src/client/ui/component/file-explorer/file-explorer.css +475 -11
  37. package/src/client/ui/component/file-explorer/file-explorer.html +45 -65
  38. package/src/client/ui/component/file-explorer/file-explorer.mts +1164 -98
  39. package/src/client/ui/component/nested-chat/chat/chat.mts +5 -90
  40. package/src/client/ui/component/nested-chat/nested-chat.mts +10 -8
  41. package/src/client/ui/component/timeline/timeline.css +16 -1
  42. package/src/client/ui/component/timeline/timeline.mts +37 -93
  43. package/src/client/ui/component/tutorial/index.mts +9 -0
  44. package/src/client/ui/component/tutorial/scripts/pitch-tour-script.mts +265 -0
  45. package/src/client/ui/component/tutorial/tutorial-controller.mts +622 -0
  46. package/src/client/ui/component/tutorial/tutorial-types.mts +45 -0
  47. package/src/client/ui/component/tutorial/tutorial.css +260 -0
  48. package/src/client/ui/router/space-gib-router-helpers.mts +33 -233
  49. package/src/client/ui/router/space-gib-router-helpers.respec.mts +298 -122
  50. package/src/client/ui/router/space-gib-router-service.mts +28 -151
  51. package/src/client/ui/router/space-gib-router-types.mts +32 -76
  52. package/src/client/ui/shell/cosmic-big-bang.mts +12 -3
  53. package/src/client/ui/shell/space-gib-shell-service.mts +715 -143
  54. package/dist/client/chunk-RXWLL2AI.mjs +0 -30
@@ -1,54 +1,31 @@
1
- import{$a as Vt,$c as Pt,A as Ln,Ad as no,B as Tt,Bd as oo,C as Sr,Cd as so,D as pt,Dd as ze,E as qe,F as ht,Fa as oe,H as U,Ha as Rn,Id as Br,Jd as Nr,Ld as io,Ma as kn,Md as co,N as Fa,Na as On,O as Ma,Ob as O,Od as lo,Qb as jn,Rb as Xn,Sa as Fn,Sb as Kn,T as Ua,Tb as Bt,Va as vt,Yb as De,Za as gt,Zb as jt,_a as Mn,a as p,ab as Un,b as bt,bc as Qe,bd as j,c as pa,cb as Vn,cc as Xt,cd as qn,d as Xe,dd as zn,e as mt,ed as Jn,f as Ye,fc as Cr,fd as Zn,g as Z,gb as ut,gc as Wn,h as ge,hb as ot,hc as Hn,hd as Qn,i as Ra,j as g,ja as Gr,jb as Ce,jc as Tr,kb as st,kc as Nt,kd as eo,lb as Va,lc as ha,m as ka,mb as Ar,mc as we,nb as Re,nc as Yn,ob as ie,od as vr,p as Dn,pb as Ze,q as y,qb as $r,qc as ke,rb as _r,u as Q,ud as to,va as ue,vd as ja,wa as se,wd as ao,ya as de,z as Oa,zd as ro}from"./chunk-RXWLL2AI.mjs";var Xa="sync",Te="syncmsg",Pr="@payloadAddrsDomain",ai="init",ri="ack",ni="delta",oi="commit",ce={init:ai,ack:ri,delta:ni,commit:oi},tc=Object.values(ce),si="abort",ii="optimistic-graft-longest-common-subsequence",ve={abort:si,optimisticWithLCS:ii},xt=Object.values(ve);function Ka(o){return xt.includes(o)}p(Ka,"isValidSyncConflictStrategy");var ci="push",di="pull",li="sync",xr={push:ci,pull:di,sync:li},sc=Object.values(xr);var fi="sender",bi="receiver",Wa={sender:fi,receiver:bi},ic=Object.values(Wa);var Kt="graftinfo",Me=Kt,fo="latestcommonaddr",yt="base",et="orphan",bo="dnaapplied",mi="longest-common-subsequence",Dr={lcs:mi},lc=Object.values(Dr);var ga=!1;async function pi({data:o}){if(!o.conflictStrategy)throw new Error("(UNEXPECTED) data.conflictStrategy required for GraftInfoIb (E: 2c0968a0dac8d0ab3d67da9756d6df26)");if(!Ka(o.conflictStrategy))throw new Error(`invalid data.conflictStrategy (${o.conflictStrategy}). valid conflict strategies: ${xt} (E: 41e2680089786d4d28046b4c0884bd26)`);return[Kt,o.conflictStrategy].join(" ")}p(pi,"getGraftInfoIb");async function ua({conflictStrategy:o,details:e,addlGraftDetails:t,latestCommonFrameAddr:a,baseAddrsSinceLCA:r,orphanAddrsSinceLCA:n,dnaAddrsApplied:s}){let i=`[${ua.name}]`;try{if(ga&&console.log(`${i} starting... (I: 0030f62cbae28cf5882f87981edc3826)`),r.length===0)throw new Error("(UNEXPECTED) baseAddrsSinceLCA empty? (E: 005f8449a9236d445902a148f59fc826)");if(n.length===0)throw new Error("(UNEXPECTED) orphanAddrsSinceLCA empty? (E: 19e4082e82c67759c880392aca186826)");let c={conflictStrategy:o,description:e};t&&(c.addlGraftDetails=t);let d={[fo]:[a],[yt]:r.concat(),[et]:n.concat(),[bo]:s.concat()},f=await pi({data:c});return await U.stone({parentPrimitiveIb:Kt,ib:f,data:c,rel8ns:d,uuid:!0})}catch(c){throw console.error(`${i} ${g(c)}`),c}finally{ga&&console.log(`${i} complete.`)}}p(ua,"createGraftInfo");async function mo({textA:o,textB:e}){if(o===e)return o;if(o==="")return e;if(e==="")return o;function t(d,f){let b=d.length,m=f.length,u=Array(b+1).fill(0).map(()=>Array(m+1).fill(0));for(let w=1;w<=b;w++)for(let A=1;A<=m;A++)d[w-1]===f[A-1]?u[w][A]=u[w-1][A-1]+1:u[w][A]=Math.max(u[w-1][A],u[w][A-1]);let h=b,I=m,E=[];for(;h>0&&I>0;)d[h-1]===f[I-1]?(E.unshift({line:d[h-1],indexA:h-1,indexB:I-1}),h--,I--):u[h-1][I]>u[h][I-1]?h--:I--;return E}p(t,"longestCommonSubsequence");let a=o.split(`
2
- `),r=e.split(`
3
- `),n=t(a,r),s=[],i=0,c=0;for(let d of n){for(;i<d.indexA;)s.push(a[i]),i++;for(;c<d.indexB;)s.push(r[c]),c++;s.push(d.line),i++,c++}for(;i<a.length;)s.push(a[i]),i++;for(;c<r.length;)s.push(r[c]),c++;return s.join(`
4
- `)}p(mo,"mergeTextByLongestCommonSubsequence");function Lr(o){let e=`[${Lr.name}]`;try{if(ga&&console.log(`${e} starting... (I: fe9adfe1a3175d87982507c8851f5826)`),!o)throw new Error("(UNEXPECTED) not a graft info, ibGib falsy? (E: bf06cdd700788e777f72fe5a5bdb0e26)");if(!o.data)throw new Error("not a graft info, ibGib.data falsy (E: 5e1b28843ec8571a7623046a06195826)");if(!o.ib.startsWith(Kt))throw new Error(`not graft info, ibgib.ib does not start with ${Kt} (E: cec6a8e25ff8746aef813e38cbebce26)`);return!0}catch(t){return ga&&console.error(`${e} ${g(t)}`),!1}finally{ga&&console.log(`${e} complete.`)}}p(Lr,"isGraftInfo");var Ie=!1;async function Rr({data:o}){let e=`[${Rr.name}]`;try{return[Xa,o.uuid].join(" ")}catch(t){throw console.error(`${e} ${g(t)}`),t}}p(Rr,"getSyncIb");async function po(){return`tmp_sync_space_${(await Z()).substring(0,8)}`}p(po,"getTempSpaceName");async function Wt({olderAddr:o,newerAddr:e,space:t}){let a=`[${Wt.name}]`;try{if(Ie&&console.log(`${a} starting... (I: 4b3548cbc9a2eb749f447ed82fdcf826)`),o===e)return!0;let r,n=await ue({space:t,addr:e});if(n.success&&n.ibGibs?.length===1)r=n.ibGibs[0];else throw new Error(`couldn't get newerAddr (${e}) from space (${t.ib}). (E: 36c758c22b181b2c89a1cd28937a6826)`);if(!r.rel8ns)return console.warn(`${a} newerIbGib.rel8ns falsy? newerAddr: ${e}. (W: 6f920811f7080281189f767813814826)`),!1;let s=r.rel8ns.past??[];if(s.length===0)return!1;if(s.includes(o))return!0;let i=s[0];return await Wt({olderAddr:o,newerAddr:i,space:t})}catch(r){throw console.error(`${a} ${g(r)}`),r}finally{Ie&&console.log(`${a} complete.`)}}p(Wt,"isPastFrame");async function Dt({sagaIbGib:o,localSpace:e}){let t=`[${Dt.name}]`,a=p(async i=>{let c=await ue({space:e,addrs:i});if(c.success&&c.ibGibs?.length===i.length)return c.ibGibs;{let d=c.rawResultIbGib;throw d.data?new Error(`(UNEXPECTED) couldn't find addrs? addrsNotFound: ${d.data.addrsNotFound}? space.ib: ${e.ib} (E: 43b7b5a6ad982715c8f3eed69bfa0d26)`):new Error("(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: c26c681d2f831fc537ba6f48fee36d26)")}},"fnGet"),r=await Ha({sagaIbGib:o});if(r.length>0)throw new Error(`invalid sync sagaIbGib. validationErrors: ${r} (E: 19f9e8c9643858ff41312b62293d2126)`);if(!o.rel8ns)throw new Error("(UNEXPECTED) validated sagaIbGib.rel8ns falsy? (E: 73af48be8bbf271ec5cf78187ce8c826)");let n=o.rel8ns[Te],s=await a(n);return{sagaIbGib:o,msgStones:s}}p(Dt,"getSyncSagaFrameDependencyGraph");async function Ht({sagaIbGib:o,space:e}){let t=`[${Ht.name}]`;try{if(Ie&&console.log(`${t} starting... (I: 1ea3f804dd07d1e917a2afaaad497826)`),!o.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: fe0a0d0965e87ac852fe7ba4710cc826)");if(!o.rel8ns)throw new Error("(UNEXPECTED) sagaIbGib.rel8ns falsy? (E: b79ff82a732346bdf8a9e1eb9ac96826)");let a=y({ibGib:o}),r=o.rel8ns.past&&o.rel8ns.past.length>0?[...o.rel8ns.past,a]:[a],n=[];for(let s of r){let i,c=await ue({addr:s,space:e});if(c.success&&c.ibGibs&&c.ibGibs.length===1)i=c.ibGibs[0];else throw Ie&&console.log(`${t} failed getting full history of sagaIbGib:
5
- ${ge(o)} (I: 2a35685bfe038f63182c7db39b44c826)`),new Error(`couldn't get saga addr (${s}) from space (${e.ib}) (E: 865b78ecd918c244158813650bea7d26)`);let d=await Dt({sagaIbGib:i,localSpace:e});n.push(d)}return n}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Ie&&console.log(`${t} complete.`)}}p(Ht,"getFullSyncSagaHistory");async function Ha({sagaIbGib:o}){let e=`[${Ha.name}]`;try{Ie&&console.log(`${e} starting... (I: dac978e9ec5820f128fbbff817b82826)`);let t=await ht({ibGib:o})??[];if(t.length>0)return t;if(o.data){let{data:a}=o;a.uuid||t.push("data.uuid required (E: aa24eeda7b88d22e5832a2e8083c0826)"),a.timestamp||t.push("data.timestamp required (E: 9c82a88548f4b63c38687428754b3826)"),a.timestampMs||a.timestampMs===0||t.push("data.timestampMs required (E: 9c82a88548f4b63c38687428754b3826)"),a.conflictStrategy?Ka(a.conflictStrategy)||t.push(`data.conflictStrategy (${a.conflictStrategy}) is invalid. Must be one of "${xt}". (E: 6223a8813b688fa2c8644fa8a491bf26)`):t.push("data.conflictStrategy required (E: 9c82a88548f4b63c38687428754b3826)"),a.expirationTimestamp,a.errors,a.successCount}else t.push("sagaIbGib.data falsy (E: 4de5e8de589d0af7245600fb4fe30926)");if(o.rel8ns){let a=o.rel8ns[Te];a&&a.length>0||t.push("sagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME] required. (E: df648dc18148e718682acb4842ecf826)")}else t.push("sagaIbGib.rel8ns falsy (E: da37aa492a7275b68a5e1912c7a5e126)");return t}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{Ie&&console.log(`${e} complete.`)}}p(Ha,"validateSyncSagaFrame");async function Ya({history:o}){let e=`[${Ya.name}]`;try{return Ie&&console.log(`${e} starting... (I: df02b802f6989096b8d8f728e2c0a526)`),console.error(`${e} NAG ERROR (NOT THROWN) need to implement more validation on full saga history. (E: 9bfcc9247a1c783fd361a4a8216fef26)`),[]}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{Ie&&console.log(`${e} complete.`)}}p(Ya,"validateFullSyncSagaHistory");async function Et({ibGibs:o,space:e}){let t=`[${Et.name}]`;try{Ie&&console.log(`${t} starting... (I: aa3ab828402836b3914800a8ffa1b826)`);let a=[],r=[];for(let n of o)Ln({ibGib:n})||(Oa({ibGib:n})?a.push(n):r.push(n));return a.length>0&&await se({ibGibs:a,isDna:!0,space:e}),r.length>0&&await se({ibGibs:r,isDna:!1,space:e}),{payload_Dnas:a,payload_NonDnas:r}}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Ie&&console.log(`${t} complete.`)}}p(Et,"putInSpace_dnasThenNonDnas");function Yt({sagaFrame:o}){let e=`[${Yt.name}]`;try{if(Ie&&console.log(`${e} starting... (I: 93521332d0dd2f5e88398b7db95e8126)`),!o)throw new Error("(UNEXPECTED) sagaFrame falsy? (E: 01fb28be6668d88ea49bb298c739c926)");if(!o.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: 998298eb17685bdb9a85b46488ccd826)");if(!o.data.n&&o.data.n!==0)throw new Error("(UNEXPECTED) sagaFrame.data.n falsy and not 0? (E: 0394919d5b58300ceb09ba6a264ad826)");let t=o.data.n%2;if(t===0)return Wa.sender;if(t===1)return Wa.receiver;throw new Error("(UNEXPECTED) modulo is neither 0 nor 1? my logic sucks! This was way too defensive on my part... (E: 559488a2eef8d17b57079ca8886ee826)")}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{Ie&&console.log(`${e} complete.`)}}p(Yt,"getSyncSagaFrameOrigin");async function qa({sagaHistory:o}){let e=`[${qa.name}]`;try{Ie&&console.log(`${e} starting... (I: fe93a8f29e5d8ab2c8bd0e08e56f7826)`);let t=o.findLast(n=>n.msgStones.some(s=>s.data.stage===ce.delta));if(!t)throw new Error("(UNEXPECTED) no delta frame? What are we calling this function for? (E: 9b3201207908f79868b93cd893a91626)");let a=t.msgStones.filter(n=>n.data.stage===ce.delta);if(a.length>1)throw new Error("(UNEXPECTED) multiple delta stones in history slice? we're expecting a single delta stone per saga frame. (E: a4bd5860b4aa0743753d4798d3163826)");return a[0].data.conflicts}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{Ie&&console.log(`${e} complete.`)}}p(qa,"getFinalConflictsInfo");async function kr({sagaHistory:o,myTempSpace:e}){let t=`[${kr.name}]`;try{Ie&&console.log(`${t} starting... (I: b755627e99c9a221566d86a81b0da526)`);let a=await qa({sagaHistory:o});if(!a||a.length===0)return Ie&&console.log(`${t} no conflicts found. returning empty array (I: 5dce98010128a284c8ec92cd466a3826)`),[];let r=[];for(let n of a){if(!n.resolved)throw new Error("(UNEXPECTED) conflict.resolved falsy? we're expecting all conflicts to be resolved when getting orphaned addresses. (E: 3861e89a18c8ff405eb2117f6d4b9b26)");if(!n.graftInfoAddr)throw new Error("(UNEXPECTED) conflict.graftInfoAddr falsy? we're expecting a resolved conflict whose final ibgib (graft tip) was the graft info and for this addr to be in conflict.graftInfoAddr. (E: 80d86e333028585908f4757bc4d6f826)");let s=await Re({addrs:[n.graftInfoAddr],space:e});if(s.length!==1)throw new Error(`(UNEXPECTED) couldn't get conflict.graftInfoAddr (${n.graftInfoAddr}) from myTempSpace (${e.ib})? (E: cf1fe87096f8ea22f84f250d7ab30226)`);let i=s[0];if(!Lr(i))throw new Error(`(UNEXPECTED) graft info from conflict.graftInfoAddr (${n.graftInfoAddr}) does not pass the isGraftInfo guard? We're expecting this addr to point to a valid GraftInfoIbGib_V1 (E: 6aa9ecb9a428d92be8d1bdbe0696f826)`);let c=i.rel8ns[et];if(!c||c.length===0)throw new Error(`(UNEXPECTED) orphanedAddrs empty for conflict graftInfo (${n.graftInfoAddr})? we're expecting a graft to always necessarily orphan one or other branches, otherwise what are we "grafting"? (E: 3ed1284f6ca84754582801484d751926)`);c.forEach(d=>r.push(d))}return r}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Ie&&console.log(`${t} complete.`)}}p(kr,"getAllOrphanedAddresses");async function Lt({senderSecret:o,sagaId:e}){let t=`[${Lt.name}]`;try{if(Ie&&console.log(`${t} starting... (I: 0de03f8dcd3e32f1fca244e8f2a8a826)`),!o)throw new Error("(UNEXPECTED) senderSecret falsy? (E: 8ce053fe59825a6678713128953b9d26)");if(!e)throw new Error("(UNEXPECTED) sagaId falsy? (E: 3a17e0c1b2f849de8a42cd15b8ee6826)");return await Xn({masterSecret:o,kdfOpts:{strategy:jn.recursive_salt_wrap,salt:e,rounds:1e4,algorithm:"SHA-256"}})}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Ie&&console.log(`${t} complete.`)}}p(Lt,"deriveSessionSecret");var za="sync_sagacontext";var ya=!1;async function Or({data:o}){let e=`[${Or.name}]`;try{if(!o)throw new Error("data required (E: 839d82138c234b3e89582855594191fe)");let t=o["@payloadAddrsDomain"]?o["@payloadAddrsDomain"].length:0;return[za,o.sagaN,t].join(" ")}catch(t){throw console.error(`${e} ${g(t)}`),t}}p(Or,"getSyncSagaContextIb");async function wt({context:o}){let e=`[${wt.name}]`;try{ya&&console.log(`${e} starting... (I: 7797f8294bd8f7e5089cb722ad468226)`);let t=[],a=await ht({ibGib:o});if(a&&a.length>0)return a.forEach(r=>t.push(r)),t;if(o.sagaFrame?(await Ha({sagaIbGib:o.sagaFrame})).forEach(n=>t.push(n)):t.push("context.sagaFrame is falsy. (E: b4edd88f4963f493789f83b29ba2df26)"),o.sagaFrameMsg){if((await ht({ibGib:o.sagaFrameMsg})??[]).forEach(n=>t.push(n)),o.sagaFrame){let n=o.sagaFrame.rel8ns?.[Te]?.[0];if(n){let s=y({ibGib:o.sagaFrameMsg});s!==n&&t.push(`context.sagaFrameMsg address (${s}) does not match the stone address referenced in sagaFrame relations (${n}). (E: a983b271fcae46bbad7e82098bc24826)`)}else t.push(`context.sagaFrame is missing the message stone relation '${Te}'. (E: da872cf3a8d46dbbad89d0a68d712826)`)}}else t.push("context.sagaFrameMsg is falsy. (E: ed405a72ab0d8bbdca7b9605d8f9a26)");return t.length>0?t:[]}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{ya&&console.log(`${e} complete.`)}}p(wt,"validateContextAndSagaFrame");async function Fr({context:o,space:e}){let t=`[${Fr.name}]`;try{ya&&console.log(`${t} starting... (I: 3c34e8f1d6ef965f98725c88459ea926)`);let a=[];if(!o.data)throw new Error("(UNEXPECTED) context.data falsy? (E: 3e4ddd0eb4b828ad489658d88d9a6326)");if(!o.rel8ns)throw new Error("(UNEXPECTED) context.rel8ns falsy? (E: 8026589d4fed69c828334ee842074326)");let{sagaFrame:r,signedSessionIdentity:n}=o;if(!r.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: b61cc82d25984c92f75db74a5a855b26)");if(!n)return console.error(`${t}[NAG] (NOT THROWN) sagaFrame.data.sessionIdentityTjpAddr logic needs to be added in coordinator (E: 4fc47800a1086c917a47381824280826)`),r.data.sessionIdentityTjpAddr?(a.push("Context has no session identity, but sync saga frame shows a session identity (sagaFrame.data.sessionIdentityTjpAddr is truthy). (E: 69dd6cdc2e1859c0f3d62958c4339826)"),a):o.rel8ns.sessionIdentity?(a.push("Context has no signed session identity, but context.rel8ns.sessionIdentity is truthy. (E: 96a04a8a6c88ea8bf88118f89ad8e326)"),a):(ya&&console.log(`${t} context has no signedSessionIdentity and sync saga frame doesn't state there should be session identity. So nothing further to authenticate - returning early with no authentication errors. (I: d708735f9a2899ee98f762b8a09ed826)`),[]);let s=y({ibGib:n}),i=o.rel8ns?.sessionIdentity??[];if(i.length===0)return a.push("context.rel8ns.sessionIdentity is falsy/empty but context.signedSessionIdentity is present. (E: 66f906421eb2468c0b33f908a3cf2826)"),a;if(i.length>1)return a.push("context.rel8ns.sessionIdentity has multiple identity addrs. (E: 489428bfe6fdaa4cd885b938dc4c5826)"),a;let c=i[0],d=await vt({addrs:[c],space:e});if(!d)throw new Error(`(UNEXPECTED) resGetLatestAddr for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 7b207e5cbcec9037ea5adbe822ead826)`);if(!d.data)throw new Error(`(UNEXPECTED) resGetLatestAddr.data for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: de4eb8d730c8c4dcb59c8b9c79277826)`);if(!d.data.success)throw new Error("(UNEXPECTED) resGetLatestAddr.data.success falsy? (E: c94298dfd9684ad6a87eb748459aa826)");let{latestAddrsMap:f}=d.data;if(!f)throw new Error("(UNEXPECTED) resGetLatestAddr.data.latestAddrsMap falsy? (E: 19f1fd5fe798cf2e5fa923919169d826)");if(Object.keys(f).length!==1)throw new Error("(UNEXPECTED) Object.keys(latestAddrsMap).length !== 1? (E: fe526a0747589c6427a8bcc86da34a26)");let b=f[c];if(!b)return a.push(`prevSessionIdentityAddr (${c}) not found in space (${e.ib}). this should have been the incoming prevSessionIdentityAddr (E: f6d042bd6b54819998653228dee34226)`),a;if(c!==b&&b!==s)return a.push(`context.rel8ns.sessionIdentity does not point to the most recent in the space (${e.ib}). (E: 2f8288f53c87b6aa47bd2178d9df0c26)`),console.log(`context: ${ge(st({ibGib:o}))}`),console.log(`prevSessionIdentityAddr (context.rel8ns.sessionIdentity): ${c}`),console.log(`prevSessionIdentityAddr_latest: ${b}`),console.log(`currSessionIdentity (context.signedSessionIdentity): ${ge(st({ibGib:{ib:n.ib,gib:n.gib,rel8ns:n.rel8ns,data:{...n.data,challengePools:n.data.challengePools.map(k=>({...k,challenges:{}}))}}}))}`),console.log(`currSessionIdentityAddr: ${s}`),a;let m=await ue({addr:c,space:e});if(!m.success||m.ibGibs?.length!==1)return a.push(`could not fetch latest sender identity ${c} from space (${e.ib}). (E: fd48c3e64c9fa4efd8a1f8280af18226)`),a;let u=m.ibGibs[0],h=await Rn({ibGib:u,naive:!0,space:e});if(!h)throw new Error(`(UNEXPECTED) couldn't get sessionIdentityTjp in space (${e.ib})? we have already gotten the identity itself in the space, so we would expect the entire timeline to exist in it. (E: 9be0382ff1c8a0e77645ea38c096f826)`);let I=y({ibGib:h});if(I!==r.data.sessionIdentityTjpAddr)throw new Error("(UNEXPECTED) sessionIdentityTjpAddr !== sagaFrame.data.sessionIdentityTjpAddr? (E: c9a4ad5c2728fe38e86afc58e4abaf26)");let E=h.data.frameDetails;if(!E)return a.push("Invalid session identity tjp: sessionIdentityTjp.data.frameDetails is falsy. (E: 0187f8f804a84256281720586620b826)"),a;let{senderIdentityAddr:w,senderIdentityTjpAddr:A}=E;if(!w)throw new Error("sessionGenesisFrameDetails.senderIdentityAddr falsy (E: 02a0c80a3ead9e3af8af4cf3b156e826)");if(!A)throw new Error("sessionGenesisFrameDetails.senderIdentityTjpAddr falsy (E: 271928090ff5dc56d4bb63d8d5c68826)");let G=await vt({addrs:[A,w],space:e});if(!G)throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 2e4ae8083b6fb7cbb8fae2a519062926)`);if(!G.data)throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity.data for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 2e231850c2a898cc282b4b2841056826)`);if(!G.data.success)throw new Error("(UNEXPECTED) resGetLatestAddr_senderIdentity.data.success falsy? (E: e93508f03e0475925875b00746ffd826)");let{latestAddrsMap:T}=G.data;if(!T)throw new Error("(UNEXPECTED) resGetLatestAddr_senderIdentity.data.latestAddrsMap falsy? (E: 87a91e3f9968ad9ba79cdfe8cd878326)");if(Object.keys(T).length!==2&&A!==w)throw new Error("(UNEXPECTED) Object.keys(latestAddrsMap_senderIdentity).length !== 2 && senderIdentityTjpAddr !== senderIdentityAddr? (E: fe46bd584853d8e1e8e2d11f52012826)");let C=T[A],S=T[w];if(!S)throw new Error("(UNEXPECTED) senderIdentityAddr_latest falsy? (E: e151798ae2e9241578d09948937c4b26)");if(C!==S)throw new Error("senderIdentityTjpAddr_latest !== senderIdentityAddr_latest (E: 52478a1053589e72665031a853cc1826)");let _=await ue({addr:S,space:e});if(!_.success||_.ibGibs?.length!==1)return a.push(`could not fetch latest sender identity ${c} from space (${e.ib}). (E: 3565ff0ed458f5a2384c40b16e849826)`),a;let $=_.ibGibs[0];if(!$.data.proofs)return a.push("Invalid sender identity. Proofs empty/falsy. (E: ebf488853061614d2b5b137828119526)"),a;let B=$.data.proofs.find(k=>k.claim.verb===De)?.claim;if(!B)return a.push(`Most recent senderIdentity has no proof whose claim.verb === ${De}. (E: b0f488ecccbbfe43d9a0b7c8a29d7826)`),a;if(B.target!==I)return a.push(`Most recent sender identity claim has claim.verb === ${De} but DOES NOT target expected session identity addr ${c}. (E: 3e7f18d99848969be8586423d5ccb826)`),a;let N=await new ke().validate({currentIbGib:n,prevIbGib:u});N.length>0&&a.push(`Invalid session identity transition: ${N.join(", ")} (E: da1c81c6d3c86aec3254f48fe7514226)`);let x=y({ibGib:o});return n.data?.proofs?.some(k=>k.claim.target===x)||a.push(`Session identity signature does not target current context ibgib (${x}). (E: acae68938c287178c878d1b88bebb826)`),a}catch(a){let r=`${t} ${g(a)}`;return console.error(r),[`authentication produced an error: ${r} (E: 45e014b82af81993d936611ca6fc4d26)`]}finally{ya&&console.log(`${t} complete.`)}}p(Fr,"authenticateContextIntrinsically");var Be=!1,qt=class o extends to{static{p(this,"SyncPeer_V1")}lc=`[${o.name}]`;opts;payloadIbGibsDomainReceived$;currentSessionIdentity;get currentSessionIdentityAddr(){return this.currentSessionIdentity?y({ibGib:this.currentSessionIdentity}):void 0}async signContext({contextAddr:e}){let t=`${this.lc}[${this.signContext.name}]`;try{if(!this.currentSessionIdentity)return;if(!this.opts)throw new Error("opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)");let{fnSenderSecret:a,sagaId:r,localMetaspace:n,localSpace:s}=this.opts;if(!a)throw new Error("fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)");if(!r)throw new Error("sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)");let i=await a(),c=await Lt({senderSecret:i,sagaId:r}),f=await new ke().sign({latestKeystone:this.currentSessionIdentity,masterSecret:c,claim:{verb:De,target:e},metaspace:n,space:s});return this.currentSessionIdentity=f,f}catch(a){throw console.error(`${t} ${g(a)}`),a}}async signContextConnect({challengeUuid:e,demandedIds:t}){let a=`${this.lc}[${this.signContextConnect.name}]`;try{if(!this.currentSessionIdentity)return;if(!this.opts)throw new Error("opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)");let{fnSenderSecret:r,sagaId:n,localMetaspace:s,localSpace:i}=this.opts;if(!r)throw new Error("fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)");if(!n)throw new Error("sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)");let c=await r(),d=await Lt({senderSecret:c,sagaId:n}),b=await new ke().sign({latestKeystone:this.currentSessionIdentity,masterSecret:d,poolId:Qe,requiredChallengeIds:t,claim:{verb:jt,target:e},metaspace:s,space:i});return this.currentSessionIdentity=b,b}catch(r){throw console.error(`${a} ${g(r)}`),r}}get classname(){if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 1ab1841e9338b54f3aa615fa37024826)");if(!this.data.classname)throw new Error("invalid peer. this.data.classname is falsy (E: b0ee28a0abb84a06588d9de7afcef826)");return this.data.classname}constructor(e,t){super(e,t)}async initialize(){this.payloadIbGibsDomainReceived$=await ja()}async connect(e){let t=`${this.lc}[${this.connect.name}]`;try{Be&&console.log(`${t} starting... (I: ad89d8137351662fb8a30114a1fa4826)`),await this.preConnectCheck(e),await this.connectImpl(e)}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Be&&console.log(`${t} complete.`)}}async establishSessionIdentity(){let e=`${this.lc}[${this.establishSessionIdentity.name}]`;try{if(Be&&console.log(`${e} starting... (I: cdc208b8197f646e0abe05f101a0f126)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? Call initializeOpts first. (E: 5c6a6bf6b872e4ce08055b71348e8a26)");let{senderIdentity:t,fnSenderSecret:a,senderDomainAddr:r,sagaId:n,localMetaspace:s,localSpace:i}=this.opts;if(!t||!a){Be&&console.log(`${e} no senderIdentity/fnSenderSecret \u2014 skipping establish (I: f29348a77d1542326d14043ea4b69126)`);return}if(!r)throw new Error("(UNEXPECTED) senderDomainAddr falsy but senderIdentity/fnSenderSecret truthy? if identity is used, senderDomainAddr must be provided. (E: c288fa8e9d3d82fc)");let c=y({ibGib:t}),d=Ce({ibGib:t});if(!d)throw new Error("(UNEXPECTED) senderIdentityTjpAddr falsy? (E: d5d8c3ab25a83a2c127904fe96de1526)");if(!n)throw new Error("(UNEXPECTED) sagaId falsy? Must be set in initializeOpts before calling establishSessionIdentity. (E: c6ba389d51b8af07d82458f875cf9826)");let f=await a();if(!f)throw new Error("senderSecret falsy. senderSecret required. (E: 1a8b0298bf78cbdf284b7988983b9826)");let b=await Lt({senderSecret:f,sagaId:n}),m=new ke;if(!this.opts.sessionConnectPoolConfig)throw new Error("(UNEXPECTED) opts.sessionConnectPoolConfig falsy? (E: 3351fd566eb8bbd2f821bb08c4419826)");if(!this.opts.sessionSyncPoolConfig)throw new Error("(UNEXPECTED) opts.sessionSyncPoolConfig falsy? (E: dbffa810d9e7ff6079088deb5b8e7826)");let u={senderIdentityAddr:c,senderIdentityTjpAddr:d};this.opts.targetAddrs&&(u.targetAddrs=this.opts.targetAddrs);let h=await m.genesis({masterSecret:b,configs:[this.opts.sessionConnectPoolConfig,this.opts.sessionSyncPoolConfig],frameDetails:u,metaspace:s,space:i}),I=y({ibGib:h}),E=await m.sign({latestKeystone:t,masterSecret:f,claim:{verb:De,target:I},metaspace:s,space:i});await this.postEstablishToReceiver({newSenderIdentity:E,sessionIdentity:h}),this.currentSessionIdentity=h}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{Be&&console.log(`${e} complete.`)}}async initializeOpts(e){let t=`${this.lc}[${this.initializeOpts.name}]`;try{Be&&console.log(`${t} starting... (I: 31bd5fda37c89fa37fbaf14daf5fe726)`),this.opts=e}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Be&&console.log(`${t} complete.`)}}setOptionalOpts(e){let t=`${this.lc}[${this.setOptionalOpts.name}]`;try{if(Be&&console.log(`${t} starting... (I: ae5ddbd3577db267f84743175a736626)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: 0dd4d6080a6e2f31d86cf4d86e11b826)");Be&&console.log(`${t} updating opts. arg keys: ${Object.keys(e)} (I: 452d78a558f8fc3468c8e2e68c70b226)`),this.opts={...this.opts,...e}}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Be&&console.log(`${t} complete.`)}}async authenticateAndValidate({context:e}){let t=`${this.lc}[${this.authenticateAndValidate.name}]`;try{if(Be&&console.log(`${t} starting... (I: add238055cd84a222c5b8c89913af526)`),!this.opts)throw new Error("(UNEXPECTED) opts falsy in authenticateValidateAuthorize (E: b7e5a8ad99d84e1ba8d8f7facd288826)");let{localSpace:a}=this.opts,r=await Fr({context:e,space:a});if(r.length>0)throw new Error(`invalid context authentication. authenticationErrors: ${r} (E: da89da5ee1269aeb78952d475d607526)`);let n=await wt({context:e});if(n.length>0)throw new Error(`invalid context received. validationErrors: ${n} (E: 8b34c875c968af29bc433138e57a7826)`)}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Be&&console.log(`${t} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{if(Be&&console.log(`${t} starting...`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? Concrete class should have initialized sender opts by now. (E: 0b9e28287318fdf8bf9f5a6886a24826)");if(!e.sagaFrame)throw new Error("context.sagaFrame falsy. (E: a33dd88aa108e2bad9e885885731ce26)");await this.authenticateAndValidate({context:e});let a=await this.sendContextRequest(e);if(a){let r=await Ht({sagaIbGib:e.sagaFrame,space:this.opts.localSpace});return a}else{Be&&console.log(`${t} No response from peer. this may be normal if we just sent the very last commit frame. (I: 1855b7728c8898e1f9c001f8170ba826)`);return}}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Be&&console.log(`${t} complete.`)}}async getLocalIbGib(e){let t=`${this.lc}[${this.getLocalIbGib.name}]`;try{if(Be&&console.log(`${t} starting... (I: 27b248cb9801eeb2386b71485389a826)`),console.warn(`${t} possibly a bottleneck here, getLocalIbGib only gets a single ibgib... (W: 2fd448a435480e6b128f6b8bcbef4826)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: cfb9431f2fb851f24a6c88e80c3b3326)");let a=await ue({space:this.opts.localSpace,addr:e});if(a.success&&a.ibGibs&&a.ibGibs.length===1)return a.ibGibs[0];throw new Error(`couldn't get addr (${e}) from local space ${this.opts.localSpace}. reason: ${a.errorMsg??"unknown error (E: 926ef8bf4fcc299ab89dba34ea691a26)"} (E: d8a89807e471d3f8b938ab21df44cb26)`)}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Be&&console.log(`${t} complete.`)}}};var ho=!1,It={COMMON:{ALGO:pa.sha_256,TYPE:Kn.hash_reveal_v1,ROUNDS:2,REPLENISH:Bt.topUp},CONNECT_POOL:{ID:Qe,VERB:jt,SIZE:10,SELECT_SEQUENTIALLY:2,SELECT_RANDOMLY:2,TARGET_BINDING_COUNT:0,SERVER_DEMAND_COUNT:3}};function Ja(o){let e=`[${Ja.name}]`;try{ho&&console.log(`${e} starting... (I: 3c791af2f978a00a087dfdde90884826)`);let t=(o.data?.challengePools??[]).find(s=>s.id===It.CONNECT_POOL.ID);if(!t)throw new Error(`Keystone missing "${It.CONNECT_POOL.ID}" pool (E: 6382e29260e4ddbac42ed18f49733526)`);let a=Object.keys(t.challenges).sort();if(a.length===0)throw new Error("Connect pool has no challenges (E: 1ef62fdbda182a790835c8c796475226)");let r=a[0],n=t.challenges[r];return{challengeId:r,challenge:n}}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{ho&&console.log(`${e} complete.`)}}p(Ja,"getConnectChallenge");var hi="auth-challenge-init",gi="auth-init",ui="auth-challenge",yi="auth-proof",Ei="auth-ok",wi="auth-fail",Ii="sync-frame",Si="sync-frame-response",Gi="sync-frame-authenticated",Ai="sync-frame-response-authenticated",$i="domain-payload",_i="sync-error",H={auth_challenge_init:hi,auth_init:gi,auth_challenge:ui,auth_proof:yi,auth_ok:Ei,auth_fail:wi,sync_frame:Ii,sync_frame_response:Si,sync_frame_authenticated:Gi,sync_frame_response_authenticated:Ai,domain_payload:$i,sync_error:_i},Za=Object.values(H);function Mr(o){return Za.includes(o)}p(Mr,"isSyncWebSocketMsgType");function go(o){throw new Error(`Unhandled message type: ${o} (E: e928a3f82cd7469a98ef1bc248a3f826)`)}p(go,"assertUnreachable");var Je=!1,zt=class o extends qt{static{p(this,"SyncPeerWebSocketSender_V1")}lc=`[${o.name}]`;get classname(){return o.name}get isSocketOpen(){return this.ws!==void 0&&this.ws.readyState===WebSocket.OPEN}ws;activeResolve;activeReject;pendingPayloadsToSend=[];handshakeMessageListener;constructor(e,t){super(e,t)}async preConnectCheck(e){let t=`${this.lc}[${this.preConnectCheck.name}]`;if(!this.data?.wsUrl)throw new Error("Missing wsUrl in peer data (E: 144c6ddf53980554cf08fa0896bd9826)");if(!this.data?.httpEvolveUrl)throw new Error("Missing httpEvolveUrl in peer data (E: 53425c1a13f829b8e8a55c2cea3a4a26)")}async postEstablishToReceiver({newSenderIdentity:e,sessionIdentity:t}){let a=`${this.lc}[${this.postEstablishToReceiver.name}]`;try{if(Je&&console.log(`${a} posting evolved keystones to ${this.data.httpEvolveUrl}...`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: d642e8a9af18b532c87c6f581aa53b26)");if(!this.data.httpEvolveUrl)throw new Error("(UNEXPECTED) this.data.httpEvolveUrl falsy? (E: 8589ddbb155914d85c09658881da2c26)");let r=await fetch(this.data.httpEvolveUrl,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:e,relatedKeystoneIbGibs:[t]})});if(!r.ok){let n=await r.json().catch(()=>({})),s=n.message||n.error||"Unknown error";throw new Error(`HTTP ${r.status} evolution post rejected. errorMsg: ${s} (E: e8a478291b88d05c68cf6b385684b826)`)}Je&&console.log(`${a} evolve post accepted by server.`)}catch(r){throw console.error(`${a} establish post failed: ${g(r)}`),r}}async connectImpl(e){let t=`${this.lc}[${this.connectImpl.name}]`;try{Je&&console.log(`${t} starting...`);let{senderIdentity:a,fnSenderSecret:r,sagaId:n,localMetaspace:s,localSpace:i}=this.opts;if(!a||!r||!n)throw new Error("Missing identity parameters in peer options (E: ed49b6711ac82efcdb42b8a28c5b6826)");let c=await r(),d=await Lt({senderSecret:c,sagaId:n}),f=y({ibGib:a}),b=y({ibGib:(a.rel8ns?.past,a)}),m=await s.getLatestAddr({ibGib:a,space:i});if(!m)throw new Error("senderIdentityLatestAddr falsy. we should have a latest addr that is different than the sender identity at this point (done in the peer establish phase) (E: 225607318bef485d7821f82de97b6826)");let I=((await s.get({addrs:[m],space:i})).ibGibs?.[0]).data.proofs.at(0)?.claim.target;if(!I)throw new Error("Could not locate session keystone target from identity (E: 5ec4882f7e5e4c33fbd00ab8b3166726)");let w=(await s.get({addrs:[I],space:i})).ibGibs?.[0];if(!w)throw new Error(`Session keystone not found in local space: ${I} (E: 9ba818e6622808bb4ae749be31f80b26)`);let A=(w.data?.challengePools??[]).find(B=>B.id===It.CONNECT_POOL.ID);if(!A)throw new Error("Session keystone missing connect pool (E: f50968afca04b6d38ec19824ea201826)");let{challengeId:G}=Ja(w),T=Tr.create({config:A.config}),C=await T.derivePoolSecret({masterSecret:d}),S=await T.generateSolution({poolSecret:C,poolId:It.CONNECT_POOL.ID,challengeId:G}),_=`${this.data.wsUrl}?sAddr=${encodeURIComponent(I)}&solution=${encodeURIComponent(S.value)}`;Je&&console.log(`${t} connecting to WebSocket: ${_}`);let $=new WebSocket(_);return this.ws=$,new Promise((B,D)=>{let N=!1;$.addEventListener("open",()=>{Je&&console.log(`${t} WebSocket opened. Awaiting challenge...`)}),this.handshakeMessageListener=async x=>{try{let L=JSON.parse(x.data);Je&&console.log(`${t} received handshake frame: ${L.type}`);let k=L.type;if(!Mr(k)){let te=Za.join(", ");throw new Error(`Unknown message type '${k}' received during connection handshake. Valid types are: ${te} (E: e983271bc84f46928e4695be2409826)`)}switch(k){case H.auth_challenge_init:await this.handleHandshakeAuthChallengeInit($,I);break;case H.auth_challenge:await this.handleHandshakeAuthChallenge($,L,w,d);break;case H.auth_ok:N=!0,this.handleHandshakeAuthOk($,B);break;case H.auth_fail:this.handleHandshakeAuthFail(L,D);break;case H.sync_error:this.handleHandshakeSyncError(L,D);break;case H.auth_init:case H.auth_proof:case H.sync_frame:case H.sync_frame_response:case H.sync_frame_authenticated:case H.sync_frame_response_authenticated:case H.domain_payload:throw new Error(`Unexpected message type '${k}' during connection handshake (E: e3f80c68ab2a46c2b1858c8a1e2f8926)`);default:go(k)}}catch(L){console.error(`${t} ${g(L)}`),D(L)}},$.addEventListener("message",this.handshakeMessageListener),$.addEventListener("close",x=>{N||(this.disconnect(),D(new Error(`WebSocket closed before connect completed (code: ${x.code})`)))}),$.addEventListener("error",x=>{N||(this.disconnect(),D(new Error("WebSocket connection error")))})})}catch(a){throw console.error(`${t} connect failed: ${g(a)}`),a}}disconnect(){let e=`${this.lc}[${this.disconnect.name}]`;try{if(Je&&console.log(`${e} starting... (I: 35c4b85fca0c6e9d042f5ff87cde3826)`),this.ws){this.handshakeMessageListener&&(this.ws.removeEventListener("message",this.handshakeMessageListener),this.handshakeMessageListener=void 0);try{this.ws.close()}catch(t){console.error(`${e} failed to close websocket: ${g(t)}`)}this.ws=void 0}}catch(t){console.error(`${e} ${g(t)}`)}finally{Je&&console.log(`${e} complete.`)}}async handleRuntimeMessage(e){let t=`${this.lc}[${this.handleRuntimeMessage.name}]`;try{let a=JSON.parse(e.data);Je&&console.log(`${t} received runtime frame: ${a.type}`);let r=a.type;if(!Mr(r)){let n=Za.join(", ");throw new Error(`Unknown message type '${r}' received during active sync saga loop. Valid types are: ${n} (E: e23a8d10b74d47fb90518f8e3f4b826)`)}switch(r){case H.sync_frame_response:await this.handleRuntimeSyncFrameResponse(a);break;case H.sync_frame_authenticated:this.handleRuntimeSyncFrameAuthenticated();break;case H.domain_payload:this.handleRuntimeDomainPayload(a);break;case H.sync_error:this.handleRuntimeSyncError(a);break;case H.auth_challenge_init:case H.auth_init:case H.auth_challenge:case H.auth_proof:case H.auth_ok:case H.auth_fail:case H.sync_frame:case H.sync_frame_response_authenticated:throw new Error(`Unexpected message type '${r}' during active sync saga loop (E: e982b12cf92c448bbad0e84b7263c826)`);default:go(r)}}catch(a){if(console.error(`${t} failed parsing/handling runtime frame: ${g(a)}`),this.disconnect(),this.activeReject){let r=this.activeReject;this.activeResolve=void 0,this.activeReject=void 0,r(a)}}}async handleHandshakeAuthChallengeInit(e,t){e.send(JSON.stringify({type:H.auth_init,sAddr:t}))}async handleHandshakeAuthChallenge(e,t,a,r){let{challengeUuid:n,demandedIds:s}=t;Je&&console.log(`${this.lc} solving demanded challenges: ${s.join(", ")}`);let i=await this.signContextConnect({challengeUuid:n,demandedIds:s});if(!i)throw new Error("Failed to sign connect challenge proof (E: e9807f28ae9248bbadd0a7f1a8e9826)");e.send(JSON.stringify({type:H.auth_proof,proofFrame:i}))}handleHandshakeAuthOk(e,t){Je&&console.log(`${this.lc} WebSocket connect SUCCESS!`),this.handshakeMessageListener&&(e.removeEventListener("message",this.handshakeMessageListener),this.handshakeMessageListener=void 0),e.addEventListener("message",a=>this.handleRuntimeMessage(a)),t()}handleHandshakeAuthFail(e,t){this.disconnect(),t(new Error(`Handshake auth failed: ${e.message||"Unknown fail reason"} (E: f380b271a2be498db257bc8209fa8926)`))}handleHandshakeSyncError(e,t){this.disconnect(),t(new Error(`Handshake sync error: ${e.message||e.error||"Unknown sync error"} (E: f9208a01fe434cbbad83f210ea8f3426)`))}async handleRuntimeSyncFrameResponse(e){let t=e.context,a=await wt({context:t});if(a.length>0)throw new Error(`Invalid response context received: ${a.join(", ")} (E: d7b5a283cf4c43ba8659c803800cf826)`);let r=[st({ibGib:t}),t.sagaFrame,t.sagaFrameMsg];t.signedSessionIdentity&&r.push(t.signedSessionIdentity);let{localSpace:n}=this.opts;for(let i of r)await se({space:n,ibGibs:[i]}),await oe({space:n,ibGib:i});if((t.data?.["@payloadAddrsDomain"]||[]).length>0&&this.ws.send(JSON.stringify({type:H.sync_frame_response_authenticated,contextAddr:y({ibGib:t})})),this.activeResolve){let i=this.activeResolve;this.activeResolve=void 0,this.activeReject=void 0,i(t)}}handleRuntimeSyncFrameAuthenticated(){let e=this.pendingPayloadsToSend||[];this.pendingPayloadsToSend=[];for(let t of e)this.ws.send(JSON.stringify({type:H.domain_payload,ibGib:t}))}handleRuntimeDomainPayload(e){let t=e.ibGib;this.payloadIbGibsDomainReceived$.next(t)}handleRuntimeSyncError(e){let t=e.message||e.error||"Unknown sync runtime error",a=new Error(`Sync runtime error from receiver: ${t} (E: e983bc1c828d447fa0581da2b8004f26)`);if(this.activeReject){let r=this.activeReject;this.activeResolve=void 0,this.activeReject=void 0,r(a)}else throw a}async sendContextRequest(e){let t=`${this.lc}[${this.sendContextRequest.name}]`;try{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected or open (E: 2979923231b882c5d6529e88b3f16826)");let a=e.payloadIbGibsDomain??[];this.pendingPayloadsToSend=[...a];let r={...e};return delete r.payloadIbGibsDomain,new Promise((n,s)=>{this.activeResolve=n,this.activeReject=s,this.ws.send(JSON.stringify({type:H.sync_frame,context:r}))})}catch(a){throw console.error(`${t} sendContextRequest failed: ${g(a)}`),a}}};var tt;(function(o){o.timestamp="timestamp",o.receiver="receiver",o.sender="sender"})(tt||(tt={}));var Qa="sync_sagamsg";async function Ur({data:o}){let e=`[${Ur.name}]`;try{return[Qa,o.sagaId,o.stage].join(" ")}catch(t){throw console.error(`${e} ${g(t)}`),t}}p(Ur,"getSyncSagaMessageIb");async function Vr({frameIbGib:o,space:e}){let t=`[${Vr.name}]`;try{let r=(await Un({ibGib:o,rel8nNames:[Te],space:e}))[Te];if(!r||r.length===0)throw new Error(`(UNEXPECTED) No sync message stone found found for frame: ${o.ib} (E: f9fa2ec64bc84191687609080373c826)`);if(r.length>1)throw new Error(`(UNEXPECTED) Multiple sync message stones found (${r.length}) for frame: ${o.ib}. logic not currently equipped to handle multiple messages per frame. (E: a9876fdd114f0109cdafbb08f79ca826)`);return r[0]}catch(a){throw console.error(`${t} ${g(a)}`),a}}p(Vr,"getSyncSagaMessageFromFrame");var uo=!1,Jt=class{static{p(this,"GraftMergeStrategyBase_V1")}defaultGraftPreference;constructor(e){this.defaultGraftPreference=e?.defaultGraftPreference??tt.timestamp}resolveBaseAndOrphan({graftPreference:e,tipA_sender:t,branchA_sender_sinceLCA:a,tipB_receiver:r,branchB_receiver_sinceLCA:n}){let s=e||this.defaultGraftPreference;if(s===tt.receiver)return{baseTip:r,baseBranch:n,orphanTip:t,orphanBranch:a};if(s===tt.sender)return{baseTip:t,baseBranch:a,orphanTip:r,orphanBranch:n};{let i=Ar({ibGib:t}),c=i.valid?Number.parseInt(i.ticks):Number.MAX_SAFE_INTEGER,d=i.valid?i.ms??0:0,f=Ar({ibGib:r}),b=f.valid?Number.parseInt(f.ticks):Number.MAX_SAFE_INTEGER,m=f.valid?f.ms??0:0;return c<b||c===b&&d<=m?{baseTip:t,baseBranch:a,orphanTip:r,orphanBranch:n}:{baseTip:r,baseBranch:n,orphanTip:t,orphanBranch:a}}}async applyTransformAndRegister({resTransform:e,space:t,newGraftDnaIbGibs:a,newGraftedIntermediateIbGibs_ordered:r}){let n=`[${this.constructor.name}][${this.applyTransformAndRegister.name}]`;try{if(uo&&console.log(`${n} starting... (I: d4f66e62cbcc81636354e0583c15b826)`),!e)throw new Error("(UNEXPECTED) resTransform falsy (E: 83b27a8102f4423ab194e82f7c001826)");if(!e.newIbGib)throw new Error("(UNEXPECTED) resTransform.newIbGib falsy (E: a71823901bcf4502b4d9158bc7991826)");if(!e.dnas||e.dnas.length===0)throw new Error("(UNEXPECTED) resTransform.dnas falsy/empty (E: b65c19208a0d421297fb1c26b8911826)");for(let s of e.dnas)a.push(s);return r.push(e.newIbGib),t&&(await de({resTransform:e,space:t}),await oe({ibGib:e.newIbGib,space:t})),e.newIbGib}catch(s){throw console.error(`${n} ${g(s)} (E: d2384a8b792e42429bc7891234567826)`),s}finally{uo&&console.log(`${n} complete.`)}}};var er=!1,Ea=class extends Jt{static{p(this,"DefaultDnaReplayGraftStrategy")}strategyId="DefaultDnaReplayGraftStrategy";canGraft(e){return!0}async graft(e){let t=`[${this.strategyId}][${this.graft.name}]`;try{let C=function(J){let he=`${t}[${C.name}]`;for(let be of J){if(!be.rel8ns)throw new Error(`(UNEXPECTED) ${he} someIbGib.rel8ns falsy? All ibgibs with mergeable timelines are expected to have rel8ns. addr: ${y({ibGib:be})} (E: 5534a478cd183a5ee27b28487448b226)`);if(!be.rel8ns.dna)throw new Error(`(UNEXPECTED) someIbGib.rel8ns.dna falsy? We only have implemented grafting for dna. addr: ${y({ibGib:be})} (E: d86b388c627afd613f897e3819d8ab26)`);if(be.rel8ns.dna.length===0)throw new Error(`(UNEXPECTED) someIbGib.rel8ns.dna.length === 0? We only have implemented grafting for dna. addr: ${y({ibGib:be})} (E: bf973662a0689dd9089912b861af2826)`)}};var a=C;p(C,"throwIfUnexpected"),er&&console.log(`${t} starting default DNA replay graft... (I: 66404c06d838a8c43886f128127bc826)`);let{conflictStrategy:r,timelineAddrsA:n,timelineAddrsB:s,latestCommonFrameAddr:i,ibGibReadCache:c,space:d,graftPreference:f}=e,b=[],m=[];if(n.length===0)throw new Error("timelineAddrsA empty (E: 93a78cd1cd2a4a16ba99bd4820468f26)");if(s.length===0)throw new Error("timelineAddrsB empty (E: 76d53848152a66971b734068c3316826)");let u=n.lastIndexOf(i),h=n.slice(u+1),I=await Re({readCache_graph:c,addrs:h,space:d}),E=I.at(-1),w=s.lastIndexOf(i),A=s.slice(w+1),G=await Re({readCache_graph:c,addrs:A,space:d}),T=G.at(-1);C(I),C(G);let{baseTip:S,baseBranch:_,orphanTip:$,orphanBranch:B}=this.resolveBaseAndOrphan({graftPreference:f,tipA_sender:E,branchA_sender_sinceLCA:I,tipB_receiver:T,branchB_receiver_sinceLCA:G}),D=y({ibGib:S}),N=_.map(J=>y({ibGib:J})),x=y({ibGib:$}),L=B.map(J=>y({ibGib:J}));er&&console.log(`${t} baseTipAddr: ${D} (I: 93353d9b9b68b17088f57958df85e826)`),er&&console.log(`${t} orphanTipAddr: ${x} (I: 14df8867adc5dab97ff3c1e989b40e26)`);let[k]=await Re({addrs:[i],space:d});if(!k)throw new Error("(UNEXPECTED) latestCommonFrameIbGib falsy? (E: ead2020b7ab8e4c4f824573133e33826)");if(!k.rel8ns?.dna||k.rel8ns.dna.length===0)throw new Error("(UNEXPECTED) latestCommonFrameIbGib.rel8ns.dna falsy/empty? (E: 98fd8c725f484d85c8d23ceb181ce826)");let te=k.rel8ns.dna.concat(),X=[];for(let J of B){if(!J.rel8ns)throw new Error("(UNEXPECTED) orphanFrame.rel8ns falsy? (E: ed910e3b930b1b5388d87c6f736a4826)");let he=ro({base:te,extended:J.rel8ns.dna??[],throwIfExtendedDoesntContainBase:!0});he.forEach(be=>te.push(be)),he.forEach(be=>X.push(be))}let W=await Re({addrs:X,readCache_graph:c,space:d}),Ge=[],Ee=await no({src:S,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:X.concat(),allLocalIbGibs:W,createdIbGibs_Running:Ge});if(d&&Ge.length>0){await se({space:d,ibGibs:Ge});let{mapWithTjp_YesDna:J}=ut({ibGibs:Ge}),he=Object.values(J),be=ot({ibGibs:he});if(Object.keys(be).length>0){Object.values(be)[0].forEach(F=>b.push(F));for(let F of b)await oe({ibGib:F,space:d})}}let ne=[];if(r===ve.optimisticWithLCS){let J=S.data?.text,he=$.data?.text;if(typeof J=="string"&&typeof he=="string"&&J!==he){let be=await mo({textA:J,textB:he});if(be!==Ee.data?.text){let F=await pt({src:Ee,dataToAddOrPatch:{text:be},dna:!0,nCounter:!!Ee.data?.n});for(let je of F.dnas??[])m.push(je);b.push(F.newIbGib),d&&(await de({resTransform:F,space:d}),await oe({ibGib:F.newIbGib,space:d})),Ee=F.newIbGib;let me={mergeTextStrategy:Dr.lcs,textAAddr:y({ibGib:S}),textBAddr:y({ibGib:$})};ne.push(me)}}}let $e=await ua({conflictStrategy:r,details:`Replayed ${X.length} transforms from orphan (${x}) onto base (${D}).`,addlGraftDetails:ne.length>0?ne:void 0,latestCommonFrameAddr:i,baseAddrsSinceLCA:N,orphanAddrsSinceLCA:L,dnaAddrsApplied:X});d&&await se({ibGib:$e,space:d});let K=y({ibGib:$e}),z=await qe({src:Ee,rel8nsToAddByAddr:{[Me]:[K]},dna:!0,nCounter:!!Ee.data?.n});for(let J of z.dnas??[])m.push(J);d&&(await de({resTransform:z,space:d}),await oe({ibGib:z.newIbGib,space:d}));let fe=z.newIbGib;return{dnasReplayed:W,dnasCreatedInGraft:m,intermediateIbGibsCreatedInGraft:b,ancillaryIbGibsCreated:[],newGraftTip:fe,graftInfoCreated:$e}}catch(r){throw console.error(`${t} ${g(r)} (E: 090d7445aa6aefd9a89dade8e834f826)`),r}finally{er&&console.log(`${t} complete.`)}}};var Zt=!1,jr="[graft-strategy-service]",Qt=class o{static{p(this,"GraftStrategyService")}static _instance;static get instance(){return this._instance||(this._instance=new o),this._instance}_registeredStrategies=[];_fallbackStrategy=new Ea;registerStrategy(e){let t=`${jr}[${this.registerStrategy.name}]`;if(!e)throw new Error("(UNEXPECTED) strategy falsy (E: 777b77f4cf48e0c2b83159f8dbd06226)");this._registeredStrategies.some(a=>a.strategyId===e.strategyId)||(Zt&&console.log(`${t} registering strategy ${e.strategyId} (I: ad6a7f678526d2991684cc2c1c16cd26)`),this._registeredStrategies.push(e))}setFallbackStrategy(e){let t=`${jr}[${this.setFallbackStrategy.name}]`;if(!e)throw new Error("(UNEXPECTED) fallback strategy falsy (E: 09819876bb2ad7b788432518ce727826)");Zt&&console.log(`${t} setting fallback strategy ${e.strategyId} (I: e7e4d88de1d8a7fbc8dfa021f2900826)`),this._fallbackStrategy=e}getFallbackStrategy(){return this._fallbackStrategy}getRegisteredStrategies(){return this._registeredStrategies.slice()}reset(){let e=`${jr}[${this.reset.name}]`;Zt&&console.log(`${e} resetting strategies to default fallback... (I: edc9e8c23808995ade1cc3c8da474f26)`),this._registeredStrategies=[],this._fallbackStrategy=new Ea}async graftTimelines({timelineAddrsA:e,timelineAddrsB:t,latestCommonFrameAddr:a,conflictStrategy:r,ibGibReadCache:n,space:s,graftPreference:i}){let c=`[${this.graftTimelines.name}]`;try{if(Zt&&console.log(`${c} starting... (I: 3b4c3e8e59c883d9d3c352efd6380826)`),e.length===0)throw new Error("timelineAddrsA empty (E: 93a78cd1cd2a4a16ba99bd4820468f26)");if(t.length===0)throw new Error("timelineAddrsB empty (E: 76d53848152a66971b734068c3316826)");if(a){if(!e.includes(a))throw new Error(`timelineAddrsA does not include latestCommonFrameAddr (${a}). timelineAddrsA: ${e} (E: c5a9afe371888da2a79963983426e826)`);if(!t.includes(a))throw new Error(`timelineAddrsB does not include latestCommonFrameAddr (${a}). timelineAddrsB: ${t} (E: 7e641f67c452b67d582d78484a88c826)`)}else if(a=e.findLast(u=>t.includes(u)),!a)throw new Error(`timelines do not share a common frame. A: ${e}. B: ${t} (E: 4c0e78a88a375d8588736668573f1e26)`);if(e.at(-1)===a)throw new Error("timelineAddrsA.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 3796fc4074a8c5899d549bb8c2e68826)");if(t.at(-1)===a)throw new Error("timelineAddrsB.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 66fbb86e9e98531549888bf10a344f26)");let d={conflictStrategy:r,timelineAddrsA:e,timelineAddrsB:t,latestCommonFrameAddr:a,ibGibReadCache:n,space:s,graftPreference:i},f=[],b=this.getRegisteredStrategies();if(b&&b.length>0)for(let u of b)await u.canGraft(d)&&f.push(u);if(f.push(o.instance.getFallbackStrategy()),f.length===0)throw new Error("(UNEXPECTED) strategyPipeline.length === 0? We should at least have the fallback strategy. (E: 1d9bef958b54f8d0d9498bc7fd597226)");let m;for(let u of f)if(Zt&&console.log(`${c} executing graft strategy ${u.strategyId} (I: 066466905d08792d480c5f285fe4f826)`),m=await u.graft(d),m)break;if(!m)throw new Error("(UNEXPECTED) resGraft falsy? Our fallback strategy should have at least replayed the dna. (E: 6b2d78b52b39a7ff9853c0d8f8628826)");return m}catch(d){throw console.error(`${c} ${g(d)} (E: 05ed0ae869b6658d278fe1480fe19826)`),d}finally{Zt&&console.log(`${c} complete.`)}}};var P=!1,tr=!1,Ue="[ControlDomain]",le=class o{static{p(this,"SyncSagaCoordinator")}lc=`[${o.name}]`;constructor(){}defaultSessionConnectPoolConfig(){return Cr({id:Qe,salt:`session-connect-${Date.now()}`,verbs:[jt],size:20,sequential:2,random:2,targetBinding:0,replenishStrategy:Bt.deleteAll})}defaultSessionSyncPoolConfig(){return Cr({id:Xt,salt:`session-sync-${Date.now()}`,verbs:[De],size:200,sequential:3,random:3,targetBinding:3,replenishStrategy:Bt.topUp})}async sync({peer:e,domainIbGibs:t,senderIdentityInfo:a,fnSenderSecret:r,conflictStrategy:n=ve.abort,graftPreference:s,metaspace:i,localSpace:c}){let d=`${this.lc}[${this.sync.name}]`;if(P&&console.log(`${d} starting...`),!c){debugger;throw new Error(`${d} source (or localSpace) required (E: 25df3761f7686a1099a552f83c95d326)`)}if(a||r){if(!a)throw new Error("(UNEXPECTED) senderIdentityInfo falsy but fnSenderSecret truthy? if either is used, both must be truthy. (E: e366628a4919c7d727d2cbd8e5b75e26)");if(!r)throw new Error("(UNEXPECTED) fnSenderSecret falsy but senderIdentityInfo truthy? if either is used, both must be truthy. (E: 7d55ce37ae482fec48e3398158161926)");let{senderIdentity:T,senderDomainAddr:C}=a;if(!T)throw new Error("(UNEXPECTED) senderIdentity falsy in senderIdentityInfo? if senderIdentityInfo is provided, both senderIdentity and senderDomainAddr must be truthy. (E: a3c17fae2978926d)");if(!C)throw new Error("(UNEXPECTED) senderDomainAddr falsy in senderIdentityInfo? if senderIdentityInfo is provided, both senderIdentity and senderDomainAddr must be truthy. (E: d288fae39b7d825c)")}let{senderIdentity:f,senderDomainAddr:b}=a??{},m=await Z(),u=await ja();if(!u.next)throw new Error("(UNEXPECTED) updates$.next falsy? (E: d24cd82184aec130c89a320819b39126)");let h,I,E=new Promise((T,C)=>{h=T,I=C}),w=await po(),A=await i.createNewLocalSpace({opts:{allowCancel:!1,spaceName:w,getFnPrompt:i.getFnPrompt,logalot:P}});if(!A)throw new Error("Failed to create temp space (E: 8f4e2f3d6c1b4b1a8f4e2f3d6c1b4b1a)");await A.initialized;let G=p(async()=>{},"cleanup");return(async()=>{try{let T=t?t.map(_=>y({ibGib:_})):void 0;e.setOptionalOpts({sagaId:m,senderIdentity:f,senderDomainAddr:b,fnSenderSecret:r,sessionConnectPoolConfig:this.defaultSessionConnectPoolConfig(),sessionSyncPoolConfig:this.defaultSessionSyncPoolConfig(),targetAddrs:T}),await e.establishSessionIdentity(),await e.connect({sagaId:m});let{initFrame:C,initDomainGraph:S}=await this.createInitFrame({sagaId:m,domainIbGibs:t,conflictStrategy:n,graftPreference:s,metaspace:i,localSpace:c,tempSpace:A,peer:e});if(await this.executeSagaLoop({initFrame:C,initDomainGraph:S,peer:e,updates$:u,localSpace:c,tempSpace:A,metaspace:i}),h(),!u.complete)throw new Error("(UNEXPECTED) updates$.complete falsy? (E: d24cd82184aec130c89a320819b39126)");u.complete()}catch(T){if(console.error(`${d} ${g(T)}`),I(T),!u.error)throw new Error("(UNEXPECTED) updates$.error falsy? (E: 392ce77c073272e4c398c3e86583ce26)");u.error(T)}finally{await G()}})(),{sagaId:m,updates$:u,done:E}}async continueSync({sagaContext:e,mySpace:t,myTempSpace:a,metaspace:r,peer:n}){let s=`${this.lc}[${this.continueSync.name}]`;try{P&&console.log(`${s} starting... (I: f64e08bf77d1425378601f380384ec26)`);let i=await this.handleResponseSagaContext({sagaContext:e,mySpace:t,myTempSpace:a,metaspace:r});if(i){if(i.nextFrameInfo?.sagaComplete)return null}else return P&&console.log(`${s} Handler returned null (Saga End). (I: 43da8bb6c846b1fe7766332643be0e26)`),null;if(i.errorMsg)throw new Error(`Couldn't handle response saga context. errorMsg: ${i.errorMsg} (E: 7b41a183cf3cb58a5859c803800cf826)`);if(!i.nextFrameInfo)throw new Error("(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: 5740542f5eb8ccb41dfec188d87c1e26)");let{frame:c,payloadIbGibsDomain:d}=i.nextFrameInfo,f=await this.createSyncSagaContext({sagaFrame:c,localSpace:t,payloadIbGibsDomain:d,metaspace:r,sessionIdentityAddr:e.rel8ns?.sessionIdentity?.[0],peer:n,skipSign:!0}),b=await wt({context:f});if(b.length>0)throw new Error(`(UNEXPECTED) just created sync saga context () and there were immediateValidationErrors? immediateValidationErrors: ${b} (E: c120e8e0aa98673d685267a8a36e5826)`);return f}catch(i){throw console.error(`${s} ${g(i)}`),i}finally{P&&console.log(`${s} complete.`)}}async executeSagaLoop({initFrame:e,initDomainGraph:t,peer:a,updates$:r,localSpace:n,tempSpace:s,metaspace:i}){let c=`${this.lc}[${this.executeSagaLoop.name}]`,d=e,f=[];for(;d;){let b=new Map,m=`${c}[peer.payloadIbGibsDomainReceived$]`,u=await a.payloadIbGibsDomainReceived$.subscribe(eo({next:p(async h=>{P&&console.log(`${m} next fired. (I: 2b4bdf502a38a90ba33d9711e7cb7826)`);let I=y({ibGib:h});tr&&console.log(`${c}${Ue} DOMAIN STREAM RECEIVED <- observable: ${I} (I: d69ee80fcaece272483ec33b2d289826)`),b.set(I,h)},"next"),error:p(async h=>{Va(h)?console.error(`${m} error fired. error: ${JSON.stringify(h.data)} (E: 01cc08ba05ad99682831174fd7c31a26)`):(console.dir(h),console.error(`${m} error fired. error: ${g(h)} (E: 73d3d61464e8e4ce4cd6efd8b9675826)`))},"error"),complete:p(async()=>{P&&console.log(`${m} complete fired. (I: a47218aa9e4433fdb97c068880a45826)`),await u.unsubscribe()},"complete")}));try{let h=await this.createSyncSagaContext({sagaFrame:d,payloadIbGibsDomain:f,localSpace:n,metaspace:i,sessionIdentityAddr:a.currentSessionIdentityAddr,peer:a});if(tr){let S=f.map(_=>y({ibGib:_}));console.log(`${c}${Ue} SENDER TRANSMIT -> peer.witness (I: 5b0081803698770f0bf64992220b312)`),console.log(`${c}${Ue} Context: ${y({ibGib:h})}`),console.log(`${c}${Ue} Frame: ${y({ibGib:d})}`),console.log(`${c}${Ue} DOMAIN Payloads (${S.length}): ${S.join(", ")||"(none)"}`)}r.next(h),a.setOptionalOpts({localSpace:n,localTempSpace:s});let I=await a.witness(h);if(!I)if(d)if((await Vr({frameIbGib:d,space:n}))?.data?.stage===ce.commit){P&&console.log(`${c} Sender sent Commit. Peer returned no response. Saga Complete. (I: 26f9ee073858ca78b8284753368b5226)`),d=null;break}else throw new Error("(UNEXPECTED) responseCtx falsy and currentFrame truthy, but we're not in the commit stage? This may be expected ultimately, but atow I am not seeing this as being expected. (E: cc34498962bd370deeff351fac939f26)");else throw new Error("(UNEXPECTED) no response and currentFrame falsy? (E: 8d1085ea2f28cfc3f9c922649864a826)");if(!I.data)throw new Error("(UNEXPECTED) responseCtx.data falsy? (E: a969992bae53ab18a827ec58aec15826)");r.next(I);let E=await wt({context:I});if(E.length>0)throw new Error(`contextAndSagaFrameValidationErrors: ${E} (E: 6eebe8e7fa437c00a8cde3ada3c66826)`);let w=await this.validateReturnContext({requestCtx:h,responseCtx:I,localSpace:n});if(w.length>0)throw new Error(`validateReturnContext errors: ${w.join(", ")} (E: cb8a023b9d0728cceb09fa3da0bb8226)`);let A=I.data[Pr]||[];if(A.length>0&&(I.payloadIbGibsDomain=await this.pollForDomainPayloads({expectedAddrs:A,pollIntervalMs:20,domainPayloadsMap:b,tempSpace:s})),!I.sagaFrame)throw new Error("(UNEXPECTED) responseCtx.sagaFrame falsy? the Peer should have set this when it got the response back from the remote. (E: e650adadf9a2063ec6764a1e31d3d826)");if(tr){let S=I.data?.["@payloadAddrsControl"]||[];console.log(`${c}${Ue} SENDER RECEIVED <- peer.witness (I: 3dc76a9744d89a4fc3e2f076c2be4826)`),console.log(`${c}${Ue} Response Context: ${y({ibGib:I})}`),console.log(`${c}${Ue} Response Saga Frame: ${y({ibGib:I.sagaFrame})}`),console.log(`${c}${Ue} CONTROL Payloads (${S.length}): ${S.join(", ")||"(none)"}`),console.log(`${c}${Ue} DOMAIN Payloads (${A.length}): ${A.join(", ")||"(none)"}`)}let G=await this.handleResponseSagaContext({sagaContext:I,initDomainGraph:t,mySpace:n,myTempSpace:s,metaspace:i});if(G){if(G.nextFrameInfo?.sagaComplete){P&&console.log(`${c} Handler returned null (Saga End). (I: 123bf9e7dca8886de72553a8d4f29e26)`);break}}else{console.error(`${c} NAG ERROR (DOES NOT THROW): does this ever hit now? (E: e04d02efc2a8e72a88b79f1f0f95ca26)`);break}if(G.errorMsg)throw new Error(`Couldn't handle response saga context. errorMsg: ${G.errorMsg} (E: c948e81d513b2a0eb8b8afa878edc626)`);if(!G.nextFrameInfo)throw new Error("(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: c287a82e823e662a77923278e2418826)");let{frame:T,payloadIbGibsDomain:C}=G.nextFrameInfo;if(d=T,f=[...C||[]],tr){let S=f.map(_=>y({ibGib:_}));console.log(`${c}${Ue} HANDLER RESULT -> next iteration (I: 6b0d88c4c28857ccd812381515bd7826)`),console.log(`${c}${Ue} Next Frame: ${y({ibGib:d})}`),console.log(`${c}${Ue} DOMAIN for next (${S.length}): ${S.join(", ")||"(none)"}`)}}finally{await u.unsubscribe()}}}async createSyncSagaContext({sagaFrame:e,payloadIbGibsDomain:t,metaspace:a,localSpace:r,sessionIdentityAddr:n,peer:s,skipSign:i}){let c=`[${this.createSyncSagaContext.name}]`;try{if(P&&console.log(`${c} starting... (I: 6b87bee313e811d1d2fc90e87fbec826)`),!e.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: 04c49b4cccba6842a8b52e4c6f570726)");if(!e.data.n&&e.data.n!==0)throw new Error("(UNEXPECTED) sagaFrame.data.n falsy and not 0? (E: 45b508da64a8b28428b11765d684b826)");let d=new Date,f=mt(d),b=d.getMilliseconds(),m={timestamp:f,timestampMs:b,sagaN:e.data.n},u=t?t?.map(C=>y({ibGib:C})):void 0;u&&u.length>0&&(m[Pr]=u);let h={sagaFrame:[y({ibGib:e})]},I;if(n){n=await a.getLatestAddr({addr:n,space:r})??n;let C=await ue({addr:n,space:r});if(C.success&&C.ibGibs?.length===1)I=C.ibGibs[0],h.sessionIdentity=[n];else{debugger;throw new Error(`Couldn't get sessionIdentityAddr (${n}) in space: ${r.ib} (E: 5c29e80d68dbd1749866c358be093826)`)}}let E=await Or({data:m}),w=await U.stone({parentPrimitiveIb:za,ib:E,data:m,rel8ns:h}),A=y({ibGib:w}),G;I&&!i&&(G=await s.signContext({contextAddr:A})),await se({ibGib:w,space:r}),await oe({ibGib:w,space:r,fnBroadcast:void 0}),w.sagaFrame=e;let{msgStones:T}=await Dt({sagaIbGib:e,localSpace:r});if(T.length!==1)throw new Error("(UNEXPECTED) msgStones.length !== 1 inside createSyncSagaContext? (E: a98165cf46ab4e82b7bd5e45a273b826)");return w.sagaFrameMsg=T[0],t&&t.length>0&&(w.payloadIbGibsDomain=t),G&&(w.signedSessionIdentity=G),w}catch(d){throw console.error(`${c} ${g(d)}`),d}finally{P&&console.log(`${c} complete.`)}}async getKnowledgeMap({space:e,metaspace:t,domainIbGibs:a,tjpAddrs:r}){let n=`${this.lc}[${this.getKnowledgeMap.name}]`;try{if(P&&console.log(`${n} starting... (I: e184f8a7818666febfbbd2d841ed3826)`),!(a&&a.length>0)&&!(r&&r.length>0))throw new Error("(UNEXPECTED) domainIbGibs and tjpAddrs falsy/empty? we need one or the other (E: f674285111c8648398cd79d8c08ec826)");if(a&&a.length>0&&r&&r.length>0)throw new Error("(UNEXPECTED) both domainIbGibs and tjpAddrs truthy? only pass in one or the other. (E: f674285111c8648398cd79d8c08ec826)");let s=[];if(r)s=r;else if(a&&a.length>0){let{mapWithTjp_YesDna:c,mapWithTjp_NoDna:d}=ut({ibGibs:a}),f=[...Object.values(c),...Object.values(d)],b=ot({ibGibs:f});s=Object.keys(b)}else return console.warn(`${n} No domainIbGibs or tjpAddrs provided. Returning empty Knowledge. (W: 2b0e115e7578a83d1b26f7c726bf9426)`),{};if(s.length===0)return{};let i=await vt({space:e,tjpAddrs:s});if(!i.data||!i.data.latestAddrsMap)throw new Error(`${n} Failed to get latest addrs. (E: 7d395940c0e1419165c5196c39c6c826)`);return i.data.latestAddrsMap}catch(s){throw console.error(`${n} ${g(s)}`),s}finally{P&&console.log(`${n} complete.`)}}async analyzeDomainIbGibs({domainIbGibs:e,space:t}){let a=`${this.lc}[${this.analyzeDomainIbGibs.name}]`;if(e.length===0)throw new Error("invalid domainIbGibs. expected at least one, but array is empty. (E: 820a719bcac5a16878a2af697113b826)");let r=await Nt({ibGibs:e,live:!0,space:t}),n=r&&Object.keys(r).length>0;P&&console.log(`${a} graph generated. nodes: ${n?Object.keys(r).length:0}`);let s=n?Object.values(r):[],{mapWithTjp_YesDna:i,mapWithTjp_NoDna:c,mapWithoutTjps:d}=ut({ibGibs:s}),f=Object.values(d),b=[...Object.values(i),...Object.values(c)],m=ot({ibGibs:b}),u=this.sortTimelinesTopologically(m);return{stones:f,timelinesMap:m,topologicallySortedTjpAddrs:u,fullGraph:r}}async createInitFrame({sagaId:e,domainIbGibs:t,conflictStrategy:a,graftPreference:r,metaspace:n,localSpace:s,tempSpace:i,peer:c}){let d=`${this.lc}[${this.createInitFrame.name}]`;try{P&&console.log(`${d} starting... (I: 551af8b411ae9be712ce3358d43ee726)`);let f=await this.analyzeDomainIbGibs({domainIbGibs:t,space:s}),{timelinesMap:b,fullGraph:m,stones:u}=f;await se({ibGibs:Object.values(m),space:i});let h={};Object.keys(b).forEach(A=>{let T=b[A].at(-1);h[A]=y({ibGib:T})});let I={sagaId:e,stage:ce.init,knowledgeMap:h,mode:xr.sync,stones:u.map(A=>y({ibGib:A}))};P&&(console.log(`${d} SyncStage.init: ${ce.init}, SyncStage.commit: ${ce.commit}`),console.log(`${d} initData.stage: ${I.stage}`));let E=await this.createSyncMsgStone({data:I,localSpace:s,metaspace:n}),w=await this.evolveSyncSagaIbGib({msgStones:[E],conflictStrategy:a,graftPreference:r,metaspace:n,localSpace:s,sessionIdentity:c.currentSessionIdentity});return P&&console.log(`${d} sagaFrame (init): ${ge(w)} (I: b3d6a8be69248f18713cc3073cb08626)`),{initFrame:w,initDomainGraph:m}}catch(f){throw console.error(`${d} ${g(f)}`),f}finally{P&&console.log(`${d} complete.`)}}async validateReturnContext({requestCtx:e,responseCtx:t,localSpace:a}){let r=`${this.lc}[${this.validateReturnContext.name}]`,n=[];try{if(e.sagaFrame&&t.sagaFrame){let c=y({ibGib:e.sagaFrame}),d=y({ibGib:t.sagaFrame});try{await Wt({olderAddr:c,newerAddr:d,space:a})||n.push(`Response saga frame (${d}) is not a valid continuation of request saga frame (${c}). (E: 2c85e8d97318ff24ac8a02bd3a068226)`)}catch(f){throw console.error(`${r} isPastFrame just threw (E: 477888443fe89eca2c19fb684bf60126)`),f}}else n.push("Missing sagaFrame on requestCtx or responseCtx. (E: b65c68ff891000ddca8d22384a088226)");let s=e.signedSessionIdentity?y({ibGib:e.signedSessionIdentity}):e.rel8ns?.sessionIdentity?.[0],i=t.rel8ns?.sessionIdentity?.[0];s!==i&&n.push(`Session identity mismatch. Expected ${s}, got ${i}. (E: ab98716bca88d2243cc822187768226)`)}catch(s){n.push(`Error during validateReturnContext: ${g(s)} (E: da878e1239aa88ee27bdfca005c28226)`)}return P&&n.length>0&&console.log(`${r} errors: ${n.join(`
6
- `)} (I: cbc119df45aa13daa9009de392c4b226)`),n}async pollForDomainPayloads({expectedAddrs:e,pollIntervalMs:t,domainPayloadsMap:a,tempSpace:r}){let n=`${this.lc}[${this.pollForDomainPayloads.name}]`;try{P&&console.log(`${n} starting... (I: 26dce86bfca572939885798802d6e926)`);let s=[],i=[...new Set(e)],c=[...i],d=Date.now(),f=5*60*1e3;for(;c.length>0;){if(Date.now()-d>f)throw new Error(`Timeout waiting for payloads: ${c.join(", ")} (E: 46e1683c9578095261aaf798bd5e1826)`);let b=[],m=[];for(let u of c)a.has(u)?(m.push(a.get(u)),a.delete(u)):b.push(u);m.length>0&&(await se({space:r,ibGibs:m}),m.forEach(u=>s.push(u))),c=b,c.length>0&&await Ra(t)}if(i.length!==s.length)throw new Error("(UNEXPECTED) uniqueExpectedAddrs.length !== resultDomainPayloads.length? at this point, we expect all of the payload ibgibs to have been received. (E: 03749a7478c4b8b28bfc86951887a826)");return s}catch(s){throw console.error(`${n} ${g(s)}`),s}finally{P&&console.log(`${n} complete.`)}}async handleResponseSagaContext({sagaContext:e,initDomainGraph:t,mySpace:a,myTempSpace:r,metaspace:n}){let s=`${this.lc}[${this.handleResponseSagaContext.name}]`;try{P&&console.log(`${s} starting... (I: 5deec8a1f7a6d263c88cd458ad990826)`);let i=e.sagaFrame;if(!i.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 71b938adf1d87c2527bfd4f86dfd0826)");P&&console.log(`${s} sagaIbGib: ${ge(i)} (I: 1b99d87d262e9d18d8a607a80b1a0126)`);let{stage:c,messageData:d}=await this.getStageAndPayloadFromFrame({sagaFrame:i,space:a});P&&console.log(`${s} handling frame stage: ${c}`);let f;switch(c){case ce.init:f=await this.handleInitFrame({sagaIbGib:i,messageData:d,metaspace:n,mySpace:a,myTempSpace:r});break;case ce.ack:if(!t)throw new Error("(UNEXPECTED) initDomainGraph falsy on the sender? (E: a3d758ad954829aba88663188eafc826)");f=await this.handleAckFrame({sagaContext:e,sagaIbGib:i,initDomainGraph:t,metaspace:n,mySpace:a,myTempSpace:r});break;case ce.delta:f=await this.handleDeltaFrame({sagaContext:e,sagaIbGib:i,metaspace:n,mySpace:a,myTempSpace:r});break;case ce.commit:P&&console.log(`${s}[${Yt({sagaFrame:i})}] mySpace.ib: ${a.ib} (I: 5b270996d848907238d817fffa64a126)`),f=await this.handleCommitFrame({sagaIbGib:i,metaspace:n,mySpace:a,myTempSpace:r});break;default:throw new Error(`${s} (UNEXPECTED) Unknown sync stage: ${c} (E: 9c2b4c8a6d34469f8263544710183355)`)}return P&&console.log(`${s} nextFrameInfo: ${f?ge(f):"undefined"} (I: a8ad281ca8e89385686d18327a105726)`),{errorMsg:void 0,nextFrameInfo:f}}catch(i){let c=`${s} ${g(i)}`;return console.error(c),{errorMsg:c}}finally{P&&console.log(`${s} complete.`)}}async handleInitFrame({sagaIbGib:e,messageData:t,mySpace:a,myTempSpace:r,metaspace:n}){let s=`${this.lc}[${this.handleInitFrame.name}]`;try{P&&console.log(`${s} starting... (I: 9d88dcad0408c029e898a4bcf3b08426)`),P&&console.log(`${s} [TEST DEBUG] Receiver mySpace: ${a.ib}`);let i=t;if(i.stage!==ce.init)throw new Error(`${s} Invalid init frame: initData.stage !== SyncStage.init (E: c91be82970e4decc58f56bf8fc1ffc26)`);if(!i||!i.knowledgeMap)throw new Error(`${s} Invalid init frame: missing knowledgeMap (E: ed02c869e028d2d06841b9c7f80f2826)`);let c=e.data.conflictStrategy||ve.abort,d=[],f=[],b=[],m=i.stones||[];if(m.length>0){P&&console.log(`${s} processing stones: ${m.length}`);let _=(await ue({space:a,addrs:m})).rawResultIbGib;if(!_.data)throw new Error("(UNEXPECTED) rawResultIbGib.data falsy? (E: f3c40b492adc02c3f480b998fc7a5926)");let $=_.data.addrsNotFound;$&&$.length>0&&(P&&console.log(`${s} stones missing (requesting): ${$.length}`),$.forEach(B=>{f.some(D=>D.addr===B)||f.push({addr:B})}))}let u=i.knowledgeMap;P&&console.log(`${s} senderKnowledge: ${ge(u)} (I: 9f957862356dfeae183c200854e86e26)`);let h=Object.keys(u);P&&console.log(`${s} [TEST DEBUG] senderTjpAddrs: ${JSON.stringify(h)}`),P&&console.log(`${s} senderTjpAddrs: ${ge(h)} (I: 86ea4c53db0dc184c8b253386c402126)`);let I={};if(h.length>0){let S=await vt({space:a,tjpAddrs:h});if(!S.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: b180d813c088042b38e1e02e06a16926)");if(!S.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 16bc386dd51d0ff53a49620b1e641826)");I=S.data.latestAddrsMap,P&&console.log(`${s} [TEST DEBUG] receiverLatestAddrsMap: ${JSON.stringify(I)}`),P&&console.log(`${s} receiverLatestAddrsMap: ${ge(I)} (I: 980975642cbccd8018cf0cd808d30826)`)}for(let S of h){let _=u[S],$=I[S];if(!$){P&&console.log(`${s} [TEST DEBUG] Missing receiver timeline for TJP: ${S}. Requesting remoteAddr: ${_}`),f.push({addr:_,tjpAddr:S});continue}if($===_){P&&console.log(`${s} [TEST DEBUG] TJP ${S}: Synced (receiverTipAddr === remoteAddr)`);continue}P&&console.log(`${s} [TEST DEBUG] TJP ${S}: receiverTipAddr=${$}, remoteAddr=${_} - checking for divergence...`);let B;try{B=await Wt({olderAddr:_,newerAddr:$,space:a})}catch{console.log(`${s} isPastFrame just threw (E: b297244176e7380ffcaaef4861799326)`),B=!1}if(B){P&&console.log(`${s} [TEST DEBUG] TJP ${S}: Remote (sender) is in past - offering push`);let D=await ha({ibGibAddr:$,live:!1,latestCommonFrameAddr:_,space:a});b.push({tjpAddr:S,addrs:Object.keys(D)})}else{let D=!1;try{D=await Wt({olderAddr:$,newerAddr:_,space:a})}catch(N){P&&console.log(`${s} isPastFrame just threw, but is an expected error if we don't have remote. verbose logging error though: ${g(N)} (I: 47ea08d0b418cf4aa8a502a7bcb80826)`)}if(D)P&&console.log(`${s} [TEST DEBUG] TJP ${S}: receiver is in past - requesting delta`),f.push({addr:_,tjpAddr:S,latestAddrAlreadyHave:$});else if(P&&console.log(`${s} [TEST DEBUG] TJP ${S}: DIVERGENCE DETECTED! conflictStrategy=${c}`),c==="abort")d.push({tjpAddr:S,receiverTipAddr:$,senderTipAddr:_,receiverKnowledgeTimelineAddrs:[],reason:"divergence",terminal:!0});else if(c===ve.optimisticWithLCS){let N=await ue({addr:$,space:a});if(!N.success||N.ibGibs?.length!==1)throw new Error(`couldn't get local tip (${$}) from space (${a.ib}). errorMsg: ${N.errorMsg??"[unknown error (E: b3c3d823276300aa384ebdba4a8eb826)]"} (E: 83cb88a767e22bbda99c6788bec50526)`);let x=N.ibGibs[0],L=await Jn({timeline:x,space:a,metaspace:n});d.push({tjpAddr:S,receiverTipAddr:$,senderTipAddr:_,receiverKnowledgeTimelineAddrs:[...L,$],reason:"divergence",terminal:!1})}else throw new Error(`${s} Unsupported conflict strategy: ${c}. Only these currently implemented: ${xt} (E: 8f12384180f8a718a983a749fe0adf26)`)}}if(d.some(S=>S.terminal))throw P&&console.warn(`${s} ABORTING Sync Saga due to terminal conflicts: ${JSON.stringify(d)}`),new Error(`the saga has terminal conflicts. conflicts: ${JSON.stringify(d)} (E: f2edbe93cc07a63b38bfc013d2213b26)`);if(!e.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 24203af4600fb226ae6c1afbde442826)");let A={sagaId:e.data.uuid,stage:ce.ack,deltaRequestAddrInfos:f,pushOfferInfos:b};d?.length>0&&(A.conflicts=d);let G=await this.createSyncMsgStone({data:A,localSpace:a,metaspace:n});P&&console.log(`${s} ackStone created: ${ge(G)} (I: 313708132dd53ff946befb7833657826)`);let T=await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[G],localSpace:a,metaspace:n}),C;if(b.length>0){let S=[];C=[];let _=b.flatMap(x=>x.addrs),$=await ue({addrs:_,space:a}),B=$.rawResultIbGib?.data;if(!B)throw new Error("(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: 1a2cc8cb99a1ffa60837e45a8229b826)");let D=B.addrsNotFound??[],N=B.addrsErrored??[];if($.ibGibs&&$.ibGibs.length===_.length)$.ibGibs.forEach(x=>{C.push(x)});else if($.ibGibs&&$.ibGibs.length>0)if($.ibGibs.forEach(L=>{C.push(L)}),C.length+D.length+N.length===_.length)D.forEach(L=>S.push(L)),N.forEach(L=>S.push(L));else throw D.length===0&&N.length===0?new Error("(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored both empty? (E: ef1b2cf5bab8de2298ec507abe04e826)"):new Error("(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored don't contain the addrs not found? (E: ae9e015109f8c3c3a813da584cd98826)");else console.warn(`${s} we were expecting all domainAddrs in mySpace (${a.ib}) but we couldn't get all of them. addrsNotFound: ${D??[]}. addrsErrored: ${N??[]}. Trying temp space (${r.ib}). (W: f61908e264f8dddd2e3fb9084463d826)`),_.forEach(x=>S.push(x));if(S.length>0){P&&console.log(`${s} couldn't get all addrs in mySpace (${a.ib}). searchSecondSpaceAddrs: ${S} (I: 233fd954dbd84e51bca02fa8eed5f826)`);let x=await ue({addrs:S,space:r});if(x.success&&x.ibGibs&&x.ibGibs.length===S.length)x.ibGibs.forEach(L=>C.push(L));else{x.ibGibs?.forEach(k=>C.push(k));let L=_.filter(k=>!C.map(te=>y({ibGib:te})).includes(k));throw new Error(`couldn't get some or all of addrs from either mySpace (${a.ib}) or myTempSpace (${r.ib}). addrsFailed: ${L} (E: 1394d412c4ffa4dd085f269b43338826)`)}}}return{frame:T,payloadIbGibsDomain:C}}catch(i){throw console.error(`${s} ${g(i)}`),i}finally{P&&console.log(`${s} complete.`)}}async handleAckFrame({sagaContext:e,sagaIbGib:t,initDomainGraph:a,mySpace:r,myTempSpace:n,metaspace:s}){let i=`${this.lc}[${this.handleAckFrame.name}]`;try{P&&console.log(`${i} starting... (I: 605b6860e898267a5b50c6d85704be26)`);let{messageData:c}=await this.getStageAndPayloadFromFrame({sagaFrame:t,space:r}),d=c,f=!0;if(!d)throw new Error(`${i} ackData falsy (E: 3b8415edc876084c88a25b98e2d55826)`);if(d.stage!==ce.ack)throw new Error(`${i} Invalid ack frame: ackData.stage !== SyncStage.ack (E: 2e8b0a94b5954a66a6a1a7a0b3f5b7a1)`);if(P&&console.log(`${i} ackData: ${ge(d)} (I: b817c5571c5e916fe8f90b892b3e8e26)`),!t.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: e3f2e8f162484859787651b85c011826)");let b=d.conflicts?Xe(d.conflicts):[];P&&console.log(`${i} [CONFLICT DEBUG] Received conflicts from Ack: ${b.length}`),P&&b.length>0&&console.log(`${i} [CONFLICT DEBUG] Conflicts detail: ${JSON.stringify(b,null,2)}`);let m=b.filter(S=>S.terminal);if(m.length>0)throw P&&console.warn(`${i} Received terminal conflicts from Ack: ${JSON.stringify(m)}`),new Error(`${i} Peer reported terminal conflicts. (E: 23a0096ee05a2ccfa89334e8f156b426)`);let u=[],h=[];if(b.length>0){P&&console.log(`${i} [CONFLICT DEBUG] Processing ${b.length} non-terminal conflicts`);for(let S of b){let{receiverTipAddr:_,reason:$,senderTipAddr:B,terminal:D,receiverKnowledgeTimelineAddrs:N,tjpAddr:x}=S;if(D)throw new Error("(UNEXPECTED) conflict.terminal truthy? We expect this to already throw/abort the saga before this point in execution. (E: b42e982edca8b1156765de38f9e74626)");let L=a[B];if(!L)throw new Error(`(UNEXPECTED) senderTipIbGib falsy? initDomainGraph should have had the senderTipAddr (${B}) that was included in the ack frame conflicts. tjpAddr: ${x}. reason: ${$} (E: 3bd80f2054a924be98e6a7421bff4626)`);let{headIbGib:k,orderedPastIbGibs:te}=await zn({timeline:L,getLatest:!0,metaspace:s,space:r}),X=te.map(K=>y({ibGib:K})),W=y({ibGib:k});if(S.senderKnowledgeTimelineAddrs=[...X,W],k.gib!==L.gib&&(S.senderTipAddr=W,!Object.keys(a).includes(W))){let K=await Nt({ibGibAddr:W,live:!0,space:r}),z=Object.keys(K);for(let fe of z)a[fe]||(a[fe]=K[fe])}let Ge=N.findLast(K=>X.includes(K));if(!Ge)throw new Error(`(UNEXPECTED) no latestCommonFrameAddr in the conflicts.receiverKnowledgeTimelineAddrs (${N.join(`
7
- `)})? This would mean that it doesn't even have the tjpAddr (${x}). So what are we doing here? (E: 8931d1bdd6d8e100bf55f7c8a6924826)`);let Ee=await ha({ibGibAddr:W,live:!0,latestCommonFrameAddr:Ge,space:r}),ne=[];if(Object.keys(Ee).forEach(K=>{ne.push(K);let z=Ee[K];u.push(z)}),Ge===_)P&&console.log(`${i} [CONFLICT DEBUG] TJP ${x}: Fast-forward detected (receiver behind sender). Excluding from active conflicts and sending delta payload.`);else{if(S.accretivePayloadAddrs)throw new Error("(UNEXPECTED) conflict.accretivePayloadAddrs already truthy? This is expected to be falsy at this point in the sync. (E: 6b6b1846779867849cbde208f4374326)");S.accretivePayloadAddrs=ne,h.push(S)}}h.length>0?f=!1:f=!0,P&&console.log(`${i} [CONFLICT DEBUG] Finished processing ${b.length} conflicts. Active (divergent) conflicts: ${h.length}. outgoingPayloadIbGibsDomain_conflicts.length (total outgoing payload ibgibs for ALL conflicts): ${u.length}`)}else P&&console.log(`${i} [CONFLICT DEBUG] No optimistic conflicts to process`);let I=await this.getPayloadsForRequestedInfos({deltaRequestAddrInfos:d.deltaRequestAddrInfos||[],mySpace:r}),E=[...u,...I],w;E.length===0?E=void 0:w=E.map(S=>y({ibGib:S}));let A={sagaId:t.data.uuid,stage:ce.delta,conflicts:h,payloadAddrsDomain:w,deltaRequestAddrInfos:void 0,proposeCommit:f},G;P&&console.log(`${i} Creating Delta Stone. Data stage: ${A.stage}`);let T=await this.createSyncMsgStone({data:A,rel8ns:G,localSpace:r,metaspace:s}),C=await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[T],localSpace:r,metaspace:s});return P&&console.log(`${i} Delta Frame created. Rel8ns: ${JSON.stringify(C.rel8ns)}`),{frame:C,payloadIbGibsDomain:E}}catch(c){throw console.error(`${i} ${g(c)}`),c}finally{P&&console.log(`${i} complete.`)}}async handleDeltaFrame({sagaContext:e,sagaIbGib:t,mySpace:a,myTempSpace:r,metaspace:n}){let s=`${this.lc}[${this.handleDeltaFrame.name}]`;try{P&&console.log(`${s} starting... (I: a1d0a85eb4189466f86dfd61e3df2626)`);let{messageData:i}=await this.getStageAndPayloadFromFrame({sagaFrame:t,space:a}),c=i;if(!t.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 8874e83e1a1b307938ee832862ec5826)");if(!t.data.conflictStrategy)throw new Error("(UNEXPECTED) sagaIbGib.data.conflictStrategy falsy? (E: 636205ab5b78fcb31d0cb1880770c826)");if(!c)throw new Error(`${s} deltaData falsy (E: 7c28c8d8f08a4421b8344e6727271421)`);if(c.stage!==ce.delta)throw new Error(`${s} Invalid delta frame: deltaData.stage !== SyncStage.delta (E: 0c28c8d8f08a4421b8344e6727271421)`);P&&console.log(`${s} deltaData: ${ge(c)} (I: a76008681df458cfbcdc4848f825a826)`),P&&console.log(`${s} [CONFLICT DEBUG] deltaData.payloadAddrsDomain count: ${c.payloadAddrsDomain?.length||0}`);let{conflictStrategy:d,graftPreference:f}=t.data,{deltaRequestAddrInfos:b,payloadAddrsDomain:m,proposeCommit:u}=c,h=c.proposeCommit??!1,I=e.payloadIbGibsDomain??[];P&&console.log(`${s} [CONFLICT DEBUG] Fulfilling ${(c.deltaRequestAddrInfos||[]).length} peer requests`);let E=await this.getPayloadsForRequestedInfos({deltaRequestAddrInfos:c.deltaRequestAddrInfos||[],mySpace:a});P&&console.log(`${s} [CONFLICT DEBUG] Outgoing payload size (with deps): ${E.length}`);let w=c.conflicts?Xe(c.conflicts):[],A=w.filter(S=>!S.resolved);if(A.length>0){if(d!==ve.optimisticWithLCS)throw new Error(`(UNEXPECTED) conflictStrategy (${d}) is not ${ve.optimisticWithLCS}? right now, this is the only one we've implemented. (E: ba3e08d92a66b24075016208a0f83226)`);for(let S of A){let _={};if(I.length>0){await Et({ibGibs:I,space:r});for(let F of I)_[y({ibGib:F})]=F}for(let F of S.accretivePayloadAddrs??[]){let me=I.find(je=>y({ibGib:je})===F);me&&(_[F]=me)}S.latestCommonFrameAddr;let{receiverKnowledgeTimelineAddrs:$,senderKnowledgeTimelineAddrs:B,reason:D,receiverTipAddr:N,senderTipAddr:x,tjpAddr:L}=S;if(!B)throw new Error("(UNEXPECTED) senderKnowledgeTimelineAddrs falsy? (E: 2a608892d11bd848e8f0c7a8d676d826)");let k=await Nt({ibGibAddrs:[N],live:!0,space:a}),te=Object.values(k);await Et({ibGibs:te,space:r});for(let F of $){let me=k[F];await oe({ibGib:me,space:r})}for(let[F,me]of Object.entries(k))_[F]||(_[F]=me);let X=B.findLast(F=>$.includes(F));if(!X)throw new Error("(UNEXPECTED) latestCommonFrameAddr falsy? how we can have a conflict without a common point in history? (E: 53de0a181838b3e5bf98d0887994b826)");let W=await ha({ibGibAddr:S.receiverTipAddr,latestCommonFrameAddr:X,live:!0,space:a});Object.values(W).forEach(F=>E.push(F));let Ee=await Qt.instance.graftTimelines({conflictStrategy:d,timelineAddrsA:B,timelineAddrsB:$,latestCommonFrameAddr:X,ibGibReadCache:_,space:r,graftPreference:f||tt.timestamp}),{dnasCreatedInGraft:ne,dnasReplayed:$e,intermediateIbGibsCreatedInGraft:K,ancillaryIbGibsCreated:z,newGraftTip:fe,graftInfoCreated:J}=Ee;if(S.createdDnaAddrs=ne.map(F=>y({ibGib:F})),S.replayedDnaAddrs=$e.map(F=>y({ibGib:F})),S.createdDomainAddrs=[...K.map(F=>y({ibGib:F})),...z.map(F=>y({ibGib:F})),y({ibGib:J}),y({ibGib:fe})],!fe.rel8ns)throw new Error("(UNEXPECTED) newGraftTip.rel8ns falsy? we expect this to have graftinfo rel8ns, let alone dna (E: 718788f5a44e815618ac1ba621c8a826)");let he=fe.rel8ns[Me];if(!he||he.length===0)throw new Error(`(UNEXPECTED) newGraftTip.rel8ns.${Me} falsy/empty? we expect to always have graft info attached to timelines that are grafted. (E: 45abf31654c8aa517df4d0882b996826)`);S.graftInfoAddr=he.at(-1);let be=[ne,$e,K,z,[J,fe]];for(let F of be.flat())if((await ht({ibGib:F})??[]).length>0){console.dir(F);debugger;console.log(ge(F))}S.accretivePayloadAddrs??=[],be.forEach(F=>F.forEach(me=>{let je=y({ibGib:me});S.accretivePayloadAddrs.includes(je)||S.accretivePayloadAddrs.push(je),E.some(la=>y({ibGib:la})===je)||E.push(me)})),S.resolved=!0}}let G=[],T=E.length>0,C=G.length>0;if(T||C){let S={sagaId:c.sagaId,stage:ce.delta,payloadAddrsDomain:E.map(B=>y({ibGib:B})),requests:C?G:void 0,conflicts:w},_=await this.createSyncMsgStone({data:S,localSpace:a,metaspace:n});return{frame:await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[_],localSpace:a,metaspace:n}),payloadIbGibsDomain:E}}else if(h){let S=await Ht({sagaIbGib:t,space:a}),_=await Ya({history:S});return _.length>0?{frame:await this.createCommitFrame({sagaIbGib:t,errors:_,metaspace:n,mySpace:a})}:(await this.executeLocalCommit({sagaHistory:S,deltaFrame:t,localTempSpace:r,localSpace:a,metaspace:n}),{frame:await this.createCommitFrame({sagaIbGib:t,errors:void 0,metaspace:n,mySpace:a})})}else{let S={sagaId:c.sagaId,stage:ce.delta,proposeCommit:!0,conflicts:w},_=await this.createSyncMsgStone({data:S,localSpace:a,metaspace:n}),$=await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[_],localSpace:a,metaspace:n});if(c.proposeCommit){P&&console.log(`${s} Peer proposed commit. Accepting & Committing.`);let B={sagaId:c.sagaId,stage:ce.commit,success:!0},D=await this.createSyncMsgStone({data:B,localSpace:a,metaspace:n});return{frame:await this.evolveSyncSagaIbGib({prevSagaIbGib:$,msgStones:[D],localSpace:a,metaspace:n})}}return{frame:$,payloadIbGibsDomain:E}}}catch(i){throw console.error(`${s} ${g(i)}`),i}finally{P&&console.log(`${s} complete.`)}}async executeLocalCommit({deltaFrame:e,commitFrame:t,sagaHistory:a,metaspace:r,localSpace:n,localTempSpace:s}){let i=`${this.lc}[${this.executeLocalCommit.name}]`;try{if(P&&console.log(`${i} starting... (I: 6734980446b86a63c1af6e2e206de826)`),!e&&!t)throw new Error("(UNEXPECTED) !deltaFrame && !commitFrame? we're expecting to execute the commit based off of EITHER a delta OR a commit frame. (E: 10cae319a2685a672866f5583514e326)");if(e&&t)throw new Error("(UNEXPECTED) deltaFrame && commitFrame? we're expecting to execute the commit based off of EITHER a delta OR a commit frame. (E: b9037b1ed6d8684ac8a5d01328bad826)");let d=!!e?e:t;if(!d)throw new Error("(UNEXPECTED) !currentFrame? something wrong with my logic. (E: 4ec0ce6625cc1d677bc902c839ca1a26)");let f=Yt({sagaFrame:d});if(P&&console.log(`${i} currentFrameOrigin: ${f} (I: 3add8f8390c89743ae554bd3cc60b826)`),!d.data)throw new Error("(UNEXPECTED) currentFrame.data falsy? (E: a8be68d48668d93d992d793834823826)");let b=[],m=p(G=>{b.includes(G)||b.push(G)},"fnAddPayloadAddr"),u=a.filter(G=>{let T=Yt({sagaFrame:G.sagaIbGib});return f!==T});a.filter(G=>{let T=Yt({sagaFrame:G.sagaIbGib});return f===T}).forEach(G=>{if(!G.sagaIbGib.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 34d7f8cdee14717ce828878d98f89826)");G.msgStones.forEach(T=>{if(!T.data)throw new Error("(UNEXPECTED) msgStone.data falsy? (E: 21406101f91847514cc759c8a7382f26)");if(T.data.stage===ce.ack){let C=T.data;C.pushOfferInfos&&C.pushOfferInfos.length>0&&C.pushOfferInfos.forEach(S=>{S.addrs.forEach(_=>m(_))})}else if(T.data.stage===ce.delta){let C=T.data;C.payloadAddrsDomain&&C.payloadAddrsDomain.length>0&&C.payloadAddrsDomain.forEach(S=>m(S))}})}),P&&console.log(`${i}[${f}] allPayloadAddrsDomainTransferred: ${b.length>0?b.join(", "):"none"} (I: a1950eb3ca95bdc9ec18a4b8823e9826)`);let I=[];if(b.length>0){let G=await ue({addrs:b,space:s});if(G.success&&G.ibGibs&&G.ibGibs.length===b.length)I=G.ibGibs.concat();else{if(!G.rawResultIbGib)throw new Error("(UNEXPECTED) !resGetAllTransferred.rawResultIbGib falsy? (E: dc6cf8729668f4fbe8c024f887d97a26)");let{addrsNotFound:T,addrsErrored:C,errors:S}=G.rawResultIbGib.data;throw new Error(`(UNEXPECTED) we couldn't get all addrs transferred throughout the saga from the tempspace (${s.ib})? addrsNotFound: ${T??[]}. addrsErrored: ${C??[]}. errors: ${S??[]}(E: 222e341e634862b4d88ae7282584d826)`)}}let E=[],w=await qa({sagaHistory:a});if(w)for(let G of w){if(!G.resolved)throw new Error("(UNEXPECTED) finalConflict.resolved falsy? right now, we're expecting to resolve all conflicts. (E: a40ca8f1f54665407892ec21123a4f26)");if(!G.graftInfoAddr)throw new Error("(UNEXPECTED) finalConflict resolved but graftInfoAddr falsy? we're expecting all resolved conflicts to have a graftInfoAddr (E: d082488347570947b82008a835200126)");if(!(await Re({addrs:[G.graftInfoAddr],space:s})).at(0))throw new Error(`(UNEXPECTED) couldn't get finalConflictGraftInfo from localTempSpace (${s})? (E: 35e3c8130608d991e8fb295807812826)`);let{createdDnaAddrs:S,replayedDnaAddrs:_,createdDomainAddrs:$}=G;if(!S||S.length===0)throw new Error("(UNEXPECTED) finalConflict.createdDnaAddrs falsy/empty? (E: 9689f8be5bd19650b8d4a058b65db826)");if((!_||_.length===0)&&P&&console.log(`${i} finalConflict.replayedDnaAddrs falsy/empty (I: e88eb8a76b5815e07f10cbb2fa2ab826)`),!$||$.length===0)throw new Error("(UNEXPECTED) finalConflict.createdDomainAddrs falsy/empty? (E: cc41251d1acfe91a48d1b6080259ed26)");(await Re({addrs:_&&_.length>0?[...S,..._,...$]:[...S,...$],space:s})).forEach(D=>E.push(D))}let A=[];if(I.forEach(G=>A.push(G)),E.forEach(G=>A.push(G)),A.length===0)P&&console.log(`${i}[${f}] no changes on this end (I: fa30d18e83a87ee9e8487fbb5d632b26)`);else{P&&console.log(`${i}[${f}] ${A.length} changes detected (I: fa30d18e83a87ee9e8487fbb5d632b26)`),P&&console.log(`${i} put all into localSpace (${n.ib}) starting... (I: d5e0d9870e380b61e80c729660058826)`);let{payload_Dnas:G,payload_NonDnas:T}=await Et({ibGibs:A,space:n});P&&console.log(`${i} put all into localSpace (${n.ib}) complete. (I: d5e0d9870e380b61e80c729660058826)`);let C=await kr({sagaHistory:a,myTempSpace:s}),{mapWithTjp_NoDna:S,mapWithTjp_YesDna:_,mapWithoutTjps:$}=ut({ibGibs:T,filterPrimitives:!0});P&&console.log(`${i} register mapWithoutTjps starting... (I: 2b84d8f8dda85adde88696d8419bf726)`);let B=Object.values($);for(let k of B)P&&console.log(`${i} registering ${y({ibGib:k})} (I: 4647b4f42d27cffe0fbfce8846755826)`),await r.registerNewIbGib({ibGib:k,space:n});P&&console.log(`${i} mapWithoutTjps complete. (I: 2b84d8f8dda85adde88696d8419bf726)`),P&&console.log(`${i} register mapWithTjp_NoDna starting... (I: 96e648e4db382499b8bfaa1b37c24826)`);let D=ot({ibGibs:Object.values(S)}),N=Object.keys(D);for(let k of N){let te=D[k];for(let X of te)await r.registerNewIbGib({ibGib:X,space:n})}P&&console.log(`${i} register mapWithTjp_NoDna complete. (I: 96e648e4db382499b8bfaa1b37c24826)`),P&&console.log(`${i} register mapWithTjp_YesDna starting... (I: d54a820e9442dee4681f6228a6795926)`);let x=ot({ibGibs:Object.values(_)}),L=Object.keys(x);for(let k of L){let te=x[k];for(let X of te)C.includes(y({ibGib:X}))||await r.registerNewIbGib({ibGib:X,space:n})}P&&console.log(`${i} register mapWithTjp_YesDna complete. (I: d54a820e9442dee4681f6228a6795926)`)}}catch(c){throw console.error(`${i} ${g(c)}`),c}finally{P&&console.log(`${i} complete.`)}}async createCommitFrame({sagaIbGib:e,errors:t,metaspace:a,mySpace:r}){let n=`[${this.createCommitFrame.name}]`;try{P&&console.log(`${n} starting... (I: 48fc57c023f80122135a284855757526)`);let s=t&&t.length>0?{sagaId:e.data.uuid,stage:ce.commit,success:!1,errors:t}:{sagaId:e.data.uuid,stage:ce.commit,success:!0},i=await this.createSyncMsgStone({data:s,localSpace:r,metaspace:a});return await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[i],localSpace:r,metaspace:a})}catch(s){throw console.error(`${n} ${g(s)}`),s}finally{P&&console.log(`${n} complete.`)}}async handleCommitFrame({sagaIbGib:e,mySpace:t,myTempSpace:a,metaspace:r}){let n=`${this.lc}[${this.handleCommitFrame.name}]`;try{if(P&&console.log(`${n} starting... (I: e179573bdd881202f8ba3168da1c3826)`),!e.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: cbc31dbb7d28b5b8c8cddb510d7d2826)");if(e.data.errors&&e.data.errors.length>0)throw new Error("not implemented...saga errored out on other end but we've already committed our changes. we need to implement undoing our changes, i.e., rollback commit, which basically is deleting all the payloads that we already put in in our previous commit. (E: e8eb789e0c08f0b3cf93607cb73e9f26)");{let s=await Ht({sagaIbGib:e,space:t}),i=await Ya({history:s});return i.length>0?{frame:await this.createCommitFrame({sagaIbGib:e,metaspace:r,mySpace:t,errors:i})}:(await this.executeLocalCommit({commitFrame:e,sagaHistory:s,localSpace:t,localTempSpace:a,metaspace:r}),console.error(`${n} NAG ERROR (NOT THROWN): implement cleanup logic, including add a cleanup method to the peer (E: 3a9a24befb98a981a88fbdbf52920e26)`),P&&console.log(`${n} Peer committed. Finalizing saga locally. Saga Complete.`),{sagaComplete:!0})}}catch(s){let i=`${n} ${g(s)}`;return console.error(i),{frame:await this.createCommitFrame({sagaIbGib:e,errors:[i],metaspace:r,mySpace:t})}}finally{P&&console.log(`${n} complete.`)}}async createSyncMsgStone({data:e,rel8ns:t,localSpace:a,metaspace:r}){let n=`${this.lc}[${this.createSyncMsgStone.name}]`;try{P&&console.log(`${n} starting... (I: 5f7f98e8ff980364f7191fcee4531e26)`);let s=await Ur({data:e}),i=await U.stone({ib:s,parentPrimitiveIb:Qa,data:e,rel8ns:t,uuid:!0});return P&&console.log(`${n} Created stone: ${y({ibGib:i})}`),await r.put({ibGib:i,space:a}),await r.registerNewIbGib({ibGib:i}),i}catch(s){throw console.error(`${n} ${g(s)}`),s}finally{P&&console.log(`${n} complete.`)}}async getPayloadsForRequestedInfos({deltaRequestAddrInfos:e,mySpace:t}){let a=`${this.lc}[${this.getPayloadsForRequestedInfos.name}]`;try{P&&console.log(`${a} starting... (I: 4fe13d0d80050f20a8b74ba80cee5826)`);let r={};for(let{addr:s,latestAddrAlreadyHave:i}of e){let c;if(i?c=await ha({ibGibAddr:s,latestCommonFrameAddr:i,space:t,live:!0}):c=await Nt({ibGibAddr:s,space:t,live:!0}),Object.keys(c).length===0)throw new Error(`(UNEXPECTED) couldn't get requested addrs in mySpace (${t.ib})? How did the receiver know to ask for these addrs if they weren't in our original graph? (E: 281eaebcdf77dd73e8245b2872100826)`);Object.values(c).forEach(f=>{r[y({ibGib:f})]=f})}return Object.values(r)}catch(r){throw console.error(`${a} ${g(r)}`),r}finally{P&&console.log(`${a} complete.`)}}async evolveSyncSagaIbGib({prevSagaIbGib:e,conflictStrategy:t,graftPreference:a,msgStones:r,localSpace:n,metaspace:s,sessionIdentity:i}){let c=`${this.lc}[${this.evolveSyncSagaIbGib.name}]`;try{if(!r||r.length===0)throw new Error(`${c} msgStones required (E: d13f8afcfb8816aeb26baae7df3ef726)`);let d=r[0].data;if(!d?.sagaId||!d?.stage)throw new Error(`${c} Invalid stone data (missing sagaId or stage) (E: c004f85ce8f8958b11839f8d68c38826)`);let f=d.sagaId,b=d.stage;for(let m of r){let u=m.data;if(u.sagaId!==f)throw new Error(`${c} Mismatched sagaId in stones. Expected ${f}, got ${u.sagaId} (E: 29e02719e426ecbbf8ee66887a2be226)`);if(u.stage!==b)throw new Error(`${c} Mismatched stage in stones. Expected ${b}, got ${u.stage} (E: d12c6571b0882f762921b60880c3f826)`)}if(e){let m=[{rel8nName:Te,ibGibs:r}];if(!e.rel8ns)throw new Error("(UNEXPECTED) prevSagaIbGib.rel8ns falsy? (E: 81375841aff85b1e48ea42ca218e6826)");if(!e.rel8ns[Te]||e.rel8ns[Te].length===0)throw new Error("(UNEXPECTED) prevSagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME] falsy/empty? (E: 15156baad26fcccda80aa3a31718c726)");let u=[{rel8nName:Te,ibGibAddrs:e.rel8ns[Te]}];return await Pt({timeline:e,rel8nInfos:m,rel8nRemovalInfos:u,metaspace:s,space:n,noDna:!0})}else{let m={uuid:f,n:0,isTjp:!0,conflictStrategy:t,graftPreference:a};if(i){let w=Ce({ibGib:i});if(!w)throw new Error("(UNEXPECTED) sessionIdentity is truthy but sessionIdentityTjpAddr falsy? (E: f52004c10288987a6886f4e8fdf90826)");m.sessionIdentityTjpAddr=w}let u=await Rr({data:m}),h=r.map(w=>y({ibGib:w})),I={[Te]:h},E=await qn({space:n,metaspace:s,ib:u,data:m,rel8ns:I,parentIb:Xa,noDna:!0});if(E.intermediateIbGibs)throw new Error("(UNEXPECTED) resNew.intermediateIbGibs? we were assuming we were creating a single frame. (E: 456818147235d991ccb4d10d0bbe4826)");return E.newIbGib}}catch(d){throw console.error(`${c} ${g(d)}`),d}}async getStageAndPayloadFromFrame({sagaFrame:e,space:t}){let a=`${this.lc}[${this.getStageAndPayloadFromFrame.name}]`;try{if(P&&console.log(`${a} starting... (I: fddc287bd4d55253dc50e519fd352226)`),!e.rel8ns)throw new Error("(UNEXPECTED) sagaFrame.rel8ns falsy? (E: 725bc8eb5dfe5c7058907ad8e3063826)");let r=e.rel8ns?.[Te];if(r&&r.length>0){let n=r[0],s=await ue({addr:n,space:t});if(s.ibGibs&&s.ibGibs.length>0){let i=s.ibGibs[0];if(!i.data)throw new Error("(UNEXPECTED) message stone.data falsy? (E: 4d4abcea90d87ba1328434e83d0d0826)");if(!i.data.stage)throw new Error("(UNEXPECTED) message stone.data.stage falsy? (E: 72c8d22310996644ecdd2b5fdb288c26)");return{stage:i.data.stage,messageData:i.data}}else throw new Error(`couldn't get stoneAddr (${n}) from space (${t.ib}) (E: f3c826e756f8a5c358beb88aa4a65e26)`)}else throw new Error(`(UNEXPECTED) no stone addrs rel8d to sync saga ibgib frame? sagaFrame addr: ${y(e)} (E: 43eae8579e289d016741b5526052f226)`)}catch(r){throw console.error(`${a} ${g(r)}`),r}finally{P&&console.log(`${a} complete.`)}}sortTimelinesTopologically(e){let t=`${this.lc}[${this.sortTimelinesTopologically.name}]`,a=Object.keys(e);if(a.length===0)return[];let r={};a.forEach(f=>{e[f].forEach(b=>{let m=y({ibGib:b});r[m]=f})});let n={};a.forEach(f=>n[f]=new Set),a.forEach(f=>{e[f].forEach(b=>{b.rel8ns&&Object.values(b.rel8ns).flat().forEach(m=>{if(!m)return;let u=r[m];u&&u!==f&&n[f].add(u)})})});let s=new Set,i=new Set,c=[],d=p(f=>{if(i.has(f)){console.warn(`${t} Cycle detected involving ${f}. Ignoring edge to break cycle. (W: 7e7352347102431aa5318db962459929)`);return}s.has(f)||(i.add(f),n[f].forEach(b=>d(b)),s.add(f),i.delete(f),c.push(f))},"visit");return a.forEach(f=>{s.has(f)||d(f)}),c}};var yo={$schema:"../../../../libs/core-gib/dist/keystone/policy/schemas/keystone.medium.schema.json",metadata:{name:"Space-Gib Default Identity Policy",securityLevel:"medium"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:200,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:5}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-512",rounds:10,behavior:{size:2e3,replenish:"replace-all",selectSequentially:5,selectRandomly:5,targetBindingCount:16}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-512",rounds:10,behavior:{size:2e3,replenish:"delete-all",selectSequentially:5,selectRandomly:5,targetBindingCount:16}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:20,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:3}}}};var Ti=yo.pools;function ar(o,e){let t=Ti[o];if(!t)throw new Error(`Pool template not found in space-gib JSON config: ${o}`);return Hn({template:t,salt:e})}p(ar,"getSpaceGibPoolConfig");var ae={COMMON:It.COMMON,DEFAULT_POOL:{ID:"default",SIZE:20,SELECT_SEQUENTIALLY:2,SELECT_RANDOMLY:2,TARGET_BINDING_COUNT:3},CONNECT_POOL:It.CONNECT_POOL},bf={MIN_DEFAULT_POOL_SIZE:50,ALLOWED_ALGORITHMS:[pa.sha_256,pa.sha_512]};var V=class extends Zn{static{p(this,"SpaceGibApiBridge")}lc="[SpaceGibApiBridge]"},vi=new V;Qn(vi);var q="[dev-tools]",v={};window.ibgibDebugState=v;function l(o){let e=document.getElementById("dev-panel-log");if(!e)return;let t=new Date().toISOString().slice(11,23);e.textContent=`[${t}] ${o}
8
- `+e.textContent}p(l,"devLog");async function Eo({domainI:o,masterSecret:e,syncSalt:t,metaspace:a,space:r,apiBridge:n}){let s=new ke,i=await Ye({s:`${e}-sync-delegate`}),c=await s.genesis({masterSecret:i,configs:[ar("sync",`${t}-delegate`)],metaspace:a,space:r,frameDetails:{client:"space-gib-web-dev-delegate",timestamp:mt()}}),d=await s.registerDelegate({parentKeystone:o,delegateKeystone:c,masterSecret:e,signingPoolId:"manage",metaspace:a,space:r,allowedVerbs:[De]}),f=y({ibGib:o}),b=await n.putEvolveKeystone({domainAddr:f,keystoneIbGib:d,relatedKeystoneIbGibs:[c]});if(!b.success)throw new Error(`Server rejected delegate evolution: ${b.message}`);return{evolvedDomainI:d,delegateKeystone:c,delegateSecret:i}}p(Eo,"createAndRegisterSyncDelegate");async function Xr({domainI:o,masterSecret:e,metaspace:t,space:a}){let r=o,n=p(async()=>e,"fnSenderSecret"),s=Object.values(o.data?.delegates??{}).find(i=>i.allowedVerbs?.includes(De));if(s){let i=s.delegateTjpAddr;if(i){let c=await t.getLatestAddr({addr:i,space:a});if(c){let d=await t.get({addr:c,space:a});if(d.success&&d.ibGibs&&d.ibGibs.length>0){r=d.ibGibs[0];let f=await Ye({s:`${e}-sync-delegate`});n=p(async()=>f,"fnSenderSecret")}}}}return{senderIdentity:r,fnSenderSecret:n}}p(Xr,"getSenderIdentityInfo");async function at(o){let e=`${q}[performPhaseSetup(${o.phaseText})]`,t=document.getElementById(o.btnId);if(t)try{t.disabled=!0,l(`${o.phaseText} Setup: Generating Alice's long-lived Domain Keystone (I) and Target (X)...`);let a=await O(),r=await a.getLocalUserSpace({});if(!r)throw new Error("No default space found in metaspace.");let s=await new ke().genesis({masterSecret:o.masterSecret,configs:[ar("manage",o.manageSalt)],metaspace:a,space:r,frameDetails:{client:"space-gib-web-dev",timestamp:mt()}});l(`${o.phaseText} Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:s})}`),l(`${o.phaseText} Setup: Starting postGenesisKeystone...`);let i=new V,c=await i.postGenesisKeystone(s);if(c.success)l(`${o.phaseText} Setup: \u2713 Domain Keystone registered and stored on receiver (server).`);else throw l(`${o.phaseText} Setup: X postGenesisKeystone failed: ${c.message}.`),new Error(`${o.phaseText} Setup: Server rejected genesis domain keystone: ${c.message}`);l(`${o.phaseText} Setup: Generating and registering sync delegate...`);let{evolvedDomainI:d,delegateKeystone:f}=await Eo({domainI:s,masterSecret:o.masterSecret,syncSalt:o.syncSalt,metaspace:a,space:r,apiBridge:i});v.domainI=d,v.domainIMasterSecret=o.masterSecret,l(`${o.phaseText} Setup: \u2713 Registered Sync Delegate: ${y({ibGib:f})}`);let b=await U.firstGen({parentIbGib:Q,ib:o.ib,data:o.data,dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),m=b.newIbGib;await a.persistTransformResult({resTransform:b,space:r}),await a.registerNewIbGib({ibGib:m}),v.targetX=m,l(`${o.phaseText} Setup: \u2713 Target (X) created and persisted locally: ${y({ibGib:m})}`),l(`\u2713 ${o.phaseText} Setup Complete! Ready for ${o.phaseText} Sync.`),t.textContent=`\u2713 ${o.phaseText} Setup Complete`;let u=document.getElementById(o.nextBtnId);u&&(u.disabled=!1)}catch(a){l(`\u2717 ${o.phaseText} Setup FAILED: ${g(a)}`),console.error(`${e} ${o.phaseText} Setup error:`,a),t.disabled=!1}}p(at,"performPhaseSetup");async function St(o){let e=`${q}[performPhaseSync(${o.phaseText})]`,t=document.getElementById(o.btnId);if(t)try{t.disabled=!0,l(`${o.phaseText} Sync: Executing senderCoordinator.sync(...) using WebSocket Peer...`);let a=v.domainI,r=v.targetX;if(!a||!r){l(`\u26A0 ${o.phaseText} Sync: Missing setup state. Please run Setup first.`),t.disabled=!1;return}let n=y({ibGib:a}),s=await O(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=location.protocol==="https:"?"wss:":"ws:",d=new zt({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(n)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(n)}`}),f=new le,b=await Z();v.sagaId=b,v.senderPeer=d;let{senderIdentity:m,fnSenderSecret:u}=await Xr({domainI:a,masterSecret:v.domainIMasterSecret,metaspace:s,space:i});await d.initializeOpts({localMetaspace:s,localSpace:i,senderIdentity:m,fnSenderSecret:u,sagaId:b,sessionConnectPoolConfig:ae.CONNECT_POOL,sessionSyncPoolConfig:ae.DEFAULT_POOL,targetAddrs:[n]});try{await(await f.sync({domainIbGibs:[r],senderIdentityInfo:{senderIdentity:m,senderDomainAddr:n},fnSenderSecret:u,peer:d,localSpace:i,metaspace:s,conflictStrategy:ve.optimisticWithLCS})).done}catch(I){if(o.expectSyncFailure)l(`${o.phaseText} Sync: Coordinator sync executed (${o.failureMessageSuffix??"errors expected"}): ${g(I)}`);else throw I}l(`\u2713 ${o.phaseText} Sync Execution Complete! Ready for State Checks.`),t.textContent=`\u2713 ${o.phaseText} Sync Run`;let h=document.getElementById(o.nextBtnId);h&&(h.disabled=!1)}catch(a){l(`\u2717 ${o.phaseText} Sync FAILED: ${g(a)}`),console.error(`${e} ${o.phaseText} Sync error:`,a),t.disabled=!1}}p(St,"performPhaseSync");async function Kr({localI:o,metaspace:e,space:t}){let a=Object.values(o.data?.delegates??{}).find(f=>f.allowedVerbs?.includes(De));if(!a)return{};let r=a.delegateTjpAddr;if(!r)return{};let n=await e.getLatestAddr({addr:r,space:t});if(!n)return{delegateTjpAddr:r};let i=(await e.get({addrs:[n],space:t})).ibGibs?.[0];if(!i)return{delegateTjpAddr:r,latestLocalDelegateAddr:n};let d=i.data?.proofs?.find(f=>f.claim?.verb==="sync")?.claim?.target;return{delegateTjpAddr:r,latestLocalDelegateAddr:n,localDelegate:i,sessionIdentityTjpAddr:d}}p(Kr,"getDelegateAndSessionInfo");async function ee({domainIbGibs:o,passLabel:e,metaspace:t,space:a}){let r=v.domainI,n=v.domainIMasterSecret;if(!r||!n)throw new Error(`runSyncPass[${e}]: Missing domain identity or secret in debugState. Run Setup first.`);let s=y({ibGib:r}),i=location.protocol==="https:"?"wss:":"ws:",{senderIdentity:c,fnSenderSecret:d}=await Xr({domainI:r,masterSecret:n,metaspace:t,space:a});l(`Sync: ${e} \u2014 using sender: ${y({ibGib:c}).slice(0,40)}...`);let f=new zt({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(s)}`,wsUrl:`${i}//${location.host}/api/sync/ws/${encodeURIComponent(s)}`}),b=new le,m=await Z();v.sagaId=m,v.senderPeer=f,await f.initializeOpts({localMetaspace:t,localSpace:a,senderIdentity:c,fnSenderSecret:d,sagaId:m,sessionConnectPoolConfig:ae.CONNECT_POOL,sessionSyncPoolConfig:ae.DEFAULT_POOL,targetAddrs:[s]}),await(await b.sync({domainIbGibs:o,senderIdentityInfo:{senderIdentity:c,senderDomainAddr:s},fnSenderSecret:d,peer:f,localSpace:a,metaspace:t,conflictStrategy:ve.optimisticWithLCS})).done;let h=await t.getLatestAddr({addr:s,space:a});if(h&&h!==y({ibGib:r})){let I=await t.get({addrs:[h],space:a});I.ibGibs?.[0]&&(v.domainI=I.ibGibs[0])}}p(ee,"runSyncPass");async function Oe({domainIbGibs:o,passLabel:e,metaspace:t,space:a,primarySpace:r,domainI:n,masterSecret:s}){let i=y({ibGib:n}),c=location.protocol==="https:"?"wss:":"ws:",{senderIdentity:d,fnSenderSecret:f}=await Xr({domainI:n,masterSecret:s,metaspace:t,space:a});l(`Sync: ${e} \u2014 using sender: ${y({ibGib:d}).slice(0,40)}...`);let b=new zt({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),m=new le,u=await Z();v.sagaId=u,v.senderPeer=b,await b.initializeOpts({localMetaspace:t,localSpace:a,senderIdentity:d,fnSenderSecret:f,sagaId:u,sessionConnectPoolConfig:ae.CONNECT_POOL,sessionSyncPoolConfig:ae.DEFAULT_POOL,targetAddrs:[i]}),await(await m.sync({domainIbGibs:o,senderIdentityInfo:{senderIdentity:d,senderDomainAddr:i},fnSenderSecret:f,peer:b,localSpace:a,metaspace:t,conflictStrategy:ve.optimisticWithLCS})).done;let I=await t.getLatestAddr({addr:i,space:a});if(I){let w=(await t.get({addrs:[I],space:a})).ibGibs?.[0];w&&(v.domainI=w,r&&await xe({domainI:w,metaspace:t,fromSpace:a,toSpace:r}))}}p(Oe,"runSyncPassFromSpace");async function Pe({masterSecret:o,syncSalt:e,manageSalt:t,metaspace:a,space:r,apiBridge:n,phaseText:s}){let c=await new ke().genesis({masterSecret:o,configs:[ar("manage",t)],metaspace:a,space:r,frameDetails:{client:"space-gib-web-dev",timestamp:mt()}});l(`${s} Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:c})}`),l(`${s} Setup: Starting postGenesisKeystone...`);let d=await n.postGenesisKeystone(c);if(d.success)l(`${s} Setup: \u2713 Domain Keystone registered and stored on receiver (server).`);else throw l(`${s} Setup: X postGenesisKeystone failed: ${d.message}.`),new Error(`${s} Setup: Server rejected genesis domain keystone: ${d.message}`);l(`${s} Setup: Generating and registering sync delegate...`);let{evolvedDomainI:f,delegateKeystone:b}=await Eo({domainI:c,masterSecret:o,syncSalt:e,metaspace:a,space:r,apiBridge:n});return v.domainI=f,v.domainIMasterSecret=o,{domainI:f,delegateKeystone:b}}p(Pe,"setupDomainAndDelegateIdentities");async function ea({localI:o,metaspace:e,space:t,apiBridge:a,domainAddr:r}){let n=await e.getLatestAddr({addr:r,space:t});if(!n)throw new Error("Evolved domain keystone tip NOT found in local space!");l("\u2713 Check: Evolved Domain Keystone exists locally.");let{latestLocalDelegateAddr:s,sessionIdentityTjpAddr:i}=await Kr({localI:o,metaspace:e,space:t});if(!s)throw new Error("Evolved delegate keystone tip NOT found in local space!");if(!i)throw new Error("Delegate sync claim does not target a session keystone.");l("\u2713 Check: Delegate Keystone and Sync Claim to Session verified locally.");let c=await a.getIbGib(r,s);if(!c.success||!c.ibGib)throw new Error("Evolved Delegate Keystone NOT found on server!");l("\u2713 Check: Evolved Delegate Keystone exists on server.");let d=await a.getIbGib(r,n);if(!d.success||!d.ibGib)throw new Error("Evolved Domain Keystone NOT found on server!");return l("\u2713 Check: Evolved Domain Keystone exists on server."),{latestLocalIAddr:n,latestLocalDelegateAddr:s,sessionIdentityTjpAddr:i}}p(ea,"verifyIdentitiesOnServer");async function xe({domainI:o,metaspace:e,fromSpace:t,toSpace:a}){let r=y({ibGib:o}),n=await e.getLatestAddr({addr:r,space:t});if(!n)throw new Error("Could not find latest domain I address.");let i=(await e.get({addrs:[n],space:t})).ibGibs?.[0];if(!i)throw new Error("Could not get latest domain I.");let c=await e.getDependencyGraph({ibGibAddr:n,space:t});await e.put({ibGibs:Object.values(c),space:a}),await e.registerNewIbGib({ibGib:i,space:a});let d=Object.values(i.data?.delegates??{}).find(f=>f.allowedVerbs?.includes(De));if(d){let f=d.delegateTjpAddr;if(f){let b=await e.getLatestAddr({addr:f,space:t});if(b){let u=(await e.get({addrs:[b],space:t})).ibGibs?.[0];if(u){let h=await e.getDependencyGraph({ibGibAddr:b,space:t});await e.put({ibGibs:Object.values(h),space:a}),await e.registerNewIbGib({ibGib:u,space:a})}}}}}p(xe,"copyIdentitiesToSpace");var it=null;function wo(){let o=`${q}[initWsTestButton]`,e=document.getElementById("btn-test-ws");if(!e){console.warn(`${o} btn-test-ws not found \u2014 skipping`);return}e.addEventListener("click",()=>{try{if(it&&it.readyState===WebSocket.OPEN){it.send(JSON.stringify({ping:"hello from client",ts:Date.now()})),l("\u2192 sent ping on existing connection");return}let a=`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/api/debug/ws-echo`;l(`\u2192 connecting to ${a}`),it=new WebSocket(a),it.addEventListener("open",()=>{l("\u2713 WebSocket connected"),e.textContent="Send WS Ping"}),it.addEventListener("message",r=>{l(`\u2190 ${r.data}`)}),it.addEventListener("close",r=>{l(`\u2717 WebSocket closed (code ${r.code})`),e.textContent="Test WebSocket",it=null}),it.addEventListener("error",r=>{l("\u2717 WebSocket error \u2014 check console"),console.error(`${o} WebSocket error`,r)})}catch(t){l(`\u2717 ${g(t)}`),console.error(`${o} ${g(t)}`)}})}p(wo,"initWsTestButton");function Io(){let o=document.getElementById("btn-print-dev-state");o&&o.addEventListener("click",()=>{l("Printing debug state to console..."),console.dir(v)})}p(Io,"initPrintStateButton");function So(){let o=`${q}[initCreateDomainKeystoneButton]`,e=document.getElementById("btn-create-domain-keystone");e&&e.addEventListener("click",async()=>{try{e.disabled=!0,l("Generating dummy Domain Keystone (I)...");let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space found in metaspace.");let r="password",s=await new ke().genesis({masterSecret:r,configs:[Wn({id:"default",salt:await Z(),replenishStrategy:Bt.topUp})],metaspace:t,space:a,frameDetails:{client:"space-gib-web-dev",timestamp:mt()}}),i=y({ibGib:s});l(`\u2713 Local genesis complete: ${i}`),v.domainI=s,v.domainIMasterSecret=r,l("Posting genesis keystone to server...");let d=await new V().postGenesisKeystone(s);if(!d.success){l(`\u2717 Server rejected genesis keystone: ${d.message}`),e.disabled=!1;return}l("\u2713 Server accepted Domain Keystone (I)"),e.textContent="\u2713 Domain Keystone Created";let f=document.getElementById("btn-create-test-ibgib");f&&(f.disabled=!1)}catch(t){l(`\u2717 ${g(t)}`),console.error(`${o} ${g(t)}`),e.disabled=!1}})}p(So,"initCreateDomainKeystoneButton");function Go(){let o=`${q}[initCreateTestIbGibButton]`,e=document.getElementById("btn-create-test-ibgib");if(!e){console.warn(`${o} btn-create-test-ibgib not found \u2014 skipping`);return}e.addEventListener("click",async()=>{try{l("Generating dummy X^Xtjp ibgib...");let a=(await U.firstGen({parentIbGib:Q,ib:"test data",data:{hello:"world",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}})).newIbGib,r=y({ibGib:a});v.targetX=a,l(`\u2713 Created X: ${r}`),e.textContent="\u2713 Test IbGib (X) Created";let n=document.getElementById("btn-create-session-keystone");n&&(n.disabled=!1)}catch(t){l(`\u2717 ${g(t)}`),console.error(`${o} ${g(t)}`)}})}p(Go,"initCreateTestIbGibButton");function Ao(){let o=`${q}[initCreateSessionKeystoneButton]`,e=document.getElementById("btn-create-session-keystone");if(!e){console.warn(`${o} btn-create-session-keystone not found \u2014 skipping`);return}e.addEventListener("click",async()=>{try{l("Generating Session Keystone (S^Stjp)...");let t=v.domainI,a=v.targetX;if(!t){l("\u26A0 No domain keystone (I) found in state. Please Create Domain Keystone first.");return}if(!a){l("\u26A0 No target ibgib (X) found in state. Please Create Test IbGib first.");return}let r=await O(),n=await r.getLocalUserSpace({});if(!n)throw new Error("No default space found in metaspace.");let s="ephemeral-"+Math.random().toString(),i=new ke;console.warn(`${q}[NAG] placeholder genesis keystone config right now (W: 69b108687cf8bec0f9a8e148bcca8d26)`);let c=await i.genesis({masterSecret:s,configs:[{id:ae.DEFAULT_POOL.ID,salt:await Z(),type:ae.COMMON.TYPE,algo:ae.COMMON.ALGO,rounds:ae.COMMON.ROUNDS,behavior:{size:ae.DEFAULT_POOL.SIZE,replenish:ae.COMMON.REPLENISH,selectSequentially:ae.DEFAULT_POOL.SELECT_SEQUENTIALLY,selectRandomly:ae.DEFAULT_POOL.SELECT_RANDOMLY,targetBindingCount:ae.DEFAULT_POOL.TARGET_BINDING_COUNT},allowedVerbs:[]},{id:ae.CONNECT_POOL.ID,salt:await Z(),type:ae.COMMON.TYPE,algo:ae.COMMON.ALGO,rounds:ae.COMMON.ROUNDS,behavior:{size:ae.CONNECT_POOL.SIZE,replenish:ae.COMMON.REPLENISH,selectSequentially:ae.CONNECT_POOL.SELECT_SEQUENTIALLY,selectRandomly:ae.CONNECT_POOL.SELECT_RANDOMLY,targetBindingCount:ae.CONNECT_POOL.TARGET_BINDING_COUNT},allowedVerbs:[ae.CONNECT_POOL.VERB]}],metaspace:r,space:n,frameDetails:{client:"space-gib-web-session",target_I:t?y({ibGib:t}):void 0,target_X:a?y({ibGib:a}):void 0}}),d=y({ibGib:c});v.sessionS=c,v.sessionSecret=s,l(`\u2713 Created Session Keystone: ${d}`),e.textContent="\u2713 Session Keystone Created"}catch(t){l(`\u2717 ${g(t)}`),console.error(`${o} ${g(t)}`)}})}p(Ao,"initCreateSessionKeystoneButton");function $o(){let o=document.getElementById("btn-1b-setup");o&&o.addEventListener("click",()=>{at({phaseText:"1B",btnId:"btn-1b-setup",nextBtnId:"btn-1b-sync",masterSecret:"test-sender-secret-phase1",syncSalt:"senderidentitysyncsaltphase1",manageSalt:"senderidentitymanagesaltphase1",ib:"test data",data:{hello:"world",random:Math.random()}})})}p($o,"init1bSetupButton");function _o(){let o=document.getElementById("btn-1b-sync");o&&o.addEventListener("click",()=>{St({phaseText:"1B",btnId:"btn-1b-sync",nextBtnId:"btn-1b-check",expectSyncFailure:!0,failureMessageSuffix:"establish phase successfully run; connection/sync errors expected in 1B"})})}p(_o,"init1bSyncButton");function Co(){let o=`${q}[init1bCheckButton]`,e=document.getElementById("btn-1b-check");e&&e.addEventListener("click",async()=>{try{l("1B Check: Asserting cryptographic and durable state expectations from respec...");let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space.");let r=v.domainI,n=v.targetX,s=await t.getLatestAddr({addr:y({ibGib:r}),space:a});if(!s){l("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}l("\u2713 Check: Evolved Domain Keystone (I1) created and stored locally.");let c=(await t.get({addrs:[s],space:a})).ibGibs?.[0];if(!c){l("\u2717 Check: Failed to load I1 from local space.");return}let d=c.data?.proofs?.find(_=>_.claim?.verb==="sync");d?l("\u2713 Check: I1 contains valid sync-verb claim proof."):l("\u2717 Check: I1 is missing sync-verb claim proof!");let f=d?.claim?.target;if(!f){l("\u2717 Check: I1 sync claim does not target a session keystone.");return}l(`\u2713 Check: Sync claim targets session keystone: ${f}`);let m=(await t.get({addrs:[f],space:a})).ibGibs?.[0];if(!m){l("\u2717 Check: Session Keystone (S) NOT found in local space.");return}l("\u2713 Check: Session Keystone (S) successfully created locally.");let u=m.data?.challengePools??[],h=u.some(_=>_.id===Qe),I=u.some(_=>_.id===Xt);h&&I?l("\u2713 Check: S contains both connect and sync challenge pools."):l(`\u2717 Check: S is missing challenge pools! (connect: ${h}, sync: ${I})`),l("Check: Verifying registrations on server (receiver metaspace)...");let E=new V,w=!1,A=!1,G=!1,T=y({ibGib:r}),C=await E.getKeystoneGraph(T);if(C.success&&C.graph){let _=C.graph;w=_[T]!==void 0,A=_[s]!==void 0}else l(`\u2717 Check Server: Failed to fetch keystone graph from server: ${C.message}`);let S=await E.getIbGib(T,f);if(S.success&&S.ibGib?G=!0:l(`\u2717 Check Server: Failed to fetch session keystone from server: ${S.message}`),w?l("\u2713 Check Server: Genesis Domain Keystone (I) registered on server."):l("\u2717 Check Server: Genesis Domain Keystone (I) missing on server!"),A?l("\u2713 Check Server: Evolved Domain Keystone (I1) accepted and stored on server."):l("\u2717 Check Server: Evolved Domain Keystone (I1) missing on server!"),G?l("\u2713 Check Server: Session Keystone (S) accepted and stored on server."):l("\u2717 Check Server: Session Keystone (S) missing on server!"),w&&A&&G){l("\u{1F389} ALL PHASE 1B ESTABLISH CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 1B All Passed";let _=document.getElementById("btn-2b-setup");_&&(_.disabled=!1)}}catch(t){l(`\u2717 1B Check FAILED: ${g(t)}`),console.error(`${o} 1B Check error:`,t)}})}p(Co,"init1bCheckButton");function To(){let o=document.getElementById("btn-2b-setup");o&&o.addEventListener("click",()=>{at({phaseText:"2B",btnId:"btn-2b-setup",nextBtnId:"btn-2b-sync",masterSecret:"test-sender-secret-phase2",syncSalt:"senderidentitysyncsaltphase2",manageSalt:"senderidentitymanagesaltphase2",ib:"test data",data:{hello:"world2",random:Math.random()}})})}p(To,"init2bSetupButton");function vo(){let o=document.getElementById("btn-2b-sync");o&&o.addEventListener("click",()=>{St({phaseText:"2B",btnId:"btn-2b-sync",nextBtnId:"btn-2b-check",expectSyncFailure:!0,failureMessageSuffix:"connect phase successfully run; subsequent sync errors expected in 2B"})})}p(vo,"init2bSyncButton");function Bo(){let o=`${q}[init2bCheckButton]`,e=document.getElementById("btn-2b-check");e&&e.addEventListener("click",async()=>{try{l("2B Check: Asserting cryptographic and WebSocket state expectations...");let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space.");let r=v.domainI,n=y({ibGib:r}),s=await t.getLatestAddr({addr:n,space:a});if(!s){l("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}l("\u2713 Check: Evolved Domain Keystone (I1) created and stored locally.");let c=(await t.get({addrs:[s],space:a})).ibGibs?.[0];if(!c){l("\u2717 Check: Failed to load I1 from local space.");return}let f=c.data?.proofs?.find(G=>G.claim?.verb==="sync")?.claim?.target;if(!f){l("\u2717 Check: I1 sync claim does not target a session keystone.");return}l(`\u2713 Check: Sync claim targets session keystone: ${f}`);let b=await t.getLatestAddr({addr:f,space:a});if(!b){l("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}l("\u2713 Check: Found latest session keystone (S) locally.");let u=(await t.get({addrs:[b],space:a})).ibGibs?.[0];if(!u){l("\u2717 Check: Failed to load latest Session Keystone (S).");return}let h=u.data?.challengePools??[],I=h.find(G=>G.id===Qe),E=h.find(G=>G.id===Xt);if(I&&E)l("\u2713 Check: S contains both connect and sync challenge pools.");else{l(`\u2717 Check: S is missing challenge pools! (connect: ${!!I}, sync: ${!!E})`);return}let w=Object.keys(I.challenges).length;if(w===0)l("\u2713 Check: S connect pool successfully depleted (0 challenges remaining).");else{l(`\u2717 Check: S connect pool not depleted! (${w} challenges remaining)`);return}if(v.senderPeer&&v.senderPeer.isSocketOpen)l("\u2713 Check: WebSocket connection is active and OPEN.");else{l("\u2717 Check: WebSocket connection is NOT open or peer is missing!");return}l("\u{1F389} ALL PHASE 2B CONNECT CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 2B All Passed";let A=document.getElementById("btn-3b-setup");A&&(A.disabled=!1)}catch(t){l(`\u2717 2B Check FAILED: ${g(t)}`),console.error(`${o} 2B Check error:`,t)}})}p(Bo,"init2bCheckButton");function No(){let o=document.getElementById("btn-3b-setup");o&&o.addEventListener("click",()=>{at({phaseText:"3B",btnId:"btn-3b-setup",nextBtnId:"btn-3b-sync",masterSecret:"test-sender-secret-phase3",syncSalt:"senderidentitysyncsaltphase3",manageSalt:"senderidentitymanagesaltphase3",ib:"test data 3b",data:{hello:"world3",random:Math.random()}})})}p(No,"init3bSetupButton");function Po(){let o=document.getElementById("btn-3b-sync");o&&o.addEventListener("click",()=>{St({phaseText:"3B",btnId:"btn-3b-sync",nextBtnId:"btn-3b-check"})})}p(Po,"init3bSyncButton");function xo(){let o=`${q}[init3bCheckButton]`,e=document.getElementById("btn-3b-check");e&&e.addEventListener("click",async()=>{try{l("3B Check: Asserting cryptographic and WebSocket state expectations...");let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space.");let r=v.domainI,n=v.targetX,s=y({ibGib:n}),i=y({ibGib:r}),c=await t.getLatestAddr({addr:s,space:a});if(!c){l("\u2717 Check: Evolved target X NOT found in local space!");return}l(`\u2713 Check: Evolved target X found locally at: ${c}`);let d=await t.getDependencyGraph({ibGibAddr:c,space:a});if(!d||Object.keys(d).length===0){l("\u2717 Check: Failed to load target X dependency graph locally.");return}l(`\u2713 Check: Target X local graph loaded (${Object.keys(d).length} nodes).`);let f=new V,b=await f.getIbGibGraph(i,s,!0);if(!b.success||!b.graph){l(`\u2717 Check: Failed to fetch target X graph from server: ${b.message}`);return}let m=b.graph;if(l(`\u2713 Check: Target X server graph loaded (${Object.keys(m).length} nodes).`),we({graphA:d,graphB:m}))l("\u2713 Check: Target X dependency graphs are equivalent on client and server.");else{l("\u2717 Check: Target X dependency graphs mismatch between client and server!");return}let h=await t.getLatestAddr({addr:i,space:a});if(!h){l("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}l("\u2713 Check: Evolved Domain Keystone (I1) exists locally.");let E=(await t.get({addrs:[h],space:a})).ibGibs?.[0];if(!E){l("\u2717 Check: Failed to load I1 from local space.");return}let A=E.data?.proofs?.find(L=>L.claim?.verb==="sync")?.claim?.target;if(!A){l("\u2717 Check: I1 sync claim does not target a session keystone.");return}let G=await f.getIbGib(i,h);if(!G.success||!G.ibGib){l("\u2717 Check: Evolved Domain Keystone (I1) NOT found on server!");return}l("\u2713 Check: Evolved Domain Keystone (I1) exists on server.");let T=await t.getLatestAddr({addr:A,space:a});if(!T){l("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}l(`\u2713 Check: Found latest session keystone (S) locally: ${T}`);let S=(await t.get({addrs:[T],space:a})).ibGibs?.[0];if(!S){l("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let _=S.data?.n;l(`\u2713 Check: S tip evolved to n = ${_}.`),_!==3&&_!==4&&l(`\u26A0 Check: Expected S to evolve to n = 3 or 4, got n = ${_}. Continuing anyway...`);let $=await f.getIbGib(i,T);if(!$.success||!$.ibGib){l("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}l("\u2713 Check: Latest Session Keystone (S) exists on server.");let B=await t.getDependencyGraph({ibGibAddr:T,space:a}),D=await f.getIbGibGraph(i,A,!0);if(!D.success||!D.graph){l(`\u2717 Check: Failed to fetch session S graph from server: ${D.message}`);return}let N=D.graph;if(we({graphA:B,graphB:N}))l("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{l("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}l("\u{1F389} ALL PHASE 3B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 3B All Passed"}catch(t){l(`\u2717 3B Check FAILED: ${g(t)}`),console.error(`${o} 3B Check error:`,t)}})}p(xo,"init3bCheckButton");function Do(){let o=document.getElementById("btn-4-1b-setup");o&&o.addEventListener("click",()=>{at({phaseText:"4.1B",btnId:"btn-4-1b-setup",nextBtnId:"btn-4-1b-sync",masterSecret:"test-sender-secret-phase4-1",syncSalt:"senderidentitysyncsaltphase4-1",manageSalt:"senderidentitymanagesaltphase4-1",ib:"test data 4.1b",data:{hello:"world4_1",random:Math.random()}})})}p(Do,"init4_1bSetupButton");function Lo(){let o=document.getElementById("btn-4-1b-sync");o&&o.addEventListener("click",()=>{St({phaseText:"4.1B",btnId:"btn-4-1b-sync",nextBtnId:"btn-4-1b-check"})})}p(Lo,"init4_1bSyncButton");function Ro(){let o=`${q}[init4_1bCheckButton]`,e=document.getElementById("btn-4-1b-check");e&&e.addEventListener("click",async()=>{try{l("4.1B Check: Asserting cryptographic and WebSocket state expectations...");let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space.");let r=v.domainI,n=v.targetX,s=y({ibGib:n}),i=y({ibGib:r}),c=await t.getLatestAddr({addr:s,space:a});if(!c){l("\u2717 Check: Evolved target X NOT found in local space!");return}l(`\u2713 Check: Evolved target X found locally at: ${c}`);let d=await t.getDependencyGraph({ibGibAddr:c,space:a});if(!d||Object.keys(d).length===0){l("\u2717 Check: Failed to load target X dependency graph locally.");return}l(`\u2713 Check: Target X local graph loaded (${Object.keys(d).length} nodes).`);let f=new V,b=await f.getIbGibGraph(i,s,!0);if(!b.success||!b.graph){l(`\u2717 Check: Failed to fetch target X graph from server: ${b.message}`);return}let m=b.graph;if(l(`\u2713 Check: Target X server graph loaded (${Object.keys(m).length} nodes).`),we({graphA:d,graphB:m}))l("\u2713 Check: Target X dependency graphs are equivalent on client and server.");else{l("\u2717 Check: Target X dependency graphs mismatch between client and server!");return}let h=await t.getLatestAddr({addr:i,space:a});if(!h){l("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}l("\u2713 Check: Evolved Domain Keystone (I1) exists locally.");let E=(await t.get({addrs:[h],space:a})).ibGibs?.[0];if(!E){l("\u2717 Check: Failed to load I1 from local space.");return}let{latestLocalDelegateAddr:w,sessionIdentityTjpAddr:A}=await Kr({localI:E,metaspace:t,space:a});if(!w){l("\u2717 Check: Evolved delegate keystone tip NOT found in local space!");return}if(!A){l("\u2717 Check: Delegate sync claim does not target a session keystone.");return}l("\u2713 Check: Delegate Keystone and Sync Claim to Session verified locally.");let G=await f.getIbGib(i,w);if(!G.success||!G.ibGib){l("\u2717 Check: Evolved Delegate Keystone NOT found on server!");return}l("\u2713 Check: Evolved Delegate Keystone exists on server.");let T=await f.getIbGib(i,h);if(!T.success||!T.ibGib){l("\u2717 Check: Evolved Domain Keystone (I1) NOT found on server!");return}l("\u2713 Check: Evolved Domain Keystone (I1) exists on server.");let C=await t.getLatestAddr({addr:A,space:a});if(!C){l("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}l(`\u2713 Check: Found latest session keystone (S) locally: ${C}`);let _=(await t.get({addrs:[C],space:a})).ibGibs?.[0];if(!_){l("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let $=_.data?.n;l(`\u2713 Check: S tip evolved to n = ${$}.`),$!==3&&$!==4&&l(`\u26A0 Check: Expected S to evolve to n = 3 or 4, got n = ${$}. Continuing anyway...`);let B=await f.getIbGib(i,C);if(!B.success||!B.ibGib){l("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}l("\u2713 Check: Latest Session Keystone (S) exists on server.");let D=await t.getDependencyGraph({ibGibAddr:C,space:a}),N=await f.getIbGibGraph(i,A,!0);if(!N.success||!N.graph){l(`\u2717 Check: Failed to fetch session S graph from server: ${N.message}`);return}let x=N.graph;if(we({graphA:D,graphB:x}))l("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{l("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}l("\u{1F389} ALL PHASE 4.1B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.1B All Passed"}catch(t){l(`\u2717 4.1B Check FAILED: ${g(t)}`),console.error(`${o} 4.1B Check error:`,t)}})}p(Ro,"init4_1bCheckButton");function ko(){let o=document.getElementById("btn-4-2b-setup");o&&o.addEventListener("click",()=>{at({phaseText:"4.2B",btnId:"btn-4-2b-setup",nextBtnId:"btn-4-2b-sync",masterSecret:"test-sender-secret-phase4-2",syncSalt:"senderidentitysyncsaltphase4-2",manageSalt:"senderidentitymanagesaltphase4-2",ib:"dummy target 4.2b",data:{hello:"dummy"}})})}p(ko,"init4_2bSetupButton");async function Bi(){let o=`${q}[performPhaseSync4_2b]`,e=document.getElementById("btn-4-2b-sync");if(e)try{if(e.disabled=!0,l("4.2B Sync: Creating Constants and executing three-pass WebSocket Sync..."),!v.domainI){l("\u26A0 4.2B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space.");let r=await U.constant({parentPrimitiveIb:"root",ib:"constant_c1_"+(await Z()).slice(0,8),data:{some:"data_4_2b",random:Math.random()}}),n=y({ibGib:r});await t.put({ibGib:r,space:a}),await t.registerNewIbGib({ibGib:r}),v.targetC1=r,l(`4.2B Sync: \u2713 Constant C1 created: ${n}`),l("4.2B Sync: Starting Pass 1 (Sync C1)..."),await ee({domainIbGibs:[r],passLabel:"Pass 1 (Sync C1)",metaspace:t,space:a}),l("4.2B Sync: \u2713 Pass 1 Complete."),l("4.2B Sync: Starting Pass 2 (Sync C1 - Idempotent)..."),await ee({domainIbGibs:[r],passLabel:"Pass 2 (Sync C1 idempotent)",metaspace:t,space:a}),l("4.2B Sync: \u2713 Pass 2 Complete.");let s=await U.constant({ib:"constant_c2_"+(await Z()).slice(0,8),parentPrimitiveIb:"root",rel8ns:{link:[n]}}),i=y({ibGib:s});await t.put({ibGib:s,space:a}),await t.registerNewIbGib({ibGib:s}),v.targetC2=s,l(`4.2B Sync: \u2713 Constant C2 created linking to C1: ${i}`),l("4.2B Sync: Starting Pass 3 (Sync C2)..."),await ee({domainIbGibs:[s],passLabel:"Pass 3 (Sync C2)",metaspace:t,space:a}),l("4.2B Sync: \u2713 Pass 3 Complete."),l("\u2713 4.2B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.2B Sync Run";let c=document.getElementById("btn-4-2b-check");c&&(c.disabled=!1)}catch(t){l(`\u2717 4.2B Sync FAILED: ${g(t)}`),console.error(`${o} 4.2B Sync error:`,t),e.disabled=!1}}p(Bi,"performPhaseSync4_2b");function Oo(){let o=document.getElementById("btn-4-2b-sync");o&&o.addEventListener("click",()=>{Bi()})}p(Oo,"init4_2bSyncButton");function Fo(){let o=`${q}[init4_2bCheckButton]`,e=document.getElementById("btn-4-2b-check");e&&e.addEventListener("click",async()=>{try{l("4.2B Check: Asserting cryptographic and WebSocket state expectations...");let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space.");let r=v.domainI,n=v.targetC1,s=v.targetC2,i=y({ibGib:n}),c=y({ibGib:s}),d=y({ibGib:r}),f=new V,b=await t.get({addrs:[i],space:a}),m=await t.get({addrs:[c],space:a});if(!b.success||!b.ibGibs?.[0]){l("\u2717 Check: Constant C1 NOT found locally.");return}if(!m.success||!m.ibGibs?.[0]){l("\u2717 Check: Constant C2 NOT found locally.");return}l("\u2713 Check: Constants C1 and C2 exist locally.");let u=await f.getIbGib(d,i),h=await f.getIbGib(d,c);if(!u.success||!u.ibGib){l(`\u2717 Check: Constant C1 NOT found on server: ${u.message}`);return}if(!h.success||!h.ibGib){l(`\u2717 Check: Constant C2 NOT found on server: ${h.message}`);return}l("\u2713 Check: Constants C1 and C2 exist on server.");let I=await t.getDependencyGraph({ibGibAddr:c,space:a}),E=await f.getIbGibGraph(d,c,!0);if(!E.success||!E.graph){l(`\u2717 Check: Failed to fetch C2 graph from server: ${E.message}`);return}if(!we({graphA:I,graphB:E.graph})){l("\u2717 Check: C2 dependency graphs mismatch between client and server!");return}l("\u2713 Check: C2 dependency graphs are equivalent on client and server.");let w=await t.getLatestAddr({addr:d,space:a});if(!w){l("\u2717 Check: Domain keystone tip not found locally!");return}let G=(await t.get({addrs:[w],space:a})).ibGibs?.[0];if(!G){l("\u2717 Check: Failed to load domain keystone!");return}let T=G.data?.n;if(l(`\u2713 Check: Evolved I tip is at n = ${T}.`),T!==1){l(`\u2717 Check: Expected I to evolve to n = 1 (delegate registration only), got n = ${T}.`);return}let{sessionIdentityTjpAddr:C}=await ea({localI:G,metaspace:t,space:a,apiBridge:f,domainAddr:d}),S=await t.getLatestAddr({addr:C,space:a});if(!S){l("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}l(`\u2713 Check: Found latest session keystone (S) locally: ${S}`);let $=(await t.get({addrs:[S],space:a})).ibGibs?.[0];if(!$){l("\u2717 Check: Failed to load Session Keystone (S) locally.");return}let B=$.data?.n;if(l(`\u2713 Check: Latest session S tip evolved to n = ${B}.`),B!==3){l(`\u2717 Check: Expected latest session S to evolve to n = 3 (connect+sync+disconnect), got n = ${B}.`);return}let D=await f.getIbGib(d,S);if(!D.success||!D.ibGib){l("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}l("\u2713 Check: Latest Session Keystone (S) exists on server.");let N=await t.getDependencyGraph({ibGibAddr:S,space:a}),x=await f.getIbGibGraph(d,C,!0);if(!x.success||!x.graph){l(`\u2717 Check: Failed to fetch session S graph from server: ${x.message}`);return}if(!we({graphA:N,graphB:x.graph})){l("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}l("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server."),l("\u{1F389} ALL PHASE 4.2B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.2B All Passed"}catch(t){l(`\u2717 4.2B Check FAILED: ${g(t)}`),console.error(`${o} 4.2B Check error:`,t)}})}p(Fo,"init4_2bCheckButton");function Mo(){let o=document.getElementById("btn-4-3b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.3B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1...");let e=await O(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let a=new V;await Pe({masterSecret:"test-sender-secret-phase4-3",syncSalt:"senderidentitysyncsaltphase4-3",manageSalt:"senderidentitymanagesaltphase4-3",metaspace:e,space:t,apiBridge:a,phaseText:"4.3B"});let r=await U.firstGen({parentIbGib:Q,ib:"timeline_root_partial_4_3b",data:{type:"root",label:"Root4_3b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),n=r.newIbGib;await e.persistTransformResult({resTransform:r,space:t}),await e.registerNewIbGib({ibGib:n});let s=await j({timeline:n,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_3b"}},metaspace:e,space:t});v.targetC1=s,v.targetX=s,l(`4.3B Setup: \u2713 Timeline V0 -> V1 created and stored locally. V1: ${y({ibGib:s})}`),l("\u2713 4.3B Setup Complete! Ready for 4.3B Sync."),o.textContent="\u2713 4.3B Setup Complete";let i=document.getElementById("btn-4-3b-sync");i&&(i.disabled=!1)}catch(e){l(`\u2717 4.3B Setup FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(Mo,"init4_3bSetupButton");async function Ni(){let o=`${q}[performPhaseSync4_3b]`,e=document.getElementById("btn-4-3b-sync");if(e)try{e.disabled=!0;let t=v.targetX;if(!v.domainI||!t){l("\u26A0 4.3B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let a=await O(),r=await a.getLocalUserSpace({});if(!r)throw new Error("No default space.");l("4.3B Sync: Starting Pass 1 (Sync V1 to server)..."),await ee({domainIbGibs:[t],passLabel:"Pass 1 (Sync V1)",metaspace:a,space:r}),l("4.3B Sync: \u2713 Pass 1 Complete (V1 synced)."),l("4.3B Sync: Mutating V1 to V2 locally...");let n=await j({timeline:t,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_3b"}},metaspace:a,space:r});v.targetX=n,l(`4.3B Sync: \u2713 V2 created locally: ${y({ibGib:n})}`),l("4.3B Sync: Starting Pass 2 (Sync V2 delta to server)..."),await ee({domainIbGibs:[n],passLabel:"Pass 2 (Sync V2)",metaspace:a,space:r}),l("4.3B Sync: \u2713 Pass 2 Complete (V2 synced)."),l("\u2713 4.3B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.3B Sync Run";let s=document.getElementById("btn-4-3b-check");s&&(s.disabled=!1)}catch(t){l(`\u2717 4.3B Sync FAILED: ${g(t)}`),console.error(t),e.disabled=!1}}p(Ni,"performPhaseSync4_3b");function Uo(){let o=document.getElementById("btn-4-3b-sync");o&&o.addEventListener("click",()=>{Ni()})}p(Uo,"init4_3bSyncButton");function Vo(){let o=`${q}[init4_3bCheckButton]`,e=document.getElementById("btn-4-3b-check");e&&e.addEventListener("click",async()=>{try{l("4.3B Check: Asserting cryptographic and WebSocket state expectations...");let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space.");let r=v.domainI,n=v.targetC1,s=v.targetX,i=y({ibGib:n}),c=y({ibGib:s}),d=y({ibGib:r}),f=new V,b=await t.get({addrs:[i],space:a}),m=await t.get({addrs:[c],space:a});if(!b.success||!b.ibGibs?.[0]){l("\u2717 Check: Timeline frame V1 NOT found locally.");return}if(!m.success||!m.ibGibs?.[0]){l("\u2717 Check: Timeline frame V2 NOT found locally.");return}l("\u2713 Check: Timeline frames V1 and V2 exist locally.");let u=await f.getIbGib(d,c);if(!u.success||!u.ibGib){l(`\u2717 Check: Timeline frame V2 NOT found on server: ${u.message}`);return}l("\u2713 Check: Timeline frame V2 exists on server.");let h=u.ibGib.rel8ns?.past?.at(-1);if(h===i)l("\u2713 Check: Server V2 correctly references V1 in its past relation.");else{l(`\u2717 Check: Server V2 does not reference V1 in past relation! got: ${h}`);return}let I=await t.getDependencyGraph({ibGibAddr:c,space:a}),E=await f.getIbGibGraph(d,c,!0);if(!E.success||!E.graph){l(`\u2717 Check: Failed to fetch V2 graph from server: ${E.message}`);return}if(!we({graphA:I,graphB:E.graph})){l("\u2717 Check: V2 timeline dependency graphs mismatch between client and server!");return}l("\u2713 Check: V2 timeline dependency graphs are equivalent on client and server.");let w=await t.getLatestAddr({addr:d,space:a});if(!w){l("\u2717 Check: Domain keystone tip not found locally!");return}let G=(await t.get({addrs:[w],space:a})).ibGibs?.[0];if(!G){l("\u2717 Check: Failed to load domain keystone!");return}let T=G.data?.n;if(l(`\u2713 Check: Evolved I tip is at n = ${T}.`),T!==1){l(`\u2717 Check: Expected I to evolve to n = 1 (delegate registration only), got n = ${T}.`);return}let{sessionIdentityTjpAddr:C}=await ea({localI:G,metaspace:t,space:a,apiBridge:f,domainAddr:d}),S=await t.getLatestAddr({addr:C,space:a});if(!S){l("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}l(`\u2713 Check: Found latest session keystone (S) locally: ${S}`);let $=(await t.get({addrs:[S],space:a})).ibGibs?.[0];if(!$){l("\u2717 Check: Failed to load Session Keystone (S) locally.");return}let B=$.data?.n;if(l(`\u2713 Check: Latest session S tip evolved to n = ${B}.`),B!==3){l(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${B}.`);return}let D=await f.getIbGib(d,S);if(!D.success||!D.ibGib){l("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}l("\u2713 Check: Latest Session Keystone (S) exists on server.");let N=await t.getDependencyGraph({ibGibAddr:S,space:a}),x=await f.getIbGibGraph(d,C,!0);if(!x.success||!x.graph){l(`\u2717 Check: Failed to fetch session S graph from server: ${x.message}`);return}if(!we({graphA:N,graphB:x.graph})){l("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}l("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server."),l("\u{1F389} ALL PHASE 4.3B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.3B All Passed"}catch(t){l(`\u2717 4.3B Check FAILED: ${g(t)}`),console.error(`${o} 4.3B Check error:`,t)}})}p(Vo,"init4_3bCheckButton");function jo(){let o=document.getElementById("btn-4-4b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.4B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1 -> V2...");let e=await O(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let a=new V;await Pe({masterSecret:"test-sender-secret-phase4-4",syncSalt:"senderidentitysyncsaltphase4-4",manageSalt:"senderidentitymanagesaltphase4-4",metaspace:e,space:t,apiBridge:a,phaseText:"4.4B"});let r=await U.firstGen({parentIbGib:Q,ib:"timeline_root_deep_4_4b",data:{type:"root",label:"Root4_4b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),n=r.newIbGib;await e.persistTransformResult({resTransform:r,space:t}),await e.registerNewIbGib({ibGib:n}),v.targetC1=n;let s=await j({timeline:n,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_4b"}},metaspace:e,space:t});v.targetC2=s;let i=await j({timeline:s,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_4b"}},metaspace:e,space:t});v.targetX=i,l(`4.4B Setup: \u2713 Timeline V0 -> V1 -> V2 created locally. V2 Tip: ${y({ibGib:i})}`),l("\u2713 4.4B Setup Complete! Ready for 4.4B Sync."),o.textContent="\u2713 4.4B Setup Complete";let c=document.getElementById("btn-4-4b-sync");c&&(c.disabled=!1)}catch(e){l(`\u2717 4.4B Setup FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(jo,"init4_4bSetupButton");async function Pi(){let o=`${q}[performPhaseSync4_4b]`,e=document.getElementById("btn-4-4b-sync");if(e)try{e.disabled=!0,l("4.4B Sync: Initiating WebSocket Sync of V2 Tip...");let t=v.targetX;if(!v.domainI||!t){l("\u26A0 4.4B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let a=await O(),r=await a.getLocalUserSpace({});if(!r)throw new Error("No default space.");await ee({domainIbGibs:[t],passLabel:"Pass 1 (Sync V2 tip)",metaspace:a,space:r}),l("4.4B Sync: \u2713 WebSocket Sync completed."),l("\u2713 4.4B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.4B Sync Run";let n=document.getElementById("btn-4-4b-check");n&&(n.disabled=!1)}catch(t){l(`\u2717 4.4B Sync FAILED: ${g(t)}`),console.error(t),e.disabled=!1}}p(Pi,"performPhaseSync4_4b");function Xo(){let o=document.getElementById("btn-4-4b-sync");o&&o.addEventListener("click",()=>{Pi()})}p(Xo,"init4_4bSyncButton");function Ko(){let o=`${q}[init4_4bCheckButton]`,e=document.getElementById("btn-4-4b-check");e&&e.addEventListener("click",async()=>{try{l("4.4B Check: Asserting cryptographic and WebSocket state expectations...");let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space.");let r=v.domainI,n=v.targetC1,s=v.targetC2,i=v.targetX,c=y({ibGib:n}),d=y({ibGib:s}),f=y({ibGib:i}),b=y({ibGib:r}),m=new V,u=await t.get({addrs:[c],space:a}),h=await t.get({addrs:[d],space:a}),I=await t.get({addrs:[f],space:a});if(!u.success||!u.ibGibs?.[0]){l("\u2717 Check: Timeline frame V0 NOT found locally.");return}if(!h.success||!h.ibGibs?.[0]){l("\u2717 Check: Timeline frame V1 NOT found locally.");return}if(!I.success||!I.ibGibs?.[0]){l("\u2717 Check: Timeline frame V2 NOT found locally.");return}l("\u2713 Check: Timeline frames V0, V1, and V2 exist locally.");let E=await m.getIbGib(b,f);if(!E.success||!E.ibGib){l(`\u2717 Check: Timeline frame V2 NOT found on server: ${E.message}`);return}l("\u2713 Check: Timeline frame V2 exists on server.");let w=E.ibGib.rel8ns?.past?.at(-1);if(w===d)l("\u2713 Check: Server V2 correctly references V1 in its past relation.");else{l(`\u2717 Check: Server V2 does not reference V1 in past relation! got: ${w}`);return}let A=await m.getIbGib(b,d);if(!A.success||!A.ibGib){l(`\u2717 Check: Timeline frame V1 NOT found on server: ${A.message}`);return}l("\u2713 Check: Timeline frame V1 exists on server.");let G=A.ibGib.rel8ns?.past?.at(-1);if(G===c)l("\u2713 Check: Server V1 correctly references V0 in its past relation.");else{l(`\u2717 Check: Server V1 does not reference V0 in past relation! got: ${G}`);return}let T=await t.getDependencyGraph({ibGibAddr:f,space:a}),C=await m.getIbGibGraph(b,f,!0);if(!C.success||!C.graph){l(`\u2717 Check: Failed to fetch V2 graph from server: ${C.message}`);return}if(!we({graphA:T,graphB:C.graph})){l("\u2717 Check: V2 timeline dependency graphs mismatch between client and server!");return}l("\u2713 Check: V2 timeline dependency graphs are equivalent on client and server.");let S=await t.getLatestAddr({addr:b,space:a});if(!S){l("\u2717 Check: Domain keystone tip not found locally!");return}let $=(await t.get({addrs:[S],space:a})).ibGibs?.[0];if(!$){l("\u2717 Check: Failed to load domain keystone!");return}l(`\u2713 Check: Evolved Domain Keystone exists locally: ${S}`);let B=$.data?.n;if(l(`\u2713 Check: Evolved I tip is at n = ${B}.`),B!==1){l(`\u2717 Check: Expected I to evolve to n = 1, got n = ${B}.`);return}let{sessionIdentityTjpAddr:D}=await ea({localI:$,metaspace:t,space:a,apiBridge:m,domainAddr:b}),N=await t.getLatestAddr({addr:D,space:a});if(!N){l("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}l(`\u2713 Check: Found latest session keystone (S) locally: ${N}`);let L=(await t.get({addrs:[N],space:a})).ibGibs?.[0];if(!L){l("\u2717 Check: Failed to load Session Keystone (S) locally.");return}let k=L.data?.n;if(l(`\u2713 Check: Latest session S tip evolved to n = ${k}.`),k!==3){l(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${k}.`);return}let te=await m.getIbGib(b,N);if(!te.success||!te.ibGib){l("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}l("\u2713 Check: Latest Session Keystone (S) exists on server.");let X=await t.getDependencyGraph({ibGibAddr:N,space:a}),W=await m.getIbGibGraph(b,D,!0);if(!W.success||!W.graph){l(`\u2717 Check: Failed to fetch session S graph from server: ${W.message}`);return}if(!we({graphA:X,graphB:W.graph})){l("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}l("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server."),l("\u{1F389} ALL PHASE 4.4B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.4B All Passed"}catch(t){l(`\u2717 4.4B Check FAILED: ${g(t)}`),console.error(`${o} 4.4B Check error:`,t)}})}p(Ko,"init4_4bCheckButton");var Ho={},Wo="test-sender-secret-phase4-5b";function Yo(){let o=document.getElementById("btn-4-5b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.5B Setup: Generating Domain Keystone (I), target timeline, and seeding server from two spaces...");let e=await O(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let a=new V;await Pe({masterSecret:Wo,syncSalt:"senderidentitysyncsaltphase4-5b",manageSalt:"senderidentitymanagesaltphase4-5b",metaspace:e,space:t,apiBridge:a,phaseText:"4.5B"});let r=await U.firstGen({parentIbGib:Q,ib:"timeline_root_partial_4_5b",data:{type:"root",label:"Root4_5b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),n=r.newIbGib;await e.persistTransformResult({resTransform:r,space:t}),await e.registerNewIbGib({ibGib:n,space:t});let s=await j({timeline:n,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_5b"}},metaspace:e,space:t});v.targetC1=s,l(`4.5B Setup: \u2713 Local timeline V0 -> V1 created. V1 Tip: ${y({ibGib:s})}`),l("4.5B Setup: Seeding V1 to the server via WebSocket..."),await ee({domainIbGibs:[s],passLabel:"Seed V1 to server",metaspace:e,space:t}),l("4.5B Setup: \u2713 Pass 1 Sync (V1 to server) complete."),l('4.5B Setup: Creating secondary local space simulating "remote" client...');let i=`remote-${await Z()}`,c=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:i,getFnPrompt:e.getFnPrompt}});if(!c)throw new Error("Failed to create remote space");await c.initialized;let d=await e.getDependencyGraph({ibGibAddr:y({ibGib:s}),space:t});await e.put({ibGibs:Object.values(d),space:c}),await e.registerNewIbGib({ibGib:s,space:c});let f=v.domainI;await xe({domainI:f,metaspace:e,fromSpace:t,toSpace:c}),l("4.5B Setup: \u2713 Copied V1 and identities (domain and delegate) to remoteSpace."),l("4.5B Setup: Mutating V1 -> V2 in remoteSpace...");let b=await j({timeline:s,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_5b"}},metaspace:e,space:c});Ho.targetV2=b,l(`4.5B Setup: \u2713 Mutated to V2 in remoteSpace: ${y({ibGib:b})}`),l("4.5B Setup: Syncing V2 from remoteSpace to the server..."),await Oe({domainIbGibs:[b],passLabel:"Seed V2 from remoteSpace",metaspace:e,space:c,primarySpace:t,domainI:f,masterSecret:Wo}),l("4.5B Setup: \u2713 Pass 2 Sync (V2 to server) complete. debugState.domainI updated."),l("\u2713 4.5B Setup Complete! Server has V2, default local space has V1. Ready for 4.5B Sync."),o.textContent="\u2713 4.5B Setup Complete";let m=document.getElementById("btn-4-5b-sync");m&&(m.disabled=!1)}catch(e){l(`\u2717 4.5B Setup FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(Yo,"init4_5bSetupButton");function qo(){let o=document.getElementById("btn-4-5b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.5B Sync: Initiating WebSocket Sync from default local space (which has V1, server has V2)...");let e=v.targetC1;if(!v.domainI||!e){l("\u26A0 4.5B Sync: Missing setup state. Please run Setup first."),o.disabled=!1;return}let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space.");await ee({domainIbGibs:[e],passLabel:"Pull V2 from server",metaspace:t,space:a}),l("\u2713 4.5B Sync Execution Complete! Ready for 4.5B Check."),o.textContent="\u2713 4.5B Sync Run";let r=document.getElementById("btn-4-5b-check");r&&(r.disabled=!1)}catch(e){l(`\u2717 4.5B Sync FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(qo,"init4_5bSyncButton");function zo(){let o=document.getElementById("btn-4-5b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.5B Check: Verifying that V2 was pulled down to default local space...");let e=Ho.targetV2;if(!e||!v.domainI){l("\u26A0 4.5B Check: Missing target V2 in state. Did Setup run?"),o.disabled=!1;return}let t=y({ibGib:e}),a=y({ibGib:v.domainI}),r=await O(),n=await r.getLocalUserSpace({});if(!n)throw new Error("No default space.");let s=await r.get({addr:t,space:n});if(!s.success||s.ibGibs?.length!==1)throw new Error(`V2 tip (${t}) is NOT present in local space!`);let i=s.ibGibs[0];l(`4.5B Check: \u2713 V2 Tip found locally. Label: "${i.data?.label}"`);let c=await r.getDependencyGraph({ibGibAddr:t,space:n});l("4.5B Check: Fetching V2 dependency graph from server...");let f=await new V().getIbGibGraph(a,t,!0);if(!f.success||!f.graph)throw new Error(`Failed to fetch V2 graph from server: ${f.message}`);if(we({graphA:c,graphB:f.graph}))l("\u2713 4.5B Check SUCCESS: V2 and all dependencies are fully equivalent on client and server!"),o.textContent="\u2713 4.5B Check Success";else throw new Error("Dependency graphs on local space and server are NOT equivalent.")}catch(e){l(`\u2717 4.5B Check FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(zo,"init4_5bCheckButton");var ta={},xi="test-sender-secret-phase4-6b";function Jo(){let o=document.getElementById("btn-4-6b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.6B Setup: Generating Domain Keystone (I) and two independent target timelines (Alpha and Beta)...");let e=await O(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let a=new V;await Pe({masterSecret:xi,syncSalt:"senderidentitysyncsaltphase4-6b",manageSalt:"senderidentitymanagesaltphase4-6b",metaspace:e,space:t,apiBridge:a,phaseText:"4.6B"});let r=await U.firstGen({parentIbGib:Q,ib:"timeline_root_alpha_4_6b",data:{type:"root",label:"Alpha4_6b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),n=r.newIbGib;await e.persistTransformResult({resTransform:r,space:t}),await e.registerNewIbGib({ibGib:n,space:t});let s=await j({timeline:n,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"A1_4_6b"}},metaspace:e,space:t});ta.targetAlphaV1=s,v.targetC1=s,l(`4.6B Setup: \u2713 Local Timeline A created. A1 Tip: ${y({ibGib:s})}`);let i=await U.firstGen({parentIbGib:Q,ib:"timeline_root_beta_4_6b",data:{type:"root",label:"Beta4_6b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c,space:t});let d=await j({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"B1_4_6b"}},metaspace:e,space:t}),f=await j({timeline:d,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"B2_4_6b"}},metaspace:e,space:t});ta.targetBetaV2=f,v.targetC2=f,l(`4.6B Setup: \u2713 Local Timeline B created. B2 Tip: ${y({ibGib:f})}`),l("\u2713 4.6B Setup Complete! Timelines created locally. Ready for 4.6B Sync."),o.textContent="\u2713 4.6B Setup Complete";let b=document.getElementById("btn-4-6b-sync");b&&(b.disabled=!1)}catch(e){l(`\u2717 4.6B Setup FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(Jo,"init4_6bSetupButton");function Zo(){let o=document.getElementById("btn-4-6b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.6B Sync: Initiating WebSocket Sync for both Timeline A and Timeline B in one call...");let e=ta.targetAlphaV1,t=ta.targetBetaV2;if(!v.domainI||!e||!t){l("\u26A0 4.6B Sync: Missing setup state. Please run Setup first."),o.disabled=!1;return}let a=await O(),r=await a.getLocalUserSpace({});if(!r)throw new Error("No default space.");await ee({domainIbGibs:[e,t],passLabel:"Sync Alpha A1 + Beta B2",metaspace:a,space:r}),l("\u2713 4.6B Sync Execution Complete! Ready for 4.6B Check."),o.textContent="\u2713 4.6B Sync Run";let n=document.getElementById("btn-4-6b-check");n&&(n.disabled=!1)}catch(e){l(`\u2717 4.6B Sync FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(Zo,"init4_6bSyncButton");function Qo(){let o=document.getElementById("btn-4-6b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.6B Check: Verifying both Timeline A and Timeline B exist on the server with matching dependency graphs...");let e=ta.targetAlphaV1,t=ta.targetBetaV2;if(!v.domainI||!e||!t){l("\u26A0 4.6B Check: Missing state. Did Setup and Sync run?"),o.disabled=!1;return}let a=y({ibGib:v.domainI}),r=y({ibGib:e}),n=y({ibGib:t}),s=await O(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=new V;l("4.6B Check: Fetching Timeline A dependency graph from server...");let d=await c.getIbGibGraph(a,r,!0);if(!d.success||!d.graph)throw new Error(`Failed to fetch Timeline A graph from server: ${d.message}`);let f=await s.getDependencyGraph({ibGibAddr:r,space:i});if(!we({graphA:f,graphB:d.graph}))throw new Error("Timeline A dependency graphs on local space and server are NOT equivalent.");l("4.6B Check: \u2713 Timeline A graphs are equivalent."),l("4.6B Check: Fetching Timeline B dependency graph from server...");let b=await c.getIbGibGraph(a,n,!0);if(!b.success||!b.graph)throw new Error(`Failed to fetch Timeline B graph from server: ${b.message}`);let m=await s.getDependencyGraph({ibGibAddr:n,space:i});if(!we({graphA:m,graphB:b.graph}))throw new Error("Timeline B dependency graphs on local space and server are NOT equivalent.");l("4.6B Check: \u2713 Timeline B graphs are equivalent."),l("\u2713 4.6B Check SUCCESS: Both independent timelines are fully synced and identical on client and server!"),o.textContent="\u2713 4.6B Check Success"}catch(e){l(`\u2717 4.6B Check FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(Qo,"init4_6bCheckButton");var Rt={},es="test-sender-secret-phase4-7b";function ts(){let o=document.getElementById("btn-4-7b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.7B Setup: Setting up identities, seeding history, and creating divergent branches...");let e=await O(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let a=new V;await Pe({masterSecret:es,syncSalt:"senderidentitysyncsaltphase4-7b",manageSalt:"senderidentitymanagesaltphase4-7b",metaspace:e,space:t,apiBridge:a,phaseText:"4.7B"});let r=v.domainI,n=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_7b",getFnPrompt:e.getFnPrompt}});await n.initialized,await e.put({ibGib:r,space:n}),await e.registerNewIbGib({ibGib:r,space:n});let s=await U.firstGen({parentIbGib:Q,ib:"timeline_root_conflict_4_7b",data:{type:"root",label:"CommonRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),i=s.newIbGib;await e.persistTransformResult({resTransform:s,space:t}),await e.registerNewIbGib({ibGib:i,space:t}),Rt.testRoot=i;let c=await j({timeline:i,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1Common"}},metaspace:e,space:t}),d=await e.getDependencyGraph({ibGibAddr:y({ibGib:i}),space:t}),f=await e.getDependencyGraph({ibGibAddr:y({ibGib:c}),space:t});await e.put({ibGibs:Object.values({...d,...f}),space:n}),await e.registerNewIbGib({ibGib:i,space:n}),await e.registerNewIbGib({ibGib:c,space:n}),l("4.7B Setup: Syncing v1_common to server..."),await ee({domainIbGibs:[c],passLabel:"Seed v1_common",metaspace:e,space:t}),l("4.7B Setup: \u2713 Seeding complete on server.");let b=v.domainI;await xe({domainI:b,metaspace:e,fromSpace:t,toSpace:n});let m=await j({timeline:c,mut8Opts:{dataToAddOrPatch:{fieldA:"source_edit"}},metaspace:e,space:t});Rt.targetAlphaV2a=m,l(`4.7B Setup: \u2713 Created client divergent edit V2a: ${y({ibGib:m})}`);let u=await j({timeline:c,mut8Opts:{dataToAddOrPatch:{fieldB:"dest_edit"}},metaspace:e,space:n});Rt.targetBetaV2b=u,l(`4.7B Setup: \u2713 Created remote divergent edit V2b: ${y({ibGib:u})}`),l("4.7B Setup: Pushing V2b from remote space to server..."),await Oe({domainIbGibs:[u],passLabel:"Push V2b from remoteSpace",metaspace:e,space:n,primarySpace:t,domainI:b,masterSecret:es}),l("4.7B Setup: \u2713 Server tip is now V2b."),l("\u2713 4.7B Setup Complete! Ready for 4.7B Sync."),o.textContent="\u2713 4.7B Setup Complete";let h=document.getElementById("btn-4-7b-sync");h&&(h.disabled=!1)}catch(e){l(`\u2717 4.7B Setup FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(ts,"init4_7bSetupButton");function as(){let o=document.getElementById("btn-4-7b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.7B Sync: Initiating WebSocket Sync for divergent edit V2a...");let e=Rt.targetAlphaV2a;if(!v.domainI||!e){l("\u26A0 4.7B Sync: Missing setup state. Please run Setup first."),o.disabled=!1;return}let t=await O(),a=await t.getLocalUserSpace({});if(!a)throw new Error("No default space.");await ee({domainIbGibs:[e],passLabel:"Sync V2a (conflict merge)",metaspace:t,space:a}),l("\u2713 4.7B Sync Execution Complete! Ready for 4.7B Check."),o.textContent="\u2713 4.7B Sync Run";let r=document.getElementById("btn-4-7b-check");r&&(r.disabled=!1)}catch(e){l(`\u2717 4.7B Sync FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(as,"init4_7bSyncButton");function rs(){let o=document.getElementById("btn-4-7b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.7B Check: Verifying merged tip (V3) contains both edits on client and server...");let e=Rt.testRoot,t=Rt.targetAlphaV2a,a=Rt.targetBetaV2b;if(!v.domainI||!e||!t||!a){l("\u26A0 4.7B Check: Missing state. Did Setup and Sync run?"),o.disabled=!1;return}let r=y({ibGib:v.domainI}),n=Ce({ibGib:e,defaultIfNone:"incomingAddr"})??y({ibGib:e}),s=await O(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let d=(await s.getLocalUserSpace({}).then(A=>new le().getKnowledgeMap({space:A,metaspace:s,domainIbGibs:[e]})))[n];if(l(`4.7B Check: Client tip address: ${d}`),!d)throw new Error("Client default space is missing the timeline tip.");let f=await s.get({addr:d,space:i});if(!f.success||!f.ibGibs?.length)throw new Error("Client tip not found in default local space.");let b=f.ibGibs[0];if(!b.data?.fieldA||!b.data?.fieldB)throw new Error(`Merged client tip missing edits: fieldA: ${b.data?.fieldA}, fieldB: ${b.data?.fieldB}`);l("4.7B Check: \u2713 Client tip has both fieldA and fieldB edits.");let m=b.rel8ns?.[Me];if(!m?.[0])throw new Error("Client tip is missing graftinfo relations.");let u=await s.get({addr:m[0],space:i});if(!u.success||!u.ibGibs?.length)throw new Error("GraftInfo not found in local space.");let h=u.ibGibs[0];if(!h.rel8ns?.[yt]||!h.rel8ns?.[et])throw new Error("GraftInfo is missing graftbase or graftorphan relations.");l("4.7B Check: \u2713 Client graft base and orphan relations are correctly set.");let E=await new V().getIbGibGraph(r,d,!0);if(!E.success||!E.graph)throw new Error(`Failed to fetch merged graph from server: ${E.message}`);let w=E.graph[d];if(!w)throw new Error("Merged V3 tip is not present on the server!");if(w.data?.fieldA!=="source_edit"||w.data?.fieldB!=="dest_edit")throw new Error("Server tip data edits do not match merged values.");l("4.7B Check: \u2713 Server tip has matching merged edits."),l("\u2713 4.7B Check SUCCESS: Divergent branches merged successfully via optimistic graft!"),o.textContent="\u2713 4.7B Check Success"}catch(e){l(`\u2717 4.7B Check FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(rs,"init4_7bCheckButton");var Ke={};function ns(){let o=document.getElementById("btn-4-8b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.8B Setup: Setting up identities, seeding history, and creating divergent branches in client and remote...");let e=await O(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let a=new V;await Pe({masterSecret:"test-sender-secret-phase4-8b",syncSalt:"senderidentitysyncsaltphase4-8b",manageSalt:"senderidentitymanagesaltphase4-8b",metaspace:e,space:t,apiBridge:a,phaseText:"4.8B"});let r=v.domainI;Ke.domainI_latest=r;let n=y({ibGib:r});l("4.8B Setup: Creating temporary remote space...");let s=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_8b",getFnPrompt:e.getFnPrompt}});await s.initialized,await xe({domainI:r,metaspace:e,fromSpace:t,toSpace:s});let i=await U.firstGen({parentIbGib:Q,ib:"timeline_root_conflict_4_8b",data:{type:"root",label:"CommonRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c,space:t}),Ke.testRoot=c;let d=await j({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1Common"}},metaspace:e,space:t}),f=await e.getDependencyGraph({ibGibAddr:y({ibGib:c}),space:t}),b=await e.getDependencyGraph({ibGibAddr:y({ibGib:d}),space:t}),m={...f,...b};await e.put({ibGibs:Object.values(m),space:s}),await e.registerNewIbGib({ibGib:c,space:s}),await e.registerNewIbGib({ibGib:d,space:s}),l("4.8B Setup: Syncing v1_common to server..."),await ee({domainIbGibs:[d],passLabel:"Seed v1_common",metaspace:e,space:t}),l("4.8B Setup: \u2713 Seeding complete on server."),await xe({domainI:v.domainI,metaspace:e,fromSpace:t,toSpace:s});let u=await U.firstGen({parentIbGib:Q,ib:"beta_multitimelines_withid_4_8b",data:{fieldA:"beta field A created on source"},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),h=u.newIbGib;await e.persistTransformResult({resTransform:u,space:t}),await e.registerNewIbGib({ibGib:h,space:t}),Ke.targetBetaV0=h,l(`4.8B Setup: \u2713 Created client independent related timeline Beta: ${y({ibGib:h})}`);let I=await j({timeline:d,mut8Opts:{dataToAddOrPatch:{fieldA:"source_edit"}},metaspace:e,space:t}),E=await Pt({timeline:I,metaspace:e,space:t,rel8nInfos:[{rel8nName:"testrel8n",ibGibs:[h]}]});Ke.targetAlphaV3a=E,l(`4.8B Setup: \u2713 Created client divergent edit V3a: ${y({ibGib:E})}`);let w=await j({timeline:d,mut8Opts:{dataToAddOrPatch:{fieldB:"dest_edit"}},metaspace:e,space:s});l(`4.8B Setup: \u2713 Created remote divergent edit V2b: ${y({ibGib:w})}`),l("4.8B Setup: Pushing V2b from remote space to server..."),await Oe({domainIbGibs:[w],passLabel:"Push V2b from remoteSpace",metaspace:e,space:s,primarySpace:t,domainI:v.domainI,masterSecret:"test-sender-secret-phase4-8b"}),Ke.domainI_latest=v.domainI,l("4.8B Setup: \u2713 Server tip is now V2b. Evolved identity copied back."),l("\u2713 4.8B Setup Complete! Ready for 4.8B Sync."),o.textContent="\u2713 4.8B Setup Complete";let A=document.getElementById("btn-4-8b-sync");A&&(A.disabled=!1)}catch(e){l(`\u2717 4.8B Setup FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(ns,"init4_8bSetupButton");function os(){let o=document.getElementById("btn-4-8b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.8B Sync: Initiating WebSocket Sync for divergent edit V3a (with related timeline Beta)...");let e=Ke.domainI_latest,t=Ke.targetAlphaV3a;if(!e||!t){l("\u26A0 4.8B Sync: Missing setup state. Please run Setup first."),o.disabled=!1;return}let a=await O(),r=await a.getLocalUserSpace({});if(!r)throw new Error("No default space.");await ee({domainIbGibs:[t],passLabel:"Sync V3a and merge",metaspace:a,space:r}),Ke.domainI_latest=v.domainI,l("\u2713 4.8B Sync Execution Complete! Ready for 4.8B Check."),o.textContent="\u2713 4.8B Sync Run";let n=document.getElementById("btn-4-8b-check");n&&(n.disabled=!1)}catch(e){l(`\u2717 4.8B Sync FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(os,"init4_8bSyncButton");function ss(){let o=document.getElementById("btn-4-8b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.8B Check: Verifying merged tip (V4) contains both edits on client and server...");let e=Ke.domainI_latest,t=Ke.testRoot,a=Ke.targetAlphaV3a,r=Ke.targetBetaV0;if(!e||!t||!a||!r){l("\u26A0 4.8B Check: Missing state. Did Setup and Sync run?"),o.disabled=!1;return}let n=y({ibGib:e}),s=Ce({ibGib:t,defaultIfNone:"incomingAddr"})??y({ibGib:t}),i=y({ibGib:r}),c=await O(),d=await c.getLocalUserSpace({});if(!d)throw new Error("No default space.");let b=(await c.getLocalUserSpace({}).then(_=>new le().getKnowledgeMap({space:_,metaspace:c,domainIbGibs:[t]})))[s];if(l(`4.8B Check: Client tip address: ${b}`),!b)throw new Error("Client default space is missing the timeline tip.");let m=await c.get({addr:b,space:d});if(!m.success||!m.ibGibs||m.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let u=m.ibGibs[0];if(!u.data||!u.data.fieldA||!u.data.fieldB)throw new Error(`Merged client tip is missing expected data edits: fieldA: ${u.data?.fieldA}, fieldB: ${u.data?.fieldB}`);l("4.8B Check: \u2713 Client tip has both fieldA and fieldB edits.");let h=u.rel8ns?.[Me];if(!h?.[0])throw new Error("Client tip is missing graftinfo relations.");let I=await c.get({addr:h[0],space:d});if(!I.success||!I.ibGibs||I.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let E=I.ibGibs[0],w=E.rel8ns?.[yt],A=E.rel8ns?.[et];if(!w||!A)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");l("4.8B Check: \u2713 Client graft base and orphan relations are correctly set.");let G=new V;l("4.8B Check: Fetching server timeline graph...");let T=await G.getIbGibGraph(n,b,!0);if(!T.success||!T.graph)throw new Error(`Failed to fetch merged graph from server: ${T.message}`);let C=T.graph[b];if(!C)throw new Error("Merged V4 tip is not present on the server!");if(C.data?.fieldA!=="source_edit"||C.data?.fieldB!=="dest_edit")throw new Error("Server tip data edits do not match merged values.");l("4.8B Check: \u2713 Server tip has matching merged edits."),l("4.8B Check: Verifying related timeline Beta is present on the server...");let S=await G.getIbGibGraph(n,i,!0);if(!S.success||!S.graph||!S.graph[i])throw new Error(`Related timeline Beta (${i}) is missing from the server!`);l("4.8B Check: \u2713 Related timeline Beta successfully verified on the server."),l("\u2713 4.8B Check SUCCESS: Divergent branches merged successfully and related timeline synced on server!"),o.textContent="\u2713 4.8B Check Success"}catch(e){l(`\u2717 4.8B Check FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(ss,"init4_8bCheckButton");var rt={},rr=`This is the initial quiz question.
1
+ import{$d as Wt,A as Xe,Ad as le,Cd as Nt,Dd as Ae,Ea as gt,Eb as E,Ed as tt,G as D,Gb as Et,Hb as Ne,Hd as Pt,Id as Ot,La as yt,M as $e,Ma as St,Mb as ue,N as Le,Nb as It,Nc as Be,Od as xt,Pc as T,Pd as Dt,Qc as Ct,Qd as Oe,Ra as wt,Rb as ge,Rd as Vt,S as Re,Sb as Pe,Sc as Bt,Sd as Mt,Td as Ft,Ud as Kt,Vb as vt,Vd as Ut,Wb as Gt,Wd as xe,Xd as ye,Yb as Je,Yd as Se,Zd as we,_b as W,_d as jt,a as h,ae as Y,bc as se,be as Ht,c as Ge,ce as Yt,d as Ce,de as qt,e as fe,ee as Xt,f as Ye,fb as ee,fd as At,fe as zt,g as z,gb as _t,ge as Jt,h as qe,he as Zt,ia as ze,id as kt,ie as Qt,j as b,jd as Tt,p as u,pd as Ze,qd as Qe,sd as $t,t as M,td as Lt,ua as ft,va as ut,vd as Rt,zd as et}from"./chunk-J7X3XTAI.mjs";var ea=!1,ce={COMMON:{ALGO:Ge.sha_256,TYPE:Et.hash_reveal_v1,ROUNDS:2,REPLENISH:Ne.topUp},CONNECT_POOL:{ID:ge,VERB:It,SIZE:10,SELECT_SEQUENTIALLY:2,SELECT_RANDOMLY:2,TARGET_BINDING_COUNT:0,SERVER_DEMAND_COUNT:3}};function De(r){let e=`[${De.name}]`;try{ea&&console.log(`${e} starting... (I: 3c791af2f978a00a087dfdde90884826)`);let t=(r.data?.challengePools??[]).find(i=>i.id===ce.CONNECT_POOL.ID);if(!t)throw new Error(`Keystone missing "${ce.CONNECT_POOL.ID}" pool (E: 6382e29260e4ddbac42ed18f49733526)`);let n=Object.keys(t.challenges).sort();if(n.length===0)throw new Error("Connect pool has no challenges (E: 1ef62fdbda182a790835c8c796475226)");let o=n[0],s=t.challenges[o];return{challengeId:o,challenge:s}}catch(t){throw console.error(`${e} ${b(t)}`),t}finally{ea&&console.log(`${e} complete.`)}}h(De,"getConnectChallenge");var In="auth-challenge-init",vn="auth-init",Gn="auth-challenge",Cn="auth-proof",Bn="auth-ok",An="auth-fail",kn="sync-frame",Tn="sync-frame-response",$n="sync-frame-authenticated",Ln="sync-frame-response-authenticated",Rn="domain-payload",Nn="sync-error",L={auth_challenge_init:In,auth_init:vn,auth_challenge:Gn,auth_proof:Cn,auth_ok:Bn,auth_fail:An,sync_frame:kn,sync_frame_response:Tn,sync_frame_authenticated:$n,sync_frame_response_authenticated:Ln,domain_payload:Rn,sync_error:Nn},Ve=Object.values(L);function at(r){return Ve.includes(r)}h(at,"isSyncWebSocketMsgType");function ta(r){throw new Error(`Unhandled message type: ${r} (E: e928a3f82cd7469a98ef1bc248a3f826)`)}h(ta,"assertUnreachable");var te=!1,_e=class r extends Ht{static{h(this,"SyncPeerWebSocketSender_V1")}lc=`[${r.name}]`;get classname(){return r.name}get isSocketOpen(){return this.ws!==void 0&&this.ws.readyState===WebSocket.OPEN}ws;activeResolve;activeReject;pendingPayloadsToSend=[];handshakeMessageListener;constructor(e,t){super(e,t)}async preConnectCheck(e){let t=`${this.lc}[${this.preConnectCheck.name}]`;if(!this.data?.wsUrl)throw new Error("Missing wsUrl in peer data (E: 144c6ddf53980554cf08fa0896bd9826)");if(!this.data?.httpEvolveUrl)throw new Error("Missing httpEvolveUrl in peer data (E: 53425c1a13f829b8e8a55c2cea3a4a26)")}async postEstablishToReceiver({newSenderIdentity:e,sessionIdentity:t}){let n=`${this.lc}[${this.postEstablishToReceiver.name}]`;try{if(te&&console.log(`${n} posting evolved keystones to ${this.data.httpEvolveUrl}...`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: d642e8a9af18b532c87c6f581aa53b26)");if(!this.data.httpEvolveUrl)throw new Error("(UNEXPECTED) this.data.httpEvolveUrl falsy? (E: 8589ddbb155914d85c09658881da2c26)");let o=await fetch(this.data.httpEvolveUrl,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:e,relatedKeystoneIbGibs:[t]})});if(!o.ok){let s=await o.json().catch(()=>({})),i=s.message||s.error||"Unknown error";throw new Error(`HTTP ${o.status} evolution post rejected. errorMsg: ${i} (E: e8a478291b88d05c68cf6b385684b826)`)}te&&console.log(`${n} evolve post accepted by server.`)}catch(o){throw console.error(`${n} establish post failed: ${b(o)}`),o}}async connectImpl(e){let t=`${this.lc}[${this.connectImpl.name}]`;try{te&&console.log(`${t} starting...`);let{senderIdentity:n,fnSenderSecret:o,sagaId:s,localMetaspace:i,localSpace:c}=this.opts;if(!n||!o||!s)throw new Error("Missing identity parameters in peer options (E: ed49b6711ac82efcdb42b8a28c5b6826)");let l=await o(),d=await jt({senderSecret:l,sagaId:s}),p=u({ibGib:n}),f=u({ibGib:(n.rel8ns?.past,n)}),y=await i.getLatestAddr({ibGib:n,space:c});if(!y)throw new Error("senderIdentityLatestAddr falsy. we should have a latest addr that is different than the sender identity at this point (done in the peer establish phase) (E: 225607318bef485d7821f82de97b6826)");let w=((await i.get({addrs:[y],space:c})).ibGibs?.[0]).data.proofs.at(0)?.claim.target;if(!w)throw new Error("Could not locate session keystone target from identity (E: 5ec4882f7e5e4c33fbd00ab8b3166726)");let I=(await i.get({addrs:[w],space:c})).ibGibs?.[0];if(!I)throw new Error(`Session keystone not found in local space: ${w} (E: 9ba818e6622808bb4ae749be31f80b26)`);let A=(I.data?.challengePools??[]).find(K=>K.id===ce.CONNECT_POOL.ID);if(!A)throw new Error("Session keystone missing connect pool (E: f50968afca04b6d38ec19824ea201826)");let{challengeId:v}=De(I),G=Je.create({config:A.config}),k=await G.derivePoolSecret({masterSecret:d}),$=await G.generateSolution({poolSecret:k,poolId:ce.CONNECT_POOL.ID,challengeId:v}),P=`${this.data.wsUrl}?sAddr=${encodeURIComponent(w)}&solution=${encodeURIComponent($.value)}`;te&&console.log(`${t} connecting to WebSocket: ${P}`);let O=new WebSocket(P);return this.ws=O,new Promise((K,F)=>{let U=!1;O.addEventListener("open",()=>{te&&console.log(`${t} WebSocket opened. Awaiting challenge...`)}),this.handshakeMessageListener=async j=>{try{let H=JSON.parse(j.data);te&&console.log(`${t} received handshake frame: ${H.type}`);let Q=H.type;if(!at(Q)){let be=Ve.join(", ");throw new Error(`Unknown message type '${Q}' received during connection handshake. Valid types are: ${be} (E: e983271bc84f46928e4695be2409826)`)}switch(Q){case L.auth_challenge_init:await this.handleHandshakeAuthChallengeInit(O,w);break;case L.auth_challenge:await this.handleHandshakeAuthChallenge(O,H,I,d);break;case L.auth_ok:U=!0,this.handleHandshakeAuthOk(O,K);break;case L.auth_fail:this.handleHandshakeAuthFail(H,F);break;case L.sync_error:this.handleHandshakeSyncError(H,F);break;case L.auth_init:case L.auth_proof:case L.sync_frame:case L.sync_frame_response:case L.sync_frame_authenticated:case L.sync_frame_response_authenticated:case L.domain_payload:throw new Error(`Unexpected message type '${Q}' during connection handshake (E: e3f80c68ab2a46c2b1858c8a1e2f8926)`);default:ta(Q)}}catch(H){console.error(`${t} ${b(H)}`),F(H)}},O.addEventListener("message",this.handshakeMessageListener),O.addEventListener("close",j=>{U||(this.disconnect(),F(new Error(`WebSocket closed before connect completed (code: ${j.code})`)))}),O.addEventListener("error",j=>{U||(this.disconnect(),F(new Error("WebSocket connection error")))})})}catch(n){throw console.error(`${t} connect failed: ${b(n)}`),n}}disconnect(){let e=`${this.lc}[${this.disconnect.name}]`;try{if(te&&console.log(`${e} starting... (I: 35c4b85fca0c6e9d042f5ff87cde3826)`),this.ws){this.handshakeMessageListener&&(this.ws.removeEventListener("message",this.handshakeMessageListener),this.handshakeMessageListener=void 0);try{this.ws.close()}catch(t){console.error(`${e} failed to close websocket: ${b(t)}`)}this.ws=void 0}}catch(t){console.error(`${e} ${b(t)}`)}finally{te&&console.log(`${e} complete.`)}}async handleRuntimeMessage(e){let t=`${this.lc}[${this.handleRuntimeMessage.name}]`;try{let n=JSON.parse(e.data);te&&console.log(`${t} received runtime frame: ${n.type}`);let o=n.type;if(!at(o)){let s=Ve.join(", ");throw new Error(`Unknown message type '${o}' received during active sync saga loop. Valid types are: ${s} (E: e23a8d10b74d47fb90518f8e3f4b826)`)}switch(o){case L.sync_frame_response:await this.handleRuntimeSyncFrameResponse(n);break;case L.sync_frame_authenticated:this.handleRuntimeSyncFrameAuthenticated();break;case L.domain_payload:this.handleRuntimeDomainPayload(n);break;case L.sync_error:this.handleRuntimeSyncError(n);break;case L.auth_challenge_init:case L.auth_init:case L.auth_challenge:case L.auth_proof:case L.auth_ok:case L.auth_fail:case L.sync_frame:case L.sync_frame_response_authenticated:throw new Error(`Unexpected message type '${o}' during active sync saga loop (E: e982b12cf92c448bbad0e84b7263c826)`);default:ta(o)}}catch(n){if(console.error(`${t} failed parsing/handling runtime frame: ${b(n)}`),this.disconnect(),this.activeReject){let o=this.activeReject;this.activeResolve=void 0,this.activeReject=void 0,o(n)}}}async handleHandshakeAuthChallengeInit(e,t){e.send(JSON.stringify({type:L.auth_init,sAddr:t}))}async handleHandshakeAuthChallenge(e,t,n,o){let{challengeUuid:s,demandedIds:i}=t;te&&console.log(`${this.lc} solving demanded challenges: ${i.join(", ")}`);let c=await this.signContextConnect({challengeUuid:s,demandedIds:i});if(!c)throw new Error("Failed to sign connect challenge proof (E: e9807f28ae9248bbadd0a7f1a8e9826)");e.send(JSON.stringify({type:L.auth_proof,proofFrame:c}))}handleHandshakeAuthOk(e,t){te&&console.log(`${this.lc} WebSocket connect SUCCESS!`),this.handshakeMessageListener&&(e.removeEventListener("message",this.handshakeMessageListener),this.handshakeMessageListener=void 0),e.addEventListener("message",n=>this.handleRuntimeMessage(n)),t()}handleHandshakeAuthFail(e,t){this.disconnect(),t(new Error(`Handshake auth failed: ${e.message||"Unknown fail reason"} (E: f380b271a2be498db257bc8209fa8926)`))}handleHandshakeSyncError(e,t){this.disconnect(),t(new Error(`Handshake sync error: ${e.message||e.error||"Unknown sync error"} (E: f9208a01fe434cbbad83f210ea8f3426)`))}async handleRuntimeSyncFrameResponse(e){let t=e.context,n=await Wt({context:t});if(n.length>0)throw new Error(`Invalid response context received: ${n.join(", ")} (E: d7b5a283cf4c43ba8659c803800cf826)`);let o=[_t({ibGib:t}),t.sagaFrame,t.sagaFrameMsg];t.signedSessionIdentity&&o.push(t.signedSessionIdentity);let{localSpace:s}=this.opts;for(let c of o)await ut({space:s,ibGibs:[c]}),await gt({space:s,ibGib:c});if((t.data?.["@payloadAddrsDomain"]||[]).length>0&&this.ws.send(JSON.stringify({type:L.sync_frame_response_authenticated,contextAddr:u({ibGib:t})})),this.activeResolve){let c=this.activeResolve;this.activeResolve=void 0,this.activeReject=void 0,c(t)}}handleRuntimeSyncFrameAuthenticated(){let e=this.pendingPayloadsToSend||[];this.pendingPayloadsToSend=[];for(let t of e)this.ws.send(JSON.stringify({type:L.domain_payload,ibGib:t}))}handleRuntimeDomainPayload(e){let t=e.ibGib;this.payloadIbGibsDomainReceived$.next(t)}handleRuntimeSyncError(e){let t=e.message||e.error||"Unknown sync runtime error",n=new Error(`Sync runtime error from receiver: ${t} (E: e983bc1c828d447fa0581da2b8004f26)`);if(this.activeReject){let o=this.activeReject;this.activeResolve=void 0,this.activeReject=void 0,o(n)}else throw n}async sendContextRequest(e){let t=`${this.lc}[${this.sendContextRequest.name}]`;try{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected or open (E: 2979923231b882c5d6529e88b3f16826)");let n=e.payloadIbGibsDomain??[];this.pendingPayloadsToSend=[...n];let o={...e};return delete o.payloadIbGibsDomain,new Promise((s,i)=>{this.activeResolve=s,this.activeReject=i,this.ws.send(JSON.stringify({type:L.sync_frame,context:o}))})}catch(n){throw console.error(`${t} sendContextRequest failed: ${b(n)}`),n}}};var aa={$schema:"../../../../libs/core-gib/dist/keystone/policy/schemas/keystone.medium.schema.json",metadata:{name:"Space-Gib Default Identity Policy",securityLevel:"medium"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:200,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:5}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-512",rounds:10,behavior:{size:2e3,replenish:"replace-all",selectSequentially:5,selectRandomly:5,targetBindingCount:16}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-512",rounds:10,behavior:{size:2e3,replenish:"delete-all",selectSequentially:5,selectRandomly:5,targetBindingCount:16}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:20,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:3}}}};var On=aa.pools;function Me(r,e){let t=On[r];if(!t)throw new Error(`Pool template not found in space-gib JSON config: ${r}`);return Gt({template:t,salt:e})}h(Me,"getSpaceGibPoolConfig");var V={COMMON:ce.COMMON,DEFAULT_POOL:{ID:"default",SIZE:20,SELECT_SEQUENTIALLY:2,SELECT_RANDOMLY:2,TARGET_BINDING_COUNT:3},CONNECT_POOL:ce.CONNECT_POOL},Nr={MIN_DEFAULT_POOL_SIZE:50,ALLOWED_ALGORITHMS:[Ge.sha_256,Ge.sha_512]};var B=class extends Ct{static{h(this,"SpaceGibApiBridge")}lc="[SpaceGibApiBridge]"},xn=new B;Bt(xn);var N="[dev-tools]",m={};window.ibgibDebugState=m;function a(r){let e=document.getElementById("dev-panel-log");if(!e)return;let t=new Date().toISOString().slice(11,23);e.textContent=`[${t}] ${r}
2
+ `+e.textContent}h(a,"devLog");async function na({domainI:r,masterSecret:e,syncSalt:t,metaspace:n,space:o,apiBridge:s}){let i=new se,c=await Ye({s:`${e}-sync-delegate`}),l=await i.genesis({masterSecret:c,configs:[Me("sync",`${t}-delegate`)],metaspace:n,space:o,frameDetails:{client:"space-gib-web-dev-delegate",timestamp:fe()}}),d=await i.registerDelegate({parentKeystone:r,delegateKeystone:l,masterSecret:e,signingPoolId:"manage",metaspace:n,space:o,allowedVerbs:[ue]}),p=u({ibGib:r}),f=await s.putEvolveKeystone({domainAddr:p,keystoneIbGib:d,relatedKeystoneIbGibs:[l]});if(!f.success)throw new Error(`Server rejected delegate evolution: ${f.message}`);return{evolvedDomainI:d,delegateKeystone:l,delegateSecret:c}}h(na,"createAndRegisterSyncDelegate");async function nt({domainI:r,masterSecret:e,metaspace:t,space:n}){let o=r,s=h(async()=>e,"fnSenderSecret"),i=Object.values(r.data?.delegates??{}).find(c=>c.allowedVerbs?.includes(ue));if(i){let c=i.delegateTjpAddr;if(c){let l=await t.getLatestAddr({addr:c,space:n});if(l){let d=await t.get({addr:l,space:n});if(d.success&&d.ibGibs&&d.ibGibs.length>0){o=d.ibGibs[0];let p=await Ye({s:`${e}-sync-delegate`});s=h(async()=>p,"fnSenderSecret")}}}}return{senderIdentity:o,fnSenderSecret:s}}h(nt,"getSenderIdentityInfo");async function ae(r){let e=`${N}[performPhaseSetup(${r.phaseText})]`,t=document.getElementById(r.btnId);if(t)try{t.disabled=!0,a(`${r.phaseText} Setup: Generating Alice's long-lived Domain Keystone (I) and Target (X)...`);let n=await E(),o=await n.getLocalUserSpace({});if(!o)throw new Error("No default space found in metaspace.");let i=await new se().genesis({masterSecret:r.masterSecret,configs:[Me("manage",r.manageSalt)],metaspace:n,space:o,frameDetails:{client:"space-gib-web-dev",timestamp:fe()}});a(`${r.phaseText} Setup: \u2713 Domain Keystone (I) created locally: ${u({ibGib:i})}`),a(`${r.phaseText} Setup: Starting postGenesisKeystone...`);let c=new B,l=await c.postGenesisKeystone(i);if(l.success)a(`${r.phaseText} Setup: \u2713 Domain Keystone registered and stored on receiver (server).`);else throw a(`${r.phaseText} Setup: X postGenesisKeystone failed: ${l.message}.`),new Error(`${r.phaseText} Setup: Server rejected genesis domain keystone: ${l.message}`);a(`${r.phaseText} Setup: Generating and registering sync delegate...`);let{evolvedDomainI:d,delegateKeystone:p}=await na({domainI:i,masterSecret:r.masterSecret,syncSalt:r.syncSalt,metaspace:n,space:o,apiBridge:c});m.domainI=d,m.domainIMasterSecret=r.masterSecret,a(`${r.phaseText} Setup: \u2713 Registered Sync Delegate: ${u({ibGib:p})}`);let f=await D.firstGen({parentIbGib:M,ib:r.ib,data:r.data,dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),y=f.newIbGib;await n.persistTransformResult({resTransform:f,space:o}),await n.registerNewIbGib({ibGib:y}),m.targetX=y,a(`${r.phaseText} Setup: \u2713 Target (X) created and persisted locally: ${u({ibGib:y})}`),a(`\u2713 ${r.phaseText} Setup Complete! Ready for ${r.phaseText} Sync.`),t.textContent=`\u2713 ${r.phaseText} Setup Complete`;let S=document.getElementById(r.nextBtnId);S&&(S.disabled=!1)}catch(n){a(`\u2717 ${r.phaseText} Setup FAILED: ${b(n)}`),console.error(`${e} ${r.phaseText} Setup error:`,n),t.disabled=!1}}h(ae,"performPhaseSetup");async function de(r){let e=`${N}[performPhaseSync(${r.phaseText})]`,t=document.getElementById(r.btnId);if(t)try{t.disabled=!0,a(`${r.phaseText} Sync: Executing senderCoordinator.sync(...) using WebSocket Peer...`);let n=m.domainI,o=m.targetX;if(!n||!o){a(`\u26A0 ${r.phaseText} Sync: Missing setup state. Please run Setup first.`),t.disabled=!1;return}let s=u({ibGib:n}),i=await E(),c=await i.getLocalUserSpace({});if(!c)throw new Error("No default space.");let l=location.protocol==="https:"?"wss:":"ws:",d=new _e({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(s)}`,wsUrl:`${l}//${location.host}/api/sync/ws/${encodeURIComponent(s)}`}),p=new Y,f=await z();m.sagaId=f,m.senderPeer=d;let{senderIdentity:y,fnSenderSecret:S}=await nt({domainI:n,masterSecret:m.domainIMasterSecret,metaspace:i,space:c});await d.initializeOpts({localMetaspace:i,localSpace:c,senderIdentity:y,fnSenderSecret:S,sagaId:f,sessionConnectPoolConfig:V.CONNECT_POOL,sessionSyncPoolConfig:V.DEFAULT_POOL,targetAddrs:[s]});try{await(await p.sync({domainIbGibs:[o],senderIdentityInfo:{senderIdentity:y,senderDomainAddr:s},fnSenderSecret:S,peer:d,localSpace:c,metaspace:i,conflictStrategy:xe.optimisticWithLCS})).done}catch(w){if(r.expectSyncFailure)a(`${r.phaseText} Sync: Coordinator sync executed (${r.failureMessageSuffix??"errors expected"}): ${b(w)}`);else throw w}a(`\u2713 ${r.phaseText} Sync Execution Complete! Ready for State Checks.`),t.textContent=`\u2713 ${r.phaseText} Sync Run`;let g=document.getElementById(r.nextBtnId);g&&(g.disabled=!1)}catch(n){a(`\u2717 ${r.phaseText} Sync FAILED: ${b(n)}`),console.error(`${e} ${r.phaseText} Sync error:`,n),t.disabled=!1}}h(de,"performPhaseSync");async function rt({localI:r,metaspace:e,space:t}){let n=Object.values(r.data?.delegates??{}).find(p=>p.allowedVerbs?.includes(ue));if(!n)return{};let o=n.delegateTjpAddr;if(!o)return{};let s=await e.getLatestAddr({addr:o,space:t});if(!s)return{delegateTjpAddr:o};let c=(await e.get({addrs:[s],space:t})).ibGibs?.[0];if(!c)return{delegateTjpAddr:o,latestLocalDelegateAddr:s};let d=c.data?.proofs?.find(p=>p.claim?.verb==="sync")?.claim?.target;return{delegateTjpAddr:o,latestLocalDelegateAddr:s,localDelegate:c,sessionIdentityTjpAddr:d}}h(rt,"getDelegateAndSessionInfo");async function x({domainIbGibs:r,passLabel:e,metaspace:t,space:n}){let o=m.domainI,s=m.domainIMasterSecret;if(!o||!s)throw new Error(`runSyncPass[${e}]: Missing domain identity or secret in debugState. Run Setup first.`);let i=u({ibGib:o}),c=location.protocol==="https:"?"wss:":"ws:",{senderIdentity:l,fnSenderSecret:d}=await nt({domainI:o,masterSecret:s,metaspace:t,space:n});a(`Sync: ${e} \u2014 using sender: ${u({ibGib:l}).slice(0,40)}...`);let p=new _e({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),f=new Y,y=await z();m.sagaId=y,m.senderPeer=p,await p.initializeOpts({localMetaspace:t,localSpace:n,senderIdentity:l,fnSenderSecret:d,sagaId:y,sessionConnectPoolConfig:V.CONNECT_POOL,sessionSyncPoolConfig:V.DEFAULT_POOL,targetAddrs:[i]}),await(await f.sync({domainIbGibs:r,senderIdentityInfo:{senderIdentity:l,senderDomainAddr:i},fnSenderSecret:d,peer:p,localSpace:n,metaspace:t,conflictStrategy:xe.optimisticWithLCS})).done;let g=await t.getLatestAddr({addr:i,space:n});if(g&&g!==u({ibGib:o})){let w=await t.get({addrs:[g],space:n});w.ibGibs?.[0]&&(m.domainI=w.ibGibs[0])}}h(x,"runSyncPass");async function J({domainIbGibs:r,passLabel:e,metaspace:t,space:n,primarySpace:o,domainI:s,masterSecret:i}){let c=u({ibGib:s}),l=location.protocol==="https:"?"wss:":"ws:",{senderIdentity:d,fnSenderSecret:p}=await nt({domainI:s,masterSecret:i,metaspace:t,space:n});a(`Sync: ${e} \u2014 using sender: ${u({ibGib:d}).slice(0,40)}...`);let f=new _e({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(c)}`,wsUrl:`${l}//${location.host}/api/sync/ws/${encodeURIComponent(c)}`}),y=new Y,S=await z();m.sagaId=S,m.senderPeer=f,await f.initializeOpts({localMetaspace:t,localSpace:n,senderIdentity:d,fnSenderSecret:p,sagaId:S,sessionConnectPoolConfig:V.CONNECT_POOL,sessionSyncPoolConfig:V.DEFAULT_POOL,targetAddrs:[c]}),await(await y.sync({domainIbGibs:r,senderIdentityInfo:{senderIdentity:d,senderDomainAddr:c},fnSenderSecret:p,peer:f,localSpace:n,metaspace:t,conflictStrategy:xe.optimisticWithLCS})).done;let w=await t.getLatestAddr({addr:c,space:n});if(w){let I=(await t.get({addrs:[w],space:n})).ibGibs?.[0];I&&(m.domainI=I,o&&await X({domainI:I,metaspace:t,fromSpace:n,toSpace:o}))}}h(J,"runSyncPassFromSpace");async function q({masterSecret:r,syncSalt:e,manageSalt:t,metaspace:n,space:o,apiBridge:s,phaseText:i}){let l=await new se().genesis({masterSecret:r,configs:[Me("manage",t)],metaspace:n,space:o,frameDetails:{client:"space-gib-web-dev",timestamp:fe()}});a(`${i} Setup: \u2713 Domain Keystone (I) created locally: ${u({ibGib:l})}`),a(`${i} Setup: Starting postGenesisKeystone...`);let d=await s.postGenesisKeystone(l);if(d.success)a(`${i} Setup: \u2713 Domain Keystone registered and stored on receiver (server).`);else throw a(`${i} Setup: X postGenesisKeystone failed: ${d.message}.`),new Error(`${i} Setup: Server rejected genesis domain keystone: ${d.message}`);a(`${i} Setup: Generating and registering sync delegate...`);let{evolvedDomainI:p,delegateKeystone:f}=await na({domainI:l,masterSecret:r,syncSalt:e,metaspace:n,space:o,apiBridge:s});return m.domainI=p,m.domainIMasterSecret=r,{domainI:p,delegateKeystone:f}}h(q,"setupDomainAndDelegateIdentities");async function Ee({localI:r,metaspace:e,space:t,apiBridge:n,domainAddr:o}){let s=await e.getLatestAddr({addr:o,space:t});if(!s)throw new Error("Evolved domain keystone tip NOT found in local space!");a("\u2713 Check: Evolved Domain Keystone exists locally.");let{latestLocalDelegateAddr:i,sessionIdentityTjpAddr:c}=await rt({localI:r,metaspace:e,space:t});if(!i)throw new Error("Evolved delegate keystone tip NOT found in local space!");if(!c)throw new Error("Delegate sync claim does not target a session keystone.");a("\u2713 Check: Delegate Keystone and Sync Claim to Session verified locally.");let l=await n.getIbGib(o,i);if(!l.success||!l.ibGib)throw new Error("Evolved Delegate Keystone NOT found on server!");a("\u2713 Check: Evolved Delegate Keystone exists on server.");let d=await n.getIbGib(o,s);if(!d.success||!d.ibGib)throw new Error("Evolved Domain Keystone NOT found on server!");return a("\u2713 Check: Evolved Domain Keystone exists on server."),{latestLocalIAddr:s,latestLocalDelegateAddr:i,sessionIdentityTjpAddr:c}}h(Ee,"verifyIdentitiesOnServer");async function X({domainI:r,metaspace:e,fromSpace:t,toSpace:n}){let o=u({ibGib:r}),s=await e.getLatestAddr({addr:o,space:t});if(!s)throw new Error("Could not find latest domain I address.");let c=(await e.get({addrs:[s],space:t})).ibGibs?.[0];if(!c)throw new Error("Could not get latest domain I.");let l=await e.getDependencyGraph({ibGibAddr:s,space:t});await e.put({ibGibs:Object.values(l),space:n}),await e.registerNewIbGib({ibGib:c,space:n});let d=Object.values(c.data?.delegates??{}).find(p=>p.allowedVerbs?.includes(ue));if(d){let p=d.delegateTjpAddr;if(p){let f=await e.getLatestAddr({addr:p,space:t});if(f){let S=(await e.get({addrs:[f],space:t})).ibGibs?.[0];if(S){let g=await e.getDependencyGraph({ibGibAddr:f,space:t});await e.put({ibGibs:Object.values(g),space:n}),await e.registerNewIbGib({ibGib:S,space:n})}}}}}h(X,"copyIdentitiesToSpace");var ie=null;function ra(){let r=`${N}[initWsTestButton]`,e=document.getElementById("btn-test-ws");if(!e){console.warn(`${r} btn-test-ws not found \u2014 skipping`);return}e.addEventListener("click",()=>{try{if(ie&&ie.readyState===WebSocket.OPEN){ie.send(JSON.stringify({ping:"hello from client",ts:Date.now()})),a("\u2192 sent ping on existing connection");return}let n=`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/api/debug/ws-echo`;a(`\u2192 connecting to ${n}`),ie=new WebSocket(n),ie.addEventListener("open",()=>{a("\u2713 WebSocket connected"),e.textContent="Send WS Ping"}),ie.addEventListener("message",o=>{a(`\u2190 ${o.data}`)}),ie.addEventListener("close",o=>{a(`\u2717 WebSocket closed (code ${o.code})`),e.textContent="Test WebSocket",ie=null}),ie.addEventListener("error",o=>{a("\u2717 WebSocket error \u2014 check console"),console.error(`${r} WebSocket error`,o)})}catch(t){a(`\u2717 ${b(t)}`),console.error(`${r} ${b(t)}`)}})}h(ra,"initWsTestButton");function oa(){let r=document.getElementById("btn-print-dev-state");r&&r.addEventListener("click",()=>{a("Printing debug state to console..."),console.dir(m)})}h(oa,"initPrintStateButton");function ia(){let r=`${N}[initCreateDomainKeystoneButton]`,e=document.getElementById("btn-create-domain-keystone");e&&e.addEventListener("click",async()=>{try{e.disabled=!0,a("Generating dummy Domain Keystone (I)...");let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space found in metaspace.");let o="password",i=await new se().genesis({masterSecret:o,configs:[vt({id:"default",salt:await z(),replenishStrategy:Ne.topUp})],metaspace:t,space:n,frameDetails:{client:"space-gib-web-dev",timestamp:fe()}}),c=u({ibGib:i});a(`\u2713 Local genesis complete: ${c}`),m.domainI=i,m.domainIMasterSecret=o,a("Posting genesis keystone to server...");let d=await new B().postGenesisKeystone(i);if(!d.success){a(`\u2717 Server rejected genesis keystone: ${d.message}`),e.disabled=!1;return}a("\u2713 Server accepted Domain Keystone (I)"),e.textContent="\u2713 Domain Keystone Created";let p=document.getElementById("btn-create-test-ibgib");p&&(p.disabled=!1)}catch(t){a(`\u2717 ${b(t)}`),console.error(`${r} ${b(t)}`),e.disabled=!1}})}h(ia,"initCreateDomainKeystoneButton");function sa(){let r=`${N}[initCreateTestIbGibButton]`,e=document.getElementById("btn-create-test-ibgib");if(!e){console.warn(`${r} btn-create-test-ibgib not found \u2014 skipping`);return}e.addEventListener("click",async()=>{try{a("Generating dummy X^Xtjp ibgib...");let n=(await D.firstGen({parentIbGib:M,ib:"test data",data:{hello:"world",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}})).newIbGib,o=u({ibGib:n});m.targetX=n,a(`\u2713 Created X: ${o}`),e.textContent="\u2713 Test IbGib (X) Created";let s=document.getElementById("btn-create-session-keystone");s&&(s.disabled=!1)}catch(t){a(`\u2717 ${b(t)}`),console.error(`${r} ${b(t)}`)}})}h(sa,"initCreateTestIbGibButton");function ca(){let r=`${N}[initCreateSessionKeystoneButton]`,e=document.getElementById("btn-create-session-keystone");if(!e){console.warn(`${r} btn-create-session-keystone not found \u2014 skipping`);return}e.addEventListener("click",async()=>{try{a("Generating Session Keystone (S^Stjp)...");let t=m.domainI,n=m.targetX;if(!t){a("\u26A0 No domain keystone (I) found in state. Please Create Domain Keystone first.");return}if(!n){a("\u26A0 No target ibgib (X) found in state. Please Create Test IbGib first.");return}let o=await E(),s=await o.getLocalUserSpace({});if(!s)throw new Error("No default space found in metaspace.");let i="ephemeral-"+Math.random().toString(),c=new se;console.warn(`${N}[NAG] placeholder genesis keystone config right now (W: 69b108687cf8bec0f9a8e148bcca8d26)`);let l=await c.genesis({masterSecret:i,configs:[{id:V.DEFAULT_POOL.ID,salt:await z(),type:V.COMMON.TYPE,algo:V.COMMON.ALGO,rounds:V.COMMON.ROUNDS,behavior:{size:V.DEFAULT_POOL.SIZE,replenish:V.COMMON.REPLENISH,selectSequentially:V.DEFAULT_POOL.SELECT_SEQUENTIALLY,selectRandomly:V.DEFAULT_POOL.SELECT_RANDOMLY,targetBindingCount:V.DEFAULT_POOL.TARGET_BINDING_COUNT},allowedVerbs:[]},{id:V.CONNECT_POOL.ID,salt:await z(),type:V.COMMON.TYPE,algo:V.COMMON.ALGO,rounds:V.COMMON.ROUNDS,behavior:{size:V.CONNECT_POOL.SIZE,replenish:V.COMMON.REPLENISH,selectSequentially:V.CONNECT_POOL.SELECT_SEQUENTIALLY,selectRandomly:V.CONNECT_POOL.SELECT_RANDOMLY,targetBindingCount:V.CONNECT_POOL.TARGET_BINDING_COUNT},allowedVerbs:[V.CONNECT_POOL.VERB]}],metaspace:o,space:s,frameDetails:{client:"space-gib-web-session",target_I:t?u({ibGib:t}):void 0,target_X:n?u({ibGib:n}):void 0}}),d=u({ibGib:l});m.sessionS=l,m.sessionSecret=i,a(`\u2713 Created Session Keystone: ${d}`),e.textContent="\u2713 Session Keystone Created"}catch(t){a(`\u2717 ${b(t)}`),console.error(`${r} ${b(t)}`)}})}h(ca,"initCreateSessionKeystoneButton");function da(){let r=document.getElementById("btn-1b-setup");r&&r.addEventListener("click",()=>{ae({phaseText:"1B",btnId:"btn-1b-setup",nextBtnId:"btn-1b-sync",masterSecret:"test-sender-secret-phase1",syncSalt:"senderidentitysyncsaltphase1",manageSalt:"senderidentitymanagesaltphase1",ib:"test data",data:{hello:"world",random:Math.random()}})})}h(da,"init1bSetupButton");function la(){let r=document.getElementById("btn-1b-sync");r&&r.addEventListener("click",()=>{de({phaseText:"1B",btnId:"btn-1b-sync",nextBtnId:"btn-1b-check",expectSyncFailure:!0,failureMessageSuffix:"establish phase successfully run; connection/sync errors expected in 1B"})})}h(la,"init1bSyncButton");function pa(){let r=`${N}[init1bCheckButton]`,e=document.getElementById("btn-1b-check");e&&e.addEventListener("click",async()=>{try{a("1B Check: Asserting cryptographic and durable state expectations from respec...");let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space.");let o=m.domainI,s=m.targetX,i=await t.getLatestAddr({addr:u({ibGib:o}),space:n});if(!i){a("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}a("\u2713 Check: Evolved Domain Keystone (I1) created and stored locally.");let l=(await t.get({addrs:[i],space:n})).ibGibs?.[0];if(!l){a("\u2717 Check: Failed to load I1 from local space.");return}let d=l.data?.proofs?.find(P=>P.claim?.verb==="sync");d?a("\u2713 Check: I1 contains valid sync-verb claim proof."):a("\u2717 Check: I1 is missing sync-verb claim proof!");let p=d?.claim?.target;if(!p){a("\u2717 Check: I1 sync claim does not target a session keystone.");return}a(`\u2713 Check: Sync claim targets session keystone: ${p}`);let y=(await t.get({addrs:[p],space:n})).ibGibs?.[0];if(!y){a("\u2717 Check: Session Keystone (S) NOT found in local space.");return}a("\u2713 Check: Session Keystone (S) successfully created locally.");let S=y.data?.challengePools??[],g=S.some(P=>P.id===ge),w=S.some(P=>P.id===Pe);g&&w?a("\u2713 Check: S contains both connect and sync challenge pools."):a(`\u2717 Check: S is missing challenge pools! (connect: ${g}, sync: ${w})`),a("Check: Verifying registrations on server (receiver metaspace)...");let _=new B,I=!1,A=!1,v=!1,G=u({ibGib:o}),k=await _.getKeystoneGraph(G);if(k.success&&k.graph){let P=k.graph;I=P[G]!==void 0,A=P[i]!==void 0}else a(`\u2717 Check Server: Failed to fetch keystone graph from server: ${k.message}`);let $=await _.getIbGib(G,p);if($.success&&$.ibGib?v=!0:a(`\u2717 Check Server: Failed to fetch session keystone from server: ${$.message}`),I?a("\u2713 Check Server: Genesis Domain Keystone (I) registered on server."):a("\u2717 Check Server: Genesis Domain Keystone (I) missing on server!"),A?a("\u2713 Check Server: Evolved Domain Keystone (I1) accepted and stored on server."):a("\u2717 Check Server: Evolved Domain Keystone (I1) missing on server!"),v?a("\u2713 Check Server: Session Keystone (S) accepted and stored on server."):a("\u2717 Check Server: Session Keystone (S) missing on server!"),I&&A&&v){a("\u{1F389} ALL PHASE 1B ESTABLISH CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 1B All Passed";let P=document.getElementById("btn-2b-setup");P&&(P.disabled=!1)}}catch(t){a(`\u2717 1B Check FAILED: ${b(t)}`),console.error(`${r} 1B Check error:`,t)}})}h(pa,"init1bCheckButton");function ma(){let r=document.getElementById("btn-2b-setup");r&&r.addEventListener("click",()=>{ae({phaseText:"2B",btnId:"btn-2b-setup",nextBtnId:"btn-2b-sync",masterSecret:"test-sender-secret-phase2",syncSalt:"senderidentitysyncsaltphase2",manageSalt:"senderidentitymanagesaltphase2",ib:"test data",data:{hello:"world2",random:Math.random()}})})}h(ma,"init2bSetupButton");function ba(){let r=document.getElementById("btn-2b-sync");r&&r.addEventListener("click",()=>{de({phaseText:"2B",btnId:"btn-2b-sync",nextBtnId:"btn-2b-check",expectSyncFailure:!0,failureMessageSuffix:"connect phase successfully run; subsequent sync errors expected in 2B"})})}h(ba,"init2bSyncButton");function ha(){let r=`${N}[init2bCheckButton]`,e=document.getElementById("btn-2b-check");e&&e.addEventListener("click",async()=>{try{a("2B Check: Asserting cryptographic and WebSocket state expectations...");let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space.");let o=m.domainI,s=u({ibGib:o}),i=await t.getLatestAddr({addr:s,space:n});if(!i){a("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}a("\u2713 Check: Evolved Domain Keystone (I1) created and stored locally.");let l=(await t.get({addrs:[i],space:n})).ibGibs?.[0];if(!l){a("\u2717 Check: Failed to load I1 from local space.");return}let p=l.data?.proofs?.find(v=>v.claim?.verb==="sync")?.claim?.target;if(!p){a("\u2717 Check: I1 sync claim does not target a session keystone.");return}a(`\u2713 Check: Sync claim targets session keystone: ${p}`);let f=await t.getLatestAddr({addr:p,space:n});if(!f){a("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}a("\u2713 Check: Found latest session keystone (S) locally.");let S=(await t.get({addrs:[f],space:n})).ibGibs?.[0];if(!S){a("\u2717 Check: Failed to load latest Session Keystone (S).");return}let g=S.data?.challengePools??[],w=g.find(v=>v.id===ge),_=g.find(v=>v.id===Pe);if(w&&_)a("\u2713 Check: S contains both connect and sync challenge pools.");else{a(`\u2717 Check: S is missing challenge pools! (connect: ${!!w}, sync: ${!!_})`);return}let I=Object.keys(w.challenges).length;if(I===0)a("\u2713 Check: S connect pool successfully depleted (0 challenges remaining).");else{a(`\u2717 Check: S connect pool not depleted! (${I} challenges remaining)`);return}if(m.senderPeer&&m.senderPeer.isSocketOpen)a("\u2713 Check: WebSocket connection is active and OPEN.");else{a("\u2717 Check: WebSocket connection is NOT open or peer is missing!");return}a("\u{1F389} ALL PHASE 2B CONNECT CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 2B All Passed";let A=document.getElementById("btn-3b-setup");A&&(A.disabled=!1)}catch(t){a(`\u2717 2B Check FAILED: ${b(t)}`),console.error(`${r} 2B Check error:`,t)}})}h(ha,"init2bCheckButton");function fa(){let r=document.getElementById("btn-3b-setup");r&&r.addEventListener("click",()=>{ae({phaseText:"3B",btnId:"btn-3b-setup",nextBtnId:"btn-3b-sync",masterSecret:"test-sender-secret-phase3",syncSalt:"senderidentitysyncsaltphase3",manageSalt:"senderidentitymanagesaltphase3",ib:"test data 3b",data:{hello:"world3",random:Math.random()}})})}h(fa,"init3bSetupButton");function ua(){let r=document.getElementById("btn-3b-sync");r&&r.addEventListener("click",()=>{de({phaseText:"3B",btnId:"btn-3b-sync",nextBtnId:"btn-3b-check"})})}h(ua,"init3bSyncButton");function ga(){let r=`${N}[init3bCheckButton]`,e=document.getElementById("btn-3b-check");e&&e.addEventListener("click",async()=>{try{a("3B Check: Asserting cryptographic and WebSocket state expectations...");let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space.");let o=m.domainI,s=m.targetX,i=u({ibGib:s}),c=u({ibGib:o}),l=await t.getLatestAddr({addr:i,space:n});if(!l){a("\u2717 Check: Evolved target X NOT found in local space!");return}a(`\u2713 Check: Evolved target X found locally at: ${l}`);let d=await t.getDependencyGraph({ibGibAddr:l,space:n});if(!d||Object.keys(d).length===0){a("\u2717 Check: Failed to load target X dependency graph locally.");return}a(`\u2713 Check: Target X local graph loaded (${Object.keys(d).length} nodes).`);let p=new B,f=await p.getIbGibGraph(c,i,!0);if(!f.success||!f.graph){a(`\u2717 Check: Failed to fetch target X graph from server: ${f.message}`);return}let y=f.graph;if(a(`\u2713 Check: Target X server graph loaded (${Object.keys(y).length} nodes).`),W({graphA:d,graphB:y}))a("\u2713 Check: Target X dependency graphs are equivalent on client and server.");else{a("\u2717 Check: Target X dependency graphs mismatch between client and server!");return}let g=await t.getLatestAddr({addr:c,space:n});if(!g){a("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}a("\u2713 Check: Evolved Domain Keystone (I1) exists locally.");let _=(await t.get({addrs:[g],space:n})).ibGibs?.[0];if(!_){a("\u2717 Check: Failed to load I1 from local space.");return}let A=_.data?.proofs?.find(H=>H.claim?.verb==="sync")?.claim?.target;if(!A){a("\u2717 Check: I1 sync claim does not target a session keystone.");return}let v=await p.getIbGib(c,g);if(!v.success||!v.ibGib){a("\u2717 Check: Evolved Domain Keystone (I1) NOT found on server!");return}a("\u2713 Check: Evolved Domain Keystone (I1) exists on server.");let G=await t.getLatestAddr({addr:A,space:n});if(!G){a("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}a(`\u2713 Check: Found latest session keystone (S) locally: ${G}`);let $=(await t.get({addrs:[G],space:n})).ibGibs?.[0];if(!$){a("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let P=$.data?.n;a(`\u2713 Check: S tip evolved to n = ${P}.`),P!==3&&P!==4&&a(`\u26A0 Check: Expected S to evolve to n = 3 or 4, got n = ${P}. Continuing anyway...`);let O=await p.getIbGib(c,G);if(!O.success||!O.ibGib){a("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}a("\u2713 Check: Latest Session Keystone (S) exists on server.");let K=await t.getDependencyGraph({ibGibAddr:G,space:n}),F=await p.getIbGibGraph(c,A,!0);if(!F.success||!F.graph){a(`\u2717 Check: Failed to fetch session S graph from server: ${F.message}`);return}let U=F.graph;if(W({graphA:K,graphB:U}))a("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{a("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}a("\u{1F389} ALL PHASE 3B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 3B All Passed"}catch(t){a(`\u2717 3B Check FAILED: ${b(t)}`),console.error(`${r} 3B Check error:`,t)}})}h(ga,"init3bCheckButton");function ya(){let r=document.getElementById("btn-4-1b-setup");r&&r.addEventListener("click",()=>{ae({phaseText:"4.1B",btnId:"btn-4-1b-setup",nextBtnId:"btn-4-1b-sync",masterSecret:"test-sender-secret-phase4-1",syncSalt:"senderidentitysyncsaltphase4-1",manageSalt:"senderidentitymanagesaltphase4-1",ib:"test data 4.1b",data:{hello:"world4_1",random:Math.random()}})})}h(ya,"init4_1bSetupButton");function Sa(){let r=document.getElementById("btn-4-1b-sync");r&&r.addEventListener("click",()=>{de({phaseText:"4.1B",btnId:"btn-4-1b-sync",nextBtnId:"btn-4-1b-check"})})}h(Sa,"init4_1bSyncButton");function wa(){let r=`${N}[init4_1bCheckButton]`,e=document.getElementById("btn-4-1b-check");e&&e.addEventListener("click",async()=>{try{a("4.1B Check: Asserting cryptographic and WebSocket state expectations...");let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space.");let o=m.domainI,s=m.targetX,i=u({ibGib:s}),c=u({ibGib:o}),l=await t.getLatestAddr({addr:i,space:n});if(!l){a("\u2717 Check: Evolved target X NOT found in local space!");return}a(`\u2713 Check: Evolved target X found locally at: ${l}`);let d=await t.getDependencyGraph({ibGibAddr:l,space:n});if(!d||Object.keys(d).length===0){a("\u2717 Check: Failed to load target X dependency graph locally.");return}a(`\u2713 Check: Target X local graph loaded (${Object.keys(d).length} nodes).`);let p=new B,f=await p.getIbGibGraph(c,i,!0);if(!f.success||!f.graph){a(`\u2717 Check: Failed to fetch target X graph from server: ${f.message}`);return}let y=f.graph;if(a(`\u2713 Check: Target X server graph loaded (${Object.keys(y).length} nodes).`),W({graphA:d,graphB:y}))a("\u2713 Check: Target X dependency graphs are equivalent on client and server.");else{a("\u2717 Check: Target X dependency graphs mismatch between client and server!");return}let g=await t.getLatestAddr({addr:c,space:n});if(!g){a("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}a("\u2713 Check: Evolved Domain Keystone (I1) exists locally.");let _=(await t.get({addrs:[g],space:n})).ibGibs?.[0];if(!_){a("\u2717 Check: Failed to load I1 from local space.");return}let{latestLocalDelegateAddr:I,sessionIdentityTjpAddr:A}=await rt({localI:_,metaspace:t,space:n});if(!I){a("\u2717 Check: Evolved delegate keystone tip NOT found in local space!");return}if(!A){a("\u2717 Check: Delegate sync claim does not target a session keystone.");return}a("\u2713 Check: Delegate Keystone and Sync Claim to Session verified locally.");let v=await p.getIbGib(c,I);if(!v.success||!v.ibGib){a("\u2717 Check: Evolved Delegate Keystone NOT found on server!");return}a("\u2713 Check: Evolved Delegate Keystone exists on server.");let G=await p.getIbGib(c,g);if(!G.success||!G.ibGib){a("\u2717 Check: Evolved Domain Keystone (I1) NOT found on server!");return}a("\u2713 Check: Evolved Domain Keystone (I1) exists on server.");let k=await t.getLatestAddr({addr:A,space:n});if(!k){a("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}a(`\u2713 Check: Found latest session keystone (S) locally: ${k}`);let P=(await t.get({addrs:[k],space:n})).ibGibs?.[0];if(!P){a("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let O=P.data?.n;a(`\u2713 Check: S tip evolved to n = ${O}.`),O!==3&&O!==4&&a(`\u26A0 Check: Expected S to evolve to n = 3 or 4, got n = ${O}. Continuing anyway...`);let K=await p.getIbGib(c,k);if(!K.success||!K.ibGib){a("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}a("\u2713 Check: Latest Session Keystone (S) exists on server.");let F=await t.getDependencyGraph({ibGibAddr:k,space:n}),U=await p.getIbGibGraph(c,A,!0);if(!U.success||!U.graph){a(`\u2717 Check: Failed to fetch session S graph from server: ${U.message}`);return}let j=U.graph;if(W({graphA:F,graphB:j}))a("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{a("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}a("\u{1F389} ALL PHASE 4.1B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.1B All Passed"}catch(t){a(`\u2717 4.1B Check FAILED: ${b(t)}`),console.error(`${r} 4.1B Check error:`,t)}})}h(wa,"init4_1bCheckButton");function _a(){let r=document.getElementById("btn-4-2b-setup");r&&r.addEventListener("click",()=>{ae({phaseText:"4.2B",btnId:"btn-4-2b-setup",nextBtnId:"btn-4-2b-sync",masterSecret:"test-sender-secret-phase4-2",syncSalt:"senderidentitysyncsaltphase4-2",manageSalt:"senderidentitymanagesaltphase4-2",ib:"dummy target 4.2b",data:{hello:"dummy"}})})}h(_a,"init4_2bSetupButton");async function Dn(){let r=`${N}[performPhaseSync4_2b]`,e=document.getElementById("btn-4-2b-sync");if(e)try{if(e.disabled=!0,a("4.2B Sync: Creating Constants and executing three-pass WebSocket Sync..."),!m.domainI){a("\u26A0 4.2B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space.");let o=await D.constant({parentPrimitiveIb:"root",ib:"constant_c1_"+(await z()).slice(0,8),data:{some:"data_4_2b",random:Math.random()}}),s=u({ibGib:o});await t.put({ibGib:o,space:n}),await t.registerNewIbGib({ibGib:o}),m.targetC1=o,a(`4.2B Sync: \u2713 Constant C1 created: ${s}`),a("4.2B Sync: Starting Pass 1 (Sync C1)..."),await x({domainIbGibs:[o],passLabel:"Pass 1 (Sync C1)",metaspace:t,space:n}),a("4.2B Sync: \u2713 Pass 1 Complete."),a("4.2B Sync: Starting Pass 2 (Sync C1 - Idempotent)..."),await x({domainIbGibs:[o],passLabel:"Pass 2 (Sync C1 idempotent)",metaspace:t,space:n}),a("4.2B Sync: \u2713 Pass 2 Complete.");let i=await D.constant({ib:"constant_c2_"+(await z()).slice(0,8),parentPrimitiveIb:"root",rel8ns:{link:[s]}}),c=u({ibGib:i});await t.put({ibGib:i,space:n}),await t.registerNewIbGib({ibGib:i}),m.targetC2=i,a(`4.2B Sync: \u2713 Constant C2 created linking to C1: ${c}`),a("4.2B Sync: Starting Pass 3 (Sync C2)..."),await x({domainIbGibs:[i],passLabel:"Pass 3 (Sync C2)",metaspace:t,space:n}),a("4.2B Sync: \u2713 Pass 3 Complete."),a("\u2713 4.2B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.2B Sync Run";let l=document.getElementById("btn-4-2b-check");l&&(l.disabled=!1)}catch(t){a(`\u2717 4.2B Sync FAILED: ${b(t)}`),console.error(`${r} 4.2B Sync error:`,t),e.disabled=!1}}h(Dn,"performPhaseSync4_2b");function Ea(){let r=document.getElementById("btn-4-2b-sync");r&&r.addEventListener("click",()=>{Dn()})}h(Ea,"init4_2bSyncButton");function Ia(){let r=`${N}[init4_2bCheckButton]`,e=document.getElementById("btn-4-2b-check");e&&e.addEventListener("click",async()=>{try{a("4.2B Check: Asserting cryptographic and WebSocket state expectations...");let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space.");let o=m.domainI,s=m.targetC1,i=m.targetC2,c=u({ibGib:s}),l=u({ibGib:i}),d=u({ibGib:o}),p=new B,f=await t.get({addrs:[c],space:n}),y=await t.get({addrs:[l],space:n});if(!f.success||!f.ibGibs?.[0]){a("\u2717 Check: Constant C1 NOT found locally.");return}if(!y.success||!y.ibGibs?.[0]){a("\u2717 Check: Constant C2 NOT found locally.");return}a("\u2713 Check: Constants C1 and C2 exist locally.");let S=await p.getIbGib(d,c),g=await p.getIbGib(d,l);if(!S.success||!S.ibGib){a(`\u2717 Check: Constant C1 NOT found on server: ${S.message}`);return}if(!g.success||!g.ibGib){a(`\u2717 Check: Constant C2 NOT found on server: ${g.message}`);return}a("\u2713 Check: Constants C1 and C2 exist on server.");let w=await t.getDependencyGraph({ibGibAddr:l,space:n}),_=await p.getIbGibGraph(d,l,!0);if(!_.success||!_.graph){a(`\u2717 Check: Failed to fetch C2 graph from server: ${_.message}`);return}if(!W({graphA:w,graphB:_.graph})){a("\u2717 Check: C2 dependency graphs mismatch between client and server!");return}a("\u2713 Check: C2 dependency graphs are equivalent on client and server.");let I=await t.getLatestAddr({addr:d,space:n});if(!I){a("\u2717 Check: Domain keystone tip not found locally!");return}let v=(await t.get({addrs:[I],space:n})).ibGibs?.[0];if(!v){a("\u2717 Check: Failed to load domain keystone!");return}let G=v.data?.n;if(a(`\u2713 Check: Evolved I tip is at n = ${G}.`),G!==1){a(`\u2717 Check: Expected I to evolve to n = 1 (delegate registration only), got n = ${G}.`);return}let{sessionIdentityTjpAddr:k}=await Ee({localI:v,metaspace:t,space:n,apiBridge:p,domainAddr:d}),$=await t.getLatestAddr({addr:k,space:n});if(!$){a("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}a(`\u2713 Check: Found latest session keystone (S) locally: ${$}`);let O=(await t.get({addrs:[$],space:n})).ibGibs?.[0];if(!O){a("\u2717 Check: Failed to load Session Keystone (S) locally.");return}let K=O.data?.n;if(a(`\u2713 Check: Latest session S tip evolved to n = ${K}.`),K!==3){a(`\u2717 Check: Expected latest session S to evolve to n = 3 (connect+sync+disconnect), got n = ${K}.`);return}let F=await p.getIbGib(d,$);if(!F.success||!F.ibGib){a("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}a("\u2713 Check: Latest Session Keystone (S) exists on server.");let U=await t.getDependencyGraph({ibGibAddr:$,space:n}),j=await p.getIbGibGraph(d,k,!0);if(!j.success||!j.graph){a(`\u2717 Check: Failed to fetch session S graph from server: ${j.message}`);return}if(!W({graphA:U,graphB:j.graph})){a("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}a("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server."),a("\u{1F389} ALL PHASE 4.2B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.2B All Passed"}catch(t){a(`\u2717 4.2B Check FAILED: ${b(t)}`),console.error(`${r} 4.2B Check error:`,t)}})}h(Ia,"init4_2bCheckButton");function va(){let r=document.getElementById("btn-4-3b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.3B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1...");let e=await E(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=new B;await q({masterSecret:"test-sender-secret-phase4-3",syncSalt:"senderidentitysyncsaltphase4-3",manageSalt:"senderidentitymanagesaltphase4-3",metaspace:e,space:t,apiBridge:n,phaseText:"4.3B"});let o=await D.firstGen({parentIbGib:M,ib:"timeline_root_partial_4_3b",data:{type:"root",label:"Root4_3b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),s=o.newIbGib;await e.persistTransformResult({resTransform:o,space:t}),await e.registerNewIbGib({ibGib:s});let i=await T({timeline:s,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_3b"}},metaspace:e,space:t});m.targetC1=i,m.targetX=i,a(`4.3B Setup: \u2713 Timeline V0 -> V1 created and stored locally. V1: ${u({ibGib:i})}`),a("\u2713 4.3B Setup Complete! Ready for 4.3B Sync."),r.textContent="\u2713 4.3B Setup Complete";let c=document.getElementById("btn-4-3b-sync");c&&(c.disabled=!1)}catch(e){a(`\u2717 4.3B Setup FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(va,"init4_3bSetupButton");async function Vn(){let r=`${N}[performPhaseSync4_3b]`,e=document.getElementById("btn-4-3b-sync");if(e)try{e.disabled=!0;let t=m.targetX;if(!m.domainI||!t){a("\u26A0 4.3B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let n=await E(),o=await n.getLocalUserSpace({});if(!o)throw new Error("No default space.");a("4.3B Sync: Starting Pass 1 (Sync V1 to server)..."),await x({domainIbGibs:[t],passLabel:"Pass 1 (Sync V1)",metaspace:n,space:o}),a("4.3B Sync: \u2713 Pass 1 Complete (V1 synced)."),a("4.3B Sync: Mutating V1 to V2 locally...");let s=await T({timeline:t,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_3b"}},metaspace:n,space:o});m.targetX=s,a(`4.3B Sync: \u2713 V2 created locally: ${u({ibGib:s})}`),a("4.3B Sync: Starting Pass 2 (Sync V2 delta to server)..."),await x({domainIbGibs:[s],passLabel:"Pass 2 (Sync V2)",metaspace:n,space:o}),a("4.3B Sync: \u2713 Pass 2 Complete (V2 synced)."),a("\u2713 4.3B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.3B Sync Run";let i=document.getElementById("btn-4-3b-check");i&&(i.disabled=!1)}catch(t){a(`\u2717 4.3B Sync FAILED: ${b(t)}`),console.error(t),e.disabled=!1}}h(Vn,"performPhaseSync4_3b");function Ga(){let r=document.getElementById("btn-4-3b-sync");r&&r.addEventListener("click",()=>{Vn()})}h(Ga,"init4_3bSyncButton");function Ca(){let r=`${N}[init4_3bCheckButton]`,e=document.getElementById("btn-4-3b-check");e&&e.addEventListener("click",async()=>{try{a("4.3B Check: Asserting cryptographic and WebSocket state expectations...");let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space.");let o=m.domainI,s=m.targetC1,i=m.targetX,c=u({ibGib:s}),l=u({ibGib:i}),d=u({ibGib:o}),p=new B,f=await t.get({addrs:[c],space:n}),y=await t.get({addrs:[l],space:n});if(!f.success||!f.ibGibs?.[0]){a("\u2717 Check: Timeline frame V1 NOT found locally.");return}if(!y.success||!y.ibGibs?.[0]){a("\u2717 Check: Timeline frame V2 NOT found locally.");return}a("\u2713 Check: Timeline frames V1 and V2 exist locally.");let S=await p.getIbGib(d,l);if(!S.success||!S.ibGib){a(`\u2717 Check: Timeline frame V2 NOT found on server: ${S.message}`);return}a("\u2713 Check: Timeline frame V2 exists on server.");let g=S.ibGib.rel8ns?.past?.at(-1);if(g===c)a("\u2713 Check: Server V2 correctly references V1 in its past relation.");else{a(`\u2717 Check: Server V2 does not reference V1 in past relation! got: ${g}`);return}let w=await t.getDependencyGraph({ibGibAddr:l,space:n}),_=await p.getIbGibGraph(d,l,!0);if(!_.success||!_.graph){a(`\u2717 Check: Failed to fetch V2 graph from server: ${_.message}`);return}if(!W({graphA:w,graphB:_.graph})){a("\u2717 Check: V2 timeline dependency graphs mismatch between client and server!");return}a("\u2713 Check: V2 timeline dependency graphs are equivalent on client and server.");let I=await t.getLatestAddr({addr:d,space:n});if(!I){a("\u2717 Check: Domain keystone tip not found locally!");return}let v=(await t.get({addrs:[I],space:n})).ibGibs?.[0];if(!v){a("\u2717 Check: Failed to load domain keystone!");return}let G=v.data?.n;if(a(`\u2713 Check: Evolved I tip is at n = ${G}.`),G!==1){a(`\u2717 Check: Expected I to evolve to n = 1 (delegate registration only), got n = ${G}.`);return}let{sessionIdentityTjpAddr:k}=await Ee({localI:v,metaspace:t,space:n,apiBridge:p,domainAddr:d}),$=await t.getLatestAddr({addr:k,space:n});if(!$){a("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}a(`\u2713 Check: Found latest session keystone (S) locally: ${$}`);let O=(await t.get({addrs:[$],space:n})).ibGibs?.[0];if(!O){a("\u2717 Check: Failed to load Session Keystone (S) locally.");return}let K=O.data?.n;if(a(`\u2713 Check: Latest session S tip evolved to n = ${K}.`),K!==3){a(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${K}.`);return}let F=await p.getIbGib(d,$);if(!F.success||!F.ibGib){a("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}a("\u2713 Check: Latest Session Keystone (S) exists on server.");let U=await t.getDependencyGraph({ibGibAddr:$,space:n}),j=await p.getIbGibGraph(d,k,!0);if(!j.success||!j.graph){a(`\u2717 Check: Failed to fetch session S graph from server: ${j.message}`);return}if(!W({graphA:U,graphB:j.graph})){a("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}a("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server."),a("\u{1F389} ALL PHASE 4.3B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.3B All Passed"}catch(t){a(`\u2717 4.3B Check FAILED: ${b(t)}`),console.error(`${r} 4.3B Check error:`,t)}})}h(Ca,"init4_3bCheckButton");function Ba(){let r=document.getElementById("btn-4-4b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.4B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1 -> V2...");let e=await E(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=new B;await q({masterSecret:"test-sender-secret-phase4-4",syncSalt:"senderidentitysyncsaltphase4-4",manageSalt:"senderidentitymanagesaltphase4-4",metaspace:e,space:t,apiBridge:n,phaseText:"4.4B"});let o=await D.firstGen({parentIbGib:M,ib:"timeline_root_deep_4_4b",data:{type:"root",label:"Root4_4b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),s=o.newIbGib;await e.persistTransformResult({resTransform:o,space:t}),await e.registerNewIbGib({ibGib:s}),m.targetC1=s;let i=await T({timeline:s,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_4b"}},metaspace:e,space:t});m.targetC2=i;let c=await T({timeline:i,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_4b"}},metaspace:e,space:t});m.targetX=c,a(`4.4B Setup: \u2713 Timeline V0 -> V1 -> V2 created locally. V2 Tip: ${u({ibGib:c})}`),a("\u2713 4.4B Setup Complete! Ready for 4.4B Sync."),r.textContent="\u2713 4.4B Setup Complete";let l=document.getElementById("btn-4-4b-sync");l&&(l.disabled=!1)}catch(e){a(`\u2717 4.4B Setup FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Ba,"init4_4bSetupButton");async function Mn(){let r=`${N}[performPhaseSync4_4b]`,e=document.getElementById("btn-4-4b-sync");if(e)try{e.disabled=!0,a("4.4B Sync: Initiating WebSocket Sync of V2 Tip...");let t=m.targetX;if(!m.domainI||!t){a("\u26A0 4.4B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let n=await E(),o=await n.getLocalUserSpace({});if(!o)throw new Error("No default space.");await x({domainIbGibs:[t],passLabel:"Pass 1 (Sync V2 tip)",metaspace:n,space:o}),a("4.4B Sync: \u2713 WebSocket Sync completed."),a("\u2713 4.4B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.4B Sync Run";let s=document.getElementById("btn-4-4b-check");s&&(s.disabled=!1)}catch(t){a(`\u2717 4.4B Sync FAILED: ${b(t)}`),console.error(t),e.disabled=!1}}h(Mn,"performPhaseSync4_4b");function Aa(){let r=document.getElementById("btn-4-4b-sync");r&&r.addEventListener("click",()=>{Mn()})}h(Aa,"init4_4bSyncButton");function ka(){let r=`${N}[init4_4bCheckButton]`,e=document.getElementById("btn-4-4b-check");e&&e.addEventListener("click",async()=>{try{a("4.4B Check: Asserting cryptographic and WebSocket state expectations...");let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space.");let o=m.domainI,s=m.targetC1,i=m.targetC2,c=m.targetX,l=u({ibGib:s}),d=u({ibGib:i}),p=u({ibGib:c}),f=u({ibGib:o}),y=new B,S=await t.get({addrs:[l],space:n}),g=await t.get({addrs:[d],space:n}),w=await t.get({addrs:[p],space:n});if(!S.success||!S.ibGibs?.[0]){a("\u2717 Check: Timeline frame V0 NOT found locally.");return}if(!g.success||!g.ibGibs?.[0]){a("\u2717 Check: Timeline frame V1 NOT found locally.");return}if(!w.success||!w.ibGibs?.[0]){a("\u2717 Check: Timeline frame V2 NOT found locally.");return}a("\u2713 Check: Timeline frames V0, V1, and V2 exist locally.");let _=await y.getIbGib(f,p);if(!_.success||!_.ibGib){a(`\u2717 Check: Timeline frame V2 NOT found on server: ${_.message}`);return}a("\u2713 Check: Timeline frame V2 exists on server.");let I=_.ibGib.rel8ns?.past?.at(-1);if(I===d)a("\u2713 Check: Server V2 correctly references V1 in its past relation.");else{a(`\u2717 Check: Server V2 does not reference V1 in past relation! got: ${I}`);return}let A=await y.getIbGib(f,d);if(!A.success||!A.ibGib){a(`\u2717 Check: Timeline frame V1 NOT found on server: ${A.message}`);return}a("\u2713 Check: Timeline frame V1 exists on server.");let v=A.ibGib.rel8ns?.past?.at(-1);if(v===l)a("\u2713 Check: Server V1 correctly references V0 in its past relation.");else{a(`\u2717 Check: Server V1 does not reference V0 in past relation! got: ${v}`);return}let G=await t.getDependencyGraph({ibGibAddr:p,space:n}),k=await y.getIbGibGraph(f,p,!0);if(!k.success||!k.graph){a(`\u2717 Check: Failed to fetch V2 graph from server: ${k.message}`);return}if(!W({graphA:G,graphB:k.graph})){a("\u2717 Check: V2 timeline dependency graphs mismatch between client and server!");return}a("\u2713 Check: V2 timeline dependency graphs are equivalent on client and server.");let $=await t.getLatestAddr({addr:f,space:n});if(!$){a("\u2717 Check: Domain keystone tip not found locally!");return}let O=(await t.get({addrs:[$],space:n})).ibGibs?.[0];if(!O){a("\u2717 Check: Failed to load domain keystone!");return}a(`\u2713 Check: Evolved Domain Keystone exists locally: ${$}`);let K=O.data?.n;if(a(`\u2713 Check: Evolved I tip is at n = ${K}.`),K!==1){a(`\u2717 Check: Expected I to evolve to n = 1, got n = ${K}.`);return}let{sessionIdentityTjpAddr:F}=await Ee({localI:O,metaspace:t,space:n,apiBridge:y,domainAddr:f}),U=await t.getLatestAddr({addr:F,space:n});if(!U){a("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}a(`\u2713 Check: Found latest session keystone (S) locally: ${U}`);let H=(await t.get({addrs:[U],space:n})).ibGibs?.[0];if(!H){a("\u2717 Check: Failed to load Session Keystone (S) locally.");return}let Q=H.data?.n;if(a(`\u2713 Check: Latest session S tip evolved to n = ${Q}.`),Q!==3){a(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${Q}.`);return}let be=await y.getIbGib(f,U);if(!be.success||!be.ibGib){a("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}a("\u2713 Check: Latest Session Keystone (S) exists on server.");let We=await t.getDependencyGraph({ibGibAddr:U,space:n}),he=await y.getIbGibGraph(f,F,!0);if(!he.success||!he.graph){a(`\u2717 Check: Failed to fetch session S graph from server: ${he.message}`);return}if(!W({graphA:We,graphB:he.graph})){a("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}a("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server."),a("\u{1F389} ALL PHASE 4.4B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.4B All Passed"}catch(t){a(`\u2717 4.4B Check FAILED: ${b(t)}`),console.error(`${r} 4.4B Check error:`,t)}})}h(ka,"init4_4bCheckButton");var $a={},Ta="test-sender-secret-phase4-5b";function La(){let r=document.getElementById("btn-4-5b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.5B Setup: Generating Domain Keystone (I), target timeline, and seeding server from two spaces...");let e=await E(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=new B;await q({masterSecret:Ta,syncSalt:"senderidentitysyncsaltphase4-5b",manageSalt:"senderidentitymanagesaltphase4-5b",metaspace:e,space:t,apiBridge:n,phaseText:"4.5B"});let o=await D.firstGen({parentIbGib:M,ib:"timeline_root_partial_4_5b",data:{type:"root",label:"Root4_5b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),s=o.newIbGib;await e.persistTransformResult({resTransform:o,space:t}),await e.registerNewIbGib({ibGib:s,space:t});let i=await T({timeline:s,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_5b"}},metaspace:e,space:t});m.targetC1=i,a(`4.5B Setup: \u2713 Local timeline V0 -> V1 created. V1 Tip: ${u({ibGib:i})}`),a("4.5B Setup: Seeding V1 to the server via WebSocket..."),await x({domainIbGibs:[i],passLabel:"Seed V1 to server",metaspace:e,space:t}),a("4.5B Setup: \u2713 Pass 1 Sync (V1 to server) complete."),a('4.5B Setup: Creating secondary local space simulating "remote" client...');let c=`remote-${await z()}`,l=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:c,getFnPrompt:e.getFnPrompt}});if(!l)throw new Error("Failed to create remote space");await l.initialized;let d=await e.getDependencyGraph({ibGibAddr:u({ibGib:i}),space:t});await e.put({ibGibs:Object.values(d),space:l}),await e.registerNewIbGib({ibGib:i,space:l});let p=m.domainI;await X({domainI:p,metaspace:e,fromSpace:t,toSpace:l}),a("4.5B Setup: \u2713 Copied V1 and identities (domain and delegate) to remoteSpace."),a("4.5B Setup: Mutating V1 -> V2 in remoteSpace...");let f=await T({timeline:i,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_5b"}},metaspace:e,space:l});$a.targetV2=f,a(`4.5B Setup: \u2713 Mutated to V2 in remoteSpace: ${u({ibGib:f})}`),a("4.5B Setup: Syncing V2 from remoteSpace to the server..."),await J({domainIbGibs:[f],passLabel:"Seed V2 from remoteSpace",metaspace:e,space:l,primarySpace:t,domainI:p,masterSecret:Ta}),a("4.5B Setup: \u2713 Pass 2 Sync (V2 to server) complete. debugState.domainI updated."),a("\u2713 4.5B Setup Complete! Server has V2, default local space has V1. Ready for 4.5B Sync."),r.textContent="\u2713 4.5B Setup Complete";let y=document.getElementById("btn-4-5b-sync");y&&(y.disabled=!1)}catch(e){a(`\u2717 4.5B Setup FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(La,"init4_5bSetupButton");function Ra(){let r=document.getElementById("btn-4-5b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.5B Sync: Initiating WebSocket Sync from default local space (which has V1, server has V2)...");let e=m.targetC1;if(!m.domainI||!e){a("\u26A0 4.5B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space.");await x({domainIbGibs:[e],passLabel:"Pull V2 from server",metaspace:t,space:n}),a("\u2713 4.5B Sync Execution Complete! Ready for 4.5B Check."),r.textContent="\u2713 4.5B Sync Run";let o=document.getElementById("btn-4-5b-check");o&&(o.disabled=!1)}catch(e){a(`\u2717 4.5B Sync FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Ra,"init4_5bSyncButton");function Na(){let r=document.getElementById("btn-4-5b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.5B Check: Verifying that V2 was pulled down to default local space...");let e=$a.targetV2;if(!e||!m.domainI){a("\u26A0 4.5B Check: Missing target V2 in state. Did Setup run?"),r.disabled=!1;return}let t=u({ibGib:e}),n=u({ibGib:m.domainI}),o=await E(),s=await o.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=await o.get({addr:t,space:s});if(!i.success||i.ibGibs?.length!==1)throw new Error(`V2 tip (${t}) is NOT present in local space!`);let c=i.ibGibs[0];a(`4.5B Check: \u2713 V2 Tip found locally. Label: "${c.data?.label}"`);let l=await o.getDependencyGraph({ibGibAddr:t,space:s});a("4.5B Check: Fetching V2 dependency graph from server...");let p=await new B().getIbGibGraph(n,t,!0);if(!p.success||!p.graph)throw new Error(`Failed to fetch V2 graph from server: ${p.message}`);if(W({graphA:l,graphB:p.graph}))a("\u2713 4.5B Check SUCCESS: V2 and all dependencies are fully equivalent on client and server!"),r.textContent="\u2713 4.5B Check Success";else throw new Error("Dependency graphs on local space and server are NOT equivalent.")}catch(e){a(`\u2717 4.5B Check FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Na,"init4_5bCheckButton");var Ie={},Fn="test-sender-secret-phase4-6b";function Pa(){let r=document.getElementById("btn-4-6b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.6B Setup: Generating Domain Keystone (I) and two independent target timelines (Alpha and Beta)...");let e=await E(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=new B;await q({masterSecret:Fn,syncSalt:"senderidentitysyncsaltphase4-6b",manageSalt:"senderidentitymanagesaltphase4-6b",metaspace:e,space:t,apiBridge:n,phaseText:"4.6B"});let o=await D.firstGen({parentIbGib:M,ib:"timeline_root_alpha_4_6b",data:{type:"root",label:"Alpha4_6b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),s=o.newIbGib;await e.persistTransformResult({resTransform:o,space:t}),await e.registerNewIbGib({ibGib:s,space:t});let i=await T({timeline:s,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"A1_4_6b"}},metaspace:e,space:t});Ie.targetAlphaV1=i,m.targetC1=i,a(`4.6B Setup: \u2713 Local Timeline A created. A1 Tip: ${u({ibGib:i})}`);let c=await D.firstGen({parentIbGib:M,ib:"timeline_root_beta_4_6b",data:{type:"root",label:"Beta4_6b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),l=c.newIbGib;await e.persistTransformResult({resTransform:c,space:t}),await e.registerNewIbGib({ibGib:l,space:t});let d=await T({timeline:l,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"B1_4_6b"}},metaspace:e,space:t}),p=await T({timeline:d,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"B2_4_6b"}},metaspace:e,space:t});Ie.targetBetaV2=p,m.targetC2=p,a(`4.6B Setup: \u2713 Local Timeline B created. B2 Tip: ${u({ibGib:p})}`),a("\u2713 4.6B Setup Complete! Timelines created locally. Ready for 4.6B Sync."),r.textContent="\u2713 4.6B Setup Complete";let f=document.getElementById("btn-4-6b-sync");f&&(f.disabled=!1)}catch(e){a(`\u2717 4.6B Setup FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Pa,"init4_6bSetupButton");function Oa(){let r=document.getElementById("btn-4-6b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.6B Sync: Initiating WebSocket Sync for both Timeline A and Timeline B in one call...");let e=Ie.targetAlphaV1,t=Ie.targetBetaV2;if(!m.domainI||!e||!t){a("\u26A0 4.6B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let n=await E(),o=await n.getLocalUserSpace({});if(!o)throw new Error("No default space.");await x({domainIbGibs:[e,t],passLabel:"Sync Alpha A1 + Beta B2",metaspace:n,space:o}),a("\u2713 4.6B Sync Execution Complete! Ready for 4.6B Check."),r.textContent="\u2713 4.6B Sync Run";let s=document.getElementById("btn-4-6b-check");s&&(s.disabled=!1)}catch(e){a(`\u2717 4.6B Sync FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Oa,"init4_6bSyncButton");function xa(){let r=document.getElementById("btn-4-6b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.6B Check: Verifying both Timeline A and Timeline B exist on the server with matching dependency graphs...");let e=Ie.targetAlphaV1,t=Ie.targetBetaV2;if(!m.domainI||!e||!t){a("\u26A0 4.6B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let n=u({ibGib:m.domainI}),o=u({ibGib:e}),s=u({ibGib:t}),i=await E(),c=await i.getLocalUserSpace({});if(!c)throw new Error("No default space.");let l=new B;a("4.6B Check: Fetching Timeline A dependency graph from server...");let d=await l.getIbGibGraph(n,o,!0);if(!d.success||!d.graph)throw new Error(`Failed to fetch Timeline A graph from server: ${d.message}`);let p=await i.getDependencyGraph({ibGibAddr:o,space:c});if(!W({graphA:p,graphB:d.graph}))throw new Error("Timeline A dependency graphs on local space and server are NOT equivalent.");a("4.6B Check: \u2713 Timeline A graphs are equivalent."),a("4.6B Check: Fetching Timeline B dependency graph from server...");let f=await l.getIbGibGraph(n,s,!0);if(!f.success||!f.graph)throw new Error(`Failed to fetch Timeline B graph from server: ${f.message}`);let y=await i.getDependencyGraph({ibGibAddr:s,space:c});if(!W({graphA:y,graphB:f.graph}))throw new Error("Timeline B dependency graphs on local space and server are NOT equivalent.");a("4.6B Check: \u2713 Timeline B graphs are equivalent."),a("\u2713 4.6B Check SUCCESS: Both independent timelines are fully synced and identical on client and server!"),r.textContent="\u2713 4.6B Check Success"}catch(e){a(`\u2717 4.6B Check FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(xa,"init4_6bCheckButton");var pe={},Da="test-sender-secret-phase4-7b";function Va(){let r=document.getElementById("btn-4-7b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.7B Setup: Setting up identities, seeding history, and creating divergent branches...");let e=await E(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=new B;await q({masterSecret:Da,syncSalt:"senderidentitysyncsaltphase4-7b",manageSalt:"senderidentitymanagesaltphase4-7b",metaspace:e,space:t,apiBridge:n,phaseText:"4.7B"});let o=m.domainI,s=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_7b",getFnPrompt:e.getFnPrompt}});await s.initialized,await e.put({ibGib:o,space:s}),await e.registerNewIbGib({ibGib:o,space:s});let i=await D.firstGen({parentIbGib:M,ib:"timeline_root_conflict_4_7b",data:{type:"root",label:"CommonRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c,space:t}),pe.testRoot=c;let l=await T({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1Common"}},metaspace:e,space:t}),d=await e.getDependencyGraph({ibGibAddr:u({ibGib:c}),space:t}),p=await e.getDependencyGraph({ibGibAddr:u({ibGib:l}),space:t});await e.put({ibGibs:Object.values({...d,...p}),space:s}),await e.registerNewIbGib({ibGib:c,space:s}),await e.registerNewIbGib({ibGib:l,space:s}),a("4.7B Setup: Syncing v1_common to server..."),await x({domainIbGibs:[l],passLabel:"Seed v1_common",metaspace:e,space:t}),a("4.7B Setup: \u2713 Seeding complete on server.");let f=m.domainI;await X({domainI:f,metaspace:e,fromSpace:t,toSpace:s});let y=await T({timeline:l,mut8Opts:{dataToAddOrPatch:{fieldA:"source_edit"}},metaspace:e,space:t});pe.targetAlphaV2a=y,a(`4.7B Setup: \u2713 Created client divergent edit V2a: ${u({ibGib:y})}`);let S=await T({timeline:l,mut8Opts:{dataToAddOrPatch:{fieldB:"dest_edit"}},metaspace:e,space:s});pe.targetBetaV2b=S,a(`4.7B Setup: \u2713 Created remote divergent edit V2b: ${u({ibGib:S})}`),a("4.7B Setup: Pushing V2b from remote space to server..."),await J({domainIbGibs:[S],passLabel:"Push V2b from remoteSpace",metaspace:e,space:s,primarySpace:t,domainI:f,masterSecret:Da}),a("4.7B Setup: \u2713 Server tip is now V2b."),a("\u2713 4.7B Setup Complete! Ready for 4.7B Sync."),r.textContent="\u2713 4.7B Setup Complete";let g=document.getElementById("btn-4-7b-sync");g&&(g.disabled=!1)}catch(e){a(`\u2717 4.7B Setup FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Va,"init4_7bSetupButton");function Ma(){let r=document.getElementById("btn-4-7b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.7B Sync: Initiating WebSocket Sync for divergent edit V2a...");let e=pe.targetAlphaV2a;if(!m.domainI||!e){a("\u26A0 4.7B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let t=await E(),n=await t.getLocalUserSpace({});if(!n)throw new Error("No default space.");await x({domainIbGibs:[e],passLabel:"Sync V2a (conflict merge)",metaspace:t,space:n}),a("\u2713 4.7B Sync Execution Complete! Ready for 4.7B Check."),r.textContent="\u2713 4.7B Sync Run";let o=document.getElementById("btn-4-7b-check");o&&(o.disabled=!1)}catch(e){a(`\u2717 4.7B Sync FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Ma,"init4_7bSyncButton");function Fa(){let r=document.getElementById("btn-4-7b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.7B Check: Verifying merged tip (V3) contains both edits on client and server...");let e=pe.testRoot,t=pe.targetAlphaV2a,n=pe.targetBetaV2b;if(!m.domainI||!e||!t||!n){a("\u26A0 4.7B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let o=u({ibGib:m.domainI}),s=ee({ibGib:e,defaultIfNone:"incomingAddr"})??u({ibGib:e}),i=await E(),c=await i.getLocalUserSpace({});if(!c)throw new Error("No default space.");let d=(await i.getLocalUserSpace({}).then(A=>new Y().getKnowledgeMap({space:A,metaspace:i,domainIbGibs:[e]})))[s];if(a(`4.7B Check: Client tip address: ${d}`),!d)throw new Error("Client default space is missing the timeline tip.");let p=await i.get({addr:d,space:c});if(!p.success||!p.ibGibs?.length)throw new Error("Client tip not found in default local space.");let f=p.ibGibs[0];if(!f.data?.fieldA||!f.data?.fieldB)throw new Error(`Merged client tip missing edits: fieldA: ${f.data?.fieldA}, fieldB: ${f.data?.fieldB}`);a("4.7B Check: \u2713 Client tip has both fieldA and fieldB edits.");let y=f.rel8ns?.[ye];if(!y?.[0])throw new Error("Client tip is missing graftinfo relations.");let S=await i.get({addr:y[0],space:c});if(!S.success||!S.ibGibs?.length)throw new Error("GraftInfo not found in local space.");let g=S.ibGibs[0];if(!g.rel8ns?.[Se]||!g.rel8ns?.[we])throw new Error("GraftInfo is missing graftbase or graftorphan relations.");a("4.7B Check: \u2713 Client graft base and orphan relations are correctly set.");let _=await new B().getIbGibGraph(o,d,!0);if(!_.success||!_.graph)throw new Error(`Failed to fetch merged graph from server: ${_.message}`);let I=_.graph[d];if(!I)throw new Error("Merged V3 tip is not present on the server!");if(I.data?.fieldA!=="source_edit"||I.data?.fieldB!=="dest_edit")throw new Error("Server tip data edits do not match merged values.");a("4.7B Check: \u2713 Server tip has matching merged edits."),a("\u2713 4.7B Check SUCCESS: Divergent branches merged successfully via optimistic graft!"),r.textContent="\u2713 4.7B Check Success"}catch(e){a(`\u2717 4.7B Check FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Fa,"init4_7bCheckButton");var Z={};function Ka(){let r=document.getElementById("btn-4-8b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.8B Setup: Setting up identities, seeding history, and creating divergent branches in client and remote...");let e=await E(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=new B;await q({masterSecret:"test-sender-secret-phase4-8b",syncSalt:"senderidentitysyncsaltphase4-8b",manageSalt:"senderidentitymanagesaltphase4-8b",metaspace:e,space:t,apiBridge:n,phaseText:"4.8B"});let o=m.domainI;Z.domainI_latest=o;let s=u({ibGib:o});a("4.8B Setup: Creating temporary remote space...");let i=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_8b",getFnPrompt:e.getFnPrompt}});await i.initialized,await X({domainI:o,metaspace:e,fromSpace:t,toSpace:i});let c=await D.firstGen({parentIbGib:M,ib:"timeline_root_conflict_4_8b",data:{type:"root",label:"CommonRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),l=c.newIbGib;await e.persistTransformResult({resTransform:c,space:t}),await e.registerNewIbGib({ibGib:l,space:t}),Z.testRoot=l;let d=await T({timeline:l,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1Common"}},metaspace:e,space:t}),p=await e.getDependencyGraph({ibGibAddr:u({ibGib:l}),space:t}),f=await e.getDependencyGraph({ibGibAddr:u({ibGib:d}),space:t}),y={...p,...f};await e.put({ibGibs:Object.values(y),space:i}),await e.registerNewIbGib({ibGib:l,space:i}),await e.registerNewIbGib({ibGib:d,space:i}),a("4.8B Setup: Syncing v1_common to server..."),await x({domainIbGibs:[d],passLabel:"Seed v1_common",metaspace:e,space:t}),a("4.8B Setup: \u2713 Seeding complete on server."),await X({domainI:m.domainI,metaspace:e,fromSpace:t,toSpace:i});let S=await D.firstGen({parentIbGib:M,ib:"beta_multitimelines_withid_4_8b",data:{fieldA:"beta field A created on source"},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),g=S.newIbGib;await e.persistTransformResult({resTransform:S,space:t}),await e.registerNewIbGib({ibGib:g,space:t}),Z.targetBetaV0=g,a(`4.8B Setup: \u2713 Created client independent related timeline Beta: ${u({ibGib:g})}`);let w=await T({timeline:d,mut8Opts:{dataToAddOrPatch:{fieldA:"source_edit"}},metaspace:e,space:t}),_=await Be({timeline:w,metaspace:e,space:t,rel8nInfos:[{rel8nName:"testrel8n",ibGibs:[g]}]});Z.targetAlphaV3a=_,a(`4.8B Setup: \u2713 Created client divergent edit V3a: ${u({ibGib:_})}`);let I=await T({timeline:d,mut8Opts:{dataToAddOrPatch:{fieldB:"dest_edit"}},metaspace:e,space:i});a(`4.8B Setup: \u2713 Created remote divergent edit V2b: ${u({ibGib:I})}`),a("4.8B Setup: Pushing V2b from remote space to server..."),await J({domainIbGibs:[I],passLabel:"Push V2b from remoteSpace",metaspace:e,space:i,primarySpace:t,domainI:m.domainI,masterSecret:"test-sender-secret-phase4-8b"}),Z.domainI_latest=m.domainI,a("4.8B Setup: \u2713 Server tip is now V2b. Evolved identity copied back."),a("\u2713 4.8B Setup Complete! Ready for 4.8B Sync."),r.textContent="\u2713 4.8B Setup Complete";let A=document.getElementById("btn-4-8b-sync");A&&(A.disabled=!1)}catch(e){a(`\u2717 4.8B Setup FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Ka,"init4_8bSetupButton");function Ua(){let r=document.getElementById("btn-4-8b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.8B Sync: Initiating WebSocket Sync for divergent edit V3a (with related timeline Beta)...");let e=Z.domainI_latest,t=Z.targetAlphaV3a;if(!e||!t){a("\u26A0 4.8B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let n=await E(),o=await n.getLocalUserSpace({});if(!o)throw new Error("No default space.");await x({domainIbGibs:[t],passLabel:"Sync V3a and merge",metaspace:n,space:o}),Z.domainI_latest=m.domainI,a("\u2713 4.8B Sync Execution Complete! Ready for 4.8B Check."),r.textContent="\u2713 4.8B Sync Run";let s=document.getElementById("btn-4-8b-check");s&&(s.disabled=!1)}catch(e){a(`\u2717 4.8B Sync FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Ua,"init4_8bSyncButton");function ja(){let r=document.getElementById("btn-4-8b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.8B Check: Verifying merged tip (V4) contains both edits on client and server...");let e=Z.domainI_latest,t=Z.testRoot,n=Z.targetAlphaV3a,o=Z.targetBetaV0;if(!e||!t||!n||!o){a("\u26A0 4.8B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let s=u({ibGib:e}),i=ee({ibGib:t,defaultIfNone:"incomingAddr"})??u({ibGib:t}),c=u({ibGib:o}),l=await E(),d=await l.getLocalUserSpace({});if(!d)throw new Error("No default space.");let f=(await l.getLocalUserSpace({}).then(P=>new Y().getKnowledgeMap({space:P,metaspace:l,domainIbGibs:[t]})))[i];if(a(`4.8B Check: Client tip address: ${f}`),!f)throw new Error("Client default space is missing the timeline tip.");let y=await l.get({addr:f,space:d});if(!y.success||!y.ibGibs||y.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let S=y.ibGibs[0];if(!S.data||!S.data.fieldA||!S.data.fieldB)throw new Error(`Merged client tip is missing expected data edits: fieldA: ${S.data?.fieldA}, fieldB: ${S.data?.fieldB}`);a("4.8B Check: \u2713 Client tip has both fieldA and fieldB edits.");let g=S.rel8ns?.[ye];if(!g?.[0])throw new Error("Client tip is missing graftinfo relations.");let w=await l.get({addr:g[0],space:d});if(!w.success||!w.ibGibs||w.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let _=w.ibGibs[0],I=_.rel8ns?.[Se],A=_.rel8ns?.[we];if(!I||!A)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");a("4.8B Check: \u2713 Client graft base and orphan relations are correctly set.");let v=new B;a("4.8B Check: Fetching server timeline graph...");let G=await v.getIbGibGraph(s,f,!0);if(!G.success||!G.graph)throw new Error(`Failed to fetch merged graph from server: ${G.message}`);let k=G.graph[f];if(!k)throw new Error("Merged V4 tip is not present on the server!");if(k.data?.fieldA!=="source_edit"||k.data?.fieldB!=="dest_edit")throw new Error("Server tip data edits do not match merged values.");a("4.8B Check: \u2713 Server tip has matching merged edits."),a("4.8B Check: Verifying related timeline Beta is present on the server...");let $=await v.getIbGibGraph(s,c,!0);if(!$.success||!$.graph||!$.graph[c])throw new Error(`Related timeline Beta (${c}) is missing from the server!`);a("4.8B Check: \u2713 Related timeline Beta successfully verified on the server."),a("\u2713 4.8B Check SUCCESS: Divergent branches merged successfully and related timeline synced on server!"),r.textContent="\u2713 4.8B Check Success"}catch(e){a(`\u2717 4.8B Check FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(ja,"init4_8bCheckButton");var ne={},Fe=`This is the initial quiz question.
9
3
  It has multiple lines.
10
- Students will answer this.`,is=`
11
- Instructor added hint.`,cs=`Student note: Confusing!
12
- `;function ds(){let o=document.getElementById("btn-4-9b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.9B Setup: Setting up identities, seeding text history, and creating divergent branches...");let e=await O(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let a=new V;await Pe({masterSecret:"test-sender-secret-phase4-9b",syncSalt:"senderidentitysyncsaltphase4-9b",manageSalt:"senderidentitymanagesaltphase4-9b",metaspace:e,space:t,apiBridge:a,phaseText:"4.9B"});let r=v.domainI;rt.domainI_latest=r;let n=y({ibGib:r});l("4.9B Setup: Creating temporary remote space...");let s=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_9b",getFnPrompt:e.getFnPrompt}});await s.initialized,await xe({domainI:r,metaspace:e,fromSpace:t,toSpace:s});let i=await U.firstGen({parentIbGib:Q,ib:"timeline_root_text_conflict_4_9b",data:{text:rr,label:"TextRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c,space:t}),rt.testRoot=c;let d=await e.getDependencyGraph({ibGibAddr:y({ibGib:c}),space:t});await e.put({ibGibs:Object.values(d),space:s}),await e.registerNewIbGib({ibGib:c,space:s}),l("4.9B Setup: Syncing testRoot to server..."),await ee({domainIbGibs:[c],passLabel:"Seed testRoot",metaspace:e,space:t}),l("4.9B Setup: \u2713 Seeding complete on server."),await xe({domainI:v.domainI,metaspace:e,fromSpace:t,toSpace:s});let f=await j({timeline:c,mut8Opts:{mut8Ib:c.ib+"_appended",dataToAddOrPatch:{text:rr+is}},metaspace:e,space:t});rt.targetAlphaV1Source=f,l(`4.9B Setup: \u2713 Created client appended edit: ${y({ibGib:f})}`);let b=await j({timeline:c,mut8Opts:{mut8Ib:c.ib+"_prepended",dataToAddOrPatch:{text:cs+rr}},metaspace:e,space:s});l(`4.9B Setup: \u2713 Created remote prepended edit: ${y({ibGib:b})}`),l("4.9B Setup: Pushing remote prepended edit to server..."),await Oe({domainIbGibs:[b],passLabel:"Push remote prepended edit",metaspace:e,space:s,primarySpace:t,domainI:v.domainI,masterSecret:"test-sender-secret-phase4-9b"}),rt.domainI_latest=v.domainI,l("4.9B Setup: \u2713 Server tip is now the prepended edit. Evolved identity copied back."),l("\u2713 4.9B Setup Complete! Ready for 4.9B Sync."),o.textContent="\u2713 4.9B Setup Complete";let m=document.getElementById("btn-4-9b-sync");m&&(m.disabled=!1)}catch(e){l(`\u2717 4.9B Setup FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(ds,"init4_9bSetupButton");function ls(){let o=document.getElementById("btn-4-9b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.9B Sync: Initiating WebSocket Sync for divergent edit (LCS text merge)...");let e=rt.domainI_latest,t=rt.targetAlphaV1Source;if(!e||!t){l("\u26A0 4.9B Sync: Missing setup state. Please run Setup first."),o.disabled=!1;return}let a=await O(),r=await a.getLocalUserSpace({});if(!r)throw new Error("No default space.");await ee({domainIbGibs:[t],passLabel:"Sync divergent edit and merge",metaspace:a,space:r}),rt.domainI_latest=v.domainI,l("\u2713 4.9B Sync Execution Complete! Ready for 4.9B Check."),o.textContent="\u2713 4.9B Sync Run";let n=document.getElementById("btn-4-9b-check");n&&(n.disabled=!1)}catch(e){l(`\u2717 4.9B Sync FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(ls,"init4_9bSyncButton");function fs(){let o=document.getElementById("btn-4-9b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.9B Check: Verifying LCS merged text on client and server...");let e=rt.domainI_latest,t=rt.testRoot,a=rt.targetAlphaV1Source;if(!e||!t||!a){l("\u26A0 4.9B Check: Missing state. Did Setup and Sync run?"),o.disabled=!1;return}let r=y({ibGib:e}),n=Ce({ibGib:t,defaultIfNone:"incomingAddr"})??y({ibGib:t}),s=await O(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let d=(await s.getLocalUserSpace({}).then(C=>new le().getKnowledgeMap({space:C,metaspace:s,domainIbGibs:[t]})))[n];if(l(`4.9B Check: Client tip address: ${d}`),!d)throw new Error("Client default space is missing the timeline tip.");let f=await s.get({addr:d,space:i});if(!f.success||!f.ibGibs||f.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let b=f.ibGibs[0],m=cs+rr+is;if(b.data?.text!==m)throw new Error(`Merged client tip text mismatch! Expected:
13
- ${m}
4
+ Students will answer this.`,Wa=`
5
+ Instructor added hint.`,Ha=`Student note: Confusing!
6
+ `;function Ya(){let r=document.getElementById("btn-4-9b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.9B Setup: Setting up identities, seeding text history, and creating divergent branches...");let e=await E(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=new B;await q({masterSecret:"test-sender-secret-phase4-9b",syncSalt:"senderidentitysyncsaltphase4-9b",manageSalt:"senderidentitymanagesaltphase4-9b",metaspace:e,space:t,apiBridge:n,phaseText:"4.9B"});let o=m.domainI;ne.domainI_latest=o;let s=u({ibGib:o});a("4.9B Setup: Creating temporary remote space...");let i=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_9b",getFnPrompt:e.getFnPrompt}});await i.initialized,await X({domainI:o,metaspace:e,fromSpace:t,toSpace:i});let c=await D.firstGen({parentIbGib:M,ib:"timeline_root_text_conflict_4_9b",data:{text:Fe,label:"TextRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),l=c.newIbGib;await e.persistTransformResult({resTransform:c,space:t}),await e.registerNewIbGib({ibGib:l,space:t}),ne.testRoot=l;let d=await e.getDependencyGraph({ibGibAddr:u({ibGib:l}),space:t});await e.put({ibGibs:Object.values(d),space:i}),await e.registerNewIbGib({ibGib:l,space:i}),a("4.9B Setup: Syncing testRoot to server..."),await x({domainIbGibs:[l],passLabel:"Seed testRoot",metaspace:e,space:t}),a("4.9B Setup: \u2713 Seeding complete on server."),await X({domainI:m.domainI,metaspace:e,fromSpace:t,toSpace:i});let p=await T({timeline:l,mut8Opts:{mut8Ib:l.ib+"_appended",dataToAddOrPatch:{text:Fe+Wa}},metaspace:e,space:t});ne.targetAlphaV1Source=p,a(`4.9B Setup: \u2713 Created client appended edit: ${u({ibGib:p})}`);let f=await T({timeline:l,mut8Opts:{mut8Ib:l.ib+"_prepended",dataToAddOrPatch:{text:Ha+Fe}},metaspace:e,space:i});a(`4.9B Setup: \u2713 Created remote prepended edit: ${u({ibGib:f})}`),a("4.9B Setup: Pushing remote prepended edit to server..."),await J({domainIbGibs:[f],passLabel:"Push remote prepended edit",metaspace:e,space:i,primarySpace:t,domainI:m.domainI,masterSecret:"test-sender-secret-phase4-9b"}),ne.domainI_latest=m.domainI,a("4.9B Setup: \u2713 Server tip is now the prepended edit. Evolved identity copied back."),a("\u2713 4.9B Setup Complete! Ready for 4.9B Sync."),r.textContent="\u2713 4.9B Setup Complete";let y=document.getElementById("btn-4-9b-sync");y&&(y.disabled=!1)}catch(e){a(`\u2717 4.9B Setup FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Ya,"init4_9bSetupButton");function qa(){let r=document.getElementById("btn-4-9b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.9B Sync: Initiating WebSocket Sync for divergent edit (LCS text merge)...");let e=ne.domainI_latest,t=ne.targetAlphaV1Source;if(!e||!t){a("\u26A0 4.9B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let n=await E(),o=await n.getLocalUserSpace({});if(!o)throw new Error("No default space.");await x({domainIbGibs:[t],passLabel:"Sync divergent edit and merge",metaspace:n,space:o}),ne.domainI_latest=m.domainI,a("\u2713 4.9B Sync Execution Complete! Ready for 4.9B Check."),r.textContent="\u2713 4.9B Sync Run";let s=document.getElementById("btn-4-9b-check");s&&(s.disabled=!1)}catch(e){a(`\u2717 4.9B Sync FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(qa,"init4_9bSyncButton");function Xa(){let r=document.getElementById("btn-4-9b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.9B Check: Verifying LCS merged text on client and server...");let e=ne.domainI_latest,t=ne.testRoot,n=ne.targetAlphaV1Source;if(!e||!t||!n){a("\u26A0 4.9B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let o=u({ibGib:e}),s=ee({ibGib:t,defaultIfNone:"incomingAddr"})??u({ibGib:t}),i=await E(),c=await i.getLocalUserSpace({});if(!c)throw new Error("No default space.");let d=(await i.getLocalUserSpace({}).then(k=>new Y().getKnowledgeMap({space:k,metaspace:i,domainIbGibs:[t]})))[s];if(a(`4.9B Check: Client tip address: ${d}`),!d)throw new Error("Client default space is missing the timeline tip.");let p=await i.get({addr:d,space:c});if(!p.success||!p.ibGibs||p.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let f=p.ibGibs[0],y=Ha+Fe+Wa;if(f.data?.text!==y)throw new Error(`Merged client tip text mismatch! Expected:
7
+ ${y}
14
8
  Actual:
15
- ${b.data?.text}`);l("4.9B Check: \u2713 Client tip text contains both prepend and append edits merged correctly.");let u=b.rel8ns?.[Me];if(!u?.[0])throw new Error("Client tip is missing graftinfo relations.");let h=await s.get({addr:u[0],space:i});if(!h.success||!h.ibGibs||h.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let I=h.ibGibs[0],E=I.rel8ns?.[yt],w=I.rel8ns?.[et];if(!E||!w)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");l("4.9B Check: \u2713 Client graft base and orphan relations are correctly set.");let A=new V;l("4.9B Check: Fetching server timeline graph...");let G=await A.getIbGibGraph(r,d,!0);if(!G.success||!G.graph)throw new Error(`Failed to fetch merged graph from server: ${G.message}`);let T=G.graph[d];if(!T)throw new Error("Merged tip is not present on the server!");if(T.data?.text!==m)throw new Error(`Server tip text mismatch! Expected:
16
- ${m}
9
+ ${f.data?.text}`);a("4.9B Check: \u2713 Client tip text contains both prepend and append edits merged correctly.");let S=f.rel8ns?.[ye];if(!S?.[0])throw new Error("Client tip is missing graftinfo relations.");let g=await i.get({addr:S[0],space:c});if(!g.success||!g.ibGibs||g.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let w=g.ibGibs[0],_=w.rel8ns?.[Se],I=w.rel8ns?.[we];if(!_||!I)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");a("4.9B Check: \u2713 Client graft base and orphan relations are correctly set.");let A=new B;a("4.9B Check: Fetching server timeline graph...");let v=await A.getIbGibGraph(o,d,!0);if(!v.success||!v.graph)throw new Error(`Failed to fetch merged graph from server: ${v.message}`);let G=v.graph[d];if(!G)throw new Error("Merged tip is not present on the server!");if(G.data?.text!==y)throw new Error(`Server tip text mismatch! Expected:
10
+ ${y}
17
11
  Actual:
18
- ${T.data?.text}`);l("4.9B Check: \u2713 Server tip text matches the client-side merged text."),l("\u2713 4.9B Check SUCCESS: LCS text field merge conflict resolved and verified on both client and server!"),o.textContent="\u2713 4.9B Check Success"}catch(e){l(`\u2717 4.9B Check FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(fs,"init4_9bCheckButton");var M={},Yr="testrel8n";function bs(){let o=document.getElementById("btn-4-10b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.10B Setup: Setting up identities and preparing Round 1 & Round 2 divergence...");let e=await O(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let a=new V;await Pe({masterSecret:"test-sender-secret-phase4-10b",syncSalt:"senderidentitysyncsaltphase4-10b",manageSalt:"senderidentitymanagesaltphase4-10b",metaspace:e,space:t,apiBridge:a,phaseText:"4.10B"});let r=v.domainI;M.domainI_initial=r,M.domainI_latest=r;let n=y({ibGib:r});l("4.10B Setup: Creating temporary remote space...");let s=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_10b",getFnPrompt:e.getFnPrompt}});await s.initialized,M.remoteSpace=s,await xe({domainI:r,metaspace:e,fromSpace:t,toSpace:s}),l("4.10B Setup: Creating common history for alpha...");let i=await U.firstGen({parentIbGib:Q,ib:"timeline_root_alpha_4_10b",data:{commonField:"common field R1 val",label:"AlphaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;M.alpha_v0=c,await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c,space:t});let d=Ce({ibGib:c,defaultIfNone:"incomingAddr"});M.alpha_tjpAddr=d,await e.persistTransformResult({resTransform:i,space:s}),await e.registerNewIbGib({ibGib:c,space:s}),l("4.10B Setup: Seeding alpha_v0 to server..."),await ee({domainIbGibs:[c],passLabel:"Seed alpha_v0",metaspace:e,space:t}),M.domainI_latest=v.domainI,l("4.10B Setup: \u2713 alpha_v0 seeded on server."),await xe({domainI:v.domainI,metaspace:e,fromSpace:t,toSpace:s});let f=await U.firstGen({parentIbGib:Q,ib:"timeline_root_beta_4_10b",data:{fieldA:"beta field A created on source",label:"BetaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),b=f.newIbGib;await e.persistTransformResult({resTransform:f,space:t}),await e.registerNewIbGib({ibGib:b,space:t}),M.r2_beta_v0_source=b;let m=Ce({ibGib:b,defaultIfNone:"incomingAddr"});M.beta_tjpAddr=m;let u=await j({timeline:c,mut8Opts:{mut8Ib:c.ib+"_r2client",dataToAddOrPatch:{fieldA:"source_edit_r2"}},metaspace:e,space:t});l(`r2_alpha_v1_source_sansBeta.gib: ${u.gib}`),Hr=y({ibGib:b});let h=await Pt({timeline:u,metaspace:e,space:t,rel8nInfos:[{rel8nName:Yr,ibGibs:[b]}]});M.r2_alpha_v3_source_rel8beta=h,l(`r2_alpha_v2_source_rel8dBeta.gib: ${h.gib}`),l("4.10B Setup: \u2713 Created client Round 2 edits (alpha fieldA edit + relate beta).");let I=await j({timeline:c,mut8Opts:{mut8Ib:c.ib+"_r2remote",dataToAddOrPatch:{fieldB:"remote_edit_r2"}},metaspace:e,space:s});console.log(`alpha_v0: ${ge(c)}`),console.log(`r2_alpha_v1_remote: ${ge(I)}`),l(`r2_alpha_v1_remote.gib: ${I.gib}`),l("4.10B Setup: Pushing remote Round 2 edit to server..."),await Oe({domainIbGibs:[I],passLabel:"Push remote Round 2 edit",metaspace:e,space:s,primarySpace:t,domainI:v.domainI,masterSecret:"test-sender-secret-phase4-10b"}),M.domainI_latest=v.domainI,l("\u2713 4.10B Setup Complete! Ready for 4.10B Sync (which runs Round 2, 3, and 4 in succession)."),o.textContent="\u2713 4.10B Setup Complete";let E=document.getElementById("btn-4-10b-sync");E&&(E.disabled=!1)}catch(e){l(`\u2717 4.10B Setup FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(bs,"init4_10bSetupButton");var Wr,Hr;function ms(){let o=document.getElementById("btn-4-10b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.10B Sync: Initiating WebSocket Sync for Round 2, 3, and 4 sequential evolution...");let e=M.domainI_latest,t=M.remoteSpace,a=M.alpha_tjpAddr,r=M.beta_tjpAddr,n=M.alpha_v0,s=await O(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=location.protocol==="https:"?"wss:":"ws:",d=y({ibGib:M.domainI_initial});l("4.10B Sync: Running Round 2 Sync (merging divergent alpha edits)..."),await ee({domainIbGibs:[M.r2_alpha_v3_source_rel8beta],passLabel:"Sync divergent alpha edits R2",metaspace:s,space:i}),M.domainI_latest=v.domainI,l("4.10B Sync: \u2713 Round 2 Sync complete."),await xe({domainI:v.domainI,metaspace:s,fromSpace:i,toSpace:t}),l("4.10B Sync: Preparing Round 3 divergence (multiple conflicting timelines)...");let f=await new le().getKnowledgeMap({domainIbGibs:[M.r2_alpha_v3_source_rel8beta,M.r2_beta_v0_source],space:i,metaspace:s}),b=f[a],m=f[r],u=await s.get({addr:b,space:i}),h=await s.get({addr:m,space:i}),I=await j({timeline:u.ibGibs[0],mut8Opts:{mut8Ib:n.ib+"_r3client",dataToAddOrPatch:{fieldC:"source_edit_r3"}},metaspace:s,space:i}),E=await j({timeline:h.ibGibs[0],mut8Opts:{mut8Ib:M.r2_beta_v0_source.ib+"_r3client",dataToAddOrPatch:{betaFieldA:"source_beta_edit_r3"}},metaspace:s,space:i});l("4.10B Sync: Updating remote space to latest merged tips...");let w=await s.getLatestAddr({addr:a,space:t}),T=[(await s.get({addr:w,space:t})).ibGibs[0]],C=await s.getLatestAddr({addr:r,space:t});if(C){let fa=await s.get({addr:C,space:t});T.push(fa.ibGibs[0])}await Oe({domainIbGibs:T,passLabel:"Pull merged R2 tips to remoteSpace",metaspace:s,space:t,primarySpace:i,domainI:v.domainI,masterSecret:"test-sender-secret-phase4-10b"}),M.domainI_latest=v.domainI;let S=await new le().getKnowledgeMap({space:t,metaspace:s,domainIbGibs:[n,M.r2_beta_v0_source]}),_=S[a],$=S[r],B=await s.get({addr:_,space:t}),D=await s.get({addr:$,space:t}),N=await j({timeline:B.ibGibs[0],mut8Opts:{mut8Ib:n.ib+"_r3remote",dataToAddOrPatch:{fieldD:"remote_edit_r3"}},metaspace:s,space:t}),x=await j({timeline:D.ibGibs[0],mut8Opts:{mut8Ib:M.r2_beta_v0_source.ib+"_r3remote",dataToAddOrPatch:{betaFieldB:"remote_beta_edit_r3"}},metaspace:s,space:t});l("4.10B Sync: Pushing remote Round 3 edits to server..."),await Oe({domainIbGibs:[N,x],passLabel:"Push remote Round 3 edits",metaspace:s,space:t,primarySpace:i,domainI:v.domainI,masterSecret:"test-sender-secret-phase4-10b"}),M.domainI_latest=v.domainI,l("4.10B Sync: Running Round 3 Client Sync (merging alpha & beta divergence)..."),await ee({domainIbGibs:[I,E],passLabel:"Sync Client Round 3 edits",metaspace:s,space:i}),M.domainI_latest=v.domainI,l("4.10B Sync: \u2713 Round 3 Sync complete."),await xe({domainI:v.domainI,metaspace:s,fromSpace:i,toSpace:t}),l("4.10B Sync: Preparing Round 4 divergence (post-graft chain edits & new timeline)...");let L=await new le().getKnowledgeMap({space:i,metaspace:s,domainIbGibs:[n,M.r2_beta_v0_source]}),k=L[a],te=L[r],X=await s.get({addr:k,space:i}),W=await s.get({addr:te,space:i}),Ge=await j({timeline:X.ibGibs[0],mut8Opts:{mut8Ib:n.ib+"_r4client_v5",dataToAddOrPatch:{fieldE:"source_edit_r4_v5"}},metaspace:s,space:i}),Ee=await U.firstGen({parentIbGib:Q,ib:"timeline_root_gamma_4_10b",data:{gammaField:"gamma created on client",label:"GammaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),ne=Ee.newIbGib;await s.persistTransformResult({resTransform:Ee,space:i}),await s.registerNewIbGib({ibGib:ne,space:i});let $e=Ce({ibGib:ne,defaultIfNone:"incomingAddr"});M.gamma_tjpAddr=$e,Wr=y({ibGib:ne});let K=await Pt({timeline:Ge,metaspace:s,space:i,rel8nInfos:[{rel8nName:Yr,ibGibs:[ne]}]}),z=await j({timeline:K,mut8Opts:{mut8Ib:n.ib+"_r4client_v7",dataToAddOrPatch:{fieldF:"source_edit_r4_v7"}},metaspace:s,space:i}),fe=await j({timeline:W.ibGibs[0],mut8Opts:{mut8Ib:M.r2_beta_v0_source.ib+"_r4client_v2",dataToAddOrPatch:{betaFieldD:"source_beta_edit_r4_v2"}},metaspace:s,space:i});l("4.10B Sync: Updating remote space to Round 3 merged tips...");let J=await s.getLatestAddr({addr:a,space:t}),F=[(await s.get({addr:J,space:t})).ibGibs[0]],me=await s.getLatestAddr({addr:r,space:t});if(me){let fa=await s.get({addr:me,space:t});F.push(fa.ibGibs[0])}await Oe({domainIbGibs:F,passLabel:"Pull merged R3 tips to remoteSpace",metaspace:s,space:t,primarySpace:i,domainI:v.domainI,masterSecret:"test-sender-secret-phase4-10b"}),M.domainI_latest=v.domainI;let je=await new le().getKnowledgeMap({space:t,metaspace:s,domainIbGibs:[n,M.r2_beta_v0_source]}),da=je[a],va=je[r],la=await s.get({addr:da,space:t}),gr=await s.get({addr:va,space:t}),Ba=await j({timeline:la.ibGibs[0],mut8Opts:{mut8Ib:n.ib+"_r4remote_v5",dataToAddOrPatch:{fieldG:"remote_edit_r4_v5"}},metaspace:s,space:t}),Na=await j({timeline:gr.ibGibs[0],mut8Opts:{mut8Ib:M.r2_beta_v0_source.ib+"_r4remote_v2",dataToAddOrPatch:{betaFieldC:"remote_beta_edit_r4_v2"}},metaspace:s,space:t});l("4.10B Sync: Pushing remote Round 4 edits to server..."),await Oe({domainIbGibs:[Ba,Na],passLabel:"Push remote Round 4 edits",metaspace:s,space:t,primarySpace:i,domainI:v.domainI,masterSecret:"test-sender-secret-phase4-10b"}),M.domainI_latest=v.domainI,l("4.10B Sync: Running final Round 4 Client Sync (merging alpha, beta, and propagating gamma)..."),await ee({domainIbGibs:[z,fe,ne],passLabel:"Sync final Round 4 edits",metaspace:s,space:i}),M.domainI_latest=v.domainI,l("\u2713 4.10B Sync: All rounds of divergent edits and merges complete!"),o.textContent="\u2713 4.10B Sync Complete";let Pa=document.getElementById("btn-4-10b-check");Pa&&(Pa.disabled=!1)}catch(e){l(`\u2717 4.10B Sync FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(ms,"init4_10bSyncButton");function ps(){let o=document.getElementById("btn-4-10b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,l("4.10B Check: Verifying multi-round merged timelines on client and server...");let e=M.domainI_latest,t=M.alpha_tjpAddr,a=M.beta_tjpAddr,r=M.gamma_tjpAddr,n=await O(),s=await n.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=y({ibGib:M.domainI_initial}),c=await new le().getKnowledgeMap({space:s,metaspace:n,domainIbGibs:[M.domainI_initial]}),d=await n.getLatestAddr({addr:t,space:s}),f=await n.getLatestAddr({addr:a,space:s}),b=await n.getLatestAddr({addr:r,space:s});if(!d||!f||!b)throw new Error("Client space is missing timeline tips for Alpha, Beta, or Gamma.");let m=await n.get({addr:d,space:s}),u=await n.get({addr:f,space:s}),h=m.ibGibs[0],I=u.ibGibs[0];if(h.data?.fieldA!=="source_edit_r2")throw new Error(`Alpha fieldA mismatch! Expected 'source_edit_r2', got '${h.data?.fieldA}'`);if(h.data?.fieldB!=="remote_edit_r2")throw new Error(`Alpha fieldB mismatch! Expected 'remote_edit_r2', got '${h.data?.fieldB}'`);if(h.data?.fieldC!=="source_edit_r3")throw new Error(`Alpha fieldC mismatch! Expected 'source_edit_r3', got '${h.data?.fieldC}'`);if(h.data?.fieldD!=="remote_edit_r3")throw new Error(`Alpha fieldD mismatch! Expected 'remote_edit_r3', got '${h.data?.fieldD}'`);if(h.data?.fieldE!=="source_edit_r4_v5")throw new Error(`Alpha fieldE mismatch! Expected 'source_edit_r4_v5', got '${h.data?.fieldE}'`);if(h.data?.fieldF!=="source_edit_r4_v7")throw new Error(`Alpha fieldF mismatch! Expected 'source_edit_r4_v7', got '${h.data?.fieldF}'`);if(h.data?.fieldG!=="remote_edit_r4_v5")throw new Error(`Alpha fieldG mismatch! Expected 'remote_edit_r4_v5', got '${h.data?.fieldG}'`);if(l("4.10B Check: \u2713 Client Alpha merged tip contains all Round 2, 3, and 4 edits."),I.data?.betaFieldA!=="source_beta_edit_r3")throw new Error(`Beta betaFieldA mismatch! Expected 'source_beta_edit_r3', got '${I.data?.betaFieldA}'`);if(I.data?.betaFieldB!=="remote_beta_edit_r3")throw new Error(`Beta betaFieldB mismatch! Expected 'remote_beta_edit_r3', got '${I.data?.betaFieldB}'`);if(I.data?.betaFieldC!=="remote_beta_edit_r4_v2")throw new Error(`Beta betaFieldC mismatch! Expected 'remote_beta_edit_r4_v2', got '${I.data?.betaFieldC}'`);if(I.data?.betaFieldD!=="source_beta_edit_r4_v2")throw new Error(`Beta betaFieldD mismatch! Expected 'source_beta_edit_r4_v2', got '${I.data?.betaFieldD}'`);l("4.10B Check: \u2713 Client Beta merged tip contains all Round 3 and 4 edits.");let E=h.rel8ns?.[Yr]||[];if(!Hr)throw new Error("(UNEXPECTED) betaAddr falsy? (E: 81c032ae7a93bddfd8eed6664d314826)");if(!E.includes(Hr))throw new Error("Client Alpha tip is missing relation to Beta timeline.");if(!Wr)throw new Error("(UNEXPECTED) gammaAddr falsy? (E: 12220a81d3b86385d1683d5a6bae5826)");if(!E.includes(Wr))throw new Error("Client Alpha tip is missing relation to Gamma timeline.");l("4.10B Check: \u2713 Client Alpha tip retains relation to Gamma.");let w=new V;l("4.10B Check: Fetching server timeline graphs...");let A=await w.getIbGibGraph(i,d,!0),G=await w.getIbGibGraph(i,f,!0);if(!A.success||!A.graph||!G.success||!G.graph)throw new Error("Failed to fetch merged graphs from server.");let T=A.graph[d],C=G.graph[f];if(!T||!C)throw new Error("Server is missing the final merged tips for Alpha or Beta.");if(T.data?.fieldF!=="source_edit_r4_v7"||T.data?.fieldG!=="remote_edit_r4_v5")throw new Error("Server Alpha tip does not match final client merged state.");if(C.data?.betaFieldC!=="remote_beta_edit_r4_v2"||C.data?.betaFieldD!=="source_beta_edit_r4_v2")throw new Error("Server Beta tip does not match final client merged state.");l("4.10B Check: \u2713 Server tips match client merged states perfectly."),l("\u2713 4.10B Check SUCCESS: Advanced multi-round/timeline conflict resolved and verified on both client and server!"),o.textContent="\u2713 4.10B Check Success"}catch(e){l(`\u2717 4.10B Check FAILED: ${g(e)}`),console.error(e),o.disabled=!1}})}p(ps,"init4_10bCheckButton");var hs="Space witness for projecting and observing workspace hierarchies.";var We="workspace_scan";var qr={version:"1",uuid:Fa,name:Ma,classname:"WorkspaceProjectionSpaceBase_V1",workspaceRoot:"",vcsFolderName:".vcsgib",persistOptsAndResultIbGibs:!1,validateIbGibAddrsMatchIbGibs:!1,longPollingIntervalMs:Ua,allowPrimitiveArgs:!1,catchAllErrors:!0,description:hs,trace:!1};var kt=!1,nr=class o extends ao{static{p(this,"WorkspaceProjectionSpaceBase_V1")}lc=`[${o.name}]`;constructor(e,t){super(e??Xe(qr),t)}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{kt&&console.log(`${e} starting...`),this.data||(this.data=Xe(qr)),this.data.classname||(this.data.classname="WorkspaceProjectionSpaceBase_V1"),this.data.uuid??=await Z(),this.ib=Fn({space:this,classname:this.data.classname}),this.gib=await Tt({ibGib:this})}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{kt&&console.log(`${e} complete.`)}}async validateWitnessArg(e){let t=`${this.lc}[${this.validateWitnessArg.name}]`,a=[];try{if(!e)return a.push("arg required (E: a222db3b668e4bb09cfd82e75c07bfa6)"),a;if(!e.data)return a.push("arg.data required (E: 8ee544d7d88a45c6adcbc15838a283a7)"),a;if(!this.data)return a.push("this.data required (E: 64f80642d7de44329355d6f907e272c8)"),a;let{cmd:r}=e.data,n=e.data.cmdModifiers??[];return r||a.push("arg.data.cmd required (E: 72a11ee87a0d4896bcacd65a9c0284d9)"),r===Gr.get&&!n.includes(We)&&!e.data.subPath&&!e.data.relPath&&(!e.data.ibGibAddrs||e.data.ibGibAddrs.length===0)&&a.push("ibGibAddrs, relPath, subPath, or workspace_scan modifier required for get (E: ee55a3f60b90423cbe054f27c34ab7d5)"),a}catch(r){throw console.error(`${t} ${g(r)}`),r}}async routeAndDoCommand({cmd:e,cmdModifiers:t,arg:a}){let r=`${this.lc}[${this.routeAndDoCommand.name}]`;return e===Gr.get&&t.includes(We)?this.scanWorkspace(a):super.routeAndDoCommand({cmd:e,cmdModifiers:t,arg:a})}async scanWorkspace(e){let t=`${this.lc}[${this.scanWorkspace.name}]`,a={optsAddr:y({ibGib:e})};try{kt&&console.log(`${t} scanning workspace...`);let n=await this.scanWorkspaceImpl({subPath:e.data?.subPath,filterPatterns:e.data?.filterPatterns??this.data?.filterPatterns});a.success=!0,a.scanResult=n}catch(n){console.error(`${t} ${g(n)} (E: 411edc38cbf8473358cfbb9d0ea8d826)`),a.success=!1,a.errors=[g(n)]}return await this.resulty({resultData:a})}async putImpl(e){let t=`${this.lc}[${this.putImpl.name}]`,a={optsAddr:y({ibGib:e})};try{kt&&console.log(`${t} putting to workspace...`);let n=e.ibGibs??[];if(n.length===0)throw new Error(`${t} No ibGib(s) provided in put arg (E: f7c1bfd5dda81a5422ebbabafe846d26)`);for(let s of n)await this.putItemToWorkspaceImpl({item:s,subPath:e.data?.subPath});a.success=!0}catch(n){console.error(`${t} ${g(n)} (E: 5922341ff2d485727afa306876ef1826)`),a.success=!1,a.errors=[g(n)]}return await this.resulty({resultData:a})}async getImpl(e){let t=`${this.lc}[${this.getImpl.name}]`,a={optsAddr:y({ibGib:e})},r=[];try{if((e.data?.cmdModifiers??[]).includes(We)){kt&&console.log(`${t} scanning workspace...`);let i=await this.scanWorkspaceImpl({subPath:e.data?.subPath??e.data?.relPath,filterPatterns:e.data?.filterPatterns??this.data?.filterPatterns});a.success=!0,a.scanResult=i}else{kt&&console.log(`${t} getting file binary from workspace...`);let i=[...e.data?.ibGibAddrs||[],...e.data?.relPath?[e.data.relPath]:[]];for(let c of i){let d=await this.getFileBytesImpl({relPath:c});if(d!==void 0){let f=await crypto.subtle.digest("SHA-256",d.buffer),m=`bin ${Array.from(new Uint8Array(f)).map(I=>I.toString(16).padStart(2,"0")).join("")}`,u=await Tt({ibGib:{ib:m,data:d}}),h={ib:m,gib:u,data:d};r.push(h)}}a.success=!0}}catch(s){console.error(`${t} ${g(s)} (E: 2b2f38560368242a8862f569378ba826)`),a.success=!1,a.errors=[g(s)]}return await this.resulty({resultData:a,ibGibs:r})}async deleteImpl(e){let t=`${this.lc}[${this.deleteImpl.name}]`,a={optsAddr:y({ibGib:e})};try{kt&&console.log(`${t} deleting from workspace...`);let n=e.ibGibs??[],s=e.data?.relPath??e.data?.ibGibAddrs?.[0];await this.deleteFromWorkspaceImpl({relPath:s,ibGib:n[0]}),a.success=!0}catch(n){console.error(`${t} ${g(n)} (E: a696eaa8c418c21438ad4d08fef09826)`),a.success=!1,a.errors=[g(n)]}return await this.resulty({resultData:a})}async persistOptsAndResultIbGibs({arg:e,result:t}){}};var Di="[glob-helper]",Li=!1,gs=[".vcsgib","b","ibgib","node_modules",".git"];function zr(o){let e=o.replace(/\\/g,"/"),t=e.replace(/\./g,"\\.").replace(/\?/g,"[^/]").replace(/\/\*\*\//g,"(?:/|/.+/)").replace(/\/\*\*/g,"(?:/.*)?").replace(/\*\*\//g,"(?:.*/)?").replace(/\*/g,"[^/]*");return e.endsWith("/")||(t+="(?:/.*)?"),new RegExp(`^${t}$`)}p(zr,"globToRegExp");function us(o){return o?o.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith("#")):[]}p(us,"parseFilterFileContent");function Jr({relativePath:o,isDirectory:e=!1,filterPatterns:t=[]}){let a=`${Di}[${Jr.name}]`;if(!o)return!1;let r=o.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,""),n=r.split("/")[0]||r;if(gs.includes(n)||gs.includes(r))return!0;if(t.length===0)return!1;let s=!1;for(let i of t){if(!i||i.trim()==="")continue;let c=i.trim();if(c.startsWith("regexp js ")){let h=c.substring(10);try{let I=new RegExp(h);(I.test(r)||I.test(n))&&(s=!0)}catch(I){console.error(`${a} Error evaluating regex pattern (${c}):`,I)}continue}let d=!1,f=c;f.startsWith("!")?(d=!0,f=f.substring(1).trim()):f.startsWith("include ")&&(d=!0,f=f.substring(8).trim());let b=f.endsWith("/");if(b&&!e)continue;let m=b?f.slice(0,-1):f,u=!1;if(m===n||r===m)u=!0;else if(m.includes("*")||m.includes("?")){let h=zr(m);u=h.test(r)||h.test(n)}else u=r.split("/").includes(m)||r.endsWith("/"+m);u&&(s=!d)}return Li&&console.log(`${a} relativePath: ${o}, isIgnored: ${s}`),s}p(Jr,"isPathFiltered");var ys="Web in-memory space witness for projecting and observing virtual workspace hierarchies in browser environments.";var Es={version:"1",uuid:Fa,name:Ma,classname:"WebInMemoryWorkspaceProjectionSpace_V1",workspaceRoot:"/",vcsFolderName:".vcsgib",persistOptsAndResultIbGibs:!1,validateIbGibAddrsMatchIbGibs:!1,longPollingIntervalMs:Ua,allowPrimitiveArgs:!1,catchAllErrors:!0,description:ys,trace:!1};var Zr=!1,or=class o extends nr{static{p(this,"WebInMemoryWorkspaceProjectionSpace_V1")}lc=`[${o.name}]`;backingSpace;_virtualFiles=new Map;constructor(e,t){let a,r=t,n;if(e&&("workspaceRoot"in e||"name"in e))a=e;else if(e&&typeof e=="object"){let s=e;a=s.initialData,r=s.initialRel8ns??t,n=s.backingSpace}super(a??Xe(Es),r),this.backingSpace=n}async putItemToWorkspaceImpl({item:e,subPath:t}){let a=`${this.lc}[${this.putItemToWorkspaceImpl.name}]`;try{if(Zr&&console.log(`${a} projecting item to virtual workspace...`),!e||!e.data)throw new Error(`${a} item and item.data are required (E: 469d887536c263a79853ceb4a0adef26)`);let{fsType:r,name:n}=e.data,s;if(t===void 0?s=r==="folder"?"":n||"":s=n?t?`${t}/${n}`:n:t,s=this.normalizePath(s),r==="folder"){s&&this._virtualFiles.set(s,{relPath:s,content:new Uint8Array(0),isDirectory:!0,modifiedAt:Date.now()});let i=e.rel8ns?.b2tFS_child||e.rel8ns?.b2tfs_child||[];for(let c of i){let d=await this.fetchIbGib(c);await this.putItemToWorkspaceImpl({item:d,subPath:s})}}else if(r==="file"){if(!e.rel8ns)throw new Error(`${a} item.rel8ns required for file item (E: cfa365f50fde8f65c8beb708b4630826)`);let i=e.rel8ns.bin;if(!i||i.length===0)throw new Error(`${a} item.rel8ns.bin required for file item ${n} (E: 7f994a5fe5f8123aec5f4fd870f72f26)`);let c=i.at(-1),d=await this.fetchIbGib(c);if(d.data===void 0)throw new Error(`${a} BinIbGib at addr ${c} has undefined data (E: a31a0812b1a8f40c7839be081a77ed26)`);let f;if(d.data instanceof Uint8Array)f=d.data;else if(typeof d.data=="string")f=new TextEncoder().encode(d.data);else if(typeof d.data=="object"){let b=Object.values(d.data);f=new Uint8Array(b)}else f=new Uint8Array(0);this._virtualFiles.set(s,{relPath:s,content:f,isDirectory:!1,modifiedAt:Date.now()})}}catch(r){throw console.error(`${a} ${g(r)} (E: d2b342499d289d6918197a06c02c5826)`),r}}async scanWorkspaceImpl({subPath:e,filterPatterns:t}){let a=`${this.lc}[${this.scanWorkspaceImpl.name}]`;try{Zr&&console.log(`${a} starting in-memory virtual scan...`);let r=this.data?.vcsFolderName||".vcsgib",n=t??this.data?.filterPatterns;if(!n||n.length===0){let d=this._virtualFiles.get(".ibgibignore");if(d&&!d.isDirectory){let f=new TextDecoder("utf8").decode(d.content);n=us(f)}else n=[]}let s=e?this.normalizePath(e):"",i=new Map,c=[];for(let[d,f]of this._virtualFiles.entries()){if(s&&!d.startsWith(s)||d===r||d.startsWith(r+"/")||d===".git"||d.startsWith(".git/")||d==="b"||d.startsWith("b/")||Jr({relativePath:d,isDirectory:f.isDirectory,filterPatterns:n}))continue;let b=d.split("/").pop()||d;if(f.isDirectory)i.set(d,{relPath:d,fullPath:d,isDirectory:!0});else if(this.isCommentMetadataFilename(b)){let m=d.split("/");m.pop();let u=m.join("/"),h=new TextDecoder("utf8").decode(f.content),I=this.extractCommentTopicName(b),E=u?`${u}/${I}`:I;c.push({commentRelPath:d,commentFullPath:d,targetRelPath:E,targetType:b.startsWith(".ib.")?"file":"folder",topicName:I,content:h})}else{let m=await crypto.subtle.digest("SHA-256",f.content),u=new Uint8Array(m),h="";for(let I=0;I<u.length;I++)h+=u[I].toString(16).padStart(2,"0");i.set(d,{relPath:d,fullPath:d,isDirectory:!1,fileHash:h,size:f.content.length})}}return{files:i,pendingComments:c}}catch(r){throw console.error(`${a} ${g(r)} (E: cb667820a7a8c36f58935348f0292126)`),r}}async deleteFromWorkspaceImpl({relPath:e,ibGib:t}){let a=`${this.lc}[${this.deleteFromWorkspaceImpl.name}]`;try{Zr&&console.log(`${a} deleting from virtual workspace...`);let r=this.normalizePath(e||t?.data?.name);if(!r)throw new Error(`${a} relPath or item name required for deletion (E: 2bd0d865e962e4457211f8a8d943ca26)`);let n=[];for(let s of this._virtualFiles.keys())(s===r||s.startsWith(`${r}/`))&&n.push(s);for(let s of n)this._virtualFiles.delete(s)}catch(r){throw console.error(`${a} ${g(r)} (E: a7cd788f4281a682d8f867c8ebed6c26)`),r}}async getFileBytesImpl({relPath:e}){return this.getVirtualFile(e)}getVirtualFile(e){let t=this.normalizePath(e),a=this._virtualFiles.get(t);if(!(!a||a.isDirectory))return a.content}getVirtualText(e){let t=this.getVirtualFile(e);if(t!==void 0)return new TextDecoder("utf8").decode(t)}setVirtualFile(e,t){let a=this.normalizePath(e),r=typeof t=="string"?new TextEncoder().encode(t):t,n=a.split("/");for(let s=1;s<n.length;s++){let i=n.slice(0,s).join("/");this._virtualFiles.has(i)||this._virtualFiles.set(i,{relPath:i,content:new Uint8Array(0),isDirectory:!0,modifiedAt:Date.now()})}this._virtualFiles.set(a,{relPath:a,content:r,isDirectory:!1,modifiedAt:Date.now()})}listVirtualPaths(){return Array.from(this._virtualFiles.keys()).sort()}clearVirtualFiles(){this._virtualFiles.clear()}normalizePath(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}isCommentMetadataFilename(e){return e.startsWith(".ib.")&&e.endsWith(".md")&&e.length>7}extractCommentTopicName(e){return this.isCommentMetadataFilename(e)?e.slice(4,-3):""}async fetchIbGib(e){let t=`${this.lc}[${this.fetchIbGib.name}]`;try{if(!this.backingSpace)throw new Error(`${t} backingSpace required to fetch IbGib at ${e} (E: 7ae09891d6a8f7a725787b58ad543826)`);let a=await ue({space:this.backingSpace,addrs:[e]});if(!a.success||!a.ibGibs||a.ibGibs.length===0){let n=a.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`${t} couldn't find addr ${e} in backingSpace. addrsNotFound: ${n} (E: 84be78955e98be16aa5630186a2bd826)`)}return a.ibGibs[0]}catch(a){throw console.error(`${t} ${g(a)} (E: 6ac378f35e08e1c4d11489d151994826)`),a}}};var ws="b2s_",sr="b2tfs_branch",Ne="main";var Is="[branch-helper]",Fe=!1;function Qr(o){let e=o.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${ws}${e}`}p(Qr,"getB2tFSBranchSpaceName");function Ri({branchName:o,uuid:e}){if(!o)throw new Error("branchName falsy (E: 61f048e02ea84a2276b3cd6d731fa826)");if(!e)throw new Error("uuid falsy (E: 3e54a910bb1815433822c78a9c48b826)");if(!bt.test(e))throw new Error(`uuid (${e}) does not match UUID_REGEXP (${bt.source}) (E: 64794844e948435c38f58a8891b6e126)`);return`${sr} ${o} v1 ${e}`}p(Ri,"getBranchIb");function wa({ib:o}){let e=`[${wa.name}]`;try{Fe&&console.log(`${e} starting... (I: cbd009f57961884dd3024c18f7b01926)`);let[t,a,r,n]=o.split(" ");if(!t)throw new Error("atom falsy (E: 68fb989be1ebaeb6220570618ee53826)");if(t!==sr)throw new Error(`atom !== ${sr} (b2tfs branch atom) (E: 389d481f8ca86472f81eaa61c55fdc26)`);if(!a)throw new Error("branchName falsy (E: d698cb6dc8b8b307485305e1527f5826)");if(!r)throw new Error("version falsy (E: 37ccf82d9718c38678c3f271e675c826)");if(r!=="v1")throw new Error(`version (${r}) !== 'v1' (E: 1122d86884d8231dcb7fddd889c9e626)`);if(!n)throw new Error("uuid falsy (E: 9edca4d919a8d44188d002b807aab826)");if(!bt.test(n))throw new Error(`uuid (${n}) does not match UUID_REGEXP (${bt.source}) (E: b60587540c5ddf17482eb47804909426)`);return{atom:t,branchName:a,version:r,uuid:n}}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{Fe&&console.log(`${e} complete.`)}}p(wa,"parseBranchIb");async function Ot(o){let e=`${Is}[${Ot.name}]`,{branchName:t,rootItem:a,space:r,metaspace:n}=o;if(!t||!a)throw new Error("branchName and rootItem required (E: c67bb2a61e6d4270d8056f0afb01d426)");let s=await Z(),i=y({ibGib:a}),c={name:t,uuid:s,classname:"B2tFSBranchIbGib_V1"},d={b2tfs_item:[i]},f=await U.firstGen({parentIbGib:Q,ib:Ri({branchName:t,uuid:s}),data:c,rel8ns:d,tjp:{timestamp:!0},dna:!0,nCounter:!0}),b=f.newIbGib;return await de({resTransform:f,space:r}),await oe({ibGib:b,space:r}),Fe&&console.log(`${e} Created branch IbGib: ${b.ib}`),b}p(Ot,"createB2tFSBranchIbGib");function Ve({targetDir:o,repoRoot:e,galaxyIbGib:t}){if(!e)throw new Error("(UNEXPECTED) repoRoot falsy when resolving contextual branch name (E: 71b3e819ac4092ad63e805da12480826)");if(!t)throw new Error("(UNEXPECTED) galaxyIbGib falsy when resolving contextual branch name (E: 83a04bc612984ea7c89f5d134b280826)");let a=(o||e).replace(/\\/g,"/").replace(/\/+$/,""),r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(a.startsWith(r)){let n=a.slice(r.length).replace(/^\/+/,"");if(n.startsWith("b/")||n==="b"){let s=n.split("/").filter(Boolean);if(s.length>=2&&s[0]==="b"){let i=s[1];if(i)return i}}}return t.data.activeBranchName||Ne}p(Ve,"resolveContextualBranchName");async function Gt({metaspace:o,branchName:e}){let t=`${Is}[${Gt.name}]`;try{if(Fe&&console.log(`${t} starting... (I: 237cfd38398851a997e0f399dc148826)`),!o||!e)throw new Error("metaspace and branchName are required (E: d223dc50b376e9b2d84c712fbb497826)");let a=Qr(e),n=(await o.getLocalUserSpaces({lock:!1})).find(s=>s.data?.name===a||s.ib===a);if(n){let s=ze(n.ib);return Fe&&console.log(`${t} Found existing branch space (name: ${a}, space.ib: ${n.ib}) (I: 58ef28a2eda5f501e78497381d596326)`),{space:n,spaceId:s,spaceName:a}}else{let s=await o.createLocalSpaceAndUpdateBootstrap({zeroSpace:o.zeroSpace,allowCancel:!1,createBootstrap:!1,spaceName:a});if(!s)throw new Error("(UNEXPECTED) newBranchSpace falsy? we just called the create function, so we could not create a local space and update bootstrap? But it didn't throw an exception? (E: 4b8be9dd6a182090680b60c8653f2826)");if(!s.data)throw new Error("(UNEXPECTED) newBranchSpace.data falsy? (E: dc3e78b7a3782e7dd80f4fb8609f8a26)");let i=ze(s.ib);return Fe&&console.log(`${t} Using branchName (${e}), created new branch space (ib: ${s.ib}) (I: fc08086f6cc73caa383bc72c662ee826)`),{space:s,spaceId:i,spaceName:a}}}catch(a){throw console.error(`${t} ${g(a)} (E: 091a2820de9a3eca833107883524c626)`),a}finally{Fe&&console.log(`${t} complete. (I: 8452386b1247d58618905a28cf692126)`)}}p(Gt,"getOrCreateBranchSpace");async function en({galaxyIbGib:o}){let e=`[${en.name}]`;try{Fe&&console.log(`${e} starting... (I: 86f07281948470f89ae72308e1e92826)`);let t=o.data["$@branch"];if(!t)throw new Error("galaxyIbGib.data['$@branch'] falsy. galaxyIbGib has no branches? (E: 5c622256cb08b40d89c40d787757cf26)");let a=[];for(let r of t){let n=Vt({sqAddr:r}),{ib:s}=n,i=wa({ib:s}),c=r,d=n,f=i;a.push({branchName:f.branchName,branchId:f.uuid,branchIbInfo:f,branchAddr:d.ibGibAddr,branchSqAddr:c,branchSqAddrInfo:d})}return a}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{Fe&&console.log(`${e} complete.`)}}p(en,"getAllBranchInfosFromGalaxy");async function tn({galaxyIbGib:o,branchName:e}){let t=`[${tn.name}]`;try{Fe&&console.log(`${t} starting... (I: d63138d40debdb1a8b398b6135875326)`);let a=o.data["$@branch"];if(!a)throw new Error("galaxyIbGib.data['$@branch'] falsy. galaxyIbGib has no branches? (E: 2462fdd930889869c8eb1a71f5383826)");let r,n,s;for(let i of a){let c=Vt({sqAddr:i}),{ib:d}=c,f=wa({ib:d});if(f.branchName===e){n=i,s=c,r=f;break}}if(!r||!n||!s)throw new Error(`branchName (${e}) not found in galaxyIbGib ${y({ibGib:o})} (E: 8c9cf891f118afafe853049883248826)`);return{branchName:e,branchId:r.uuid,branchIbInfo:r,branchAddr:s.ibGibAddr,branchSqAddr:n,branchSqAddrInfo:s}}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Fe&&console.log(`${t} complete.`)}}p(tn,"getBranchInfoFromGalaxy");async function an({galaxyIbGib:o,metaspace:e}){let t=`[${an.name}]`;try{if(Fe&&console.log(`${t} starting... (I: 1b14785116888c37a8b3a03189811826)`),!o)throw new Error("(UNEXPECTED) galaxyIbGib falsy? (E: 52242814ae88f24442f0dc289505b826)");let a=y({ibGib:o});if(!e)throw new Error("(UNEXPECTED) metaspace falsy? (E: 1a7dc1b555bd5ee98a826da857a5c826)");let r=o.data?.["$@branch"]||[];if(r.length===0)return Fe&&console.warn(`${t} sqBranchAddrs.length === 0? (I: 3f266c20f1bd64b56642be7f16e4b826)`),[];let n=[];for(let s of r){let i=Vt({sqAddr:s});if(!i)throw new Error("(UNEXPECTED) parsedBranchAddr falsy? (E: e875d8678427fd0673d2b9f86f59c826)");let{ibGibAddr:c,spaceId:d}=i;if(!d)throw new Error("branchSpaceId falsy (E: f062a83ebb5875bf9fd7ece8c9d93826)");let f=await e.getLocalUserSpace({lock:!1,localSpaceId:d});if(!f)throw new Error(`invalid galaxy ibgib (${a}). metaspace could not get local user space corresponding to parsedBranchAddrInfo.spaceId (${i.spaceId}) (E: 78d10468b3588b2508d029c880ecc826)`);if(!f.data)throw new Error("(UNEXPECTED) branchSpace.data falsy? (E: e5be780d68480d8166df1e8ef01cff26)");if(!f.ib)throw new Error("(UNEXPECTED) branchSpace.ib falsy? (E: 1673288d85680c991837fd57d9b3e526)");let b=await ie({addr:c,space:f,metaspace:e});if(b)n.push(b);else throw new Error(`branchIbGib falsy. could not get branchAddr (${c}) from branchSpace (ib: ${f.ib}) (E: 2a1f47785e282da798002c6e09b18326)`)}return n}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Fe&&console.log(`${t} complete.`)}}p(an,"getAllBranchIbGibsFromGalaxy");var ki=/^(\\\\|[/\\]{2})[^/\\]+[/\\]+[^/\\]+/,rn=class o{static{p(this,"DefaultPathHelper")}lc=`[${o.name}]`;toPosix(e){return e?e.replace(/\\/g,"/"):""}isAbsolute(e){return e?!!(e.startsWith("/")||e.startsWith("\\")||/^[a-zA-Z]:[/\\]/.test(e)||ki.test(e)):!1}isRelative(e){return!this.isAbsolute(e)}normalize(e){if(!e||e.trim()==="")return".";let t=e.includes("\\")||/^[a-zA-Z]:/.test(e),a=t&&e.includes("\\")&&!e.includes("/")||t&&e.includes("\\")?"\\":"/",r="",n=e,s=e.match(/^[a-zA-Z]:[/\\]?/);if(s)r=s[0],r.length===2&&(r+=e.includes("\\")?"\\":"/"),n=e.slice(s[0].length);else if(e.startsWith("\\\\")||e.startsWith("//")){let b=e.match(/^(\\\\|[/\\]{2})[^/\\]+[/\\]+[^/\\]+[/\\]?/);b?(r=b[0],n=e.slice(b[0].length)):(r=e.startsWith("\\\\")?"\\\\":"//",n=e.slice(2))}else(e.startsWith("/")||e.startsWith("\\"))&&(r=e.startsWith("\\")&&!e.includes("/")?"\\":"/",n=e.slice(1));let i=(n.endsWith("/")||n.endsWith("\\")||e.endsWith("/")||e.endsWith("\\"))&&e.length>1,c=n.split(/[/\\]+/),d=[];for(let b of c)!b||b==="."||(b===".."?d.length>0&&d.at(-1)!==".."?d.pop():r||d.push(".."):d.push(b));let f=d.join(a);return r?f?r.endsWith("/")||r.endsWith("\\")?f=r+f:f=r+a+f:f=r:f||(f="."),i&&!f.endsWith("/")&&!f.endsWith("\\")&&f!=="."&&(f+=a),f}join(...e){let t=e.filter(i=>i&&typeof i=="string"&&i.trim()!=="");if(t.length===0)return".";let a=t.some(i=>i.includes("\\")),r=t.some(i=>/^[a-zA-Z]:/.test(i)),n=(a||r)&&a?"\\":"/",s="";for(let i=0;i<t.length;i++){let c=t[i];if(i===0)s=c;else{let d=c.replace(/^[/\\]+/,"");s.endsWith("/")||s.endsWith("\\")?s+=d:s+=n+d}}return this.normalize(s)}dirname(e){if(!e||e.trim()==="")return".";let t=this.normalize(e);if(t==="/"||t==="\\"||/^[a-zA-Z]:[/\\]?$/.test(t))return t;let a=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));if(a===-1)return".";if(a===0)return t.slice(0,1);let r=t.slice(0,a);return/^[a-zA-Z]:$/.test(r)?t.slice(0,a+1):r}basename(e,t){if(!e||e.trim()==="")return"";let a=e.replace(/[/\\]+$/,""),r=Math.max(a.lastIndexOf("/"),a.lastIndexOf("\\")),n=r===-1?a:a.slice(r+1);return t&&n.endsWith(t)&&n.length>t.length&&(n=n.slice(0,n.length-t.length)),n}extname(e){if(!e)return"";let t=this.basename(e),a=t.lastIndexOf(".");return a<=0?"":t.slice(a)}relative(e,t){let a=this.normalize(e),r=this.normalize(t);if(a===r)return"";let n=a.match(/^[a-zA-Z]:/),s=r.match(/^[a-zA-Z]:/);if(n&&s&&n[0].toLowerCase()!==s[0].toLowerCase())return r;let c=a.includes("\\")||r.includes("\\")?"\\":"/",d=this.toPosix(a).split("/").filter(Boolean),f=this.toPosix(r).split("/").filter(Boolean),b=0;for(;b<d.length&&b<f.length&&d[b].toLowerCase()===f[b].toLowerCase();)b++;let m=d.length-b,u=[];for(let h=0;h<m;h++)u.push("..");return u.push(...f.slice(b)),u.join(c)||"."}},Ia=new rn;function ir(o){return Ia.toPosix(o)}p(ir,"toPosixPath");function re(...o){return Ia.join(...o)}p(re,"joinPaths");function Ss(o){return Ia.dirname(o)}p(Ss,"dirnamePath");function Gs(o,e){return Ia.basename(o,e)}p(Gs,"basenamePath");function As(o){return Ia.extname(o)}p(As,"extnamePath");var aa="b2tfs_galaxy",cr="b2tfs_galaxy";var Sa={file:"file",folder:"folder"},_h=Object.values(Sa),pe="b2tfs_child",nn="bin";var ra="b2tfs_item",Oi="v1";function Fi(o){return o?o.replace(/[^a-zA-Z0-9_\-\.]/g,"_").slice(0,32):"unnamed"}p(Fi,"getB2tFSItemSaferName");function $s(o,e,t){let a=Fi(e);return`${ra} ${o} ${a} ${Oi} ${t}`}p($s,"getB2tFSItemIb");var He=!1,on="[item-helper]";function na(o){return!o||!Va(o)?!1:o.ib.startsWith(ra)||o.data?.classname==="B2tFSItemIbGib_V1"}p(na,"isB2tFSItemIbGib");async function At({fsType:o,name:e,data:t,rel8ns:a}){let r=`${on}[${At.name}]`;try{if(He&&console.log(`${r} starting... (I: 9f7d189b5bbb4ad5a819c568ce0d7826)`),!o||!e)throw new Error("fsType and name are required (E: 488874f761040744a89ef772af873826)");let n=t?.nameHash||await Ye({s:e}),s=t?.uuid||await Z(),i=t?.diffTransactionId||await Z(),c,d;if(o==="file"){let u=e.lastIndexOf(".");u>0?(c=e.slice(0,u),d=e.slice(u+1)):(c=e,d="")}let f={name:e,nameHash:n,fsType:o,diffTransactionId:i,uuid:s,classname:"B2tFSItemIbGib_V1",...o==="file"?{fileNameSansExt:c,fileExt:d}:{},...t},b=$s(o,e,n),m=await U.firstGen({parentIbGib:U.primitive({ib:ra}),ib:b,data:f,rel8ns:a,tjp:{timestamp:!0,uuid:!0},dna:!0,nCounter:!0});return He&&console.log(`${r} Created new B2tFSItemIbGib: ${m.newIbGib.ib}^${m.newIbGib.gib} (I: aaf52cddf678c29a25875843cf2fd826)`),m}catch(n){throw console.error(`${r} ${g(n)} (E: edcfc8414233fa9b6658558808c6a826)`),n}finally{He&&console.log(`${r} complete. (I: 4927283a2dd82bc9abc4af0be0f2b826)`)}}p(At,"createB2tFSItemIbGib");async function ct({existingItem:o,dataToUpdate:e,rel8nsToUpdate:t,rel8nsToRemove:a}){let r=`${on}[${ct.name}]`;try{if(He&&console.log(`${r} starting... (I: d35e11bfe428b5dfe1dfb7b74602c826)`),!o||!o.ib||!o.gib)throw new Error("existingItem with valid ib and gib is required (E: 258048f80f954dc9786434c8dc0e8b26)");let n=o,s=[],i=[];(!n.rel8ns?.ancestor||n.rel8ns.ancestor.length===0)&&(n={...n,rel8ns:{...n.rel8ns||{},ancestor:[`${ra}^gib`]}});let c=e&&Object.keys(e).length>0,d=t&&Object.keys(t).length>0||a&&Object.keys(a).length>0,f={...e||{},diffTransactionId:e?.diffTransactionId||await Z()},b=await pt({src:n,dataToAddOrPatch:f,dna:!0,nCounter:!f.n});if(n=b.newIbGib,b.dnas&&s.push(...b.dnas),d){i.push(n);let m=await qe({src:n,rel8nsToAddByAddr:t,rel8nsToRemoveByAddr:a,dna:!0,nCounter:!0});n=m.newIbGib,m.dnas&&s.push(...m.dnas)}return(!n.rel8ns?.ancestor||n.rel8ns.ancestor.length===0)&&(n.rel8ns={...n.rel8ns||{},ancestor:[`${ra}^gib`]}),He&&console.log(`${r} Evolved B2tFSItemIbGib: ${n.ib}^${n.gib} (I: 5a5d21af206847cde30c2728bfdb3226)`),{newIbGib:n,intermediateIbGibs:i.length>0?i:void 0,dnas:s.length>0?s:void 0}}catch(n){throw console.error(`${r} ${g(n)} (E: 25eae258d173872aa8cc83dc2b7e6926)`),n}finally{He&&console.log(`${r} complete. (I: fe33389c0ed1777ce89d3428a7419826)`)}}p(ct,"evolveB2tFSItemIbGib");async function sn({rootItem:o,rootItemAddr:e,space:t,metaspace:a}){let r=`${on}[${sn.name}]`;try{He&&console.log(`${r} starting... (I: 428138d15828380a13dfff9a51944826)`);let n=await Yn({ibGib:o,ibGibAddr:e,onlyRel8nNames:[pe],space:t,metaspace:a});return{reifiedRootItem:n.reifiedIbGib,hasChanges:n.hasChanges,reifiedAddrsMap:n.reifiedAddrsMap,evolvedItems:n.evolvedIbGibs}}catch(n){throw console.error(`${r} ${g(n)} (E: f4ef9c7357e883019c09e84887ad3826)`),n}finally{He&&console.log(`${r} complete. (I: 071471754e888273f8abcfe85d478826)`)}}p(sn,"reifyB2tFSHierarchy");async function _s({branchIbGib:o,addrOnly:e,branchSpace:t}){let a=`[${_s.name}]`;try{if(He&&console.log(`${a} starting... (I: 92cc9882ded8da7128efcbd8b37ec826)`),!o.rel8ns)throw new Error("(UNEXPECTED) branchIbGib.rel8ns falsy? (E: 433b027e958503e648a0858807b85826)");if(!o.rel8ns.b2tfs_item)throw new Error("(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item falsy? (E: c5989d7fa2f836e6781a929d76958726)");if(o.rel8ns.b2tfs_item.length===0)throw new Error("(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item empty? (E: 2c634c54ec485ed638eb12083ea93826)");let r=o.rel8ns.b2tfs_item.at(-1),n;if(!e){if(!t)throw new Error("branchSpace required when addrOnly is false. (E: 51fa687228a82f3638517c7e4b249826)");n=await ie({addr:r,space:t})}return{rootItemAddr:r,rootItemIbGib:n}}catch(r){throw console.error(`${a} ${g(r)}`),r}finally{He&&console.log(`${a} complete.`)}}p(_s,"getRootItemFromBranchIbGib");async function Ae({galaxyIbGib:o,branchName:e,metaspace:t}){let a=`[${Ae.name}]`;try{He&&console.log(`${a} starting... (I: acae374202688beed805e578fec3ea26)`);let r=await tn({galaxyIbGib:o,branchName:e}),n=await t.getLocalUserSpace({localSpaceId:r.branchSqAddrInfo.spaceId,lock:!1});if(!n)throw new Error(`branchSpace not found from branchSqAddr: ${r.branchSqAddr} (E: 62dd9fb2a5b8cea6734a6038c8c6fb26)`);let{branchAddr:s}=r;if((await t.getLatestAddr({addr:s,space:n})||s)!==s)throw new Error("(UNEXPECTED) branchAddr_latest !== branchAddr? I have no idea if this will hit or not, I am just putting this exception here in case I need to account for this situation. For one thing, the branch info is wrong if this is the case. (E: d8ebd6e351b74a54b8af73e88cf74826)");let c=await ie({addr:s,space:n});if(!c)throw new Error(`(UNEXPECTED) branchAddr (${s}) not found in branchSpace (${n.ib})? (E: 8f9a48a0d5a88c99468b121edbc51826)`);let{rootItemAddr:d,rootItemIbGib:f}=await _s({branchIbGib:c,branchSpace:n,addrOnly:!1});if(!f)throw new Error("(UNEXPECTED) rootItemIbGib falsy? (E: 883d18f3c978a919a8f298b9d6971826)");let b=await t.getLatestAddr({addr:d,space:n})||d,m=f;if(b!==d&&(m=await ie({addr:b,space:n}),!m))throw new Error(`(UNEXPECTED) rootItemIbGib_latest falsy? We just got rootItemAddr_latest (${b}) from branchSpace (${n.ib}), so we should have been able to get the corresponding ibgib. (E: 86bd690fb143f0a1e80209387ff7c426)`);return{branchIbGib:c,branchInfo:r,branchSpace:n,rootItemAddr:d,rootItemAddr_latest:b,rootItemIbGib:f,rootItemIbGib_latest:m}}catch(r){throw console.error(`${a} ${g(r)}`),r}finally{He&&console.log(`${a} complete.`)}}p(Ae,"getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib");async function Cs({name:o,content:e}){return(await At({fsType:"file",name:o,data:{isVirtual:!0,virtualFileContents:e}})).newIbGib}p(Cs,"createVirtualItemIbGib");var Se=!1,$t=class o extends qt{static{p(this,"SyncPeerInnerspace_V1")}lc=`[${o.name}]`;get classname(){return o.name}constructor(e,t){super(e,t)}async preConnectCheck(e){let t=`${this.lc}[${this.preConnectCheck.name}]`;try{if(Se&&console.log(`${t} starting... (I: af5dc1a0bf980848b84e50515614be26)`),!e.sagaId)throw new Error(`${t} sagaId required for connect (E: 8a4c0a9b8f1d4f2b1c3b5d6e8a4c0a9b)`);if(!this.opts)throw new Error("this.opts falsy. required to connect (E: 4c24fd577f9cd695a8bf0dc8ddea6826)")}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Se&&console.log(`${t} complete.`)}}async connectImpl(e){let t=`${this.lc}[${this.connectImpl.name}]`;try{if(Se&&console.log(`${t} starting... (I: 2b8f8040d9b4c48a735c021c33f2a826)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: d617e80d8e082bc76853dba8bb87cc26)")}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Se&&console.log(`${t} complete.`)}}async postEstablishToReceiver({newSenderIdentity:e,sessionIdentity:t}){let a=`${this.lc}[${this.postEstablishToReceiver.name}]`;try{if(Se&&console.log(`${a} starting... (I: 6ca5e81a59a861c1f327df0885198a26)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: 1bb4b875bdb8e88bedff5ab80d1d5826)");let{receiverMetaspace:r,receiverSpace:n}=this.opts;await r.put({ibGib:e,space:n}),await r.registerNewIbGib({ibGib:e,space:n}),await r.put({ibGib:t,space:n}),await r.registerNewIbGib({ibGib:t,space:n})}catch(r){throw console.error(`${a} ${g(r)}`),r}finally{Se&&console.log(`${a} complete.`)}}async ensureReceiverTempSpace(){let e=`${this.lc}[${this.ensureReceiverTempSpace.name}]`;try{if(Se&&console.log(`${e} starting... (I: bab87f15dea77cd4892bd8a8d2e65826)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: 0f85bd4c3efdbee2a829aca860c48926)");if(!this.opts.receiverTempSpace){let{receiverMetaspace:t}=this.opts,r=`tmp_sync_recv_${(crypto.randomUUID?crypto.randomUUID():Math.random().toString(36)).substring(0,8)}`,n=await t.createNewLocalSpace({opts:{allowCancel:!1,spaceName:r,getFnPrompt:t.getFnPrompt,logalot:Se}});if(!n)throw new Error("(UNEXPECTED) receiverTempSpace falsy? couldn't create a temp space? (E: a6b8f86b0f58384b884a33b82924b826)");await n.initialized,this.opts.receiverTempSpace=n}return this.opts.receiverTempSpace}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{Se&&console.log(`${e} complete.`)}}async sendContextRequest(e){let t=`${this.lc}[${this.sendContextRequest.name}]`;try{if(Se&&console.log(`${t} starting... (I: bab87f15dea77cd4892bd8a8d2e65826)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: d8b1348e3233810128999596b1fa5826)");await this.ensureReceiverTempSpace();let{localSpace:a,localTempSpace:r,receiverSpace:n,receiverCoordinator:s,receiverMetaspace:i,receiverTempSpace:c}=this.opts;Se&&console.log(`${t} starting...Context: ${y({ibGib:e})}`);let{sagaFrame:d}=e;if(!e.data)throw new Error("(UNEXPECTED) context.data falsy? (E: 1d2ac8a9b991d451e8900588057fe626)");if(!e.rel8ns)throw new Error("(UNEXPECTED) context.rel8ns falsy? (E: 3508786f0d8880bcadd346282a807826)");if(!e.rel8ns.sagaFrame)throw new Error("(UNEXPECTED) context.rel8ns.sagaFrame falsy? (E: ac06782ad538be406882605f0a83aa26)");if(!e.sagaFrame)throw new Error("(UNEXPECTED) context.sagaFrame falsy? (E: 79cd98a6d9b88a591f4596c8bc58ff26)");if(!d.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: f30e290a8b770e1b387377420ea73a26)");if(!d.rel8ns)throw new Error("(UNEXPECTED) sagaFrame.rel8ns falsy? (E: f888caa698b8cf6b4893b7fd6df09726)");if(!c)throw new Error("(UNEXPECTED) receiverTempSpace falsy? (E: 3b46d838f6fc645c58b29215bfddb826)");if(!r)throw new Error("(UNEXPECTED) localTempSpace falsy? (E: b187a8f913c2295ae90d7ae2b47b6a26)");let{sagaIbGib:f,msgStones:b}=await Dt({sagaIbGib:d,localSpace:a});if(b.length!==1)throw new Error("(UNEXPECTED) msgStones.length !== 1? we're only geared for a single msg stone that is always present (not 0, not greater than 1) (E: 2d3138ed130f1aca116551889483e826)");let m=b[0];if(!m.data)throw new Error("(UNEXPECTED) sync saga message ibgib.data falsy? (E: 61ec18743988ad3cbab2072d1dd69826)");let u=[m,d,e].map(G=>st({ibGib:G}));e.signedSessionIdentity&&u.push(st({ibGib:e.signedSessionIdentity})),Se&&console.log(`${t} putting into receiverSpace: ${n.ib} (I: 1ba18b14a26bdd0e7800da4812898826)`),await se({ibGibs:u,space:n});for(let G of u)await oe({ibGib:G,space:n,fnBroadcast:void 0});e.payloadIbGibsDomain&&e.payloadIbGibsDomain.length>0&&(Se&&console.log(`${t} putting into receiverTempSpace: ${c.ib} (I: d0cea920b818393d68118bc8a1515526)`),await Et({ibGibs:e.payloadIbGibsDomain,space:c}));let h=await s.continueSync({sagaContext:e,metaspace:i,mySpace:n,myTempSpace:c,peer:this});if(Se&&console.log(`${t} receiverCoordinator.continueSync responseCtx: ${h?ge(h):"undefined"} (I: fb2831decde1f2b3589021f85ab19126)`),!h){Se&&console.log(`${t} receiver produced undefined response context. (I: 2e1888ffc9e836689d5b171887c36d26)`);return}let{msgStones:I}=await Dt({sagaIbGib:h.sagaFrame,localSpace:n});if(I.length!==1)throw new Error("(UNEXPECTED) msgStonesResponse.length !== 1? we're only geared for a single msg stone that is always present (not 0, not greater than 1) (E: 2d3138ed130f1aca116551889483e826)");let E=I[0];if(!E.data)throw new Error("(UNEXPECTED) sync saga message ibgib.data falsy? (E: 61ec18743988ad3cbab2072d1dd69826)");let w=[E,h.sagaFrame,h].map(G=>st({ibGib:G}));await se({ibGibs:w,space:a});for(let G of w)await oe({ibGib:G,space:a,fnBroadcast:void 0});let A=h.payloadIbGibsDomain;return A&&(new Promise(async(G,T)=>{let C=`${t}[putPayloadsPromise]`;try{if(Se&&console.log(`${C} starting... (I: 4133e736b4c80d2cf94448b87b206826)`),Se)for(let _=0;_<10;_++)console.warn(`${t} ARTIFICIALLY DELAYING PAYLOADS TO MIMIC TRANSFER LATENCY. REMOVE THIS DELAY!! (W: 5e7b28f1daa82d955897e9d8cdb16f26)`),await Ra(16);await Et({ibGibs:A,space:r});for(let S of A)await this.payloadIbGibsDomainReceived$.next(S);Se&&console.log(`${C} complete.`),G()}catch(S){let _=`${C} ${g(S)}`;console.error(_),Se&&console.log(`${C} complete. (errored)`),T(_)}}),delete h.payloadIbGibsDomain),h}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Se&&console.log(`${t} complete.`)}}};var dr={classname:$t.name};var Mi="[branch-graph-helper]",lr=!1;async function cn({sourceSpace:o,targetBranchSpace:e,rootItemIbGib:t,branchName:a,metaspace:r}){let n=`${Mi}[${cn.name}]`;try{if(lr&&console.log(`${n} starting... (I: bc5303fbf9f80cbce8423bc174313826)`),!o||!e||!t||!r)throw new Error("sourceSpace, targetBranchSpace, rootItemIbGib, and metaspace are required (E: d97b285b899e7b427840008e6ff69826)");let s=new le,i=new le,c=new $t(Xe(dr));await c.initialized,await c.initializeOpts({localMetaspace:r,localSpace:o,receiverSpace:e,receiverCoordinator:i,receiverMetaspace:r}),await(await s.sync({peer:c,localSpace:o,metaspace:r,domainIbGibs:[t]})).done,lr&&console.log(`${n} SyncSagaCoordinator sync initiated for ${t.ib} (I: f0a798bee4ae2b73f8e7e5ac921bc826)`);let f=1,b;return a&&r&&(b=await Ot({branchName:a,rootItem:t,space:e,metaspace:r})),lr&&console.log(`${n} Populated target branch space via SyncSagaCoordinator (I: c0ec8e54539765f6fe250bc820dee826)`),{syncedCount:f,branchIbGib:b}}catch(s){throw console.error(`${n} ${g(s)} (E: 353e4f45b478d33e48f898a65893b826)`),s}finally{lr&&console.log(`${n} complete. (I: 4036b819429e2a63add97a8843bbc826)`)}}p(cn,"populateBranchSpaceFromGraph");function fr(o){let e=Math.min(o.length,1024);for(let t=0;t<e;t++)if(o[t]===0)return!0;return!1}p(fr,"isBinaryBuffer");function br(o,e="utf8"){if(!o||o.length===0)return[];try{return new TextDecoder(e||"utf8",{fatal:!1}).decode(o).split(/\r?\n/)}catch{return[]}}p(br,"decodeToLines");function dn(o,e){let t=o.length,a=e.length;if(t===a&&o.every((b,m)=>b===e[m]))return[];let r=Array.from({length:t+1},()=>new Array(a+1).fill(0));for(let b=1;b<=t;b++)for(let m=1;m<=a;m++)o[b-1]===e[m-1]?r[b][m]=r[b-1][m-1]+1:r[b][m]=Math.max(r[b-1][m],r[b][m-1]);let n=t,s=a,i=[];for(;n>0||s>0;)n>0&&s>0&&o[n-1]===e[s-1]?(i.push({type:"equal",oldIdx:n-1,line:o[n-1]}),n--,s--):s>0&&(n===0||r[n][s-1]>=r[n-1][s])?(i.push({type:"insert",line:e[s-1]}),s--):n>0&&(s===0||r[n][s-1]<r[n-1][s])&&(i.push({type:"delete",oldIdx:n-1,line:o[n-1]}),n--);i.reverse();let c=[],d=null,f=0;for(let b of i)b.type==="equal"?(d&&(c.push(d),d=null),f++):(d||(d={old_i:f,oldLines:[],newLines:[]}),b.type==="delete"?(d.oldLines.push(b.line),f++):b.type==="insert"&&d.newLines.push(b.line));return d&&c.push(d),c}p(dn,"computeLineLcsDiff");var Ui="[b2tfs-3way-graft-strategy]",dt=!1,oa="[MERGE DIAGNOSTIC]";function Vi({textLCA:o,textBase:e,textOrphan:t}){if(e===t)return{mergedText:e,hasConflict:!1};if(e===o)return{mergedText:t,hasConflict:!1};if(t===o)return{mergedText:e,hasConflict:!1};let a=o.split(/\r?\n/),r=e.split(/\r?\n/),n=t.split(/\r?\n/),s=dn(a,r),i=dn(a,n);if(s.length===0)return{mergedText:t,hasConflict:!1};if(i.length===0)return{mergedText:e,hasConflict:!1};let c=!1,d=[],f=0,b=0,m=0;for(;f<a.length||b<s.length||m<i.length;){let u=s[b],h=i[m],I=u&&u.old_i===f,E=h&&h.old_i===f;if(I&&E){let w=u.newLines,A=h.newLines,G=u.oldLines.length,T=h.oldLines.length;w.join(`
19
- `)===A.join(`
20
- `)&&G===T?d.push(...w):(c=!0,d.push("<<<<<<< HEAD"),d.push(...w),d.push("======="),d.push(...A),d.push(">>>>>>>"));let C=Math.max(G,T,1);f+=C,b++,m++}else if(I){d.push(...u.newLines);let w=Math.max(u.oldLines.length,1);f+=w,b++}else if(E){d.push(...h.newLines);let w=Math.max(h.oldLines.length,1);f+=w,m++}else f<a.length?(d.push(a[f]),f++):(u&&b<s.length&&(d.push(...u.newLines),b++),h&&m<i.length&&(d.push(...h.newLines),m++))}return{mergedText:d.join(`
21
- `),hasConflict:c}}p(Vi,"perform3WayTextLineMerge");var mr=class extends Jt{static{p(this,"B2tFS3WayGraftStrategy")}strategyId="B2tFS3WayGraftStrategy";lc="[B2tFS3WayGraftStrategy]";async canGraft(e){let t=`${this.lc}[${this.canGraft.name}]`;try{let{conflictStrategy:a,timelineAddrsA:r,timelineAddrsB:n,ibGibReadCache:s,space:i}=e;if(!(a===ve.optimisticWithLCS||a==="b2tfs3WayMerge"))return!1;let d=r.at(-1),f=n.at(-1);if(!d||!f)return dt&&console.log(`${t} we don't have two tip addrs? (I: b20b6de462c35e0e74360cc8d317f126)`),!1;let[b,m]=await Re({addrs:[d,f],readCache_graph:s,space:i});if(!b)throw new Error("(UNEXPECTED) tipA falsy? (E: 752101026888140f074614e893531826)");if(!m)throw new Error("(UNEXPECTED) tipB falsy? (E: d4d4a876cad8c7869830d33832bfde26)");if(!(na(b)&&na(m)))return(na(b)||na(m))&&console.error(`${t}${oa} (UNEXPECTED)(NOT THROWN) only tipA or tipB but not both are b2tfs items? (E: cacb38796da881268898e9d1af245826)`),!1;if(b.data.fsType!==m.data.fsType)throw new Error(`(UNEXPECTED) tipA.data.fsType (${b.data.fsType}) !== tipB.data.fsType (${m.data.fsType})? (E: c01c1885ac738f679813117852c48426)`);return b.data.fsType===Sa.file}catch(a){return console.error(`${t} ${g(a)} (E: 463df8afd9a8c42008856f3737b71826)`),!1}}async graft(e){let t=`${Ui}[${this.strategyId}][${this.graft.name}]`;try{dt&&console.log(`${t} starting 3-way B2tFS snapshot graft... (I: 88cf3a0e67b3da14bfea241159296e26)`);let{conflictStrategy:a,timelineAddrsA:r,timelineAddrsB:n,latestCommonFrameAddr:s,ibGibReadCache:i,space:c,graftPreference:d}=e,f=r.lastIndexOf(s),b=r.slice(f+1),m=await Re({readCache_graph:i,addrs:b,space:c}),u=m.at(-1),h=n.lastIndexOf(s),I=n.slice(h+1),E=await Re({readCache_graph:i,addrs:I,space:c}),w=E.at(-1),{baseTip:A,baseBranch:G,orphanTip:T,orphanBranch:C}=this.resolveBaseAndOrphan({graftPreference:d,tipA_sender:u,branchA_sender_sinceLCA:m,tipB_receiver:w,branchB_receiver_sinceLCA:E}),S=y({ibGib:A}),_=G.map(_e=>y({ibGib:_e})),$=y({ibGib:T}),B=C.map(_e=>y({ibGib:_e}));dt&&(console.log(`${t} baseBranchAddrs:
22
- ${_.join(`
23
- `)} (I: 2cad420d7bc822f798b8a8785f1f8c26)`),console.log(`${t} orphanBranchAddrs:
24
- ${B.join(`
25
- `)} (I: cc86489d6737e2aced42b585cba13526)`));let D=await this.fetchIbGib({addr:s,space:c,readCache_graph:i});if(!D)throw new Error("(UNEXPECTED) lcaNode falsy? (E: a8b2d80dc4f8ba1448fa280d89dfb626)");let N=await this.resolveRootItemNode({nodeOrAddr:D,space:c,readCache_graph:i});if(!N)throw new Error("(UNEXPECTED) lcaItem falsy? (E: 0944f88dde58cbabf82342b814955826)");let x=await this.resolveRootItemNode({nodeOrAddr:A,space:c,readCache_graph:i});if(!x)throw new Error("(UNEXPECTED) baseItem falsy? (E: fac3087884cbebc7083e580514002826)");let L=await this.resolveRootItemNode({nodeOrAddr:T,space:c,readCache_graph:i});if(!L)throw new Error("(UNEXPECTED) orphanItem falsy? (E: 8e7e383753a8814f283280ee82156826)");if(N.data.fsType!==x.data.fsType)throw new Error("(UNEXPECTED) lcaItem.data.fsType !== baseItem.data.fsType? (E: 794608f3e678a399ed670388629a6826)");if(N.data.fsType!==L.data.fsType)throw new Error("(UNEXPECTED) lcaItem.data.fsType !== orphanItem.data.fsType? (E: 2813981c8c422b41f85a02fd8aa88226)");let k=N.data.fsType;if(k===Sa.folder)throw new Error("(UNEXPECTED) fsType === B2tFSType.folder? Folders fall back to DefaultDnaReplayGraftStrategy and reification. (E: b282b8f77b18575378edb902bd80a826)");if(k!==Sa.file)throw new Error(`(UNEXPECTED) fsType (${k}) is not a file? (E: 272418fe2067ea3e16dac028e86d1a26)`);let te=await this.getFilePayloadBuffer({fileItem:N,space:c,readCache_graph:i}),X=await this.getFilePayloadBuffer({fileItem:x,space:c,readCache_graph:i}),W=await this.getFilePayloadBuffer({fileItem:L,space:c,readCache_graph:i}),Ge=X?fr(X.buffer):!1,Ee=W?fr(W.buffer):!1,ne=te?fr(te.buffer):!1;if(Ge||Ee||ne){dt&&console.log(`${t} Non-text binary file detected (${x.data?.name}). Skipping 3-way line diff and falling through. (I: 8ff3a887d3ea1f162317b77feb7ec326)`);return}if(!te)throw new Error("(UNEXPECTED) lcaPayload falsy? (E: 0b82892204482f5538a430b8915b7826)");if(!X)throw new Error("(UNEXPECTED) basePayload falsy? (E: af1f68a020280b3a5d6ed4a812acd426)");if(!W)throw new Error("(UNEXPECTED) orphanPayload falsy? (E: 6a521b684763862c3a2e0ca315d62826)");let $e=br(te.buffer).join(`
26
- `),K=br(X.buffer).join(`
27
- `),z=br(W.buffer).join(`
28
- `);dt&&(console.log(`${t}${oa} file: ${x.data.name}`),console.log(`${t}${oa} textLCA:
29
- ${$e}`),console.log(`${t}${oa} textBase:
30
- ${K}`),console.log(`${t}${oa} textOrphan:
31
- ${z}`));let{mergedText:fe}=Vi({textLCA:$e,textBase:K,textOrphan:z});dt&&console.log(`${t}${oa} mergedText:
32
- ${fe}`);let J=Buffer.from(fe,"utf8"),he=await Ye({s:fe});x.data.fileExt!==L.data.fileExt&&console.warn(`${t} baseItem.data.fileExt (${x.data.fileExt}) !== orphanItem.data.fileExt (${L.data.fileExt})? Using baseItem.data.fileExt for merged fileExt (W: a999b54235bb231fa49224842e212326)`);let be=x.data.fileExt,me={ib:Vn({binHash:he,binExt:be,binEncoding:"utf8"}),data:J};me.gib=await Tt({ibGib:me,hasTjp:!1});let je=y({ibGib:me});await se({ibGib:me,space:c}),await oe({ibGib:me,space:c});let da=p(_e=>{if(_e.data.n||_e.data.n===0)return _e.data.n;throw new Error("(UNEXPECTED) item.data.n not a number? (E: 896ceae089c83ca67817fff826be5826)")},"fnGetN"),va=da(x),la=da(L),gr=Math.max(va,la),Ba=N.rel8ns?.comment||[],Na=new Set(Ba),Pa=(x.rel8ns?.comment||[]).filter(_e=>!Na.has(_e)),fa=(L.rel8ns?.comment||[]).filter(_e=>!Na.has(_e)),ur=Array.from(new Set([...Pa,...fa])),Nn=Array.from(new Set([...Ba,...ur])),ba=[];if(ur.length>0){for(let Ct of ur){let ma=await this.fetchIbGib({addr:Ct,space:c,readCache_graph:i});if(!ma)throw new Error(`(UNEXPECTED) Comment ibgib for address '${Ct}' not found in cache or space (E: eb6798734f68e8f578fe1da3a2698826)`);ba.push(ma);let La=await Nt({ibGib:ma,space:c,ibGibs:i?Object.values(i):void 0});for(let xn of Object.values(La)){let ei=y({ibGib:xn});ba.some(ti=>y({ibGib:ti})===ei)||ba.push(xn)}}let{mapWithTjp_YesDna:_e,mapWithoutTjps:Qs}=ut({ibGibs:ba});for(let Ct of Object.values(Qs))c&&await se({ibGib:Ct,space:c,isDna:Oa({ibGib:Ct})});let Pn=ot({ibGibs:Object.values(_e)});for(let Ct of Object.keys(Pn)){let ma=Pn[Ct];for(let La of ma)c&&(await se({ibGib:La,space:c}),await oe({ibGib:La,space:c}))}}let ft=await ct({existingItem:x,dataToUpdate:{fileHash:he,n:gr+1},rel8nsToUpdate:{[nn]:[je],...Nn.length>0?{comment:Nn}:{}}});if(!ft.dnas)throw new Error("(UNEXPECTED) evolveRes.dnas falsy? (E: e640e892cc76c77f98f3881301035826)");if(!ft.newIbGib)throw new Error("(UNEXPECTED) evolveRes.newIbGib falsy? (E: 9e488d07772827b66a2aff4801905426)");let yr=ft.newIbGib,qs=y({ibGib:yr});dt&&console.log(`${t} newItemAddr: ${qs} (I: d23eef651b88be1248ee29ca179eff26)`);let Er=[],wr=[];Er.push(...ft.dnas),ft.intermediateIbGibs&&ft.intermediateIbGibs.forEach(_e=>wr.push(_e)),await de({resTransform:ft,space:c}),await oe({ibGib:ft.newIbGib,space:c});let zs={baseTextB2tFSItemAddr:S,baseTextBinAddr:X.binIbGib?y({ibGib:X.binIbGib}):void 0,orphanTextB2tFSItemAddr:$,orphanTextBinAddr:W.binIbGib?y({ibGib:W.binIbGib}):void 0},xa=await ua({conflictStrategy:a,details:"Merged orphan tip text with the baseTip as a starting point.",addlGraftDetails:[zs],latestCommonFrameAddr:s,baseAddrsSinceLCA:_,orphanAddrsSinceLCA:B,dnaAddrsApplied:[]});await se({ibGib:xa,space:c}),await oe({ibGib:xa,space:c});let Js=y({ibGib:xa}),Da=await qe({src:yr,rel8nsToAddByAddr:{[Me]:[Js]},dna:!0,nCounter:!0});if(!Da.dnas)throw new Error("(UNEXPECTED) resRel8GraftInfo.dnas falsy? (E: f3f4a83d3a08bd8de84250c389aed826)");let Ir=Da.newIbGib,Zs=y({ibGib:Ir});dt&&console.log(`${t} finalGraftTipAddr: ${Zs} (I: 583ac81fb0a84827b85c3076ffeeaf26)`),wr.push(yr);for(let _e of Da.dnas)Er.push(_e);return await de({resTransform:Da,space:c}),await oe({ibGib:Ir,space:c}),{dnasReplayed:[],dnasCreatedInGraft:Er,intermediateIbGibsCreatedInGraft:wr,ancillaryIbGibsCreated:[me,...ba],newGraftTip:Ir,graftInfoCreated:xa}}catch(a){throw console.error(`${t} ${g(a)} (E: 8acdfd6742487fe88836989dbef30826)`),a}finally{dt&&console.log(`${t} complete. (I: daceba1747880a2d1837eec8129d7726)`)}}async fetchIbGib({addr:e,space:t,readCache_graph:a}){if(e){if(a){if(a[e])return a[e];let r=e.includes("^")?e.substring(e.lastIndexOf("^")+1):e,n=Object.keys(a).find(s=>s===e||r&&s.endsWith("^"+r));if(n)return a[n]}try{let r=await ue({space:t,addrs:[e]});if(r){let n=r.ibGibs?.find(s=>!!s)||r.rawResultIbGib?.ibGibs?.find(s=>!!s);if(n)return n}}catch{}}}async resolveRootItemNode({nodeOrAddr:e,space:t,readCache_graph:a}){if(!e)throw new Error("(UNEXPECTED) nodeOrAddr falsy? (E: 524108327b9caa00586207ea399f7226)");let r;if(typeof e=="string"?r=await this.fetchIbGib({addr:e,space:t,readCache_graph:a}):r=e,!r)throw new Error("(UNEXPECTED) node falsy? couldn't get node? (E: bd7d1c3b4a3881ff882746281869d826)");if(na(r))return r;throw new Error("(UNEXPECTED) node is not a B2tFSItemIbGib_V1? (E: ddabb281ccb2fb1a181109a82046b826)")}async getFilePayloadBuffer({fileItem:e,space:t,readCache_graph:a}){if(!e||!e.rel8ns)return;let n=(e.rel8ns[nn]||[]).at(-1);if(!n)return;let s=await this.fetchIbGib({addr:n,space:t,readCache_graph:a});if(!s)throw new Error(`(UNEXPECTED) couldn't fetch binIbGib? latestBinAddr: ${n}. space.ib: ${t.ib} (E: 3d1238b3a348924038a79f88264d8226)`);if(s.data===void 0)return;let i,c=s.data;if(c&&typeof c=="object"&&c._dataType==="Uint8Array_Base64"&&typeof c.value=="string")i=Buffer.from(c.value,"base64");else if(typeof c=="string")i=Buffer.from(c,"utf8");else if(c instanceof Uint8Array||Buffer.isBuffer(c))i=c;else if(typeof c=="object"&&c!==null)if(typeof c.text=="string")i=Buffer.from(c.text,"utf8");else if(typeof c.data=="string")i=Buffer.from(c.data,"utf8");else{let d=Object.values(c);i=new Uint8Array(d)}else i=new Uint8Array(0);return{buffer:i,binIbGib:s}}};var Ga=!1,Ft="[status-helper]";async function ln({item:o,space:e,metaspace:t,currentRelPath:a,outMap:r}){let n=`[${ln.name}]`;try{if(Ga&&console.log(`${n} starting... (I: 2bcc48c4fdd884784497bee826fbe126)`),!o||!o.data)return;let{fsType:s,fileHash:i}=o.data;if(a&&r.set(a,{relPath:a,fileHash:i,fsType:s}),s==="folder"){if(!o.rel8ns)throw new Error("(UNEXPECTED) item.rel8ns falsy? item.data.fsType === 'folder', so we should at least have rel8ns.tjp (E: a1271821cef893c375f390755fc89626)");let c=o.rel8ns?.[pe]||[];for(let d of c){let f=await ie({addr:d,space:e});if(f&&f.data){let b=a?re(a,f.data.name):f.data.name;await ln({item:f,space:e,metaspace:t,currentRelPath:b,outMap:r})}}}}catch(s){throw console.error(`${n} ${g(s)}`),s}finally{Ga&&console.log(`${n} complete.`)}}p(ln,"walkBranchGraph");async function fn({galaxyIbGib:o,workspaceSpace:e,localSpace:t,activeBranchSpace:a,metaspace:r,repoRoot:n,targetDir:s,vcsFolderName:i=".vcsgib",filterFilePatterns:c=[]}){let d=`${Ft}[${fn.name}]`;if(o??=await Mt({space:t,metaspace:r}),!o)throw new Error(`galaxyIbGib falsy and couldn't get any index ibgib in the localSpace (${t.ib}) via metaspace (E: 8aaf983c3166024dead6ad7922161426)`);let f=Ve({targetDir:s??"",repoRoot:n??"",galaxyIbGib:o}),b=f===Ne?n||"":n?re(n,"b",f):re("b",f),m,u=a;try{let $=await Ae({galaxyIbGib:o,branchName:f,metaspace:r});u=u||$.branchSpace,m=$.rootItemIbGib_latest||$.rootItemIbGib}catch($){Ga&&console.log(`${d} (SUPPRESSED) error: ${g($)} (E: a88ab80c909d4307d8e68b5241935826)`)}let h=new Map,I=o.data.stagedPaths||{};for(let[$,B]of Object.entries(I))h.set($,B);let E=new Map;m&&u&&await ln({item:m,space:u,metaspace:r,currentRelPath:"",outMap:E});let w=new Map,A=[],G=e;if(!G&&r&&(G=(await r.getLocalUserSpaces({lock:!1})||[]).find(B=>B.data?.classname?.includes("WorkspaceProjectionSpace")&&(!b||B.data?.workspaceRoot===b))),G){let B=(await G.witness({data:{cmd:"get",cmdModifiers:[We]}}))?.data?.scanResult;B?.files&&(w=B.files),B?.pendingComments&&(A=B.pendingComments)}if(Ga){let $=m?y({ibGib:m}):void 0;console.log(`${Ft}[getRepoStatus] branch: ${f}, branchSpace: ${u?.data?.name||u?.ib}, branchAddrs: ${JSON.stringify(o?.data?.["$@branch"])}, rootItemAddr: ${$}`),console.log(`${Ft}[getRepoStatus] branchItemsMap keys: ${JSON.stringify(Array.from(E.keys()))}`);for(let[B,D]of E.entries())console.log(`${Ft}[getRepoStatus] branch item '${B}': fileHash=${D.fileHash}`);console.log(`${Ft}[getRepoStatus] physicalItemsMap keys: ${JSON.stringify(Array.from(w.keys()))}`);for(let[B,D]of w.entries())console.log(`${Ft}[getRepoStatus] physical item '${B}': fileHash=${D.fileHash}`)}let T=[],C=[],S=[],_=[];for(let[$,B]of h.entries()){let D=E.has($),N=B.isDeleted?"deleted":D?"modified":"new";T.push({path:$,fsType:B.fsType||"file",status:"staged",stagedType:N})}for(let[$,B]of w.entries()){let D=h.get($);if(D){D.isDeleted&&_.push({path:$,fsType:B.isDirectory?"folder":"file",status:"untracked"});continue}let N=E.get($);N?!B.isDirectory&&B.fileHash&&N.fileHash&&B.fileHash!==N.fileHash&&(Ga&&console.log(`${Ft}[getRepoStatus] MODIFIED: '${$}' phys=${B.fileHash} vs branch=${N.fileHash}`),C.push({path:$,fsType:"file",status:"modified"})):_.push({path:$,fsType:B.isDirectory?"folder":"file",status:"untracked"})}for(let[$,B]of E.entries())!$||$==="."||$===""||!w.has($)&&!h.has($)&&S.push({path:$,fsType:B.fsType,status:"deleted"});return{branchName:f,activeWorktreeDir:b,staged:T,modified:C,deleted:S,untracked:_,pendingComments:A}}p(fn,"getRepoStatus");var sa="[TRACE_VCS]";function lt(o){if(!o)return"(none)";let e=o.lastIndexOf("^");if(e===-1)return o.slice(0,40);let t=o.slice(0,e),a=o.slice(e+1),r=a.indexOf("."),n=r===-1?a.slice(0,8):`${a.slice(0,8)}.${a.slice(r+1,r+9)}`;return`${t}^${n}`}p(lt,"shortAddr");async function Aa({label:o,rootItemAddr:e,space:t,metaspace:a}){let r=`${sa}[logTree][${o}]`,n=t?.data?.name||t?.data?.spaceSubPath||t?.ib||"unknown";if(console.log(`${r} === Hierarchy for root: ${lt(e)} in space: ${n} ===`),!e){console.log(`${r} rootItemAddr is falsy`);return}async function s(i,c,d){let f=" ".repeat(c),b=await ie({addr:i,space:t,metaspace:a});if(!b){console.log(`${r}${f} ? MISSING item at ${lt(i)} (path: ${d})`);return}let m=b.data?.name||"(root)",u=b.data?.fsType||"unknown",h=b.rel8ns?.comment||[],I=b.rel8ns?.[pe]||[];console.log(`${r}${f} ?? ${m} (${u}) addr: ${lt(i)} comments: ${h.length} children: ${I.length}`);for(let E of h){let w=await ie({addr:E,space:t,metaspace:a});console.log(`${r}${f} ?? comment: "${w?.data?.text?.slice(0,50)}"`)}for(let E of I)await s(E,c+1,d?re(d,m):m)}p(s,"walk"),await s(e,1,"")}p(Aa,"logTreeHierarchyDiagnostic");var $a="[galaxy-helper]",ye=!1;function ia(o,e,t){let a=(o||"").replace(/\\/g,"/");if(t){let r=t.replace(/\\/g,"/").replace(/\/+$/,"");r&&a.startsWith(r)&&(a=a.slice(r.length).replace(/^\/+/,""))}if(e&&t&&e!==t){let r=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(n)){let s=r.slice(n.length).replace(/^\/+/,"");a=s?re(s,a):a}}return a.replace(/^\/+/,"")}p(ia,"normalizeRepoRelPath");function Ts({galaxyId:o}){let e=`[${Ts.name}]`;try{if(ye&&console.log(`${e} starting... (I: 8bc9166ddaa83d56572fae1290559126)`),!bt.test(o))throw new Error(`invalid galaxyId. Must match UUID_REGEXP: ${bt.source} (E: 2e5d3e06aceb6f2ec807f6a19b1f8a26)`);return`${aa} ${o}`}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{ye&&console.log(`${e} complete.`)}}p(Ts,"getB2tFSGalaxyIb");async function mn({activeSpaceId:o,activeBranchName:e,space:t,metaspace:a,sqBranchAddr:r}){let n=`${$a}[${mn.name}]`;try{if(ye&&console.log(`${n} starting... (I: 7b2118e6beeefd9658c9a94a89bb1826)`),!Mn(r))throw new Error(`invalid sqBranchAddr (${r}) (E: d905089debc8983077b7172767f8c926)`);let i={mySpaceId:ze(t.ib),activeSpaceId:o,activeBranchName:e,uuid:await Z(),classname:"B2tFSGalaxyIbGib_V1","$@branch":[r],stagedPaths:{},staged_item:[]},c=await U.firstGen({parentIbGib:Q,ib:Ts({galaxyId:i.uuid}),data:i,tjp:{timestamp:!0},dna:!0,nCounter:!0}),d=c.newIbGib;return await a.persistTransformResult({resTransform:c,space:t}),await a.registerNewIbGib({ibGib:d,space:t}),await a.getSpecialIbGib({type:aa,initialize:!0,space:t}),await a.rel8ToSpecialIbGib({type:aa,rel8nName:cr,ibGibsToRel8:[d],space:t,linked:!0}),ye&&console.log(`${n} Created galaxy IbGib: ${d.ib} (I: 039e9e584d6a11e1b85797b89a0c6826)`),d}catch(s){throw console.error(`${n} ${g(s)} (E: fa3da104817ebf8db14172884ff2c426)`),s}finally{ye&&console.log(`${n} complete. (I: 40f5d280cfd8ec0ce39386a85ce8f826)`)}}p(mn,"createB2tFSGalaxyIbGib");async function Mt({space:o,metaspace:e,galaxyAddr:t}){let a=`${$a}[${Mt.name}]`;try{ye&&console.log(`${a} starting... (I: bddb12b7b10ddc9b86e57cae9958f826)`);let r;if(t)r=await ie({addr:t,space:o});else if(e)r=(await e.getSpecialRel8dIbGibs({type:aa,rel8nName:cr,space:o}))?.at(0);else throw new Error("(UNEXPECTED) both galaxyAddr and metaspace falsy? one of these is required. (E: fd8e58f46f668ba605fc20186a5a1626)");if(!r){t?ye&&console.log(`Could not get galaxyAddr (${t}) from space (${o.ib}). Not initialized? (I: d7da7f279a08d9c2a8971ac8d14e0826)`):ye&&console.log(`Could not get galaxyIbGib via metaspace special anchor type ${aa} and rel8nName ${cr}. Not initialized? (I: a1a26c3ac9086522db895d783999e826)`);return}let n=y({ibGib:r}),s=Ce({ibGib:r});ye&&(console.log(`${a} baseGalaxyAddr: ${n}, tjpAddr: ${s} (I: 0640288ad6a6ca19b8578e6e841b4826)`),console.log(`${a} baseGalaxyIbGib stagedPaths: ${JSON.stringify(r.data.stagedPaths)}`));let i=await $r({ibGib:r,space:o});if(!i)throw new Error(`(UNEXPECTED) baseGalaxyIbGib (${n}) exists but we couldn't get the latest galaxy ibGib? (E: d1adc82a8cc82fe3f8aa8d136aede826)`);return ye&&console.log(`${a} foundLatest stagedPaths: ${JSON.stringify(i.data.stagedPaths)}, latestAddr: ${y({ibGib:i})} (I: e7fcf8ebba68e907a8378935eb10d626)`),i}catch(r){throw console.error(`${a} ${g(r)} (E: 3d2b1875548836a2f18fc698abfbb326)`),r}finally{ye&&console.log(`${a} complete. (I: e3822fa5a5085fcb52826018b4ca2826)`)}}p(Mt,"getB2tFSGalaxyIbGib");function pn({existingSqAddrs:o,newSqAddrs:e}){let t=`[${pn.name}]`;try{ye&&console.log(`${t} starting... (I: 4d36e8695c2354f2e8dd64e82707d826)`);let a=new Map,r=p(n=>{let s=Vt({sqAddr:n}),{ib:i}=s,{branchName:c}=wa({ib:i});return c},"extractBranchNameFromBranchAddr");for(let n of o){if(!n)throw new Error("(UNEXPECTED) addr falsy in existingAddrs? (E: 9759f198d83888f5db428e182388b826)");let s=r(n);a.set(s,n)}for(let n of e){if(!n)throw new Error("(UNEXPECTED) addr falsy in newAddrs? (E: 46b6380cc5582735c814d4584555d826)");let s=r(n);a.set(s,n)}return Array.from(a.values())}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{ye&&console.log(`${t} complete.`)}}p(pn,"mergeBranchAddrs");async function Le({space:o,metaspace:e,galaxyIbGib:t,dataToUpdate:a}){let r=`${$a}[${Le.name}]`;try{ye&&console.log(`${r} starting... (I: 5536885f77b88e42741b55c890efe826)`);let n={},s={...a};if(!a||Object.keys(a).length===0)throw new Error("(UNEXPECTED) no dataToUpdate? this may be correct, but atow (08/2026), I'm assuming this is the whole point of calling this function. I don't know why the agents made it optional, so if this error surfaces, re-examine this. (E: d0e06daa7748d6def7cd7a08b9d1d826)");a?.["$@branch"]&&t.data["$@branch"]&&(n["$@branch"]=""),a.stagedPaths&&(n.stagedPaths="");let i=await pt({src:t,dataToRemove:Object.keys(n).length>0?n:void 0,dataToAddOrPatch:s,dna:!0,nCounter:!0}),c=i.newIbGib;if(ye&&console.log(`[updateB2tFSGalaxyIbGib] immediately after mut8: newIbGib.data: ${JSON.stringify(c?.data)}, n: ${c?.data?.n}, addr: ${y({ibGib:c})}, srcAddr: ${y({ibGib:t})}`),await e.persistTransformResult({resTransform:i,space:o}),await e.registerNewIbGib({ibGib:c,space:o}),ye)try{let d=await $r({ibGib:t,space:o}),f=y({ibGib:c}),b=y({ibGib:d});console.log(`[updateB2tFSGalaxyIbGib] after persist+register resolveLatestIbGibInSpace: resolvedAddr=${b}, newAddr=${f}, match=${b===f}, resolvedN=${d?.data?.n}`)}catch(d){console.error(`[updateB2tFSGalaxyIbGib] resolveLatestIbGibInSpace diagnostic error: ${d} (E: 8e2293ff521be749c46ad1255acb2826)`)}return c}catch(n){throw console.error(`${r} ${g(n)} (E: 480608b166b811f81334d59506bf4726)`),n}finally{ye&&console.log(`${r} complete. (I: 7c77287267d81c503d9d814a1936de26)`)}}p(Le,"updateB2tFSGalaxyIbGib");async function _a({galaxyIbGib:o,paths:e=[],targetDir:t="",activeWorktreeDir:a,space:r,metaspace:n,all:s=!1}){let i=`${$a}[${_a.name}]`;try{ye&&console.log(`${i} starting... (I: adf91a3648a734701d01b1010a8c4826)`);let c={...o.data?.stagedPaths||{}},d=[...o.data?.staged_item||[]],f=[],b=a||t;if(s||e.length===0||e.length===1&&(e[0]==="."||e[0]==="")){for(let h of Object.keys(c))f.push(h);return{updatedGalaxy:await Le({space:r,metaspace:n,galaxyIbGib:o,dataToUpdate:{stagedPaths:{},staged_item:[]}}),unstagedPaths:f}}for(let u of e){let h=ia(u,t,b),I=Object.keys(c).filter(E=>E===h||E.startsWith(h+"/"));for(let E of I){let w=c[E];w&&w.itemAddr&&(d=d.filter(A=>A!==w.itemAddr)),delete c[E],f.includes(E)||f.push(E)}}return{updatedGalaxy:await Le({space:r,metaspace:n,galaxyIbGib:o,dataToUpdate:{stagedPaths:c,staged_item:d}}),unstagedPaths:f}}catch(c){throw console.error(`${i} ${g(c)} (E: f839a88fb40ab2c808bf7f7807ba4826)`),c}finally{ye&&console.log(`${i} complete. (I: 3d75881c0a3404fd73241bc3744dcc26)`)}}p(_a,"unstagePathsFromGalaxy");async function hn({paths:o,targetDir:e,activeWorktreeDir:t,branchName:a,workspaceSpace:r,metaspace:n,galaxyIbGib:s}){let i=`${$a}[${hn.name}]`;try{ye&&console.log(`${i} starting... (I: fa43a9fa775855dfd8378ca631417826)`);let{branchIbGib:c,branchInfo:d,branchSpace:f,rootItemAddr_latest:b,rootItemIbGib_latest:m}=await Ae({galaxyIbGib:s,branchName:a,metaspace:n}),u=new Map;await bn({item:m,parentRelPath:"",isRoot:!0,space:f,metaspace:n,outMap:u});let h=r;!h&&n&&(h=(await n.getLocalUserSpaces({lock:!1})||[]).find(w=>w.data?.classname?.includes("WorkspaceProjectionSpace")&&(!t||w.data?.workspaceRoot===t)));let I=[];if(o.length===0||o.length===1&&(o[0]==="."||o[0]==="")){h&&await se({space:h,ibGib:m});for(let E of u.values())I.push(E.relPath)}else for(let E of o){let w=ia(E,e,t),A=0;for(let G of u.values())(G.relPath===w||G.relPath.startsWith(w+"/"))&&(h&&await h.witness({data:{cmd:"put",subPath:G.parentRelPath||void 0},ibGibs:[G.item]}),I.includes(G.relPath)||I.push(G.relPath),A++);if(A===0)throw new Error(`pathspec '${E}' did not match any committed file(s) in snapshot (E: eab774c126885663183fede7ec5d2926)`)}return{restoredPaths:I}}catch(c){throw console.error(`${i} ${g(c)} (E: f962a38c605a44d3251d3e8883b3c826)`),c}finally{ye&&console.log(`${i} complete. (I: 93460761e9786170d861f75827a5c726)`)}}p(hn,"restoreWorktreePathsFromSnapshot");async function bn({item:o,parentRelPath:e,isRoot:t=!1,space:a,metaspace:r,outMap:n}){if(!o||!o.data)return;let{fsType:s,name:i}=o.data;if(t){let c=o.rel8ns?.[pe]||[];for(let d of c){let f=await ie({addr:d,space:a,metaspace:r});f&&await bn({item:f,parentRelPath:"",isRoot:!1,space:a,metaspace:r,outMap:n})}}else{let c=e?re(e,i):i;if(n.set(c,{relPath:c,parentRelPath:e,item:o}),s==="folder"){let d=o.rel8ns?.[pe]||[];for(let f of d){let b=await ie({addr:f,space:a,metaspace:r});b&&await bn({item:b,parentRelPath:c,isRoot:!1,space:a,metaspace:r,outMap:n})}}}}p(bn,"restoreCmd_collectCommittedItems");var ji="[init-cmd]",gn=!1;async function un({metaspace:o,localSpace:e,rootFolderName:t="root",branchName:a=Ne}){let r=`${ji}[${un.name}]`;try{gn&&console.log(`${r} starting... (I: 8a9b10c11d12e13f14a15b16c17d18e1)`);let{space:n,spaceId:s,spaceName:i}=await Gt({metaspace:o,branchName:a}),c=await At({fsType:"folder",name:t}),d=c.newIbGib;await de({resTransform:c,space:n}),await o.registerNewIbGib({ibGib:d,space:n});let f=await Ot({branchName:a,rootItem:d,space:n,metaspace:o}),b=y({ibGib:f}),m=gt({spaceId:s,ibGibAddr:b}),u=await mn({space:e,metaspace:o,activeSpaceId:s,activeBranchName:a,sqBranchAddr:m});return gn&&console.log(`${r} Successfully initialized repository (spaceId: ${s}, branchName: ${a}) (I: 9a10b11c12d13e14f15a16b17c18d19e)`),{spaceId:s,branchName:a,rootItem:d,branchIbGib:f,branchSpace:n,galaxyIbGib:u}}catch(n){throw console.error(`${r} ${g(n)} (E: 470bd27dfb68abaa38827ca83fa39826)`),n}finally{gn&&console.log(`${r} complete. (I: ff39f8a7a9e8407087efd1e844e84626)`)}}p(un,"executeVcsInit");async function pr(o){return await fn(o)}p(pr,"executeVcsStatus");var Bs="[add-cmd]",vs=!1;async function En({metaspace:o,localSpace:e,activeBranchSpace:t,workspaceSpace:a,galaxyIbGib:r,paths:n=[],all:s=!1,repoRoot:i,targetDir:c=i,vcsFolderName:d=".vcsgib"}){let f=`${Bs}[${En.name}]`;try{vs&&console.log(`${f} starting... (I: d6173882c2b3e92748569c165050a826)`);let b=new Map,u=(await a.witness({data:{cmd:"get",cmdModifiers:[We]}}))?.data?.scanResult;if(u?.files&&(b=u.files),!i)throw new Error("repoRoot required for executeVcsAdd (E: e934e81561a84f3c9217646a78248826)");let h=Ve({targetDir:c||i,repoRoot:i,galaxyIbGib:r}),{rootItemIbGib_latest:I}=await Ae({galaxyIbGib:r,branchName:h,metaspace:o}),E=new Map;I&&await yn({item:I,space:t,metaspace:o,currentRelPath:"",outMap:E});let w=[],A=h===Ne?i:`${i}/b/${h}`;if(s||n.length===0||n.length===1&&(n[0]==="."||n[0]==="")){for(let[_,$]of b.entries())$.isDirectory||w.push(_);for(let[_,$]of E.entries())$.fsType==="file"&&!b.has(_)&&(w.includes(_)||w.push(_))}else for(let _ of n){let $=ia(_,c,A);if($.includes("*")||$.includes("?")){let B=zr($),D=0;for(let[N,x]of b.entries())if(!x.isDirectory){let L=N.split("/").pop()||N;(B.test(N)||B.test(L))&&(w.includes(N)||w.push(N),D++)}for(let[N,x]of E.entries())if(x.fsType==="file"&&!b.has(N)){let L=N.split("/").pop()||N;(B.test(N)||B.test(L))&&(w.includes(N)||w.push(N),D++)}if(D===0)throw new Error(`No files matched glob pattern: ${_} (E: b4f9586075918649820246a804c8be26)`)}else{let B=b.get($),D=E.get($);if(B)if(B.isDirectory){for(let[N,x]of b.entries())!x.isDirectory&&(N===$||N.startsWith($+"/"))&&(w.includes(N)||w.push(N));for(let[N,x]of E.entries())x.fsType==="file"&&!b.has(N)&&(N===$||N.startsWith($+"/"))&&(w.includes(N)||w.push(N))}else w.includes($)||w.push($);else if(D)if(D.fsType==="folder")for(let[N,x]of E.entries())x.fsType==="file"&&!b.has(N)&&(N===$||N.startsWith($+"/"))&&(w.includes(N)||w.push(N));else w.includes($)||w.push($);else{let N=0;for(let[x,L]of b.entries())!L.isDirectory&&x.startsWith($+"/")&&(w.includes(x)||w.push(x),N++);for(let[x,L]of E.entries())L.fsType==="file"&&!b.has(x)&&x.startsWith($+"/")&&(w.includes(x)||w.push(x),N++);if(N===0)throw new Error(`Path does not exist: ${_} (E: 10c11d12e13f14a15b16c17d18e19f20)`)}}}let G=[...r.data?.staged_item||[]],T={...r.data?.stagedPaths||{}},C=[];for(let _ of w){let $=b.get(_),B=E.get(_);if(!$&&B){let z=B.item?y({ibGib:B.item}):void 0;T[_]={previousItemAddr:z,fsType:B.fsType,stagedAt:new Date().toISOString(),isDeleted:!0},C.push(_);continue}let D=$?.fileHash,N,L=(await a.witness({data:{cmd:"get",ibGibAddrs:[_]}}))?.ibGibs?.find(z=>!!z);if(!L||!L.data)throw new Error(`Failed to load file data for '${_}' from workspace space (E: 8a67b120f2694b6ca5610ec1f2e34567)`);if(N=L.data instanceof Uint8Array?L.data:new Uint8Array(L.data),!D){let z=await crypto.subtle.digest("SHA-256",N.buffer);D=Array.from(new Uint8Array(z)).map(fe=>fe.toString(16).padStart(2,"0")).join("")}if(B&&B.fileHash&&B.fileHash===D)continue;let k=`bin ${D}`,te=await Tt({ibGib:{ib:k,data:N}}),X={ib:k,gib:te,data:N},W=y({ibGib:X});await se({ibGib:X,space:t}),await o.registerNewIbGib({ibGib:X,space:t});let Ge=_.split("/").pop()||_,Ee=await Ye({s:Ge}),ne;B&&B.item?ne=await ct({existingItem:B.item,dataToUpdate:{fileHash:D},rel8nsToUpdate:{bin:[W]}}):ne=await At({fsType:"file",name:Ge,data:{nameHash:Ee,fileHash:D,fileEncoding:"utf8"},rel8ns:{bin:[W]}});let $e=ne.newIbGib,K=y({ibGib:$e});await de({resTransform:ne,space:t}),await o.registerNewIbGib({ibGib:$e,space:t}),G.includes(K)||G.push(K),T[_]={itemAddr:K,binAddr:W,fileHash:D,fsType:"file",stagedAt:new Date().toISOString()},C.push(_)}if(!e)throw new Error("localSpace is required to update repository galaxy (E: 99ea3cac6d28432c4fa9dbf84e680826)");let S=await Le({space:e,metaspace:o,galaxyIbGib:r,dataToUpdate:{stagedPaths:T,staged_item:G}});return{stagedPaths:C,stagedCount:C.length,updatedGalaxy:S}}catch(b){throw console.error(`${f} ${g(b)} (E: 82708be03354a87ad499f6536eb55a26)`),b}finally{vs&&console.log(`${f} complete. (I: f5cfeba2cbe8e5a76e617348895bd326)`)}}p(En,"executeVcsAdd");async function yn({item:o,space:e,metaspace:t,currentRelPath:a,outMap:r}){if(!o||!o.data)return;let{fsType:n,fileHash:s}=o.data;if(a&&r.set(a,{relPath:a,fileHash:s,fsType:n,item:o}),n==="folder"){let i=o.rel8ns?.[pe]||[];for(let c of i){let d=await ie({addr:c,space:e,metaspace:t});if(d&&d.data){let f=a?re(a,d.data.name):d.data.name;await yn({item:d,space:e,metaspace:t,currentRelPath:f,outMap:r})}else console.warn(`${Bs}[${yn.name}] child item '${c}' could not be loaded from space during add branch graph walk (W: 4f7c19a024ef11eebe560242ac120002)`)}}}p(yn,"addCmd_walkBranchGraph");var Xi="[commit-cmd]",ca=!1;async function wn({metaspace:o,localSpace:e,activeBranchSpace:t,workspaceSpace:a,galaxyIbGib:r,message:n,author:s="vcs-user",repoRoot:i="",targetDir:c=i,vcsFolderName:d=".vcsgib",keepEmptyFolders:f=!1}){let b=`${Xi}[${wn.name}]`;try{if(ca&&console.log(`${b} starting... (I: b8615dc6ad884198a85729aa3900d726)`),!i)throw new Error("repoRoot required for executeVcsCommit (E: f490281b6a184e92a83850cb39480826)");let m=Ve({targetDir:c||i,repoRoot:i,galaxyIbGib:r});if(!m)throw new Error("(UNEXPECTED) activeBranchName falsy? (E: 61e786846d989a15ad6c9b68068c0a26)");let u=r.data.stagedPaths||{};if(Object.keys(u).length===0)throw new Error("Nothing to commit (no staged items found in galaxy) (E: b1b825a7a47f020c6978d64a70f12c26)");let{branchInfo:I,branchIbGib:E,rootItemAddr_latest:w,rootItemIbGib_latest:A}=await Ae({galaxyIbGib:r,branchName:m,metaspace:o}),G=[];if(a){let z=(await a.witness({data:{cmd:"get",cmdModifiers:[We]}}))?.data?.scanResult;z?.pendingComments&&(G=z.pendingComments)}let T=new Map,C=[];for(let K of G){let fe=(await vr({text:K.content,saveInSpace:!0,space:t})).newIbGib,J=y({ibGib:fe});await o.registerNewIbGib({ibGib:fe,space:t});let he=T.get(K.targetRelPath)||[];he.push(J),T.set(K.targetRelPath,he),C.push(K.commentRelPath)}let S=G.length;if((!n||n.trim().length===0)&&S===0)throw new Error('Commit message is required (-m "message" or companion comment files) (E: fb4714c7171820cdc491ff48aa89a626)');let{newRootItem:_,newRootAddr:$,committedPaths:B,deletedPaths:D}=await Ns({existingRootItem:A,stagedPaths:u,itemCommentsMap:T,activeBranchSpace:t,metaspace:o,keepEmptyFolders:f}),N;if(n&&n.trim().length>0){let z=(await vr({text:n.trim(),saveInSpace:!0,space:t})).newIbGib;N=y({ibGib:z}),await o.registerNewIbGib({ibGib:z,space:t});let fe=_.rel8ns?.comment||[],J=await ct({existingItem:_,rel8nsToUpdate:{comment:[...fe,N]}});await de({resTransform:J,space:t}),await o.registerNewIbGib({ibGib:J.newIbGib,space:t}),_=J.newIbGib,$=y({ibGib:_}),ca&&console.log(`[DIAG-COMMIT] branch: '${m}', message: "${n}", commentAddr: ${N}, rootItem comments: ${JSON.stringify(_.rel8ns?.comment||[])}`)}else ca&&console.log(`${b} no commit msg? do we require a commit msg? (I: 71203833c29513061814948650bd8226)`);let x={committedAt:new Date().toISOString(),committedPaths:B};D&&D.length>0&&(x.deletedPaths=D);let L=await pt({src:E,dataToAddOrPatch:x,dna:!0,nCounter:!0}),k=L.newIbGib;await de({resTransform:L,space:t});let W=await qe({src:k,rel8nsToAddByAddr:N?{comment:[N]}:void 0,rel8nsToReplaceByAddr:{b2tfs_item:[{oldAddr:w,newAddr:$}]},dna:!0,nCounter:!0});k=W.newIbGib;let Ge=y({ibGib:k});await de({resTransform:W,space:t}),await oe({ibGib:k,space:t}),await o.registerNewIbGib({ibGib:k,space:t});let Ee=gt({spaceId:ze(t.ib),ibGibAddr:Ge}),ne=r.data["$@branch"];if(!ne)throw new Error("(UNEXPECTED) existingBranchSqAddrs falsy? galaxyIbGib.data['$@branch'] should be truthy and non-empty. Empty means no branches exist. (E: 7272988592bbcbc4ec0c7dc4d6882826)");if(ne.length===0)throw new Error("(UNEXPECTED) existingBranchSqAddrs empty? galaxyIbGib.data['$@branch'] should be truthy and non-empty. Empty means no branches exist. (E: 3918979b08b6d2dab8200688fa797826)");let $e=await Le({space:e,metaspace:o,galaxyIbGib:r,dataToUpdate:{stagedPaths:{},staged_item:[],"$@branch":Dn({array:ne,target:I.branchSqAddr,replacement:Ee})}});if(a&&C.length>0)for(let K of C)try{await a.witness({data:{cmd:"delete",relPath:K,ibGibAddrs:[K]}})}catch{}return{branchName:m,commitAddr:Ge,commentAddr:N,rootItemAddr:$,committedPaths:B,deletedPaths:D,ingestedCommentsCount:S,updatedGalaxy:$e,branchIbGib:k}}catch(m){debugger;throw console.error(`${b} ${g(m)} (E: 7afb5867182883e4f8433198d4197f26)`),m}finally{ca&&console.log(`${b} complete. (I: 8d7c6286dec864a1a3b6349880e09626)`)}}p(wn,"executeVcsCommit");async function Ns({existingRootItem:o,stagedPaths:e,itemCommentsMap:t,activeBranchSpace:a,metaspace:r,keepEmptyFolders:n=!1}){let s=`[${Ns.name}]`;try{ca&&console.log(`${s} starting... (I: dfcd220de3b81323c8e1bf4ff9615926)`);let i=new Map;if(await xs({item:o,space:a,metaspace:r,currentRelPath:"",outMap:i}),!o.data.name)throw new Error("(UNEXPECTED) existingRootItem.data.name falsy? (E: 8af4e81f199479b12861c861f2482826)");let c={name:o.data.name,fsType:"folder",itemAddr:y({ibGib:o}),children:new Map};for(let[h,I]of i.entries()){let E=h.split("/").filter(Boolean),w=c;for(let A=0;A<E.length;A++){let G=E[A],T=A===E.length-1;w.children.has(G)||w.children.set(G,{name:G,fsType:T?I.fsType:"folder",itemAddr:T?y({ibGib:I.item}):void 0,children:new Map}),w=w.children.get(G)}}let d=[],f=[];for(let[h,I]of Object.entries(e)){d.push(h);let E=h.split("/").filter(Boolean),w=c;if(I.isDeleted){f.push(h);for(let A=0;A<E.length-1;A++){let G=E[A];if(w=w.children.get(G),!w)break}if(w){let A=E[E.length-1];w.children.delete(A)}}else for(let A=0;A<E.length;A++){let G=E[A],T=A===E.length-1;w.children.has(G)||w.children.set(G,{name:G,fsType:T?I.fsType:"folder",itemAddr:T?I.itemAddr:void 0,children:new Map});let C=w.children.get(G);T&&(C.itemAddr=I.itemAddr,C.fsType=I.fsType),w=C}}let b=await Ps({node:c,isRoot:!0,itemCommentsMap:t,activeBranchSpace:a,metaspace:r,keepEmptyFolders:n});if(!b)throw new Error("(UNEXPECTED) root Merkle folder returned null (E: e36a5b28d09e4f25b29c9e81f7281026)");let m=b.item,u=y({ibGib:m});return{newRootItem:m,newRootAddr:u,committedPaths:d,deletedPaths:f}}catch(i){throw console.error(`${s} ${g(i)}`),i}finally{ca&&console.log(`${s} complete.`)}}p(Ns,"commitCmd_buildFolderTree");async function Ps({node:o,parentRelPath:e,isRoot:t=!1,itemCommentsMap:a,activeBranchSpace:r,metaspace:n,keepEmptyFolders:s=!1}){let i=t?"":e?re(e,o.name):o.name,c=[];for(let[m,u]of o.children.entries())if(u.fsType==="folder"){if(!s&&u.children.size===0)continue;let h=await Ps({node:u,parentRelPath:i,isRoot:!1,itemCommentsMap:a,activeBranchSpace:r,metaspace:n,keepEmptyFolders:s});h&&c.push(h.itemAddr)}else{let h=u.itemAddr,I=i?re(i,m):m,E=a.get(I)||[];if(E.length>0&&h){let w=await ie({addr:h,space:r,metaspace:n});if(!w)throw new Error(`could not get fileItemAddr (${h}) from activeBranchSpace (${r.ib}) (E: 316865814791f792f7814d04c6af7826)`);let A=await ct({existingItem:w,rel8nsToUpdate:{comment:[...E]}});await de({resTransform:A,space:r}),await n.registerNewIbGib({ibGib:A.newIbGib,space:r}),h=y({ibGib:A.newIbGib})}h&&c.push(h)}if(!t&&!s&&c.length===0)return null;let d=a.get(i)||[],f;if(o.itemAddr){let m=await ie({addr:o.itemAddr,space:r});if(!m)throw new Error(`could not get node.itemAddr (${o.itemAddr}) from activeBranchSpace (${r.ib}) (E: a1d53d1d920878c718cd4349b204e926)`);let u=m.rel8ns?.[pe]||[],h=new Map;for(let C of u){let S=Sr({ibGibAddr:C}).tjpGib||C;h.set(S,C)}let I=new Map;for(let C of c){let S=Sr({ibGibAddr:C}).tjpGib||C;I.set(S,C)}let E=[],w=[];for(let[C,S]of h.entries()){let _=I.get(C);(!_||_!==S)&&E.push(S)}for(let[C,S]of I.entries()){let _=h.get(C);(!_||_!==S)&&w.push(S)}let A=m.rel8ns?.comment||[],G=d&&d.length>0;if(E.length===0&&w.length===0&&!G)return{item:m,itemAddr:o.itemAddr};let T=await ct({existingItem:m,rel8nsToUpdate:{...w.length>0?{[pe]:w}:{},...G?{comment:[...A,...d]}:{}},rel8nsToRemove:E.length>0?{[pe]:E}:void 0});await de({resTransform:T,space:r}),await n.registerNewIbGib({ibGib:T.newIbGib,space:r}),f=T.newIbGib}else{let m=await Ye({s:o.name}),u=await At({fsType:"folder",name:o.name,data:{nameHash:m,diffTransactionId:await Z()},rel8ns:{[pe]:c,...d.length>0?{comment:d}:{}}});await de({resTransform:u,space:r}),await n.registerNewIbGib({ibGib:u.newIbGib,space:r}),f=u.newIbGib}let b=y({ibGib:f});return{item:f,itemAddr:b}}p(Ps,"commitCmd_buildMerkleFolder");async function xs({item:o,space:e,metaspace:t,currentRelPath:a,outMap:r}){if(!o||!o.data)return;let{fsType:n}=o.data;if(a&&r.set(a,{relPath:a,fsType:n,item:o}),n==="folder"){let s=o.rel8ns?.[pe]||[],i=await Ze({addrs:s,space:e});for(let c of i){let d=a?re(a,c.data.name):c.data.name;await xs({item:c,space:e,metaspace:t,currentRelPath:d,outMap:r})}}}p(xs,"commitCmd_walkBranchGraph");var Ki="[branch-cmd]",_t=!1;async function Sn(o){let e=`${Ki}[${Sn.name}]`;try{return _t&&console.log(`${e} starting... (I: cf8e88cca798e6cb48267f950007e826)`),o.branchName?.trim()?await Ds(o):await Gn(o)}catch(t){throw console.error(`${e} ${g(t)} (E: ae6e9841d2283328f891f3f6b1a25226)`),t}finally{_t&&console.log(`${e} complete. (I: 3376f633d188c591816c9058ab659426)`)}}p(Sn,"executeVcsBranch");async function Ds(o){let e=`[${Ds.name}]`;try{_t&&console.log(`${e} starting... (I: 672388ad93a52955c8147b4f76b8cb26)`);let{metaspace:t,localSpace:a,activeBranchSpace:r,galaxyIbGib:n,branchName:s,itemPath:i}=o;if(s=s?.trim(),!s)throw new Error("(UNEXPECTED) branchName falsy? (E: ad2606a58af8d25ae8624cb8cb683426)");let{activeBranchName:c}=n.data;if(!c)throw new Error("(UNEXPECTED) activeBranchName falsy? (E: aab47f049c33ecb098591ccd3b9d3426)");if((await en({galaxyIbGib:n})).some(_=>_.branchName.toLowerCase()===s.toLowerCase()))throw new Error(`branch with branchName "${s}" already exists. (E: 507808912ba80526aaf32bf3dd6b5c26)`);let{branchIbGib:f,rootItemAddr_latest:b,rootItemIbGib_latest:m}=await Ae({galaxyIbGib:n,branchName:c,metaspace:t}),u=m;if(i&&i.trim().length>0){let _=i.trim().replace(/\\/g,"/").replace(/^\.\//,""),$=new Map;await In({item:m,space:r,metaspace:t,currentRelPath:"",outMap:$});let B=$.get(_);if(!B)throw new Error(`Item '${i}' not found in active branch '${s}' (E: ca1617c6476aaecbe8cc78db2c3ca826)`);u=B}let{space:h,spaceId:I}=await Gt({metaspace:t,branchName:s});await cn({sourceSpace:r,targetBranchSpace:h,rootItemIbGib:u,metaspace:t});let E=await Ot({branchName:s,rootItem:u,space:h,metaspace:t}),w=y({ibGib:E}),A=gt({spaceId:I,ibGibAddr:w});if(!n.data["$@branch"])throw new Error("(UNEXPECTED) galaxyIbGib.data['$@branch'] falsy? (E: 6da47820dd6af7fe7884b9bc0a779126)");if(n.data["$@branch"].length===0)throw new Error("(UNEXPECTED) galaxyIbGib.data['$@branch'] empty? (E: e6348cd8227872a26efa44f895e2f826)");let T=[...n.data["$@branch"],A],C=await Le({space:a,metaspace:t,galaxyIbGib:n,dataToUpdate:{"$@branch":T}}),{branches:S}=await Gn({...o,branchName:void 0,galaxyIbGib:C});return{branches:S,createdBranchName:s,createdBranchAddr:w,updatedGalaxy:C}}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{_t&&console.log(`${e} complete.`)}}p(Ds,"executeVcsBranch_createNewBranch");async function Gn(o){let e=`[${Gn.name}]`;try{_t&&console.log(`${e} starting... (I: 265118f9fc182b4e0802b926eb83c826)`);let{metaspace:t,galaxyIbGib:a}=o;if(!a.data.activeBranchName)throw new Error("(UNEXPECTED) galaxyIbGib.data.activeBranceName falsy? This may end up being ok, but right now we're assuming this is truthy. If this ends up being acceptable, then we should probably check against the list of branches and if there are any, then we throw. (E: 331f68f29c8b5c7d08995068bff51a26)");let r=a.data.activeBranchName,n=await an({galaxyIbGib:a,metaspace:t}),s=[];for(let i of n){let{name:c}=i.data,d=y({ibGib:i});if(!i.rel8ns)throw new Error(`(UNEXPECTED) branchIbGib.rel8ns falsy? branchAddr: ${d} (E: 3a0f47a46fb858e6f5ddfb684ceb7826)`);if(!i.rel8ns.b2tfs_item)throw new Error(`(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item falsy? branchAddr: ${d} (E: aaa7583adf555e9218a5cfae47540126)`);if(i.rel8ns.b2tfs_item.length===0)throw new Error(`(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item empty? branchAddr: ${d} (E: 4823e871cc889a90e86bbf85f5a00826)`);let f=i.rel8ns.b2tfs_item[0];s.push({name:c,isActive:c===r,branchAddr:d,rootItemAddr:f})}return{branches:s}}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{_t&&console.log(`${e} complete.`)}}p(Gn,"executeVcsBranch_listBranches");async function In({item:o,space:e,metaspace:t,currentRelPath:a,outMap:r}){let n=`[${In.name}]`;try{_t&&console.log(`${n} starting... (I: c82a58edda64ffbb550b93cfdbad6826)`);let{fsType:s}=o.data;if(a&&r.set(a,o),s==="folder")if(o.rel8ns){let i=o.rel8ns?.[pe]||[];for(let c of i){let d=await ie({addr:c,space:e,metaspace:t});if(d){let f=a?re(a,d.data.name):d.data.name;await In({item:d,space:e,metaspace:t,currentRelPath:f,outMap:r})}else console.warn(`${n} (UNEXPECTED) childAddr (${c}) not found in space (${e.ib})? Is this an error? What's up here? We need to investigate this. (W: 732698e07198dd17b9927c089c820826)`)}}else console.warn(`${n} (UNEXPECTED) item.rel8ns falsy? item addr (${y({ibGib:o})}). Not sure when this would happen, so investigate this and update this warning if it comes up. (W: 59f9587f0118e0ce371ef1a8dbf7e626)`)}catch(s){throw console.error(`${n} ${g(s)}`),s}finally{_t&&console.log(`${n} complete.`)}}p(In,"branchCmd_walkBranchGraphForItems");var Wi="[checkout-cmd]",Ls=!1;async function An({metaspace:o,localSpace:e,targetBranchSpace:t,workspaceSpace:a,galaxyIbGib:r,branchName:n,force:s=!1,repoRoot:i=""}){let c=`${Wi}[${An.name}]`;try{Ls&&console.log(`${c} starting... (I: 28b508922ce8249958263628c96e2726)`);let d=n?.trim();if(!d)throw new Error("Branch name is required for checkout (E: c896086f2d6917f73831f4d8676ff826)");let f=r.data?.activeBranchName||Ne,{branchIbGib:b,branchInfo:m,branchSpace:u,rootItemAddr_latest:h,rootItemIbGib_latest:I}=await Ae({galaxyIbGib:r,branchName:d,metaspace:o}),E=t||u;if(!I)throw new Error(`Root item not found for address '${h}' (E: ec0a28ab5a2e13f1889e3f016e64ca26)`);if(a){let T=!0;if(!s)try{let S=(await a.witness({data:{cmd:"get",cmdModifiers:[We]}}))?.data?.scanResult;(S?.files?S.files instanceof Map?S.files.size:Object.keys(S.files).length:0)>0&&(T=!1)}catch{T=!0}T&&await a.witness({data:{cmd:"put",ibGibAddrs:[h]},ibGibs:[I]})}let w=d===Ne?i:i?re(i,"b",d):re("b",d),A=ze(E.ib),G=await Le({space:e,metaspace:o,galaxyIbGib:r,dataToUpdate:{activeBranchName:d,activeSpaceId:A,stagedPaths:{},staged_item:[]}});return{previousBranch:f,currentBranch:d,worktreePath:w,updatedGalaxy:G}}catch(d){throw console.error(`${c} ${g(d)} (E: bfd24a20afeb3d0ee15bf52f427ba826)`),d}finally{Ls&&console.log(`${c} complete. (I: 0b4068603a0fba6058e8ca7a080df826)`)}}p(An,"executeVcsCheckout");var Hi="[reset-cmd]",Rs=!1;async function $n({metaspace:o,localSpace:e,activeBranchSpace:t,galaxyIbGib:a,paths:r=[],all:n=!1,targetDir:s="",activeWorktreeDir:i}){let c=`${Hi}[${$n.name}]`;try{Rs&&console.log(`${c} starting... (I: 9c70a86e0b28bd8a9862230e17379126)`);let f=await _a({galaxyIbGib:a,paths:r,targetDir:s,activeWorktreeDir:i,space:e||t,metaspace:o,all:n}),b=Object.keys(f.updatedGalaxy.data?.stagedPaths||{}).length;return{unstagedPaths:f.unstagedPaths,stagedCount:b,updatedGalaxy:f.updatedGalaxy}}catch(d){throw console.error(`${c} ${g(d)} (E: aade98ceb7b3677f68ef666822ce7826)`),d}finally{Rs&&console.log(`${c} complete. (I: 8f0b1890b1380b24184544b89a12d126)`)}}p($n,"executeVcsReset");var Yi="[restore-cmd]",ks=!1;async function _n({metaspace:o,localSpace:e,workspaceSpace:t,paths:a=[],staged:r=!1,all:n=!1,targetDir:s="",activeWorktreeDir:i=""}){let c=`${Yi}[${_n.name}]`;try{ks&&console.log(`${c} starting... (I: cee216893bed53ec4459e1eb5dacf326)`);let d=await Mt({metaspace:o,space:e});if(!d)throw new Error(`couldn't get galaxyIbGib from space (${e.ib}) via metaspace. (E: b18aa4c434cad43bc828c5641e298d26)`);let f=d.data.activeBranchName;if(r){let b=await _a({galaxyIbGib:d,paths:a,targetDir:s,activeWorktreeDir:i,space:e,metaspace:o,all:n});return{restoredPaths:[],unstagedPaths:b.unstagedPaths,updatedGalaxy:b.updatedGalaxy}}else return{restoredPaths:(await hn({paths:a,targetDir:s,activeWorktreeDir:i,branchName:f,workspaceSpace:t,metaspace:o,galaxyIbGib:d})).restoredPaths,unstagedPaths:[],updatedGalaxy:d}}catch(d){throw console.error(`${c} ${g(d)} (E: e9378836e2e8d5068b0b02c873ae6626)`),d}finally{ks&&console.log(`${c} complete. (I: 6e00780e0d9a8c91280df4051e660826)`)}}p(_n,"executeVcsRestore");var qi="[merge-cmd]",Ut=!1;async function Cn({metaspace:o,localSpace:e,baseBranchSpace:t,incomingBranchSpace:a,workspaceSpace:r,galaxyIbGib:n,incomingBranchName:s,repoRoot:i=""}){let c=`${qi}[${Cn.name}]`;try{Ut&&console.log(`${c} starting... (I: 798888825c2c7ec3c8b0e0b815a6e826)`);let d=s?.trim();if(!d)throw new Error("Branch name is required for merge (E: 4ac298f0b33f3d5a38131778bf302c26)");let f=n.data.activeBranchName;if(!f)throw new Error("(UNEXPECTED) baseBranchName falsy? galaxyIbGib.data.activeBranchName falsy? (E: e120d81b52d2210265d89c5cae5d8826)");if(f===d)throw new Error(`Cannot merge branch '${d}' into itself (E: b849951c15e8768a9150a91b8f314926)`);let{branchIbGib:b,rootItemAddr_latest:m}=await Ae({galaxyIbGib:n,branchName:f,metaspace:o}),{branchIbGib:u,rootItemAddr_latest:h,rootItemIbGib_latest:I}=await Ae({galaxyIbGib:n,branchName:d,metaspace:o});Qt.instance.registerStrategy(new mr);let E=new $t(Xe(dr));await E.initialized,await E.initializeOpts({localMetaspace:o,localSpace:a,receiverSpace:t,receiverCoordinator:new le,receiverMetaspace:o}),await(await new le().sync({peer:E,localSpace:a,metaspace:o,domainIbGibs:[I],conflictStrategy:ve.optimisticWithLCS,graftPreference:tt.receiver})).done,Ut&&(console.log(`[DIAG-MERGE] syncSaga complete. baseBranch: '${f}', incomingBranch: '${d}'`),console.log(`[DIAG-MERGE] incomingRootItem (${h}) comments: ${JSON.stringify(I.rel8ns?.comment||[])}`),console.log(`[DIAG-MERGE] currentBaseRootItem (${b.rel8ns?.b2tfs_item?.at(-1)}) comments: ${JSON.stringify(b.rel8ns?.comment||[])}`)),Ut&&await Aa({label:`executeVcsMerge: BEFORE reify (baseBranch: ${f})`,rootItemAddr:m,space:t,metaspace:o});let G=await sn({rootItemAddr:m,space:t,metaspace:o}),T=G.reifiedRootItem,C=y({ibGib:T});Ut&&(console.log(`[DIAG-MERGE] reifiedRootItem (${C}) comments: ${JSON.stringify(T.rel8ns?.comment||[])}`),Ut&&console.log(`${sa}[merge-cmd] reifyRes hasChanges: ${G.hasChanges}, currentBaseRoot: ${lt(m)} -> reifiedRoot: ${lt(C)}`),await Aa({label:`executeVcsMerge: AFTER reify (baseBranch: ${f})`,rootItemAddr:C,space:t,metaspace:o}));let S=y({ibGib:b});if(G.hasChanges&&C!==m){let x=await qe({src:b,rel8nsToReplaceByAddr:{b2tfs_item:[{oldAddr:m,newAddr:C}]},dna:!0,nCounter:!0}),L=x.newIbGib;await de({resTransform:x,space:t}),await oe({ibGib:L,space:t}),S=y({ibGib:L})}Ut&&console.log(`${sa}[merge-cmd] mergedBranchAddr: ${lt(S)}`);let _=ze(t.ib),$=gt({spaceId:_,ibGibAddr:S});if(!e)throw new Error("localSpace is required to update repository galaxy (E: 9514b8da1f483877a8f665eac3e4d826)");let B=n.data["$@branch"]||[],D=pn({existingSqAddrs:B,newSqAddrs:[$]}),N=await Le({space:e,metaspace:o,galaxyIbGib:n,dataToUpdate:{"$@branch":D}});return r&&T&&await r.witness({data:{cmd:"put",ibGibAddrs:[C]},ibGibs:[T]}),{baseBranch:f,incomingBranch:d,mergeCommitAddr:S,mergeRootAddr:C,stats:{totalFiles:0,identical:0,cleanResolved:0,conflicted:0},updatedGalaxy:N}}catch(d){throw console.error(`${c} ${g(d)} (E: 02f9688abff8e143d8fb8f78843d5326)`),d}finally{Ut&&console.log(`${c} complete. (I: 5a00080e92e65c11283ced174ab25826)`)}}p(Cn,"executeVcsMerge");var zi="[log-cmd]",Tn=!1;async function vn({metaspace:o,galaxyIbGib:e,filePath:t,branchName:a,allComments:r=!1,repoRoot:n="",targetDir:s=n}){let i=`${zi}[${vn.name}]`;try{Tn&&console.log(`${i} starting... (I: 4f79a8c2c76b572e081d6e58a0338826)`);let c=a||Ve({targetDir:s||n,repoRoot:n,galaxyIbGib:e});if(!c)throw new Error("(UNEXPECTED) branchName falsy? (E: 3f236889705ddb4de8f88d080e6cc826)");let{branchIbGib:d,branchSpace:f,rootItemAddr:b,rootItemAddr_latest:m,rootItemIbGib:u,rootItemIbGib_latest:h}=await Ae({galaxyIbGib:e,branchName:c,metaspace:o});if(!d)throw new Error(`(UNEXPECTED) branchIbGib falsy for branch ${c}? (E: 4a2f8b9195ce40bb8e9c1db166a01826)`);if(!f)throw new Error(`(UNEXPECTED) branchSpace falsy for branch ${c}? (E: 9c28e9f50db84e6db582a87d0c3d9a26)`);return t?await Ji({filePath:t,targetDir:s,repoRoot:n,branchName:c,branchSpace:f,rootItemIbGib:u,rootItemAddr:b,metaspace:o}):await Zi({branchIbGib:d,branchSpace:f,branchName:c,allComments:r,metaspace:o})}catch(c){throw console.error(`${i} ${g(c)} (E: 70db81a942bc4e5781a74d49cf308b26)`),c}finally{Tn&&console.log(`${i} complete. (I: e5cf48c58e1c3018949e0d38e47ebc26)`)}}p(vn,"executeVcsLog");async function Ji({filePath:o,targetDir:e,repoRoot:t,branchName:a,branchSpace:r,rootItemIbGib:n,rootItemAddr:s,metaspace:i}){let c=ia(o,e,t);if(!n&&s&&(n=await ie({addr:s,space:r,metaspace:i})),!n)throw new Error(`No root item found on branch ${a} (E: 8a1b6e4d9c7f4e28b8a531d04cb54a26)`);Tn&&(console.log(`${sa}[executeVcsLog] branchName: '${a}', rootItemAddr: ${lt(s)}, space: ${r?.data?.name||r?.ib}`),await Aa({label:`executeVcsLog for '${c}' on branch '${a}'`,rootItemAddr:s||y({ibGib:n}),space:r,metaspace:i}));let d=await Qi({rootItem:n,targetRelPath:c,space:r,metaspace:i});if(!d)throw new Error(`Path '${c}' not found in active branch snapshot (E: 67b84a9e2d1f463c9b7e51c88d32a026)`);let f=y({ibGib:d}),m=[...d.rel8ns?.past||[],f].reverse(),u=await Ze({addrs:m,space:r}),h=ka(u.flatMap(w=>w.rel8ns?.comment||[])),I=new Map;if(h.length>0){let w=await Ze({addrs:h,space:r}),A=await _r({ibGibs:w,space:r});for(let G=0;G<w.length;G++){let T=w[G],C=y({ibGib:T}),S=A[G]||T,_=y({ibGib:S});I.set(C,{tip:S,tipAddr:_})}}let E=[];for(let w of u){let A=y({ibGib:w}),G=w.rel8ns?.comment||[];for(let T of G){let C=I.get(T);if(C){let{tip:S,tipAddr:_}=C;E.push({commitAddr:A,commentAddr:_,message:S.data?.text||"",timestamp:S.data?.textTimestamp||S.data?.timestamp||"",author:"vcs-user"})}}}return{branchName:a,targetPath:c,commits:E}}p(Ji,"executeVcsLogFile");async function Zi({branchIbGib:o,branchSpace:e,branchName:t,allComments:a,metaspace:r}){let n=y({ibGib:o}),i=[...o.rel8ns?.past||[],n].reverse(),c=await Ze({addrs:i,space:e}),d=ka(c.map(E=>E.rel8ns?.b2tfs_item?.at(-1)||E.rel8ns?.b2tFS_item?.at(-1)).filter(Boolean)),f=d.length>0?await Ze({addrs:d,space:e}):[],b=new Map;for(let E of f)b.set(y({ibGib:E}),E);let m=ka(c.flatMap(E=>{let w=E.rel8ns?.b2tfs_item?.at(-1)||E.rel8ns?.b2tFS_item?.at(-1),A=w?b.get(w):void 0;return[...E.rel8ns?.comment||[],...A?.rel8ns?.comment||[]]}).filter(Boolean)),u=new Map;if(m.length>0){let E=await Ze({addrs:m,space:e}),w=await _r({ibGibs:E,space:e});for(let A=0;A<E.length;A++){let G=E[A],T=y({ibGib:G}),C=w[A]||G,S=y({ibGib:C});u.set(T,{tip:C,tipAddr:S})}}let h=[],I=new Set;for(let E of c){let w=y({ibGib:E}),A=E.rel8ns?.b2tfs_item?.at(-1)||E.rel8ns?.b2tFS_item?.at(-1),G=A?b.get(A):void 0,T=[...E.rel8ns?.comment||[],...G?.rel8ns?.comment||[]].reverse();for(let C of T){let S=u.get(C);if(!S)continue;let{tip:_,tipAddr:$}=S;if(I.has($))continue;I.add($);let B=_.data?.text||"(no commit message)",D=_.data?.textTimestamp||_.data?.timestamp||E.data?.committedAt||"",N=E.data?.committedPaths||[],x=[];a&&G&&await Os({item:G,space:e,metaspace:r,currentRelPath:"",outComments:x}),h.push({branchAddr:w,commitAddr:w,commentAddr:$,message:B,timestamp:D,author:"vcs-user",rootItemAddr:A,committedPaths:N,itemComments:x.length>0?x:void 0})}}return{branchName:t,commits:h}}p(Zi,"executeVcsLogBranch");async function Qi({rootItem:o,targetRelPath:e,space:t,metaspace:a}){if(!o)return;if(!e||e==="."||e==="")return o;let r=e.split("/").filter(Boolean),n=o;for(let s of r){if(n.data?.fsType!=="folder")return;let i=n.rel8ns?.[pe]||[];if(i.length===0)return;let d=(await Ze({addrs:i,space:t})).find(f=>f?.data?.name===s);if(!d)return;n=d}return n}p(Qi,"logCmd_findItemByPath");async function Os({item:o,space:e,metaspace:t,currentRelPath:a,outComments:r}){if(!o||!o.data)return;let n=o.rel8ns?.comment||[];for(let s of n){let i=await ie({addr:s,space:e,metaspace:t});i&&i.data?.text&&r.push({path:a||"(root)",name:i.data?.name,message:i.data.text})}if(o.data.fsType==="folder"){let s=o.rel8ns?.[pe]||[];if(s.length>0){let i=await Ze({addrs:s,space:e});for(let c of i){let d=a?re(a,c.data.name):c.data.name;await Os({item:c,space:e,metaspace:t,currentRelPath:d,outComments:r})}}}}p(Os,"logCmd_collectAllItemComments");var ec="[generate-comment-cmd]",Fs=!1;async function Bn({metaspace:o,localSpace:e,workspaceSpace:t,activeBranchSpace:a,galaxyIbGib:r,paths:n=[],folderTopic:s="notes",repoRoot:i,targetDir:c,vcsFolderName:d}){let f=`${ec}[${Bn.name}]`;try{if(Fs&&console.log(`${f} starting... (I: 2e8b09f7a6344adca26e846174d81226)`),!t)throw new Error("workspaceSpace is required to generate companion comments (E: e3f0980a31244e439bb4c1a851d7c326)");let b=[];if(n.length>0)for(let h of n){if(!h||typeof h!="string"||!h.trim())continue;let I=/[/\\]+$/.test(h),E=ir(h).replace(/^\.?\//,"").replace(/\/+$/,"");if(!E){b.push({relPath:"",fsType:"folder"});continue}let w;I&&(w="folder"),b.some(A=>A.relPath===E)||b.push({relPath:E,fsType:w})}else{let h=await pr({metaspace:o,localSpace:e,activeBranchSpace:a,workspaceSpace:t,galaxyIbGib:r,repoRoot:i,targetDir:c,vcsFolderName:d}),I=p(E=>{let w=ir(E.path).replace(/^\.?\//,"").replace(/\/+$/,"");b.some(A=>A.relPath===w)||b.push({relPath:w,fsType:E.fsType})},"addStatusItem");for(let E of h.staged)I(E);for(let E of h.modified)I(E);for(let E of h.untracked)I(E)}let m=[],u=[];for(let h of b){let I=h.relPath,E;if(h.fsType==="folder")E=!0;else if(h.fsType==="file")E=!1;else{let S=await t.witness({data:{cmd:"get",relPath:I}});S?.ibGibs&&S.ibGibs.length>0?E=!1:E=!As(I)}let w,A;E?(A=I,w=`.ib.${s}.md`):(A=Ss(I),w=`.ib.${Gs(I)}.md`);let G=A&&A!=="."?ir(re(A,w)):w,T=await t.witness({data:{cmd:"get",relPath:G}});if(T?.ibGibs&&T.ibGibs.length>0)u.push(G);else{let _=`# ${I?`\`${I}\``:"root"}
12
+ ${G.data?.text}`);a("4.9B Check: \u2713 Server tip text matches the client-side merged text."),a("\u2713 4.9B Check SUCCESS: LCS text field merge conflict resolved and verified on both client and server!"),r.textContent="\u2713 4.9B Check Success"}catch(e){a(`\u2717 4.9B Check FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Xa,"init4_9bCheckButton");var C={},st="testrel8n";function za(){let r=document.getElementById("btn-4-10b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.10B Setup: Setting up identities and preparing Round 1 & Round 2 divergence...");let e=await E(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=new B;await q({masterSecret:"test-sender-secret-phase4-10b",syncSalt:"senderidentitysyncsaltphase4-10b",manageSalt:"senderidentitymanagesaltphase4-10b",metaspace:e,space:t,apiBridge:n,phaseText:"4.10B"});let o=m.domainI;C.domainI_initial=o,C.domainI_latest=o;let s=u({ibGib:o});a("4.10B Setup: Creating temporary remote space...");let i=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_10b",getFnPrompt:e.getFnPrompt}});await i.initialized,C.remoteSpace=i,await X({domainI:o,metaspace:e,fromSpace:t,toSpace:i}),a("4.10B Setup: Creating common history for alpha...");let c=await D.firstGen({parentIbGib:M,ib:"timeline_root_alpha_4_10b",data:{commonField:"common field R1 val",label:"AlphaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),l=c.newIbGib;C.alpha_v0=l,await e.persistTransformResult({resTransform:c,space:t}),await e.registerNewIbGib({ibGib:l,space:t});let d=ee({ibGib:l,defaultIfNone:"incomingAddr"});C.alpha_tjpAddr=d,await e.persistTransformResult({resTransform:c,space:i}),await e.registerNewIbGib({ibGib:l,space:i}),a("4.10B Setup: Seeding alpha_v0 to server..."),await x({domainIbGibs:[l],passLabel:"Seed alpha_v0",metaspace:e,space:t}),C.domainI_latest=m.domainI,a("4.10B Setup: \u2713 alpha_v0 seeded on server."),await X({domainI:m.domainI,metaspace:e,fromSpace:t,toSpace:i});let p=await D.firstGen({parentIbGib:M,ib:"timeline_root_beta_4_10b",data:{fieldA:"beta field A created on source",label:"BetaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),f=p.newIbGib;await e.persistTransformResult({resTransform:p,space:t}),await e.registerNewIbGib({ibGib:f,space:t}),C.r2_beta_v0_source=f;let y=ee({ibGib:f,defaultIfNone:"incomingAddr"});C.beta_tjpAddr=y;let S=await T({timeline:l,mut8Opts:{mut8Ib:l.ib+"_r2client",dataToAddOrPatch:{fieldA:"source_edit_r2"}},metaspace:e,space:t});a(`r2_alpha_v1_source_sansBeta.gib: ${S.gib}`),it=u({ibGib:f});let g=await Be({timeline:S,metaspace:e,space:t,rel8nInfos:[{rel8nName:st,ibGibs:[f]}]});C.r2_alpha_v3_source_rel8beta=g,a(`r2_alpha_v2_source_rel8dBeta.gib: ${g.gib}`),a("4.10B Setup: \u2713 Created client Round 2 edits (alpha fieldA edit + relate beta).");let w=await T({timeline:l,mut8Opts:{mut8Ib:l.ib+"_r2remote",dataToAddOrPatch:{fieldB:"remote_edit_r2"}},metaspace:e,space:i});console.log(`alpha_v0: ${qe(l)}`),console.log(`r2_alpha_v1_remote: ${qe(w)}`),a(`r2_alpha_v1_remote.gib: ${w.gib}`),a("4.10B Setup: Pushing remote Round 2 edit to server..."),await J({domainIbGibs:[w],passLabel:"Push remote Round 2 edit",metaspace:e,space:i,primarySpace:t,domainI:m.domainI,masterSecret:"test-sender-secret-phase4-10b"}),C.domainI_latest=m.domainI,a("\u2713 4.10B Setup Complete! Ready for 4.10B Sync (which runs Round 2, 3, and 4 in succession)."),r.textContent="\u2713 4.10B Setup Complete";let _=document.getElementById("btn-4-10b-sync");_&&(_.disabled=!1)}catch(e){a(`\u2717 4.10B Setup FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(za,"init4_10bSetupButton");var ot,it;function Ja(){let r=document.getElementById("btn-4-10b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.10B Sync: Initiating WebSocket Sync for Round 2, 3, and 4 sequential evolution...");let e=C.domainI_latest,t=C.remoteSpace,n=C.alpha_tjpAddr,o=C.beta_tjpAddr,s=C.alpha_v0,i=await E(),c=await i.getLocalUserSpace({});if(!c)throw new Error("No default space.");let l=location.protocol==="https:"?"wss:":"ws:",d=u({ibGib:C.domainI_initial});a("4.10B Sync: Running Round 2 Sync (merging divergent alpha edits)..."),await x({domainIbGibs:[C.r2_alpha_v3_source_rel8beta],passLabel:"Sync divergent alpha edits R2",metaspace:i,space:c}),C.domainI_latest=m.domainI,a("4.10B Sync: \u2713 Round 2 Sync complete."),await X({domainI:m.domainI,metaspace:i,fromSpace:c,toSpace:t}),a("4.10B Sync: Preparing Round 3 divergence (multiple conflicting timelines)...");let p=await new Y().getKnowledgeMap({domainIbGibs:[C.r2_alpha_v3_source_rel8beta,C.r2_beta_v0_source],space:c,metaspace:i}),f=p[n],y=p[o],S=await i.get({addr:f,space:c}),g=await i.get({addr:y,space:c}),w=await T({timeline:S.ibGibs[0],mut8Opts:{mut8Ib:s.ib+"_r3client",dataToAddOrPatch:{fieldC:"source_edit_r3"}},metaspace:i,space:c}),_=await T({timeline:g.ibGibs[0],mut8Opts:{mut8Ib:C.r2_beta_v0_source.ib+"_r3client",dataToAddOrPatch:{betaFieldA:"source_beta_edit_r3"}},metaspace:i,space:c});a("4.10B Sync: Updating remote space to latest merged tips...");let I=await i.getLatestAddr({addr:n,space:t}),G=[(await i.get({addr:I,space:t})).ibGibs[0]],k=await i.getLatestAddr({addr:o,space:t});if(k){let He=await i.get({addr:k,space:t});G.push(He.ibGibs[0])}await J({domainIbGibs:G,passLabel:"Pull merged R2 tips to remoteSpace",metaspace:i,space:t,primarySpace:c,domainI:m.domainI,masterSecret:"test-sender-secret-phase4-10b"}),C.domainI_latest=m.domainI;let $=await new Y().getKnowledgeMap({space:t,metaspace:i,domainIbGibs:[s,C.r2_beta_v0_source]}),P=$[n],O=$[o],K=await i.get({addr:P,space:t}),F=await i.get({addr:O,space:t}),U=await T({timeline:K.ibGibs[0],mut8Opts:{mut8Ib:s.ib+"_r3remote",dataToAddOrPatch:{fieldD:"remote_edit_r3"}},metaspace:i,space:t}),j=await T({timeline:F.ibGibs[0],mut8Opts:{mut8Ib:C.r2_beta_v0_source.ib+"_r3remote",dataToAddOrPatch:{betaFieldB:"remote_beta_edit_r3"}},metaspace:i,space:t});a("4.10B Sync: Pushing remote Round 3 edits to server..."),await J({domainIbGibs:[U,j],passLabel:"Push remote Round 3 edits",metaspace:i,space:t,primarySpace:c,domainI:m.domainI,masterSecret:"test-sender-secret-phase4-10b"}),C.domainI_latest=m.domainI,a("4.10B Sync: Running Round 3 Client Sync (merging alpha & beta divergence)..."),await x({domainIbGibs:[w,_],passLabel:"Sync Client Round 3 edits",metaspace:i,space:c}),C.domainI_latest=m.domainI,a("4.10B Sync: \u2713 Round 3 Sync complete."),await X({domainI:m.domainI,metaspace:i,fromSpace:c,toSpace:t}),a("4.10B Sync: Preparing Round 4 divergence (post-graft chain edits & new timeline)...");let H=await new Y().getKnowledgeMap({space:c,metaspace:i,domainIbGibs:[s,C.r2_beta_v0_source]}),Q=H[n],be=H[o],We=await i.get({addr:Q,space:c}),he=await i.get({addr:be,space:c}),pn=await T({timeline:We.ibGibs[0],mut8Opts:{mut8Ib:s.ib+"_r4client_v5",dataToAddOrPatch:{fieldE:"source_edit_r4_v5"}},metaspace:i,space:c}),lt=await D.firstGen({parentIbGib:M,ib:"timeline_root_gamma_4_10b",data:{gammaField:"gamma created on client",label:"GammaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),ve=lt.newIbGib;await i.persistTransformResult({resTransform:lt,space:c}),await i.registerNewIbGib({ibGib:ve,space:c});let mn=ee({ibGib:ve,defaultIfNone:"incomingAddr"});C.gamma_tjpAddr=mn,ot=u({ibGib:ve});let bn=await Be({timeline:pn,metaspace:i,space:c,rel8nInfos:[{rel8nName:st,ibGibs:[ve]}]}),hn=await T({timeline:bn,mut8Opts:{mut8Ib:s.ib+"_r4client_v7",dataToAddOrPatch:{fieldF:"source_edit_r4_v7"}},metaspace:i,space:c}),fn=await T({timeline:he.ibGibs[0],mut8Opts:{mut8Ib:C.r2_beta_v0_source.ib+"_r4client_v2",dataToAddOrPatch:{betaFieldD:"source_beta_edit_r4_v2"}},metaspace:i,space:c});a("4.10B Sync: Updating remote space to Round 3 merged tips...");let un=await i.getLatestAddr({addr:n,space:t}),pt=[(await i.get({addr:un,space:t})).ibGibs[0]],mt=await i.getLatestAddr({addr:o,space:t});if(mt){let He=await i.get({addr:mt,space:t});pt.push(He.ibGibs[0])}await J({domainIbGibs:pt,passLabel:"Pull merged R3 tips to remoteSpace",metaspace:i,space:t,primarySpace:c,domainI:m.domainI,masterSecret:"test-sender-secret-phase4-10b"}),C.domainI_latest=m.domainI;let bt=await new Y().getKnowledgeMap({space:t,metaspace:i,domainIbGibs:[s,C.r2_beta_v0_source]}),gn=bt[n],yn=bt[o],Sn=await i.get({addr:gn,space:t}),wn=await i.get({addr:yn,space:t}),_n=await T({timeline:Sn.ibGibs[0],mut8Opts:{mut8Ib:s.ib+"_r4remote_v5",dataToAddOrPatch:{fieldG:"remote_edit_r4_v5"}},metaspace:i,space:t}),En=await T({timeline:wn.ibGibs[0],mut8Opts:{mut8Ib:C.r2_beta_v0_source.ib+"_r4remote_v2",dataToAddOrPatch:{betaFieldC:"remote_beta_edit_r4_v2"}},metaspace:i,space:t});a("4.10B Sync: Pushing remote Round 4 edits to server..."),await J({domainIbGibs:[_n,En],passLabel:"Push remote Round 4 edits",metaspace:i,space:t,primarySpace:c,domainI:m.domainI,masterSecret:"test-sender-secret-phase4-10b"}),C.domainI_latest=m.domainI,a("4.10B Sync: Running final Round 4 Client Sync (merging alpha, beta, and propagating gamma)..."),await x({domainIbGibs:[hn,fn,ve],passLabel:"Sync final Round 4 edits",metaspace:i,space:c}),C.domainI_latest=m.domainI,a("\u2713 4.10B Sync: All rounds of divergent edits and merges complete!"),r.textContent="\u2713 4.10B Sync Complete";let ht=document.getElementById("btn-4-10b-check");ht&&(ht.disabled=!1)}catch(e){a(`\u2717 4.10B Sync FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Ja,"init4_10bSyncButton");function Za(){let r=document.getElementById("btn-4-10b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,a("4.10B Check: Verifying multi-round merged timelines on client and server...");let e=C.domainI_latest,t=C.alpha_tjpAddr,n=C.beta_tjpAddr,o=C.gamma_tjpAddr,s=await E(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=u({ibGib:C.domainI_initial}),l=await new Y().getKnowledgeMap({space:i,metaspace:s,domainIbGibs:[C.domainI_initial]}),d=await s.getLatestAddr({addr:t,space:i}),p=await s.getLatestAddr({addr:n,space:i}),f=await s.getLatestAddr({addr:o,space:i});if(!d||!p||!f)throw new Error("Client space is missing timeline tips for Alpha, Beta, or Gamma.");let y=await s.get({addr:d,space:i}),S=await s.get({addr:p,space:i}),g=y.ibGibs[0],w=S.ibGibs[0];if(g.data?.fieldA!=="source_edit_r2")throw new Error(`Alpha fieldA mismatch! Expected 'source_edit_r2', got '${g.data?.fieldA}'`);if(g.data?.fieldB!=="remote_edit_r2")throw new Error(`Alpha fieldB mismatch! Expected 'remote_edit_r2', got '${g.data?.fieldB}'`);if(g.data?.fieldC!=="source_edit_r3")throw new Error(`Alpha fieldC mismatch! Expected 'source_edit_r3', got '${g.data?.fieldC}'`);if(g.data?.fieldD!=="remote_edit_r3")throw new Error(`Alpha fieldD mismatch! Expected 'remote_edit_r3', got '${g.data?.fieldD}'`);if(g.data?.fieldE!=="source_edit_r4_v5")throw new Error(`Alpha fieldE mismatch! Expected 'source_edit_r4_v5', got '${g.data?.fieldE}'`);if(g.data?.fieldF!=="source_edit_r4_v7")throw new Error(`Alpha fieldF mismatch! Expected 'source_edit_r4_v7', got '${g.data?.fieldF}'`);if(g.data?.fieldG!=="remote_edit_r4_v5")throw new Error(`Alpha fieldG mismatch! Expected 'remote_edit_r4_v5', got '${g.data?.fieldG}'`);if(a("4.10B Check: \u2713 Client Alpha merged tip contains all Round 2, 3, and 4 edits."),w.data?.betaFieldA!=="source_beta_edit_r3")throw new Error(`Beta betaFieldA mismatch! Expected 'source_beta_edit_r3', got '${w.data?.betaFieldA}'`);if(w.data?.betaFieldB!=="remote_beta_edit_r3")throw new Error(`Beta betaFieldB mismatch! Expected 'remote_beta_edit_r3', got '${w.data?.betaFieldB}'`);if(w.data?.betaFieldC!=="remote_beta_edit_r4_v2")throw new Error(`Beta betaFieldC mismatch! Expected 'remote_beta_edit_r4_v2', got '${w.data?.betaFieldC}'`);if(w.data?.betaFieldD!=="source_beta_edit_r4_v2")throw new Error(`Beta betaFieldD mismatch! Expected 'source_beta_edit_r4_v2', got '${w.data?.betaFieldD}'`);a("4.10B Check: \u2713 Client Beta merged tip contains all Round 3 and 4 edits.");let _=g.rel8ns?.[st]||[];if(!it)throw new Error("(UNEXPECTED) betaAddr falsy? (E: 81c032ae7a93bddfd8eed6664d314826)");if(!_.includes(it))throw new Error("Client Alpha tip is missing relation to Beta timeline.");if(!ot)throw new Error("(UNEXPECTED) gammaAddr falsy? (E: 12220a81d3b86385d1683d5a6bae5826)");if(!_.includes(ot))throw new Error("Client Alpha tip is missing relation to Gamma timeline.");a("4.10B Check: \u2713 Client Alpha tip retains relation to Gamma.");let I=new B;a("4.10B Check: Fetching server timeline graphs...");let A=await I.getIbGibGraph(c,d,!0),v=await I.getIbGibGraph(c,p,!0);if(!A.success||!A.graph||!v.success||!v.graph)throw new Error("Failed to fetch merged graphs from server.");let G=A.graph[d],k=v.graph[p];if(!G||!k)throw new Error("Server is missing the final merged tips for Alpha or Beta.");if(G.data?.fieldF!=="source_edit_r4_v7"||G.data?.fieldG!=="remote_edit_r4_v5")throw new Error("Server Alpha tip does not match final client merged state.");if(k.data?.betaFieldC!=="remote_beta_edit_r4_v2"||k.data?.betaFieldD!=="source_beta_edit_r4_v2")throw new Error("Server Beta tip does not match final client merged state.");a("4.10B Check: \u2713 Server tips match client merged states perfectly."),a("\u2713 4.10B Check SUCCESS: Advanced multi-round/timeline conflict resolved and verified on both client and server!"),r.textContent="\u2713 4.10B Check Success"}catch(e){a(`\u2717 4.10B Check FAILED: ${b(e)}`),console.error(e),r.disabled=!1}})}h(Za,"init4_10bCheckButton");var ct={version:"1",uuid:$e,name:Le,classname:"WorkspaceProjectionSpaceBase_V1",workspaceRoot:"",vcsFolderName:".vcsgib",persistOptsAndResultIbGibs:!1,validateIbGibAddrsMatchIbGibs:!1,longPollingIntervalMs:Re,allowPrimitiveArgs:!1,catchAllErrors:!0,description:Dt,trace:!1};var me=!1,Ke=class r extends At{static{h(this,"WorkspaceProjectionSpaceBase_V1")}lc=`[${r.name}]`;constructor(e,t){super(e??Ce(ct),t)}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{me&&console.log(`${e} starting...`),this.data||(this.data=Ce(ct)),this.data.classname||(this.data.classname="WorkspaceProjectionSpaceBase_V1"),this.data.uuid??=await z(),this.ib=wt({space:this,classname:this.data.classname}),this.gib=await Xe({ibGib:this})}catch(t){throw console.error(`${e} ${b(t)}`),t}finally{me&&console.log(`${e} complete.`)}}async validateWitnessArg(e){let t=`${this.lc}[${this.validateWitnessArg.name}]`,n=[];try{if(!e)return n.push("arg required (E: a222db3b668e4bb09cfd82e75c07bfa6)"),n;if(!e.data)return n.push("arg.data required (E: 8ee544d7d88a45c6adcbc15838a283a7)"),n;if(!this.data)return n.push("this.data required (E: 64f80642d7de44329355d6f907e272c8)"),n;let{cmd:o}=e.data,s=e.data.cmdModifiers??[];return o||n.push("arg.data.cmd required (E: 72a11ee87a0d4896bcacd65a9c0284d9)"),o===ze.get&&!s.includes(Oe)&&!e.data.subPath&&!e.data.relPath&&(!e.data.ibGibAddrs||e.data.ibGibAddrs.length===0)&&n.push("ibGibAddrs, relPath, subPath, or workspace_scan modifier required for get (E: ee55a3f60b90423cbe054f27c34ab7d5)"),n}catch(o){throw console.error(`${t} ${b(o)}`),o}}async routeAndDoCommand({cmd:e,cmdModifiers:t,arg:n}){let o=`${this.lc}[${this.routeAndDoCommand.name}]`;return e===ze.get&&t.includes(Oe)?this.scanWorkspace(n):super.routeAndDoCommand({cmd:e,cmdModifiers:t,arg:n})}async scanWorkspace(e){let t=`${this.lc}[${this.scanWorkspace.name}]`,n={optsAddr:u({ibGib:e})};try{me&&console.log(`${t} scanning workspace...`);let s=await this.scanWorkspaceImpl({subPath:e.data?.subPath,filterPatterns:e.data?.filterPatterns??this.data?.filterPatterns});n.success=!0,n.scanResult=s}catch(s){console.error(`${t} ${b(s)} (E: 411edc38cbf8473358cfbb9d0ea8d826)`),n.success=!1,n.errors=[b(s)]}return await this.resulty({resultData:n})}async putImpl(e){let t=`${this.lc}[${this.putImpl.name}]`,n={optsAddr:u({ibGib:e})};try{me&&console.log(`${t} putting to workspace...`);let s=e.ibGibs??[];if(s.length===0)throw new Error(`${t} No ibGib(s) provided in put arg (E: f7c1bfd5dda81a5422ebbabafe846d26)`);for(let i of s)await this.putItemToWorkspaceImpl({item:i,subPath:e.data?.subPath});n.success=!0}catch(s){console.error(`${t} ${b(s)} (E: 5922341ff2d485727afa306876ef1826)`),n.success=!1,n.errors=[b(s)]}return await this.resulty({resultData:n})}async getImpl(e){let t=`${this.lc}[${this.getImpl.name}]`,n={optsAddr:u({ibGib:e})},o=[];try{if((e.data?.cmdModifiers??[]).includes(Oe)){me&&console.log(`${t} scanning workspace...`);let c=await this.scanWorkspaceImpl({subPath:e.data?.subPath??e.data?.relPath,filterPatterns:e.data?.filterPatterns??this.data?.filterPatterns});n.success=!0,n.scanResult=c}else{me&&console.log(`${t} getting file binary from workspace...`);let c=[...e.data?.ibGibAddrs||[],...e.data?.relPath?[e.data.relPath]:[]];for(let l of c){let d=await this.getFileBytesImpl({relPath:l});if(d!==void 0){let p=await crypto.subtle.digest("SHA-256",d.buffer),y=`bin ${Array.from(new Uint8Array(p)).map(w=>w.toString(16).padStart(2,"0")).join("")}`,S=await Xe({ibGib:{ib:y,data:d}}),g={ib:y,gib:S,data:d};o.push(g)}}n.success=!0}}catch(i){console.error(`${t} ${b(i)} (E: 2b2f38560368242a8862f569378ba826)`),n.success=!1,n.errors=[b(i)]}return await this.resulty({resultData:n,ibGibs:o})}async deleteImpl(e){let t=`${this.lc}[${this.deleteImpl.name}]`,n={optsAddr:u({ibGib:e})};try{me&&console.log(`${t} deleting from workspace...`);let s=e.ibGibs??[],i=e.data?.relPath??e.data?.ibGibAddrs?.[0];await this.deleteFromWorkspaceImpl({relPath:i,ibGib:s[0]}),n.success=!0}catch(s){console.error(`${t} ${b(s)} (E: a696eaa8c418c21438ad4d08fef09826)`),n.success=!1,n.errors=[b(s)]}return await this.resulty({resultData:n})}async persistOptsAndResultIbGibs({arg:e,result:t}){}};var Qa="Web in-memory space witness for projecting and observing virtual workspace hierarchies in browser environments.";var en={version:"1",uuid:$e,name:Le,classname:"WebInMemoryWorkspaceProjectionSpace_V1",workspaceRoot:"/",vcsFolderName:".vcsgib",persistOptsAndResultIbGibs:!1,validateIbGibAddrsMatchIbGibs:!1,longPollingIntervalMs:Re,allowPrimitiveArgs:!1,catchAllErrors:!0,description:Qa,trace:!1};var dt=!1,Ue=class r extends Ke{static{h(this,"WebInMemoryWorkspaceProjectionSpace_V1")}lc=`[${r.name}]`;backingSpace;_virtualFiles=new Map;constructor(e,t){let n,o=t,s;if(e&&("workspaceRoot"in e||"name"in e))n=e;else if(e&&typeof e=="object"){let i=e;n=i.initialData,o=i.initialRel8ns??t,s=i.backingSpace}super(n??Ce(en),o),this.backingSpace=s}async putItemToWorkspaceImpl({item:e,subPath:t}){let n=`${this.lc}[${this.putItemToWorkspaceImpl.name}]`;try{if(dt&&console.log(`${n} projecting item to virtual workspace...`),!e||!e.data)throw new Error(`${n} item and item.data are required (E: 469d887536c263a79853ceb4a0adef26)`);let{fsType:o,name:s}=e.data,i;if(t===void 0?i=o==="folder"?"":s||"":i=s?t?`${t}/${s}`:s:t,i=this.normalizePath(i),o==="folder"){i&&this._virtualFiles.set(i,{relPath:i,content:new Uint8Array(0),isDirectory:!0,modifiedAt:Date.now()});let c=e.rel8ns?.b2tFS_child||e.rel8ns?.b2tfs_child||[];for(let l of c){let d=await this.fetchIbGib(l);await this.putItemToWorkspaceImpl({item:d,subPath:i})}}else if(o==="file"){if(!e.rel8ns)throw new Error(`${n} item.rel8ns required for file item (E: cfa365f50fde8f65c8beb708b4630826)`);let c=e.rel8ns.bin;if(!c||c.length===0)throw new Error(`${n} item.rel8ns.bin required for file item ${s} (E: 7f994a5fe5f8123aec5f4fd870f72f26)`);let l=c.at(-1),d=await this.fetchIbGib(l);if(d.data===void 0)throw new Error(`${n} BinIbGib at addr ${l} has undefined data (E: a31a0812b1a8f40c7839be081a77ed26)`);let p;if(d.data instanceof Uint8Array)p=d.data;else if(typeof d.data=="string")p=new TextEncoder().encode(d.data);else if(typeof d.data=="object"){let f=Object.values(d.data);p=new Uint8Array(f)}else p=new Uint8Array(0);this._virtualFiles.set(i,{relPath:i,content:p,isDirectory:!1,modifiedAt:Date.now()})}}catch(o){throw console.error(`${n} ${b(o)} (E: d2b342499d289d6918197a06c02c5826)`),o}}async scanWorkspaceImpl({subPath:e,filterPatterns:t}){let n=`${this.lc}[${this.scanWorkspaceImpl.name}]`;try{dt&&console.log(`${n} starting in-memory virtual scan...`);let o=this.data?.vcsFolderName||".vcsgib",s=t??this.data?.filterPatterns;if(!s||s.length===0){let d=this._virtualFiles.get(".ibgibignore");if(d&&!d.isDirectory){let p=new TextDecoder("utf8").decode(d.content);s=Mt(p)}else s=[]}let i=e?this.normalizePath(e):"",c=new Map,l=[];for(let[d,p]of this._virtualFiles.entries()){if(i&&!d.startsWith(i)||d===o||d.startsWith(o+"/")||d===".git"||d.startsWith(".git/")||d==="b"||d.startsWith("b/")||Ft({relativePath:d,isDirectory:p.isDirectory,filterPatterns:s}))continue;let f=d.split("/").pop()||d;if(p.isDirectory)c.set(d,{relPath:d,fullPath:d,isDirectory:!0});else if(this.isCommentMetadataFilename(f)){let y=d.split("/");y.pop();let S=y.join("/"),g=new TextDecoder("utf8").decode(p.content),w=this.extractCommentTopicName(f),_=S?`${S}/${w}`:w;l.push({commentRelPath:d,commentFullPath:d,targetRelPath:_,targetType:f.startsWith(".ib.")?"file":"folder",topicName:w,content:g})}else{let y=await crypto.subtle.digest("SHA-256",p.content),S=new Uint8Array(y),g="";for(let w=0;w<S.length;w++)g+=S[w].toString(16).padStart(2,"0");c.set(d,{relPath:d,fullPath:d,isDirectory:!1,fileHash:g,size:p.content.length})}}return{files:c,pendingComments:l}}catch(o){throw console.error(`${n} ${b(o)} (E: cb667820a7a8c36f58935348f0292126)`),o}}async deleteFromWorkspaceImpl({relPath:e,ibGib:t}){let n=`${this.lc}[${this.deleteFromWorkspaceImpl.name}]`;try{dt&&console.log(`${n} deleting from virtual workspace...`);let o=this.normalizePath(e||t?.data?.name);if(!o)throw new Error(`${n} relPath or item name required for deletion (E: 2bd0d865e962e4457211f8a8d943ca26)`);let s=[];for(let i of this._virtualFiles.keys())(i===o||i.startsWith(`${o}/`))&&s.push(i);for(let i of s)this._virtualFiles.delete(i)}catch(o){throw console.error(`${n} ${b(o)} (E: a7cd788f4281a682d8f867c8ebed6c26)`),o}}async getFileBytesImpl({relPath:e}){return this.getVirtualFile(e)}getVirtualFile(e){let t=this.normalizePath(e),n=this._virtualFiles.get(t);if(!(!n||n.isDirectory))return n.content}getVirtualText(e){let t=this.getVirtualFile(e);if(t!==void 0)return new TextDecoder("utf8").decode(t)}setVirtualFile(e,t){let n=this.normalizePath(e),o=typeof t=="string"?new TextEncoder().encode(t):t,s=n.split("/");for(let i=1;i<s.length;i++){let c=s.slice(0,i).join("/");this._virtualFiles.has(c)||this._virtualFiles.set(c,{relPath:c,content:new Uint8Array(0),isDirectory:!0,modifiedAt:Date.now()})}this._virtualFiles.set(n,{relPath:n,content:o,isDirectory:!1,modifiedAt:Date.now()})}listVirtualPaths(){return Array.from(this._virtualFiles.keys()).sort()}clearVirtualFiles(){this._virtualFiles.clear()}normalizePath(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}isCommentMetadataFilename(e){return e.startsWith(".ib.")&&e.endsWith(".md")&&e.length>7}extractCommentTopicName(e){return this.isCommentMetadataFilename(e)?e.slice(4,-3):""}async fetchIbGib(e){let t=`${this.lc}[${this.fetchIbGib.name}]`;try{if(!this.backingSpace)throw new Error(`${t} backingSpace required to fetch IbGib at ${e} (E: 7ae09891d6a8f7a725787b58ad543826)`);let n=await ft({space:this.backingSpace,addrs:[e]});if(!n.success||!n.ibGibs||n.ibGibs.length===0){let s=n.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`${t} couldn't find addr ${e} in backingSpace. addrsNotFound: ${s} (E: 84be78955e98be16aa5630186a2bd826)`)}return n.ibGibs[0]}catch(n){throw console.error(`${t} ${b(n)} (E: 6ac378f35e08e1c4d11489d151994826)`),n}}};var ke=".vcsgib";var R=!1,je=class r{static{h(this,"BranchingFacade")}lc=`[${r.name}]`;metaspace;workspaceSpace;fnGetWorkspaceProjectionSpace;localSpace;repoRoot;vcsFolderName;enableBranchLocking;constructor(e){this.metaspace=e.metaspace,this.workspaceSpace=e.workspaceSpace,this.fnGetWorkspaceProjectionSpace=e.fnGetWorkspaceProjectionSpace,this.localSpace=e.localSpace,this.repoRoot=e.repoRoot,this.vcsFolderName=e.vcsFolderName||ke,this.enableBranchLocking=e.enableBranchLocking??!0}async getGalaxyIbGib(){let e=`${this.lc}[${this.getGalaxyIbGib.name}]`;try{R&&console.log(`${e} starting... (I: a788a8c3b6980943a8f9ef18dc1cf726)`);let t=await Pt({space:this.localSpace,metaspace:this.metaspace});if(!t)throw new Error(`galaxyIbGib not found in localSpace (${this.localSpace.ib}) (E: c977987a2308b3dcb8f91bbbaf782d26)`);return t}catch(t){throw console.error(`${e} ${b(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async getActiveBranchSpace(e){let t=`${this.lc}[${this.getActiveBranchSpace.name}]`;try{R&&console.log(`${t} starting... (I: abe63d78f173baa5d53283c850fdf826)`);let n,o,s;if(e&&"ib"in e?n=e:e&&(n=e.galaxyIbGib,o=e.targetDir,s=e.branchName),!this.repoRoot)throw new Error("this.repoRoot required for getActiveBranchSpace. Run init or open repository first. (E: c28905d45f3c912061e809df44b10826)");let i=n||await this.getGalaxyIbGib(),c=s||Ae({targetDir:o||this.repoRoot,repoRoot:this.repoRoot,galaxyIbGib:i}),{space:l}=await tt({metaspace:this.metaspace,branchName:c});if(!l)throw new Error(`(UNEXPECTED) activeBranchSpace falsy for branch ${c}. (E: eb723f1db2a8493868ba74e8d3537b26)`);return l}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async getActiveBranchName(e){let t=`${this.lc}[${this.getActiveBranchName.name}]`;try{R&&console.log(`${t} starting... (I: 88c9e4fed434eba3e6c05ad8af10a826)`);let n=e?.galaxyIbGib||await this.getGalaxyIbGib();if(!n){R&&console.log(`${t} galaxyIbGib falsy. no active branch (I: 8312ef696a48ae71f8c9c71e9950c826)`);return}return this.repoRoot?Ae({targetDir:e?.targetDir||this.repoRoot,repoRoot:this.repoRoot,galaxyIbGib:n}):n.data.policy?.defaultBranch||le}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async getActiveWorkspaceProjectionSpace({galaxyIbGib:e,targetDir:t,activeBranchSpace:n}){let o=`${this.lc}[${this.getActiveWorkspaceProjectionSpace.name}]`;try{if(this.fnGetWorkspaceProjectionSpace&&this.repoRoot){let s=Ae({targetDir:t||this.repoRoot,repoRoot:this.repoRoot,galaxyIbGib:e}),i=n||await this.getActiveBranchSpace(e),c=s===le?this.repoRoot:et(this.repoRoot,"b",s);return await this.fnGetWorkspaceProjectionSpace({branchName:s,worktreeDir:c,backingSpace:i})}return this.workspaceSpace}catch(s){throw console.error(`${o} ${b(s)}`),s}}async withBranchLock(e,t){let n=`${this.lc}[${this.withBranchLock.name}]`,o="vcs_branch_mutation";if(!this.enableBranchLocking||!e)return await t();let s;try{s=await yt({space:e,scope:o,secondsValid:60})}catch(i){R&&console.log(`${n} error when unlocking space: ${b(i)} (I: 903cc83c8a0a0d9762038989f53b7a26)`)}try{return await t()}finally{if(s&&s.data?.success)try{await St({space:e,scope:o})}catch(i){R&&console.log(`${n} error when unlocking space: ${b(i)} (I: a57948352efad2cf08b49d988f532826)`)}}}async init(e){let t=`${this.lc}[${this.init.name}]`;try{if(R&&console.log(`${t} starting... (I: b852985dadf1edeceb0fc61244299426)`),!this.localSpace)throw new Error("this.localSpace is falsy. VcsRepository should be initialized with the localSpace (E: 930eff86de8884bb925ab159644ff826)");return await xt({metaspace:this.metaspace,localSpace:this.localSpace,rootFolderName:e.rootFolderName||"root",branchName:e.branchName||le})}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async status(e){let t=`${this.lc}[${this.status.name}]`;try{R&&console.log(`${t} starting... (I: 7fe39201061815e2b5565ae8c149ba26)`);let n=await this.getGalaxyIbGib(),o=await this.getActiveBranchSpace({galaxyIbGib:n,branchName:e?.branchName,targetDir:e?.targetDir}),s=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:n,targetDir:e?.targetDir,activeBranchSpace:o});return await Vt({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:n,activeBranchSpace:o,branchSpace:o,workspaceSpace:s,repoRoot:this.repoRoot,vcsFolderName:this.vcsFolderName,...e})}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async add(e=[],t){let n=`${this.lc}[${this.add.name}]`;try{if(R&&console.log(`${n} starting... (I: 5553e82654d8ff00cb384dd68a710d26)`),!this.repoRoot)throw new Error("this.repoRoot required for vcs add. Run init first. (E: 24dd25a7fdb80102c802a84faeb9b826)");let o=await this.getGalaxyIbGib(),s=await this.getActiveBranchSpace({galaxyIbGib:o,branchName:t?.branchName,targetDir:t?.targetDir}),i=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:o,targetDir:t?.targetDir,activeBranchSpace:s});if(!i)throw new Error("workspaceSpace or fnGetWorkspaceProjectionSpace required. (E: 52d48219f9587517911dbcfed15c8826)");return await Kt({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:o,branchName:t?.branchName,activeBranchSpace:s,branchSpace:s,workspaceSpace:i,paths:e,all:t?.all,repoRoot:this.repoRoot,targetDir:t?.targetDir||this.repoRoot,vcsFolderName:this.vcsFolderName})}catch(o){throw console.error(`${n} ${b(o)}`),o}finally{R&&console.log(`${n} complete.`)}}async commit(e){let t=`${this.lc}[${this.commit.name}]`;try{R&&console.log(`${t} starting... (I: 8ac718098f58e3f1ee1e7fd84ad3f826)`);let n=await this.getGalaxyIbGib(),o=await this.getActiveBranchSpace({galaxyIbGib:n,branchName:e?.branchName,targetDir:e?.targetDir}),s=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:n,targetDir:e?.targetDir,activeBranchSpace:o});return await this.withBranchLock(o,async()=>{if(!this.localSpace)throw new Error("localSpace required for vcs commit. Run init first. (E: 3a54587f0bfdecc8585f56685a7bbe26)");return await Ut({metaspace:this.metaspace,localSpace:this.localSpace,branchName:e?.branchName,activeBranchSpace:o,branchSpace:o,workspaceSpace:s,galaxyIbGib:n,message:e.message,author:e.author,repoRoot:this.repoRoot,targetDir:e.targetDir||this.repoRoot,vcsFolderName:this.vcsFolderName,keepEmptyFolders:e?.keepEmptyFolders})})}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async branch(e){let t=`${this.lc}[${this.branch.name}]`;try{R&&console.log(`${t} starting... (I: 009448e3384b35ac395e912f5f4a6826)`);let n=await this.getGalaxyIbGib(),o=await this.getActiveBranchSpace({galaxyIbGib:n,branchName:e?.sourceBranchName,targetDir:e?.targetDir});return await Yt({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:n,activeBranchSpace:o,sourceBranchSpace:o,branchName:e?.branchName,sourceBranchName:e?.sourceBranchName,currentBranchName:e?.currentBranchName,itemPath:e?.itemPath,repoRoot:this.repoRoot,targetDir:e?.targetDir||this.repoRoot,vcsFolderName:this.vcsFolderName})}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async checkout(e){let t=`${this.lc}[${this.checkout.name}]`;try{R&&console.log(`${t} starting... (I: 8d7318c5c2687f339806e888dab2d826)`);let n=e.branchName?.trim();if(!n)throw new Error("Branch name is required for checkout (E: e081280b32c8ffd8a8f4fd98e9f53826)");let o=await this.getGalaxyIbGib(),s=this.workspaceSpace,i=e.targetBranchSpace;if(this.fnGetWorkspaceProjectionSpace&&this.repoRoot){let c=n===le?this.repoRoot:et(this.repoRoot,"b",n);if(!i){let{space:l}=await tt({metaspace:this.metaspace,branchName:n});i=l}i&&(s=await this.fnGetWorkspaceProjectionSpace({branchName:n,worktreeDir:c,backingSpace:i}))}return await this.withBranchLock(i||e.targetBranchSpace,async()=>{let c=await qt({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:o,targetBranchSpace:i||e.targetBranchSpace,workspaceSpace:s,branchName:n,force:e.force,repoRoot:this.repoRoot,targetDir:e.targetDir||this.repoRoot,vcsFolderName:this.vcsFolderName});return s&&(this.workspaceSpace=s),c})}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async reset(e){let t=`${this.lc}[${this.reset.name}]`;try{R&&console.log(`${t} starting... (I: ffd4d1428fd8d222082b20b42d4b7826)`);let n=await this.getGalaxyIbGib(),o=await this.getActiveBranchSpace({galaxyIbGib:n,targetDir:e?.targetDir});return await Xt({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:n,activeBranchSpace:o,paths:e?.paths,all:e?.all,targetDir:e?.targetDir,activeWorktreeDir:e?.activeWorktreeDir})}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async restore(e){let t=`${this.lc}[${this.restore.name}]`;try{R&&console.log(`${t} starting... (I: be82d51cb97b3370ba8488a8d3ab8826)`);let n=await this.getGalaxyIbGib();e.metaspace??=this.metaspace;let o=Ae({targetDir:e.targetDir||this.repoRoot,repoRoot:this.repoRoot,galaxyIbGib:n}),s=await this.getActiveBranchSpace({galaxyIbGib:n,targetDir:e?.targetDir,branchName:o}),i=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:n,targetDir:e?.targetDir,activeBranchSpace:s});if(!i)throw new Error("workspaceSpace or fnGetWorkspaceProjectionSpace required. (E: 466ff89709f5e3fa485bec6df9375826)");return await zt({metaspace:this.metaspace,localSpace:this.localSpace,workspaceSpace:i,paths:e?.paths,staged:e?.staged,all:e?.all,targetDir:e?.targetDir,activeWorktreeDir:e?.activeWorktreeDir})}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async merge(e){let t=`${this.lc}[${this.merge.name}]`;try{R&&console.log(`${t} starting... (I: e3c60a1d02f7a5944252adbbd6b5fe26)`);let n=await this.getGalaxyIbGib(),o=await this.getActiveBranchSpace({galaxyIbGib:n,targetDir:e?.targetDir});if(!e.incomingBranchName)throw new Error("opts.incomingBranchName falsy (E: 5a83a806fd78f2edc27a26fd3e8cf826)");let s=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:n,targetDir:e?.targetDir,activeBranchSpace:o});return await this.withBranchLock(o,async()=>await Jt({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:n,baseBranchSpace:o,incomingBranchSpace:e.incomingBranchSpace,workspaceSpace:s,incomingBranchName:e.incomingBranchName,message:e.message,repoRoot:this.repoRoot,targetDir:e.targetDir||this.repoRoot,vcsFolderName:this.vcsFolderName}))}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async log(e){let t=`${this.lc}[${this.log.name}]`;try{R&&console.log(`${t} starting... (I: 737c6843d42e9acac8cfabd85d2e8926)`);let n=await this.getGalaxyIbGib();return await Zt({metaspace:this.metaspace,galaxyIbGib:n,branchName:e?.branchName,filePath:e?.filePath,allComments:e?.allComments,repoRoot:this.repoRoot,targetDir:e?.targetDir||this.repoRoot})}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async generateComment(e){let t=`${this.lc}[${this.generateComment.name}]`;try{R&&console.log(`${t} starting...`);let n=e?.galaxyIbGib||await this.getGalaxyIbGib(),o=e?.targetDir||this.repoRoot,s=await this.getActiveBranchSpace({galaxyIbGib:n,targetDir:o}),i=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:n,targetDir:o,activeBranchSpace:s});if(!i)throw new Error("workspaceSpace is required to generate companion comments (E: b3f2081a91e54a4bb82a720db1e54a26)");return await Qt({metaspace:this.metaspace,localSpace:this.localSpace,activeBranchSpace:s,workspaceSpace:i,galaxyIbGib:n,paths:e?.paths,folderTopic:e?.folderTopic,repoRoot:this.repoRoot,targetDir:o,vcsFolderName:this.vcsFolderName})}catch(n){throw console.error(`${t} ${b(n)}`),n}finally{R&&console.log(`${t} complete.`)}}async updateIndex(e){let t=e.targetSpace||this.localSpace;if(!t)throw new Error("localSpace required to update index (E: 5ff10877e06228e17fc1eb88d3073826)");let n=await this.getGalaxyIbGib();return await this.withBranchLock(t,async()=>await Ot({space:t,metaspace:this.metaspace,galaxyIbGib:n,dataToUpdate:e.dataToUpdate}))}};var re={};window.vcsDevState=re;function tn(){let r=document.getElementById("btn-vcs-init");r&&r.addEventListener("click",async()=>{let e=`${N}[btn-vcs-init]`;try{r.disabled=!0,a("\u23F3 Initializing in-memory branch space & sample repo via VcsRepository...");let t=await E(),n=Nt("main"),o=new Tt({...kt,name:n,spaceSubPath:n,uuid:"ws_backing_cas_space_uuid"});await o.initialized,re.backingSpace=o;try{t.localUserSpaces&&!t.localUserSpaces.includes(o)&&t.localUserSpaces.push(o),t.spaces&&!t.spaces.includes(o)&&t.spaces.push(o)}catch{}let s=new Ue({initialData:{name:"web_ws_space_main",uuid:"web_ws_uuid",workspaceRoot:"/",vcsFolderName:ke},backingSpace:o});await s.initialized,re.wsSpace=s;let i=new je({metaspace:t,workspaceSpace:s,localSpace:o,vcsFolderName:ke,repoRoot:"",enableBranchLocking:!0});re.repo=i,await i.init({rootFolderName:"my-app",branchName:le}),s.setVirtualFile("README.md",`# Space-Gib In-Memory Repo
33
13
 
34
- (Enter contemporaneous notes/comments here)
35
- `,$=await Cs({name:G,content:_});await t.witness({data:{cmd:"put"},ibGibs:[$]}),m.push(G)}}return{createdFiles:m,skippedFiles:u}}catch(b){throw console.error(`${f} ${g(b)} (E: d23e082728cb489e830e9d6d5a1b3c4f)`),b}finally{Fs&&console.log(`${f} complete. (I: a3b71946358e469d80fc4ef2b281c726)`)}}p(Bn,"executeVcsGenerateComment");var Ca=".vcsgib";var Y=!1,hr=class o{static{p(this,"VcsRepository")}lc=`[${o.name}]`;metaspace;workspaceSpace;fnGetWorkspaceProjectionSpace;localSpace;repoRoot;vcsFolderName;enableBranchLocking;constructor(e){this.metaspace=e.metaspace,this.workspaceSpace=e.workspaceSpace,this.fnGetWorkspaceProjectionSpace=e.fnGetWorkspaceProjectionSpace,this.localSpace=e.localSpace,this.repoRoot=e.repoRoot,this.vcsFolderName=e.vcsFolderName||Ca,this.enableBranchLocking=e.enableBranchLocking??!0}async getGalaxyIbGib(){let e=`${this.lc}[${this.getGalaxyIbGib.name}]`;try{Y&&console.log(`${e} starting... (I: a788a8c3b6980943a8f9ef18dc1cf726)`);let t=await Mt({space:this.localSpace,metaspace:this.metaspace});if(!t)throw new Error(`galaxyIbGib not found in localSpace (${this.localSpace.ib}) (E: c977987a2308b3dcb8f91bbbaf782d26)`);return t}catch(t){throw console.error(`${e} ${g(t)}`),t}finally{Y&&console.log(`${e} complete.`)}}async getActiveBranchSpace(e){let t=`${this.lc}[${this.getActiveBranchSpace.name}]`;try{Y&&console.log(`${t} starting... (I: abe63d78f173baa5d53283c850fdf826)`);let a,r,n;if(e&&"ib"in e?a=e:e&&(a=e.galaxyIbGib,r=e.targetDir,n=e.branchName),!this.repoRoot)throw new Error("this.repoRoot required for getActiveBranchSpace. Run init or open repository first. (E: c28905d45f3c912061e809df44b10826)");let s=a||await this.getGalaxyIbGib(),i=n||Ve({targetDir:r||this.repoRoot,repoRoot:this.repoRoot,galaxyIbGib:s}),{space:c}=await Gt({metaspace:this.metaspace,branchName:i});if(!c)throw new Error(`(UNEXPECTED) activeBranchSpace falsy for branch ${i}. (E: eb723f1db2a8493868ba74e8d3537b26)`);return c}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async getActiveBranchName(e){let t=`${this.lc}[${this.getActiveBranchName.name}]`;try{Y&&console.log(`${t} starting... (I: 88c9e4fed434eba3e6c05ad8af10a826)`);let a=e?.galaxyIbGib||await this.getGalaxyIbGib();if(!a){Y&&console.log(`${t} galaxyIbGib falsy. no active branch (I: 8312ef696a48ae71f8c9c71e9950c826)`);return}return this.repoRoot?Ve({targetDir:e?.targetDir||this.repoRoot,repoRoot:this.repoRoot,galaxyIbGib:a}):a.data.activeBranchName}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async getActiveWorkspaceProjectionSpace({galaxyIbGib:e,targetDir:t,activeBranchSpace:a}){let r=`${this.lc}[${this.getActiveWorkspaceProjectionSpace.name}]`;try{if(this.fnGetWorkspaceProjectionSpace&&this.repoRoot){let n=Ve({targetDir:t||this.repoRoot,repoRoot:this.repoRoot,galaxyIbGib:e}),s=a||await this.getActiveBranchSpace(e),i=n===Ne?this.repoRoot:re(this.repoRoot,"b",n);return await this.fnGetWorkspaceProjectionSpace({branchName:n,worktreeDir:i,backingSpace:s})}return this.workspaceSpace}catch(n){throw console.error(`${r} ${g(n)}`),n}}async withBranchLock(e,t){let a=`${this.lc}[${this.withBranchLock.name}]`,r="vcs_branch_mutation";if(!this.enableBranchLocking||!e)return await t();let n;try{n=await kn({space:e,scope:r,secondsValid:60})}catch(s){Y&&console.log(`${a} error when unlocking space: ${g(s)} (I: 903cc83c8a0a0d9762038989f53b7a26)`)}try{return await t()}finally{if(n&&n.data?.success)try{await On({space:e,scope:r})}catch(s){Y&&console.log(`${a} error when unlocking space: ${g(s)} (I: a57948352efad2cf08b49d988f532826)`)}}}async init(e){let t=`${this.lc}[${this.init.name}]`;try{if(Y&&console.log(`${t} starting... (I: b852985dadf1edeceb0fc61244299426)`),!this.localSpace)throw new Error("this.localSpace is falsy. VcsRepository should be initialized with the localSpace (E: 930eff86de8884bb925ab159644ff826)");return await un({metaspace:this.metaspace,localSpace:this.localSpace,rootFolderName:e.rootFolderName||"root",branchName:e.branchName||Ne})}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async status(e){let t=`${this.lc}[${this.status.name}]`;try{Y&&console.log(`${t} starting... (I: 7fe39201061815e2b5565ae8c149ba26)`);let a=await this.getGalaxyIbGib(),r=await this.getActiveBranchSpace(a),n=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:a,targetDir:e?.targetDir,activeBranchSpace:r});return await pr({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:a,activeBranchSpace:r,workspaceSpace:n,repoRoot:this.repoRoot,vcsFolderName:this.vcsFolderName,...e})}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async add(e=[],t){let a=`${this.lc}[${this.add.name}]`;try{if(Y&&console.log(`${a} starting... (I: 5553e82654d8ff00cb384dd68a710d26)`),!this.repoRoot)throw new Error("this.repoRoot required for vcs add. Run init first. (E: 24dd25a7fdb80102c802a84faeb9b826)");let r=await this.getGalaxyIbGib(),n=await this.getActiveBranchSpace({galaxyIbGib:r,targetDir:t?.targetDir}),s=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:r,targetDir:t?.targetDir,activeBranchSpace:n});if(!s)throw new Error("workspaceSpace or fnGetWorkspaceProjectionSpace required. (E: 52d48219f9587517911dbcfed15c8826)");return await En({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:r,activeBranchSpace:n,workspaceSpace:s,paths:e,all:t?.all,repoRoot:this.repoRoot,targetDir:t?.targetDir||this.repoRoot,vcsFolderName:this.vcsFolderName})}catch(r){throw console.error(`${a} ${g(r)}`),r}finally{Y&&console.log(`${a} complete.`)}}async commit(e){let t=`${this.lc}[${this.commit.name}]`;try{Y&&console.log(`${t} starting... (I: 8ac718098f58e3f1ee1e7fd84ad3f826)`);let a=await this.getGalaxyIbGib(),r=await this.getActiveBranchSpace({galaxyIbGib:a,targetDir:e?.targetDir}),n=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:a,targetDir:e?.targetDir,activeBranchSpace:r});return await this.withBranchLock(r,async()=>{if(!this.localSpace)throw new Error("localSpace required for vcs commit. Run init first. (E: 3a54587f0bfdecc8585f56685a7bbe26)");return await wn({metaspace:this.metaspace,localSpace:this.localSpace,activeBranchSpace:r,workspaceSpace:n,galaxyIbGib:a,message:e.message,author:e.author,repoRoot:this.repoRoot,targetDir:e.targetDir||this.repoRoot,vcsFolderName:this.vcsFolderName,keepEmptyFolders:e?.keepEmptyFolders})})}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async branch(e){let t=`${this.lc}[${this.branch.name}]`;try{Y&&console.log(`${t} starting... (I: 009448e3384b35ac395e912f5f4a6826)`);let a=await this.getGalaxyIbGib(),r=await this.getActiveBranchSpace({galaxyIbGib:a,targetDir:e?.targetDir});return await Sn({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:a,activeBranchSpace:r,branchName:e?.branchName,itemPath:e?.itemPath,repoRoot:this.repoRoot,targetDir:e?.targetDir||this.repoRoot,vcsFolderName:this.vcsFolderName})}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async checkout(e){let t=`${this.lc}[${this.checkout.name}]`;try{Y&&console.log(`${t} starting... (I: 8d7318c5c2687f339806e888dab2d826)`);let a=e.branchName?.trim();if(!a)throw new Error("Branch name is required for checkout (E: e081280b32c8ffd8a8f4fd98e9f53826)");let r=await this.getGalaxyIbGib(),n=this.workspaceSpace,s=e.targetBranchSpace;if(this.fnGetWorkspaceProjectionSpace&&this.repoRoot){let i=a===Ne?this.repoRoot:re(this.repoRoot,"b",a);if(!s){let{space:c}=await Gt({metaspace:this.metaspace,branchName:a});s=c}s&&(n=await this.fnGetWorkspaceProjectionSpace({branchName:a,worktreeDir:i,backingSpace:s}))}return await this.withBranchLock(s||e.targetBranchSpace,async()=>{let i=await An({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:r,targetBranchSpace:s||e.targetBranchSpace,workspaceSpace:n,branchName:a,force:e.force,repoRoot:this.repoRoot,targetDir:e.targetDir||this.repoRoot,vcsFolderName:this.vcsFolderName});return n&&(this.workspaceSpace=n),i})}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async reset(e){let t=`${this.lc}[${this.reset.name}]`;try{Y&&console.log(`${t} starting... (I: ffd4d1428fd8d222082b20b42d4b7826)`);let a=await this.getGalaxyIbGib(),r=await this.getActiveBranchSpace({galaxyIbGib:a,targetDir:e?.targetDir});return await $n({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:a,activeBranchSpace:r,paths:e?.paths,all:e?.all,targetDir:e?.targetDir,activeWorktreeDir:e?.activeWorktreeDir})}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async restore(e){let t=`${this.lc}[${this.restore.name}]`;try{Y&&console.log(`${t} starting... (I: be82d51cb97b3370ba8488a8d3ab8826)`);let a=await this.getGalaxyIbGib();e.metaspace??=this.metaspace;let r=Ve({targetDir:e.targetDir||this.repoRoot,repoRoot:this.repoRoot,galaxyIbGib:a}),n=await this.getActiveBranchSpace({galaxyIbGib:a,targetDir:e?.targetDir,branchName:r}),s=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:a,targetDir:e?.targetDir,activeBranchSpace:n});if(!s)throw new Error("workspaceSpace or fnGetWorkspaceProjectionSpace required. (E: 466ff89709f5e3fa485bec6df9375826)");return await _n({metaspace:this.metaspace,localSpace:this.localSpace,workspaceSpace:s,paths:e?.paths,staged:e?.staged,all:e?.all,targetDir:e?.targetDir,activeWorktreeDir:e?.activeWorktreeDir})}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async merge(e){let t=`${this.lc}[${this.merge.name}]`;try{Y&&console.log(`${t} starting... (I: e3c60a1d02f7a5944252adbbd6b5fe26)`);let a=await this.getGalaxyIbGib(),r=await this.getActiveBranchSpace({galaxyIbGib:a,targetDir:e?.targetDir});if(!e.incomingBranchName)throw new Error("opts.incomingBranchName falsy (E: 5a83a806fd78f2edc27a26fd3e8cf826)");let n=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:a,targetDir:e?.targetDir,activeBranchSpace:r});return await this.withBranchLock(r,async()=>await Cn({metaspace:this.metaspace,localSpace:this.localSpace,galaxyIbGib:a,baseBranchSpace:r,incomingBranchSpace:e.incomingBranchSpace,workspaceSpace:n,incomingBranchName:e.incomingBranchName,message:e.message,repoRoot:this.repoRoot,targetDir:e.targetDir||this.repoRoot,vcsFolderName:this.vcsFolderName}))}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async log(e){let t=`${this.lc}[${this.log.name}]`;try{Y&&console.log(`${t} starting... (I: 737c6843d42e9acac8cfabd85d2e8926)`);let a=await this.getGalaxyIbGib();return await vn({metaspace:this.metaspace,galaxyIbGib:a,branchName:e?.branchName,filePath:e?.filePath,allComments:e?.allComments,repoRoot:this.repoRoot,targetDir:e?.targetDir||this.repoRoot})}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async generateComment(e){let t=`${this.lc}[${this.generateComment.name}]`;try{Y&&console.log(`${t} starting...`);let a=e?.galaxyIbGib||await this.getGalaxyIbGib(),r=e?.targetDir||this.repoRoot,n=await this.getActiveBranchSpace({galaxyIbGib:a,targetDir:r}),s=await this.getActiveWorkspaceProjectionSpace({galaxyIbGib:a,targetDir:r,activeBranchSpace:n});if(!s)throw new Error("workspaceSpace is required to generate companion comments (E: b3f2081a91e54a4bb82a720db1e54a26)");return await Bn({metaspace:this.metaspace,localSpace:this.localSpace,activeBranchSpace:n,workspaceSpace:s,galaxyIbGib:a,paths:e?.paths,folderTopic:e?.folderTopic,repoRoot:this.repoRoot,targetDir:r,vcsFolderName:this.vcsFolderName})}catch(a){throw console.error(`${t} ${g(a)}`),a}finally{Y&&console.log(`${t} complete.`)}}async updateIndex(e){let t=e.targetSpace||this.localSpace;if(!t)throw new Error("localSpace required to update index (E: 5ff10877e06228e17fc1eb88d3073826)");let a=await this.getGalaxyIbGib();return await this.withBranchLock(t,async()=>await Le({space:t,metaspace:this.metaspace,galaxyIbGib:a,dataToUpdate:e.dataToUpdate}))}};var nt={};window.vcsDevState=nt;function Ms(){let o=document.getElementById("btn-vcs-init");o&&o.addEventListener("click",async()=>{let e=`${q}[btn-vcs-init]`;try{o.disabled=!0,l("\u23F3 Initializing in-memory branch space & sample repo via VcsRepository...");let t=await O(),a=Qr("main"),r=new so({...oo,name:a,spaceSubPath:a,uuid:"ws_backing_cas_space_uuid"});await r.initialized,nt.backingSpace=r;try{t.localUserSpaces&&!t.localUserSpaces.includes(r)&&t.localUserSpaces.push(r),t.spaces&&!t.spaces.includes(r)&&t.spaces.push(r)}catch{}let n=new or({initialData:{name:"web_ws_space_main",uuid:"web_ws_uuid",workspaceRoot:"/",vcsFolderName:Ca},backingSpace:r});await n.initialized,nt.wsSpace=n;let s=new hr({metaspace:t,workspaceSpace:n,localSpace:r,vcsFolderName:Ca,repoRoot:"",enableBranchLocking:!0});nt.repo=s,await s.init({rootFolderName:"my-app",branchName:Ne}),n.setVirtualFile("README.md",`# Space-Gib In-Memory Repo
36
-
37
- This entire repository is projected in memory inside the browser.`),n.setVirtualFile("src/index.ts",`export const app = "space-gib in-memory demo";
38
- console.log(app);`),n.setVirtualFile("src/helper.ts",`export function add(a: number, b: number): number {
14
+ This entire repository is projected in memory inside the browser.`),s.setVirtualFile("src/index.ts",`export const app = "space-gib in-memory demo";
15
+ console.log(app);`),s.setVirtualFile("src/helper.ts",`export function add(a: number, b: number): number {
39
16
  return a + b;
40
- }`),n.setVirtualFile(".ibgibignore",`node_modules/
17
+ }`),s.setVirtualFile(".ibgibignore",`node_modules/
41
18
  *.log
42
- `);let i=await s.getGalaxyIbGib(),c=await s.getActiveBranchSpace(i);await s.add([],{all:!0,galaxyIbGib:i,activeBranchSpace:c,repoRoot:s.repoRoot,paths:void 0,targetDir:void 0});let d=await s.commit({message:"Initial repository commit"});l(`\u2705 In-Memory Repo initialized via VcsRepository!
19
+ `);let c=await i.getGalaxyIbGib(),l=await i.getActiveBranchSpace(c);await i.add([],{all:!0,galaxyIbGib:c,activeBranchSpace:l,repoRoot:i.repoRoot,paths:void 0,targetDir:void 0});let d=await i.commit({message:"Initial repository commit"});a(`\u2705 In-Memory Repo initialized via VcsRepository!
43
20
  Commit: ${d.commitAddr.slice(0,8)}
44
- Files: ${n.listVirtualPaths().join(", ")}`),Ta("btn-vcs-list",!1),Ta("btn-vcs-status",!1),Ta("btn-vcs-modify",!1),Ta("btn-vcs-reset",!1)}catch(t){l(`\u274C Init failed: ${g(t)}`),console.error(`${e}`,t)}finally{o.disabled=!0}})}p(Ms,"initVcsInitButton");function Us(){let o=document.getElementById("btn-vcs-list");o&&o.addEventListener("click",()=>{try{let e=nt.wsSpace;if(!e){l("\u26A0\uFE0F Repo not initialized yet. Click (1) first.");return}let t=e.listVirtualPaths(),a=[`\u{1F4C1} --- IN-MEMORY VIRTUAL FILES (${t.length} entries) ---`];for(let r of t){let n=e.getVirtualText(r);if(n===void 0||e.getVirtualFile(r)?.length===0)a.push(` \u{1F4C1} [DIR] ${r}`);else{let i=(n||"").replace(/\n/g," ").slice(0,40);a.push(` \u{1F4C4} [FILE] ${r.padEnd(22)} (${String(n?.length||0).padStart(3)} chars) -> "${i}..."`)}}l(a.join(`
45
- `))}catch(e){l(`\u274C List failed: ${g(e)}`)}})}p(Us,"initVcsListButton");function Vs(){let o=document.getElementById("btn-vcs-status");o&&o.addEventListener("click",async()=>{try{let e=nt.repo;if(!e){l("\u26A0\uFE0F Repo not initialized yet.");return}let t=await e.status(),a=[`\u{1F4CB} --- VCS STATUS (Branch: ${t.branchName}) ---`];if(t.staged.length===0&&t.modified.length===0&&t.deleted.length===0&&t.untracked.length===0&&t.pendingComments.length===0)a.push(" \u2728 Working tree clean (no changes)");else{if(t.staged.length>0){a.push(` \u{1F7E2} Staged changes (${t.staged.length}):`);for(let r of t.staged)a.push(` staged: ${r.path}`)}if(t.modified.length>0){a.push(` \u{1F7E1} Changes not staged for commit (${t.modified.length}):`);for(let r of t.modified)a.push(` modified: ${r.path}`)}if(t.deleted.length>0){a.push(` \u{1F534} Deleted files (${t.deleted.length}):`);for(let r of t.deleted)a.push(` deleted: ${r.path}`)}if(t.untracked.length>0){a.push(` \u26AA Untracked files (${t.untracked.length}):`);for(let r of t.untracked)a.push(` untracked: ${r.path}`)}if(t.pendingComments.length>0){a.push(` \u{1F4AC} Pending companion comments (${t.pendingComments.length}):`);for(let r of t.pendingComments)a.push(` note for: ${r.targetRelPath} (${r.commentRelPath})`)}}l(a.join(`
46
- `))}catch(e){l(`\u274C Status check failed: ${g(e)}`)}})}p(Vs,"initVcsStatusButton");function js(){let o=document.getElementById("btn-vcs-modify");o&&o.addEventListener("click",()=>{try{let e=nt.wsSpace;if(!e){l("\u26A0\uFE0F Repo not initialized yet.");return}let t=["\u270F\uFE0F Simulating user edits in in-browser editor..."],a=`export const app = "space-gib (EDITED LIVE IN BROWSER!)";
21
+ Files: ${s.listVirtualPaths().join(", ")}`),Te("btn-vcs-list",!1),Te("btn-vcs-status",!1),Te("btn-vcs-modify",!1),Te("btn-vcs-reset",!1)}catch(t){a(`\u274C Init failed: ${b(t)}`),console.error(`${e}`,t)}finally{r.disabled=!0}})}h(tn,"initVcsInitButton");function an(){let r=document.getElementById("btn-vcs-list");r&&r.addEventListener("click",()=>{try{let e=re.wsSpace;if(!e){a("\u26A0\uFE0F Repo not initialized yet. Click (1) first.");return}let t=e.listVirtualPaths(),n=[`\u{1F4C1} --- IN-MEMORY VIRTUAL FILES (${t.length} entries) ---`];for(let o of t){let s=e.getVirtualText(o);if(s===void 0||e.getVirtualFile(o)?.length===0)n.push(` \u{1F4C1} [DIR] ${o}`);else{let c=(s||"").replace(/\n/g," ").slice(0,40);n.push(` \u{1F4C4} [FILE] ${o.padEnd(22)} (${String(s?.length||0).padStart(3)} chars) -> "${c}..."`)}}a(n.join(`
22
+ `))}catch(e){a(`\u274C List failed: ${b(e)}`)}})}h(an,"initVcsListButton");function nn(){let r=document.getElementById("btn-vcs-status");r&&r.addEventListener("click",async()=>{try{let e=re.repo;if(!e){a("\u26A0\uFE0F Repo not initialized yet.");return}let t=await e.status(),n=[`\u{1F4CB} --- VCS STATUS (Branch: ${t.branchName}) ---`];if(t.staged.length===0&&t.modified.length===0&&t.deleted.length===0&&t.untracked.length===0&&t.pendingComments.length===0)n.push(" \u2728 Working tree clean (no changes)");else{if(t.staged.length>0){n.push(` \u{1F7E2} Staged changes (${t.staged.length}):`);for(let o of t.staged)n.push(` staged: ${o.path}`)}if(t.modified.length>0){n.push(` \u{1F7E1} Changes not staged for commit (${t.modified.length}):`);for(let o of t.modified)n.push(` modified: ${o.path}`)}if(t.deleted.length>0){n.push(` \u{1F534} Deleted files (${t.deleted.length}):`);for(let o of t.deleted)n.push(` deleted: ${o.path}`)}if(t.untracked.length>0){n.push(` \u26AA Untracked files (${t.untracked.length}):`);for(let o of t.untracked)n.push(` untracked: ${o.path}`)}if(t.pendingComments.length>0){n.push(` \u{1F4AC} Pending companion comments (${t.pendingComments.length}):`);for(let o of t.pendingComments)n.push(` note for: ${o.targetRelPath} (${o.commentRelPath})`)}}a(n.join(`
23
+ `))}catch(e){a(`\u274C Status check failed: ${b(e)}`)}})}h(nn,"initVcsStatusButton");function rn(){let r=document.getElementById("btn-vcs-modify");r&&r.addEventListener("click",()=>{try{let e=re.wsSpace;if(!e){a("\u26A0\uFE0F Repo not initialized yet.");return}let t=["\u270F\uFE0F Simulating user edits in in-browser editor..."],n=`export const app = "space-gib (EDITED LIVE IN BROWSER!)";
47
24
  console.log(app);
48
- export const timestamp = `+Date.now()+";";e.setVirtualFile("src/index.ts",a),t.push(' \u270F\uFE0F Updated "src/index.ts" with new code content.'),e.setVirtualFile("src/new-component.ts",'export const Component = () => "<div>New UI</div>";'),t.push(' \u2795 Created untracked file "src/new-component.ts".'),e.setVirtualFile("src/.ib.index.ts.md",`# Architectural Note on index.ts
49
- Edited live from Dev Tools!`),t.push(' \u{1F4AC} Added companion comment file "src/.ib.index.ts.md".'),t.push("\u{1F449} Click (3) VCS Status to view detected changes, or (5) to commit!"),l(t.join(`
50
- `)),Ta("btn-vcs-commit",!1)}catch(e){l(`\u274C Modify failed: ${g(e)}`)}})}p(js,"initVcsModifyButton");function Xs(){let o=document.getElementById("btn-vcs-commit");o&&o.addEventListener("click",async()=>{try{o.disabled=!0;let e=nt.repo;if(!e){l("\u26A0\uFE0F Repo not initialized yet.");return}l("\u{1F4BE} Staging and committing changes via VcsRepository...");let t=await e.add([],{all:!0}),a=await e.commit({message:"Update index.ts and add new component with companion comment"}),r=["\u{1F389} Committed successfully via VcsRepository!",` Commit: ${a.commitAddr.slice(0,8)}`,` Files Changed: ${a.committedPaths.join(", ")}`,` Companion Comments Attached: ${a.ingestedCommentsCount}`,"\u{1F449} Click (3) VCS Status to verify clean working tree."];l(r.join(`
51
- `))}catch(e){l(`\u274C Commit failed: ${g(e)}`),console.error(`${q}[btn-vcs-commit]`,e)}finally{o.disabled=!1}})}p(Xs,"initVcsCommitButton");function Ks(){let o=document.getElementById("btn-vcs-reset");o&&o.addEventListener("click",async()=>{try{let{wsSpace:e,repo:t}=nt;if(!e||!t){l("\u26A0\uFE0F Repo not initialized yet.");return}l("\u{1F504} Resetting virtual working tree from branch snapshot via VcsRepository..."),await t.restore({all:!0}),e.setVirtualFile(".ibgibignore",`node_modules/
25
+ export const timestamp = `+Date.now()+";";e.setVirtualFile("src/index.ts",n),t.push(' \u270F\uFE0F Updated "src/index.ts" with new code content.'),e.setVirtualFile("src/new-component.ts",'export const Component = () => "<div>New UI</div>";'),t.push(' \u2795 Created untracked file "src/new-component.ts".'),e.setVirtualFile("src/.ib.index.ts.md",`# Architectural Note on index.ts
26
+ Edited live from Dev Tools!`),t.push(' \u{1F4AC} Added companion comment file "src/.ib.index.ts.md".'),t.push("\u{1F449} Click (3) VCS Status to view detected changes, or (5) to commit!"),a(t.join(`
27
+ `)),Te("btn-vcs-commit",!1)}catch(e){a(`\u274C Modify failed: ${b(e)}`)}})}h(rn,"initVcsModifyButton");function on(){let r=document.getElementById("btn-vcs-commit");r&&r.addEventListener("click",async()=>{try{r.disabled=!0;let e=re.repo;if(!e){a("\u26A0\uFE0F Repo not initialized yet.");return}a("\u{1F4BE} Staging and committing changes via VcsRepository...");let t=await e.add([],{all:!0}),n=await e.commit({message:"Update index.ts and add new component with companion comment"}),o=["\u{1F389} Committed successfully via VcsRepository!",` Commit: ${n.commitAddr.slice(0,8)}`,` Files Changed: ${n.committedPaths.join(", ")}`,` Companion Comments Attached: ${n.ingestedCommentsCount}`,"\u{1F449} Click (3) VCS Status to verify clean working tree."];a(o.join(`
28
+ `))}catch(e){a(`\u274C Commit failed: ${b(e)}`),console.error(`${N}[btn-vcs-commit]`,e)}finally{r.disabled=!1}})}h(on,"initVcsCommitButton");function sn(){let r=document.getElementById("btn-vcs-reset");r&&r.addEventListener("click",async()=>{try{let{wsSpace:e,repo:t}=re;if(!e||!t){a("\u26A0\uFE0F Repo not initialized yet.");return}a("\u{1F504} Resetting virtual working tree from branch snapshot via VcsRepository..."),await t.restore({all:!0}),e.setVirtualFile(".ibgibignore",`node_modules/
52
29
  *.log
53
- `),l(`\u2705 Working tree restored! All uncommitted edits discarded.
54
- \u{1F449} Click (3) VCS Status to confirm clean state.`)}catch(e){l(`\u274C Reset failed: ${g(e)}`)}})}p(Ks,"initVcsResetButton");function Ta(o,e){let t=document.getElementById(o);t&&(t.disabled=e)}p(Ta,"setBtnDisabled");function Ws(){let o=`${q}[initDevTools]`;try{let e=document.getElementById("dev-tools-row-select");e&&(e.addEventListener("change",()=>{let t=e.value;document.querySelectorAll(".dev-panel-row-container").forEach(r=>{let n=r.getAttribute("data-row-id");t==="all"||n===t?r.style.display="flex":r.style.display="none"})}),e.dispatchEvent(new Event("change"))),Io(),So(),wo(),Go(),Ao(),$o(),_o(),Co(),To(),vo(),Bo(),No(),Po(),xo(),Do(),Lo(),Ro(),ko(),Oo(),Fo(),Mo(),Uo(),Vo(),jo(),Xo(),Ko(),Yo(),qo(),zo(),Jo(),Zo(),Qo(),ts(),as(),rs(),ns(),os(),ss(),ds(),ls(),fs(),bs(),ms(),ps(),Ms(),Us(),Vs(),js(),Xs(),Ks()}catch(e){console.error(`${o} ${g(e)}`)}}p(Ws,"initDevTools");co(Nr);var Hs=Br;async function Ys(){let o=`[${Ys.name}]`;try{Hs&&console.log(`${o} starting... (I: 3d893846d02c4ff49181f9b8e586eb74)`),console.time(o),document.addEventListener("DOMContentLoaded",async()=>{try{console.timeLog(o,"DOMContentLoaded fired"),await io(Nr),console.timeLog(o,"initIbGibStorage complete"),await lo("./bootstrap.mjs"),console.timeLog(o,"dynamicallyLoadBootstrapScript complete"),Ws(),console.timeLog(o,"initDevTools complete"),console.timeEnd(o)}catch(e){throw console.error(`${o} ${g(e)}`),e}})}catch(e){console.timeEnd(o);debugger;throw console.error(`${o} ${g(e)}`),e}finally{Hs&&console.log(`${o} complete.`)}}p(Ys,"spinOffStartup");Ys();
30
+ `),a(`\u2705 Working tree restored! All uncommitted edits discarded.
31
+ \u{1F449} Click (3) VCS Status to confirm clean state.`)}catch(e){a(`\u274C Reset failed: ${b(e)}`)}})}h(sn,"initVcsResetButton");function Te(r,e){let t=document.getElementById(r);t&&(t.disabled=e)}h(Te,"setBtnDisabled");function cn(){let r=`${N}[initDevTools]`;try{let e=document.getElementById("dev-tools-row-select");e&&(e.addEventListener("change",()=>{let t=e.value;document.querySelectorAll(".dev-panel-row-container").forEach(o=>{let s=o.getAttribute("data-row-id");t==="all"||s===t?o.style.display="flex":o.style.display="none"})}),e.dispatchEvent(new Event("change"))),oa(),ia(),ra(),sa(),ca(),da(),la(),pa(),ma(),ba(),ha(),fa(),ua(),ga(),ya(),Sa(),wa(),_a(),Ea(),Ia(),va(),Ga(),Ca(),Ba(),Aa(),ka(),La(),Ra(),Na(),Pa(),Oa(),xa(),Va(),Ma(),Fa(),Ka(),Ua(),ja(),Ya(),qa(),Xa(),za(),Ja(),Za(),tn(),an(),nn(),rn(),on(),sn()}catch(e){console.error(`${r} ${b(e)}`)}}h(cn,"initDevTools");Lt(Qe);var dn=Ze;async function ln(){let r=`[${ln.name}]`;try{dn&&console.log(`${r} starting... (I: 3d893846d02c4ff49181f9b8e586eb74)`),console.time(r),document.addEventListener("DOMContentLoaded",async()=>{try{console.timeLog(r,"DOMContentLoaded fired"),await $t(Qe),console.timeLog(r,"initIbGibStorage complete"),await Rt("./bootstrap.mjs"),console.timeLog(r,"dynamicallyLoadBootstrapScript complete"),cn(),console.timeLog(r,"initDevTools complete"),console.timeEnd(r)}catch(e){throw console.error(`${r} ${b(e)}`),e}})}catch(e){console.timeEnd(r);debugger;throw console.error(`${r} ${b(e)}`),e}finally{dn&&console.log(`${r} complete.`)}}h(ln,"spinOffStartup");ln();