@davmash/bygone 0.8.16 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/cli/present.js +50 -9
- package/cli/tourFile.js +9 -0
- package/cli/tourHistory.js +354 -12
- package/docs/change-tour-format.md +168 -16
- package/docs/generating-change-tours.md +70 -17
- package/docs/present.md +126 -5
- package/docs/product-surface.md +56 -4
- package/examples/bygone-history.bygone +52 -10
- package/examples/navigation-lab.bygone.yaml +420 -0
- package/media/webview.css +1 -1
- package/media/webview.js +548 -180
- package/out/changeTour.js +423 -44
- package/out/standalone-main.js +4984 -1141
- package/out/tourCoverage.js +432 -49
- package/package.json +2 -2
- package/schemas/change-tour-source.schema.json +166 -2
- package/skills/pr-tour-guide/SKILL.md +104 -13
- package/standalone/index.html +1 -1
- package/web/index.html +107 -80
- package/web/presenter.css +558 -231
- package/web/web-host.js +374 -5
package/web/web-host.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";(()=>{function
|
|
2
|
-
`));var
|
|
1
|
+
"use strict";(()=>{function xe(){}xe.prototype={diff:function(r,i){var a,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},c=s.callback;typeof s=="function"&&(c=s,s={}),this.options=s;var f=this;function p(L){return c?(setTimeout(function(){c(void 0,L)},0),!0):L}r=this.castInput(r),i=this.castInput(i),r=this.removeEmpty(this.tokenize(r)),i=this.removeEmpty(this.tokenize(i));var t=i.length,v=r.length,g=1,m=t+v;s.maxEditLength&&(m=Math.min(m,s.maxEditLength));var w=(a=s.timeout)!==null&&a!==void 0?a:1/0,I=Date.now()+w,$=[{oldPos:-1,lastComponent:void 0}],x=this.extractCommon($[0],i,r,0);if($[0].oldPos+1>=v&&x+1>=t)return p([{value:this.join(i),count:i.length}]);var S=-1/0,E=1/0;function N(){for(var L=Math.max(S,-g);L<=Math.min(E,g);L+=2){var H=void 0,G=$[L-1],V=$[L+1];G&&($[L-1]=void 0);var J=!1;if(V){var me=V.oldPos-L;J=V&&0<=me&&me<t}var Y=G&&G.oldPos+1<v;if(!J&&!Y){$[L]=void 0;continue}if(!Y||J&&G.oldPos+1<V.oldPos?H=f.addToPath(V,!0,void 0,0):H=f.addToPath(G,void 0,!0,1),x=f.extractCommon(H,i,r,L),H.oldPos+1>=v&&x+1>=t)return p(Fo(f,H.lastComponent,i,r,f.useLongestToken));$[L]=H,H.oldPos+1>=v&&(E=Math.min(E,L-1)),x+1>=t&&(S=Math.max(S,L+1))}g++}if(c)(function L(){setTimeout(function(){if(g>m||Date.now()>I)return c();N()||L()},0)})();else for(;g<=m&&Date.now()<=I;){var A=N();if(A)return A}},addToPath:function(r,i,a,s){var c=r.lastComponent;return c&&c.added===i&&c.removed===a?{oldPos:r.oldPos+s,lastComponent:{count:c.count+1,added:i,removed:a,previousComponent:c.previousComponent}}:{oldPos:r.oldPos+s,lastComponent:{count:1,added:i,removed:a,previousComponent:c}}},extractCommon:function(r,i,a,s){for(var c=i.length,f=a.length,p=r.oldPos,t=p-s,v=0;t+1<c&&p+1<f&&this.equals(i[t+1],a[p+1]);)t++,p++,v++;return v&&(r.lastComponent={count:v,previousComponent:r.lastComponent}),r.oldPos=p,t},equals:function(r,i){return this.options.comparator?this.options.comparator(r,i):r===i||this.options.ignoreCase&&r.toLowerCase()===i.toLowerCase()},removeEmpty:function(r){for(var i=[],a=0;a<r.length;a++)r[a]&&i.push(r[a]);return i},castInput:function(r){return r},tokenize:function(r){return r.split("")},join:function(r){return r.join("")}};function Fo(e,r,i,a,s){for(var c=[],f;r;)c.push(r),f=r.previousComponent,delete r.previousComponent,r=f;c.reverse();for(var p=0,t=c.length,v=0,g=0;p<t;p++){var m=c[p];if(m.removed){if(m.value=e.join(a.slice(g,g+m.count)),g+=m.count,p&&c[p-1].added){var I=c[p-1];c[p-1]=c[p],c[p]=I}}else{if(!m.added&&s){var w=i.slice(v,v+m.count);w=w.map(function(x,S){var E=a[g+S];return E.length>x.length?E:x}),m.value=e.join(w)}else m.value=e.join(i.slice(v,v+m.count));v+=m.count,m.added||(g+=m.count)}}var $=c[t-1];return t>1&&typeof $.value=="string"&&($.added||$.removed)&&e.equals("",$.value)&&(c[t-2].value+=$.value,c.pop()),c}var Bo=new xe;function Xn(e,r,i){return Bo.diff(e,r,i)}var Kn=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Vn=/\S/,dn=new xe;dn.equals=function(e,r){return this.options.ignoreCase&&(e=e.toLowerCase(),r=r.toLowerCase()),e===r||this.options.ignoreWhitespace&&!Vn.test(e)&&!Vn.test(r)};dn.tokenize=function(e){for(var r=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),i=0;i<r.length-1;i++)!r[i+1]&&r[i+2]&&Kn.test(r[i])&&Kn.test(r[i+2])&&(r[i]+=r[i+2],r.splice(i+1,2),i--);return r};function Jn(e,r,i){return dn.diff(e,r,i)}var Zn=new xe;Zn.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
2
|
+
`));var r=[],i=e.split(/(\n|\r\n)/);i[i.length-1]||i.pop();for(var a=0;a<i.length;a++){var s=i[a];a%2&&!this.options.newlineIsToken?r[r.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),r.push(s))}return r};var Uo=new xe;Uo.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var _o=new xe;_o.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function Et(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Et=function(r){return typeof r}:Et=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Et(e)}var Ho=Object.prototype.toString,ct=new xe;ct.useLongestToken=!0;ct.tokenize=Zn.tokenize;ct.castInput=function(e){var r=this.options,i=r.undefinedReplacement,a=r.stringifyReplacer,s=a===void 0?function(c,f){return typeof f>"u"?i:f}:a;return typeof e=="string"?e:JSON.stringify(cn(e,null,null,s),s," ")};ct.equals=function(e,r){return xe.prototype.equals.call(ct,e.replace(/,([\r\n])/g,"$1"),r.replace(/,([\r\n])/g,"$1"))};function cn(e,r,i,a,s){r=r||[],i=i||[],a&&(e=a(s,e));var c;for(c=0;c<r.length;c+=1)if(r[c]===e)return i[c];var f;if(Ho.call(e)==="[object Array]"){for(r.push(e),f=new Array(e.length),i.push(f),c=0;c<e.length;c+=1)f[c]=cn(e[c],r,i,a,s);return r.pop(),i.pop(),f}if(e&&e.toJSON&&(e=e.toJSON()),Et(e)==="object"&&e!==null){r.push(e),f={},i.push(f);var p=[],t;for(t in e)e.hasOwnProperty(t)&&p.push(t);for(p.sort(),c=0;c<p.length;c+=1)t=p[c],f[t]=cn(e[t],r,i,a,t);r.pop(),i.pop()}else f=e;return f}var Tt=new xe;Tt.tokenize=function(e){return e.slice()};Tt.join=Tt.removeEmpty=function(e){return e};function Yn(e,r,i){return Tt.diff(e,r,i)}var qo=500,Wo=100,Qn=yr("BYGONE_MAX_INLINE_HIGHLIGHT_LINE_LENGTH",qo),jo=yr("BYGONE_DIFF_TIMEOUT_MS",Wo);function ae(e,r,i={}){let a=er(e),s=er(r);if(e===r)return Ko(a);let c=Go(a,s),f=Yn(c.left,c.right,{timeout:i.timeoutMs??jo});if(!f)return Vo(a,s);let p=f.map(x=>({...x,value:x.value.map(S=>c.lines[S])})),t=[],v=[],g=[],m=[],w=1,I=1;for(let x=0;x<p.length;x++){let S=p[x],E=S.removed?S.value:[],N=S.added?S.value:[];if(!S.added&&!S.removed){for(let A of S.value)v.push(he("context",A,w)),g.push(he("context",A,I)),t.push(Le(fe("context",A,w++),fe("context",A,I++)));continue}if(S.removed&&x+1<p.length&&p[x+1].added){let A=p[x+1],L=Xo(E,A.value,w,I,t,v,g,m);w=L.left,I=L.right,x++;continue}if(S.removed){let A=v.length,L=g.length;for(let H of E)v.push(he("removed",H,w)),t.push(Le(fe("removed",H,w++),He()));m.push(Rt("delete",A,v.length,L,g.length));continue}if(S.added){let A=v.length,L=g.length;for(let H of N)g.push(he("added",H,I)),t.push(Le(He(),fe("added",H,I++)));m.push(Rt("insert",A,v.length,L,g.length))}}let $=t.some(x=>x.left.kind!=="context"||x.right.kind!=="context");return{rows:t,leftLines:v,rightLines:g,blocks:m,hasChanges:$,quality:"exact"}}function Go(e,r){let i=new Map,a=[],s=c=>{let f=i.get(c);if(f!==void 0)return f;let p=a.length;return i.set(c,p),a.push(c),p};return{left:e.map(s),right:r.map(s),lines:a}}function Ko(e){return{rows:e.map((r,i)=>Le(fe("context",r,i+1),fe("context",r,i+1))),leftLines:e.map((r,i)=>he("context",r,i+1)),rightLines:e.map((r,i)=>he("context",r,i+1)),blocks:[],hasChanges:!1,quality:"exact"}}function Vo(e,r){let i=e.map((f,p)=>he("removed",f,p+1)),a=r.map((f,p)=>he("added",f,p+1)),s=[...e.map((f,p)=>Le(fe("removed",f,p+1),He())),...r.map((f,p)=>Le(He(),fe("added",f,p+1)))],c="replace";return e.length===0?c="insert":r.length===0&&(c="delete"),{rows:s,leftLines:i,rightLines:a,blocks:s.length===0?[]:[Rt(c,0,e.length,0,r.length)],hasChanges:s.length>0,quality:"fallback"}}function er(e){if(e.length===0)return[];let r=e.replace(/\r\n/g,`
|
|
3
3
|
`).split(`
|
|
4
|
-
`);return t[t.length-1]===""&&t.pop(),t}function ir(e,t,n,i,o,a,l,d){let p=Yt(e,t),m=p.filter(k=>k.left!==void 0&&k.right!==void 0&&nt(k.left,k.right)).length,f=sr(e,t,m),s=p.flatMap(k=>k.left===void 0||k.right===void 0||nt(k.left,k.right)?[k]:[{left:k.left},{right:k.right}]),x=n,T=i,A,I=a.length,y=l.length,E=()=>{A&&d.push(Oe(A,I,a.length,y,l.length))};for(let{left:k,right:N}of s){let L=f||k!==void 0&&N!==void 0?"replace":k!==void 0?"delete":"insert";A!==L&&(E(),A=L,I=a.length,y=l.length);let F,U;k!==void 0&&(F=X("removed",k,x),a.push(F)),N!==void 0&&(U=X("added",N,T),l.push(U)),F&&U?Cr(F,U):f&&(F&&Vt(F),U&&Vt(U)),o.push(se(k===void 0?ue():Z("removed",k,x++),N===void 0?ue():Z("added",N,T++)))}return E(),{left:x,right:T}}function nt(e,t){if(De(e,t).eligible)return!0;let i=pe(e);if(i&&i===pe(t))return!0;let o=new Set(we(Y(e)).filter(Dt));return we(Y(t)).some(a=>o.has(a)&&Dt(a))}var or=new Set(["and","are","for","from","into","that","the","this","to","with"]);function Dt(e){return e.length>=3&&/^[\p{L}\p{N}_$]+$/u.test(e)&&!or.has(e)}function sr(e,t,n){if(n===0)return!1;let i=Math.max(e.length,t.length);if(i<=2||n*2>=i)return!0;let o=[...e,...t].map(ar);return o[0]!==null&&o.every(a=>a===o[0])}function ar(e){let t=e.trimStart();return/^[-*+]\s+/.test(t)?"bullet":/^\d+[.)]\s+/.test(t)?"ordered":/^>\s+/.test(t)?"quote":null}var Kt=1e4,Pt=2e3,cr=.52,ur=.35,Zt=.38,lr=.33,Xt=.86,_e=.08,Re=.05,Me=-.12,Ut=5e3,dr=2e3,fr=5e7,Bt=4,hr=8,tt=4;function Yt(e,t){if(e.length===0)return t.map(f=>({right:f}));if(t.length===0)return e.map(f=>({left:f}));let n=e.reduce((f,s)=>f+s.length,0),i=t.reduce((f,s)=>f+s.length,0);if(n*i>fr)return[...e.map(f=>({left:f})),...t.map(f=>({right:f}))];if(e.length===1&&t.length===1){let f=De(e[0],t[0]);return(f.eligible||f.score>=ur)&&nt(e[0],t[0])&&it(e[0],t[0])&&be(Y(e[0]))&&be(Y(t[0]))?[{left:e[0],right:t[0]}]:[{left:e[0]},{right:t[0]}]}if(e.length*t.length>Kt)return wr(e,t);let o=gr(e,t),a=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(Number.NEGATIVE_INFINITY)),l=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(null));a[0][0]=0;for(let f=1;f<=e.length;f++)a[f][0]=a[f-1][0]+Me,l[f][0]="left";for(let f=1;f<=t.length;f++)a[0][f]=a[0][f-1]+Me,l[0][f]="right";for(let f=1;f<=e.length;f++)for(let s=1;s<=t.length;s++){let x=o[f-1][s-1],A=[{move:"left",score:a[f-1][s]+Me},{move:"right",score:a[f][s-1]+Me},{move:"match",score:x===null?Number.NEGATIVE_INFINITY:a[f-1][s-1]+x}].reduce((I,y)=>y.score>I.score?y:I);a[f][s]=A.score,l[f][s]=A.move}let d=[],p=e.length,m=t.length;for(;p>0||m>0;){let f=l[p][m];f==="match"?d.push({left:e[--p],right:t[--m]}):f==="left"?d.push({left:e[--p]}):d.push({right:t[--m]})}return d.reverse()}function De(e,t){let n=Y(e),i=Y(t),o=be(n),a=be(i);if(!o||!a||n.length>Pt||i.length>Pt)return{score:0,eligible:!1,characterSimilarity:0,tokenSimilarity:0,lengthSimilarity:0};if(n===i)return{score:1,eligible:!0,characterSimilarity:1,tokenSimilarity:1,lengthSimilarity:1};let l=we(n),d=we(i),p=Tr(n,i),m=Er(l,d),f=Math.min(n.length,i.length)/Math.max(n.length,i.length),s=kr(l,d),x=p*.52+m*.32+f*.1+s*.06,T=p>=.52||m>=.45||p>=.48&&m>=.28;return{score:x,eligible:T&&x>=cr,characterSimilarity:p,tokenSimilarity:m,lengthSimilarity:f}}function gr(e,t){let n=e.map(I=>t.map(y=>De(I,y))),i=Jt(e,t),o=n.map(I=>rt(I)),a=t.map((I,y)=>rt(n.map(E=>E[y]))),l=n.map((I,y)=>I.map((E,k)=>{if(i.has(`${y}:${k}`))return Math.max(E.score,1);if(!E.eligible)return null;let N=o[y],L=a[k],F=E.score===N.best&&E.score===L.best,U=E.score>=Xt?_e/2:_e,J=N.best-N.second>=U,ne=L.best-L.second>=U;return F&&J&&ne?E.score:null}));if(Math.max(e.length,t.length)>hr||Math.abs(e.length-t.length)>tt)return l;let d=(I,y,E)=>I.score>=Zt&&it(e[y],t[E])&&Math.abs(y-E)<=tt,p=n.map((I,y)=>Fe(I,(E,k)=>d(E,y,k))),m=t.map((I,y)=>Fe(n.map(E=>E[y]),(E,k)=>d(E,k,y))),f=(I,y,E)=>I.score>=lr&&it(e[y],t[E])&&Math.abs(y-E)<=tt,s=n.map((I,y)=>Fe(I,(E,k)=>f(E,y,k))),x=t.map((I,y)=>Fe(n.map(E=>E[y]),(E,k)=>f(E,k,y))),T=(I,y)=>{let E=n[I][y];if(!d(E,I,y))return!1;let k=p[I],N=m[y];return E.score===k.best&&E.score===N.best&&k.best-k.second>=Re&&N.best-N.second>=Re},A=(I,y)=>{let E=n[I][y];if(!f(E,I,y))return!1;let k=s[I],N=x[y];return E.score===k.best&&E.score===N.best&&k.best-k.second>=Re&&N.best-N.second>=Re};return l.map((I,y)=>I.map((E,k)=>{if(E!==null)return E;let N=T(y,k)&&(mr(l,y,k)||pr(n,y,k,T)),L=br(n,y,k,(F,U)=>f(n[F][U],F,U),A);return!N&&!L?null:n[y][k].score}))}function mr(e,t,n){return t>0&&n>0&&e[t-1][n-1]!==null||t+1<e.length&&n+1<e[t+1].length&&e[t+1][n+1]!==null}function pr(e,t,n,i){return t>0&&n>0&&i(t-1,n-1)||t+1<e.length&&n+1<e[t+1].length&&i(t+1,n+1)}function br(e,t,n,i,o){let a=t,l=n;for(;a>0&&l>0&&i(a-1,l-1);)a--,l--;let d=t,p=n,m=e[t][n].score,f=1;for(;d+1<e.length&&p+1<e[d+1].length&&i(d+1,p+1);)d++,p++,m+=e[d][p].score,f++;for(let s=t-1,x=n-1;s>=a&&x>=l;s--,x--)m+=e[s][x].score,f++;return f>=3&&m/f>=Zt&&o(a,l)&&o(d,p)}function Fe(e,t){let n=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return e.forEach((o,a)=>{t(o,a)&&(o.score>n?(i=n,n=o.score):o.score>i&&(i=o.score))}),{best:n,second:i}}function rt(e){let t=Number.NEGATIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let i of e)i.eligible&&(i.score>t?(n=t,t=i.score):i.score>n&&(n=i.score));return{best:t,second:n}}function wr(e,t){let n=yr(e,t),i=[],o=0,a=0;for(let l of n)qt(i,e.slice(o,l.leftIndex),t.slice(a,l.rightIndex)),i.push({left:e[l.leftIndex],right:t[l.rightIndex]}),o=l.leftIndex+1,a=l.rightIndex+1;return qt(i,e.slice(o),t.slice(a)),i}function yr(e,t){let n=xr(e,t);if(n===null)return[];let i=Jt(e,t),o=n.map(({leftIndex:m,rightIndex:f,exact:s})=>({leftIndex:m,rightIndex:f,exact:s,structural:i.has(`${m}:${f}`),match:De(e[m],t[f])})).filter(m=>m.exact||m.structural||m.match.eligible),a=Wt(o,"leftIndex"),l=Wt(o,"rightIndex"),d=o.filter(m=>{if(m.exact||m.structural)return!0;let f=a.get(m.leftIndex),s=l.get(m.rightIndex);if(!f||!s||m.match.score!==f.best||m.match.score!==s.best)return!1;let x=m.match.score>=Xt?_e/2:_e;return f.best-f.second>=x&&s.best-s.second>=x}),p=Ir(d,t.length);return p.length<=dr?p:[]}function xr(e,t){let n=Ht(e,Y),i=Ht(t,Y),o=new Map;for(let[d,p]of n){let m=i.get(d);if(!be(d)||p.length!==1||m?.length!==1)continue;let f=p[0],s=m[0];if(o.set(`${f}:${s}`,{leftIndex:f,rightIndex:s,exact:!0}),o.size>Ut)return null}let a=zt(e),l=zt(t);for(let[d,p]of a){let m=l.get(d);if(!(!m||p.length>Bt||m.length>Bt))for(let f of p)for(let s of m){let x=`${f}:${s}`;if(!o.has(x)&&(o.set(x,{leftIndex:f,rightIndex:s,exact:!1}),o.size>Ut))return null}}return[...o.values()]}function Ht(e,t){let n=new Map;return e.forEach((i,o)=>{let a=t(i),l=n.get(a)??[];l.push(o),n.set(a,l)}),n}function zt(e){let t=new Map;return e.forEach((n,i)=>{let o=new Set(we(Y(n)).filter(Sr));for(let a of o){let l=t.get(a)??[];l.push(i),t.set(a,l)}}),t}function Sr(e){return e.length>=2&&/[\p{L}\p{N}_$]/u.test(e)}function Wt(e,t){let n=new Map;for(let i of e){let o=n.get(i[t])??[];o.push(i.match),n.set(i[t],o)}return new Map([...n].map(([i,o])=>[i,rt(o)]))}function Ir(e,t){let n=[...e].sort((m,f)=>m.leftIndex-f.leftIndex||m.rightIndex-f.rightIndex),i=new Array(t+2).fill(0),o=new Array(t+2).fill(-1),a=new Array(n.length).fill(0),l=new Array(n.length).fill(-1);for(let m=0;m<n.length;){let f=m+1;for(;f<n.length&&n[f].leftIndex===n[m].leftIndex;)f++;for(let s=m;s<f;s++){let x=Gt(i,o,n[s].rightIndex),T=n[s].exact||n[s].structural?.5:0;a[s]=x.score+n[s].match.score+T,l[s]=x.candidateIndex}for(let s=m;s<f;s++)vr(i,o,n[s].rightIndex+1,a[s],s);m=f}let d=Gt(i,o,t+1),p=[];for(let m=d.candidateIndex;m>=0;m=l[m])p.push({leftIndex:n[m].leftIndex,rightIndex:n[m].rightIndex});return p.reverse()}function Gt(e,t,n){let i=0,o=-1;for(let a=n;a>0;a-=a&-a)e[a]>i&&(i=e[a],o=t[a]);return{score:i,candidateIndex:o}}function vr(e,t,n,i,o){for(let a=n;a<e.length;a+=a&-a)i>e[a]&&(e[a]=i,t[a]=o)}function qt(e,t,n){if(t.length*n.length<=Kt){e.push(...Yt(t,n));return}e.push(...t.map(i=>({left:i}))),e.push(...n.map(i=>({right:i})))}function Y(e){return e.trim().replace(/\s+/g," ")}function Jt(e,t){let n=jt(e),i=jt(t),o=new Set;for(let[a,l]of n){let d=i.get(a);l.length===1&&d?.length===1&&o.add(`${l[0]}:${d[0]}`)}return o}function jt(e){let t=new Map;return e.forEach((n,i)=>{let o=pe(n);if(!o)return;let a=t.get(o)??[];a.push(i),t.set(o,a)}),t}function it(e,t){let n=pe(e),i=pe(t);return!n||!i?n===i:n.split(":",1)[0]===i.split(":",1)[0]}function pe(e){let t=Y(e),n=[["function",/^(?:(?:export|default)\s+)*(?:async\s+)?function\s*\*?\s*([\p{L}_$][\p{L}\p{N}_$]*)\s*\(/u],["function",/^(?:async\s+)?def\s+([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["function",/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([\p{L}_][\p{L}\p{N}_]*)\s*(?:<[^>]*>)?\s*\(/u],["function",/^func\s+(?:\([^)]*\)\s*)?([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["class",/^(?:(?:export|default|abstract|public)\s+)*class\s+([\p{L}_$][\p{L}\p{N}_$]*)\b/u]];for(let[i,o]of n){let a=t.match(o);if(a)return`${i}:${a[1]}`}return null}function be(e){return e.length<3?!1:/[\p{L}\p{N}_$]/u.test(e)&&!/^[\s()[\]{};,.:+\-*/=>|&!?'"`]+$/.test(e)}function we(e){return e.toLowerCase().match(/[\p{L}_$][\p{L}\p{N}_$]*|\p{N}+(?:\.\p{N}+)?|[^\s\p{L}\p{N}_$]/gu)??[]}function Er(e,t){if(e.length+t.length===0)return 1;let n=new Map;e.forEach(o=>n.set(o,(n.get(o)??0)+1));let i=0;for(let o of t){let a=n.get(o)??0;a>0&&(i++,n.set(o,a-1))}return 2*i/(e.length+t.length)}function kr(e,t){if(e.length===0||t.length===0)return 0;let n=e[0]===t[0]?.5:0,i=e[e.length-1]===t[t.length-1]?.5:0;return n+i}function Tr(e,t){let n=e.length+t.length;return n===0?1:2*At(e,t).filter(o=>!o.added&&!o.removed).reduce((o,a)=>o+a.value.length,0)/n}function Cr(e,t){if(e.content.length>_t||t.content.length>_t)return;let{leftSegments:n,rightSegments:i,hasInlineChanges:o}=$r(e.content,t.content);o&&(e.segments=n,t.segments=i)}function Vt(e){/[^\s]/.test(e.content)&&(e.segments=[{kind:e.kind,text:e.content,emphasis:!0}])}function $r(e,t){let n=Rt(e,t),i=[],o=[],a=!1;for(let l of n){let d=l.value;if(!l.added&&!l.removed){let m={kind:"context",text:d,emphasis:!1};i.push(m),o.push(m);continue}let p=/[^\s]/.test(d);a=a||p,l.removed&&i.push({kind:"removed",text:d,emphasis:p}),l.added&&o.push({kind:"added",text:d,emphasis:p})}return{leftSegments:i,rightSegments:o,hasInlineChanges:a}}function ue(){return{kind:"placeholder",content:"",lineNumber:null}}function Z(e,t,n){return{kind:e,content:t,lineNumber:n}}function X(e,t,n){return{kind:e,content:t,lineNumber:n}}function se(e,t){return{left:e,right:t}}function Oe(e,t,n,i,o){return{kind:e,leftStart:t,leftEnd:n,rightStart:i,rightEnd:o}}function Qt(e,t){let n=typeof process<"u"?process.env?.[e]:void 0,i=Number.parseInt(n??"",10);return Number.isFinite(i)&&i>0?i:t}function en(){return{leftFileName:"test-file-1.js",rightFileName:"test-file-2.js",leftContent:`// Test File 1 - Example JavaScript Code
|
|
4
|
+
`);return r[r.length-1]===""&&r.pop(),r}function Xo(e,r,i,a,s,c,f,p){let t=mr(e,r),v=t.filter(N=>N.left!==void 0&&N.right!==void 0&&un(N.left,N.right)).length,g=Zo(e,r,v),m=t.flatMap(N=>N.left===void 0||N.right===void 0||un(N.left,N.right)?[N]:[{left:N.left},{right:N.right}]),w=i,I=a,$,x=c.length,S=f.length,E=()=>{$&&p.push(Rt($,x,c.length,S,f.length))};for(let{left:N,right:A}of m){let L=g||N!==void 0&&A!==void 0?"replace":N!==void 0?"delete":"insert";$!==L&&(E(),$=L,x=c.length,S=f.length);let H,G;N!==void 0&&(H=he("removed",N,w),c.push(H)),A!==void 0&&(G=he("added",A,I),f.push(G)),H&&G?wi(H,G):g&&(H&&ur(H),G&&ur(G)),s.push(Le(N===void 0?He():fe("removed",N,w++),A===void 0?He():fe("added",A,I++)))}return E(),{left:w,right:I}}function un(e,r){if(Pt(e,r).eligible)return!0;let a=dt(e);if(a&&a===dt(r))return!0;let s=new Set(ut(pe(e)).filter(tr));return ut(pe(r)).some(c=>s.has(c)&&tr(c))}var Jo=new Set(["and","are","for","from","into","that","the","this","to","with"]);function tr(e){return e.length>=3&&/^[\p{L}\p{N}_$]+$/u.test(e)&&!Jo.has(e)}function Zo(e,r,i){if(i===0)return!1;let a=Math.max(e.length,r.length);if(a<=2||i*2>=a)return!0;let s=[...e,...r].map(Yo);return s[0]!==null&&s.every(c=>c===s[0])}function Yo(e){let r=e.trimStart();return/^[-*+]\s+/.test(r)?"bullet":/^\d+[.)]\s+/.test(r)?"ordered":/^>\s+/.test(r)?"quote":null}var fr=1e4,nr=2e3,Qo=.52,ei=.35,hr=.38,ti=.33,pr=.86,Lt=.08,$t=.05,Nt=-.12,rr=5e3,ni=2e3,ri=5e7,or=4,oi=8,ln=4;function mr(e,r){if(e.length===0)return r.map(g=>({right:g}));if(r.length===0)return e.map(g=>({left:g}));let i=e.reduce((g,m)=>g+m.length,0),a=r.reduce((g,m)=>g+m.length,0);if(i*a>ri)return[...e.map(g=>({left:g})),...r.map(g=>({right:g}))];if(e.length===1&&r.length===1){let g=Pt(e[0],r[0]);return(g.eligible||g.score>=ei)&&un(e[0],r[0])&&hn(e[0],r[0])&<(pe(e[0]))&<(pe(r[0]))?[{left:e[0],right:r[0]}]:[{left:e[0]},{right:r[0]}]}if(e.length*r.length>fr)return di(e,r);let s=ii(e,r),c=Array.from({length:e.length+1},()=>new Array(r.length+1).fill(Number.NEGATIVE_INFINITY)),f=Array.from({length:e.length+1},()=>new Array(r.length+1).fill(null));c[0][0]=0;for(let g=1;g<=e.length;g++)c[g][0]=c[g-1][0]+Nt,f[g][0]="left";for(let g=1;g<=r.length;g++)c[0][g]=c[0][g-1]+Nt,f[0][g]="right";for(let g=1;g<=e.length;g++)for(let m=1;m<=r.length;m++){let w=s[g-1][m-1],$=[{move:"left",score:c[g-1][m]+Nt},{move:"right",score:c[g][m-1]+Nt},{move:"match",score:w===null?Number.NEGATIVE_INFINITY:c[g-1][m-1]+w}].reduce((x,S)=>S.score>x.score?S:x);c[g][m]=$.score,f[g][m]=$.move}let p=[],t=e.length,v=r.length;for(;t>0||v>0;){let g=f[t][v];g==="match"?p.push({left:e[--t],right:r[--v]}):g==="left"?p.push({left:e[--t]}):p.push({right:r[--v]})}return p.reverse()}function Pt(e,r){let i=pe(e),a=pe(r),s=lt(i),c=lt(a);if(!s||!c||i.length>nr||a.length>nr)return{score:0,eligible:!1,characterSimilarity:0,tokenSimilarity:0,lengthSimilarity:0};if(i===a)return{score:1,eligible:!0,characterSimilarity:1,tokenSimilarity:1,lengthSimilarity:1};let f=ut(i),p=ut(a),t=yi(i,a),v=mi(f,p),g=Math.min(i.length,a.length)/Math.max(i.length,a.length),m=gi(f,p),w=t*.52+v*.32+g*.1+m*.06,I=t>=.52||v>=.45||t>=.48&&v>=.28;return{score:w,eligible:I&&w>=Qo,characterSimilarity:t,tokenSimilarity:v,lengthSimilarity:g}}function ii(e,r){let i=e.map(x=>r.map(S=>Pt(x,S))),a=gr(e,r),s=i.map(x=>fn(x)),c=r.map((x,S)=>fn(i.map(E=>E[S]))),f=i.map((x,S)=>x.map((E,N)=>{if(a.has(`${S}:${N}`))return Math.max(E.score,1);if(!E.eligible)return null;let A=s[S],L=c[N],H=E.score===A.best&&E.score===L.best,G=E.score>=pr?Lt/2:Lt,V=A.best-A.second>=G,J=L.best-L.second>=G;return H&&V&&J?E.score:null}));if(Math.max(e.length,r.length)>oi||Math.abs(e.length-r.length)>ln)return f;let p=(x,S,E)=>x.score>=hr&&hn(e[S],r[E])&&Math.abs(S-E)<=ln,t=i.map((x,S)=>At(x,(E,N)=>p(E,S,N))),v=r.map((x,S)=>At(i.map(E=>E[S]),(E,N)=>p(E,N,S))),g=(x,S,E)=>x.score>=ti&&hn(e[S],r[E])&&Math.abs(S-E)<=ln,m=i.map((x,S)=>At(x,(E,N)=>g(E,S,N))),w=r.map((x,S)=>At(i.map(E=>E[S]),(E,N)=>g(E,N,S))),I=(x,S)=>{let E=i[x][S];if(!p(E,x,S))return!1;let N=t[x],A=v[S];return E.score===N.best&&E.score===A.best&&N.best-N.second>=$t&&A.best-A.second>=$t},$=(x,S)=>{let E=i[x][S];if(!g(E,x,S))return!1;let N=m[x],A=w[S];return E.score===N.best&&E.score===A.best&&N.best-N.second>=$t&&A.best-A.second>=$t};return f.map((x,S)=>x.map((E,N)=>{if(E!==null)return E;let A=I(S,N)&&(si(f,S,N)||ai(i,S,N,I)),L=ci(i,S,N,(H,G)=>g(i[H][G],H,G),$);return!A&&!L?null:i[S][N].score}))}function si(e,r,i){return r>0&&i>0&&e[r-1][i-1]!==null||r+1<e.length&&i+1<e[r+1].length&&e[r+1][i+1]!==null}function ai(e,r,i,a){return r>0&&i>0&&a(r-1,i-1)||r+1<e.length&&i+1<e[r+1].length&&a(r+1,i+1)}function ci(e,r,i,a,s){let c=r,f=i;for(;c>0&&f>0&&a(c-1,f-1);)c--,f--;let p=r,t=i,v=e[r][i].score,g=1;for(;p+1<e.length&&t+1<e[p+1].length&&a(p+1,t+1);)p++,t++,v+=e[p][t].score,g++;for(let m=r-1,w=i-1;m>=c&&w>=f;m--,w--)v+=e[m][w].score,g++;return g>=3&&v/g>=hr&&s(c,f)&&s(p,t)}function At(e,r){let i=Number.NEGATIVE_INFINITY,a=Number.NEGATIVE_INFINITY;return e.forEach((s,c)=>{r(s,c)&&(s.score>i?(a=i,i=s.score):s.score>a&&(a=s.score))}),{best:i,second:a}}function fn(e){let r=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let a of e)a.eligible&&(a.score>r?(i=r,r=a.score):a.score>i&&(i=a.score));return{best:r,second:i}}function di(e,r){let i=li(e,r),a=[],s=0,c=0;for(let f of i)dr(a,e.slice(s,f.leftIndex),r.slice(c,f.rightIndex)),a.push({left:e[f.leftIndex],right:r[f.rightIndex]}),s=f.leftIndex+1,c=f.rightIndex+1;return dr(a,e.slice(s),r.slice(c)),a}function li(e,r){let i=ui(e,r);if(i===null)return[];let a=gr(e,r),s=i.map(({leftIndex:v,rightIndex:g,exact:m})=>({leftIndex:v,rightIndex:g,exact:m,structural:a.has(`${v}:${g}`),match:Pt(e[v],r[g])})).filter(v=>v.exact||v.structural||v.match.eligible),c=ar(s,"leftIndex"),f=ar(s,"rightIndex"),p=s.filter(v=>{if(v.exact||v.structural)return!0;let g=c.get(v.leftIndex),m=f.get(v.rightIndex);if(!g||!m||v.match.score!==g.best||v.match.score!==m.best)return!1;let w=v.match.score>=pr?Lt/2:Lt;return g.best-g.second>=w&&m.best-m.second>=w}),t=hi(p,r.length);return t.length<=ni?t:[]}function ui(e,r){let i=ir(e,pe),a=ir(r,pe),s=new Map;for(let[p,t]of i){let v=a.get(p);if(!lt(p)||t.length!==1||v?.length!==1)continue;let g=t[0],m=v[0];if(s.set(`${g}:${m}`,{leftIndex:g,rightIndex:m,exact:!0}),s.size>rr)return null}let c=sr(e),f=sr(r);for(let[p,t]of c){let v=f.get(p);if(!(!v||t.length>or||v.length>or))for(let g of t)for(let m of v){let w=`${g}:${m}`;if(!s.has(w)&&(s.set(w,{leftIndex:g,rightIndex:m,exact:!1}),s.size>rr))return null}}return[...s.values()]}function ir(e,r){let i=new Map;return e.forEach((a,s)=>{let c=r(a),f=i.get(c)??[];f.push(s),i.set(c,f)}),i}function sr(e){let r=new Map;return e.forEach((i,a)=>{let s=new Set(ut(pe(i)).filter(fi));for(let c of s){let f=r.get(c)??[];f.push(a),r.set(c,f)}}),r}function fi(e){return e.length>=2&&/[\p{L}\p{N}_$]/u.test(e)}function ar(e,r){let i=new Map;for(let a of e){let s=i.get(a[r])??[];s.push(a.match),i.set(a[r],s)}return new Map([...i].map(([a,s])=>[a,fn(s)]))}function hi(e,r){let i=[...e].sort((v,g)=>v.leftIndex-g.leftIndex||v.rightIndex-g.rightIndex),a=new Array(r+2).fill(0),s=new Array(r+2).fill(-1),c=new Array(i.length).fill(0),f=new Array(i.length).fill(-1);for(let v=0;v<i.length;){let g=v+1;for(;g<i.length&&i[g].leftIndex===i[v].leftIndex;)g++;for(let m=v;m<g;m++){let w=cr(a,s,i[m].rightIndex),I=i[m].exact||i[m].structural?.5:0;c[m]=w.score+i[m].match.score+I,f[m]=w.candidateIndex}for(let m=v;m<g;m++)pi(a,s,i[m].rightIndex+1,c[m],m);v=g}let p=cr(a,s,r+1),t=[];for(let v=p.candidateIndex;v>=0;v=f[v])t.push({leftIndex:i[v].leftIndex,rightIndex:i[v].rightIndex});return t.reverse()}function cr(e,r,i){let a=0,s=-1;for(let c=i;c>0;c-=c&-c)e[c]>a&&(a=e[c],s=r[c]);return{score:a,candidateIndex:s}}function pi(e,r,i,a,s){for(let c=i;c<e.length;c+=c&-c)a>e[c]&&(e[c]=a,r[c]=s)}function dr(e,r,i){if(r.length*i.length<=fr){e.push(...mr(r,i));return}e.push(...r.map(a=>({left:a}))),e.push(...i.map(a=>({right:a})))}function pe(e){return e.trim().replace(/\s+/g," ")}function gr(e,r){let i=lr(e),a=lr(r),s=new Set;for(let[c,f]of i){let p=a.get(c);f.length===1&&p?.length===1&&s.add(`${f[0]}:${p[0]}`)}return s}function lr(e){let r=new Map;return e.forEach((i,a)=>{let s=dt(i);if(!s)return;let c=r.get(s)??[];c.push(a),r.set(s,c)}),r}function hn(e,r){let i=dt(e),a=dt(r);return!i||!a?i===a:i.split(":",1)[0]===a.split(":",1)[0]}function dt(e){let r=pe(e),i=[["function",/^(?:(?:export|default)\s+)*(?:async\s+)?function\s*\*?\s*([\p{L}_$][\p{L}\p{N}_$]*)\s*\(/u],["function",/^(?:async\s+)?def\s+([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["function",/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([\p{L}_][\p{L}\p{N}_]*)\s*(?:<[^>]*>)?\s*\(/u],["function",/^func\s+(?:\([^)]*\)\s*)?([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["class",/^(?:(?:export|default|abstract|public)\s+)*class\s+([\p{L}_$][\p{L}\p{N}_$]*)\b/u]];for(let[a,s]of i){let c=r.match(s);if(c)return`${a}:${c[1]}`}return null}function lt(e){return e.length<3?!1:/[\p{L}\p{N}_$]/u.test(e)&&!/^[\s()[\]{};,.:+\-*/=>|&!?'"`]+$/.test(e)}function ut(e){return e.toLowerCase().match(/[\p{L}_$][\p{L}\p{N}_$]*|\p{N}+(?:\.\p{N}+)?|[^\s\p{L}\p{N}_$]/gu)??[]}function mi(e,r){if(e.length+r.length===0)return 1;let i=new Map;e.forEach(s=>i.set(s,(i.get(s)??0)+1));let a=0;for(let s of r){let c=i.get(s)??0;c>0&&(a++,i.set(s,c-1))}return 2*a/(e.length+r.length)}function gi(e,r){if(e.length===0||r.length===0)return 0;let i=e[0]===r[0]?.5:0,a=e[e.length-1]===r[r.length-1]?.5:0;return i+a}function yi(e,r){let i=e.length+r.length;return i===0?1:2*Xn(e,r).filter(s=>!s.added&&!s.removed).reduce((s,c)=>s+c.value.length,0)/i}function wi(e,r){if(e.content.length>Qn||r.content.length>Qn)return;let{leftSegments:i,rightSegments:a,hasInlineChanges:s}=bi(e.content,r.content);s&&(e.segments=i,r.segments=a)}function ur(e){/[^\s]/.test(e.content)&&(e.segments=[{kind:e.kind,text:e.content,emphasis:!0}])}function bi(e,r){let i=Jn(e,r),a=[],s=[],c=!1;for(let f of i){let p=f.value;if(!f.added&&!f.removed){let v={kind:"context",text:p,emphasis:!1};a.push(v),s.push(v);continue}let t=/[^\s]/.test(p);c=c||t,f.removed&&a.push({kind:"removed",text:p,emphasis:t}),f.added&&s.push({kind:"added",text:p,emphasis:t})}return{leftSegments:a,rightSegments:s,hasInlineChanges:c}}function He(){return{kind:"placeholder",content:"",lineNumber:null}}function fe(e,r,i){return{kind:e,content:r,lineNumber:i}}function he(e,r,i){return{kind:e,content:r,lineNumber:i}}function Le(e,r){return{left:e,right:r}}function Rt(e,r,i,a,s){return{kind:e,leftStart:r,leftEnd:i,rightStart:a,rightEnd:s}}function yr(e,r){let i=typeof process<"u"?process.env?.[e]:void 0,a=Number.parseInt(i??"",10);return Number.isFinite(a)&&a>0?a:r}function wr(){return{leftFileName:"test-file-1.js",rightFileName:"test-file-2.js",leftContent:`// Test File 1 - Example JavaScript Code
|
|
5
5
|
const fs = require('fs');
|
|
6
6
|
const path = require('path');
|
|
7
7
|
|
|
@@ -145,7 +145,376 @@ if (require.main === module) {
|
|
|
145
145
|
}
|
|
146
146
|
|
|
147
147
|
module.exports = FileProcessor;
|
|
148
|
-
`}}function tn(e,t){if(e!==void 0){if(!Nr(e))throw new Error(`${t} must be an object.`);if(Ar(e,["id","text","status","source","confidence"],t),ot(e.id,`${t}.id`),ot(e.text,`${t}.text`),e.status!==void 0&&!["fulfilled","gap"].includes(String(e.status)))throw new Error(`${t}.status must be fulfilled or gap.`);if(Lr(e.source,`${t}.source`),e.confidence!==void 0&&!["high","medium","low"].includes(String(e.confidence)))throw new Error(`${t}.confidence must be high, medium, or low.`)}}function Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ot(e,t){if(typeof e!="string"||e.length===0)throw new Error(`${t} must be a non-empty string.`)}function Lr(e,t){e!==void 0&&ot(e,t)}function Ar(e,t,n){let i=Object.keys(e).filter(o=>!t.includes(o));if(i.length>0)throw new Error(`${n} contains unknown field${i.length===1?"":"s"}: ${i.join(", ")}`)}var st=2;function rn(e){if(M(e)&&Number.isInteger(e.version)&&Number(e.version)>st)throw new Error(`This tour uses manifest format version ${e.version}, but this version of Bygone supports up to version ${st}. Upgrade Bygone to open it.`);if(!M(e)||e.version!==1&&e.version!==st)throw new Error("Unsupported or missing change-tour manifest version.");if(R(e.title,"title"),R(e.generatedAt,"generatedAt"),e.windowTitle!==void 0&&R(e.windowTitle,"windowTitle"),e.sourceUrl!==void 0&&R(e.sourceUrl,"sourceUrl"),!M(e.range))throw new Error("Change-tour manifest range must be an object.");for(let i of["baseRef","headRef","mergeBaseOid","headOid"])R(e.range[i],`range.${i}`);if(!M(e.summary))throw new Error("Change-tour manifest summary must be an object.");for(let i of["changedFiles","includedScenes","additions","deletions","commitCount"])G(e.summary[i],`summary.${i}`);if(xe(e.summary.omittedFiles,"summary.omittedFiles"),!Array.isArray(e.commits)||!Array.isArray(e.chapters)||!Array.isArray(e.scenes))throw new Error("Change-tour manifest commits, chapters, and scenes must be arrays.");if(e.files!==void 0&&!Array.isArray(e.files))throw new Error("Change-tour manifest files must be an array.");let t=new Set;for(let[i,o]of e.scenes.entries()){if(ye(o,i),t.has(o.id))throw new Error(`Duplicate change-tour scene id: ${o.id}`);t.add(o.id)}for(let[i,o]of e.chapters.entries()){if(!M(o))throw new Error(`chapters[${i}] must be an object.`);R(o.id,`chapters[${i}].id`),R(o.title,`chapters[${i}].title`),xe(o.sceneIds,`chapters[${i}].sceneIds`);for(let a of o.sceneIds)if(!t.has(a))throw new Error(`Chapter references unknown scene id: ${a}`)}if(e.summary.includedScenes!==e.scenes.length)throw new Error("summary.includedScenes must match the number of scenes.");let n=e.files===void 0?Dr(e.scenes):e.files.map((i,o)=>(Or(i,o),i));if(e.files!==void 0&&e.summary.changedFiles!==n.length)throw new Error("summary.changedFiles must match the number of files.");return e.authoringCoverage!==void 0&&Rr(e.authoringCoverage,e.version),e.version===2&&Mr(e),{...e,files:n}}function Rr(e,t){if(!M(e)||!M(e.walkthrough)||!Array.isArray(e.explanationAssignments))throw new Error("authoringCoverage must contain walkthrough and explanationAssignments.");let n=t===2?"final":"tour";if(e.walkthrough.scope!==n)throw new Error(`authoringCoverage.walkthrough.scope must be ${n}.`);if(G(e.walkthrough.coveredUnits,"authoringCoverage.walkthrough.coveredUnits"),G(e.walkthrough.includedUnits,"authoringCoverage.walkthrough.includedUnits"),nn(e.walkthrough.coveragePercent,"authoringCoverage.walkthrough.coveragePercent"),e.walkthrough.coveredUnits>e.walkthrough.includedUnits)throw new Error("authoringCoverage.walkthrough.coveredUnits must not exceed includedUnits.");for(let[i,o]of e.explanationAssignments.entries()){let a=`authoringCoverage.explanationAssignments[${i}]`;if(!M(o))throw new Error(`${a} must be an object.`);if(R(o.sceneId,`${a}.sceneId`),G(o.assignedUnits,`${a}.assignedUnits`),G(o.excludedUnits,`${a}.excludedUnits`),G(o.completeUnits,`${a}.completeUnits`),G(o.totalUnits,`${a}.totalUnits`),nn(o.assignmentPercent,`${a}.assignmentPercent`),o.assignedUnits+o.excludedUnits!==o.completeUnits||o.completeUnits>o.totalUnits)throw new Error(`${a} contains inconsistent unit counts.`)}}function Mr(e){if(!M(e.repository)||typeof e.repository.root!="string"||!e.repository.root)throw new Error("A v2 tour requires its originating repository.root.");if(!M(e.zoom)||!Array.isArray(e.zoom.revisions)||!M(e.zoom.final))throw new Error("A v2 tour requires zoom metadata and real revision evidence.");let t=e.scenes,n=e.zoom.revisions,i=new Set;for(let[m,f]of n.entries()){if(ye(f,m),f.kind!=="stacked-diff")throw new Error("zoom.revisions must contain real stacked-diff scenes.");if(i.has(f.id))throw new Error(`Duplicate zoom revision scene: ${f.id}`);i.add(f.id);let s=e.range;if(f.stack[0].oid!==s.mergeBaseOid||f.stack[f.stack.length-1].oid!==s.headOid)throw new Error(`Revision scene ${f.id} endpoints must match the final diff range.`)}for(let m of t){if(m.kind!=="deconstructed-diff"&&m.kind!=="stacked-diff")continue;let f=n.find(s=>s.id===m.id);if(!f)throw new Error(`Scene ${m.id} is missing its real revision evidence.`);if(m.kind==="deconstructed-diff"&&(f.stack[0].oid!==m.realRange.baseOid||f.stack[f.stack.length-1].oid!==m.realRange.targetOid))throw new Error(`Deconstructed scene ${m.id} real stack endpoints must match its explanation range.`)}let o=t.some(m=>m.kind==="deconstructed-diff"),a=n.some(m=>m.stack.length>2),l=o?"explanation":a?"revisions":"final",d=[...o?["explanation"]:[],...a?["revisions"]:[],"final","history"];if(e.zoom.authoredDepth!==l||JSON.stringify(e.zoom.modes)!==JSON.stringify(d))throw new Error("zoom depth and modes must match the maximum authored depth.");if(!Array.isArray(e.files))throw new Error("A v2 tour requires final endpoint file evidence.");if(!Array.isArray(e.zoom.final.scenes)||!Array.isArray(e.zoom.final.chapters))throw new Error("A v2 tour requires a non-stacked final tour.");let p=new Set;for(let[m,f]of e.zoom.final.scenes.entries()){if(ye(f,m),f.kind==="stacked-diff"||f.kind==="deconstructed-diff")throw new Error("zoom.final must contain only non-stacked scenes.");if(p.has(f.id))throw new Error(`Duplicate final tour scene: ${f.id}`);p.add(f.id)}for(let[m,f]of e.zoom.final.chapters.entries()){if(!M(f)||!Array.isArray(f.sceneIds))throw new Error(`zoom.final.chapters[${m}] must contain sceneIds.`);R(f.id,`zoom.final.chapters[${m}].id`),R(f.title,`zoom.final.chapters[${m}].title`);for(let s of f.sceneIds)if(R(s,`zoom.final.chapters[${m}].sceneIds`),!p.has(s))throw new Error(`Final tour chapter references unknown scene: ${s}`)}}function ye(e,t){if(!M(e)||!["text-diff","discussion","walkthrough","stacked-diff","deconstructed-diff"].includes(String(e.kind)))throw new Error(`scenes[${t}] must be a text-diff, discussion, walkthrough, stacked-diff, or deconstructed-diff scene.`);for(let n of["id","title"])R(e[n],`scenes[${t}].${n}`);if(Pr(e,`scenes[${t}]`),e.kind!=="discussion"){if(e.kind==="walkthrough"){if(!Array.isArray(e.steps)||e.steps.length===0)throw new Error(`scenes[${t}].steps must be a non-empty array.`);for(let[n,i]of e.steps.entries()){let o=`scenes[${t}].steps[${n}]`;if(!M(i)||!M(i.focus)||!M(i.diff))throw new Error(`${o} must contain focus and diff objects.`);for(let a of["id","title","body"])R(i[a],`${o}.${a}`);if(i.depth!==void 0&&!["mentioned","explained","contextualized"].includes(String(i.depth)))throw new Error(`${o}.depth must be mentioned, explained, or contextualized.`);if(tn(i.requirement,`${o}.requirement`),at(i.focus,`${o}.focus`),ye(i.diff,t),i.diff.kind!=="text-diff")throw new Error(`${o}.diff must be a text-diff scene.`);if(i.connection!==void 0){if(!M(i.connection))throw new Error(`${o}.connection must be an object.`);R(i.connection.id,`${o}.connection.id`),R(i.connection.label,`${o}.connection.label`),at(i.connection.from,`${o}.connection.from`),at(i.connection.to,`${o}.connection.to`)}}return}if(e.kind==="stacked-diff"){Fr(e,t);return}if(e.kind==="deconstructed-diff"){_r(e,t);return}for(let n of["path","leftLabel","rightLabel","leftContent","rightContent"])R(e[n],`scenes[${t}].${n}`);e.previousPath!==void 0&&R(e.previousPath,`scenes[${t}].previousPath`),R(e.changeKind,`scenes[${t}].changeKind`),G(e.additions,`scenes[${t}].additions`),G(e.deletions,`scenes[${t}].deletions`),e.focusChangeIndex!==void 0&&G(e.focusChangeIndex,`scenes[${t}].focusChangeIndex`)}}function Fr(e,t){if(!Array.isArray(e.stack)||e.stack.length<2||e.stack.length>6)throw new Error(`scenes[${t}].stack must contain between 2 and 6 revisions.`);for(let[n,i]of e.stack.entries()){if(!M(i))throw new Error(`scenes[${t}].stack[${n}] must be an object.`);for(let o of["id","ref","oid","label"])R(i[o],`scenes[${t}].stack[${n}].${o}`)}on(e.files,e.stack.length,t),sn(e.steps,e.stack.length,t,!1)}function _r(e,t){if(e.stageLabel!=="Explanation stages")throw new Error(`scenes[${t}].stageLabel must be Explanation stages.`);if(!M(e.realRange))throw new Error(`scenes[${t}].realRange must be an object.`);for(let i of["baseRef","targetRef","baseOid","targetOid"])R(e.realRange[i],`scenes[${t}].realRange.${i}`);if(!Array.isArray(e.panels)||e.panels.length<2||e.panels.length>13)throw new Error(`scenes[${t}].panels must contain a baseline and between 1 and 12 stages.`);let n=e.panels;for(let[i,o]of n.entries()){if(!M(o))throw new Error(`scenes[${t}].panels[${i}] must be an object.`);for(let l of["id","label","role"])R(o[l],`scenes[${t}].panels[${i}].${l}`);let a=i===0?"baseline":"stage";if(o.role!==a)throw new Error(`scenes[${t}].panels[${i}].role must be ${a}.`);i>0&&R(o.stageId,`scenes[${t}].panels[${i}].stageId`)}if(on(e.files,n.length,t),sn(e.steps,n.length,t,!0),Array.isArray(e.steps)){let i=-1;e.steps.forEach((o,a)=>{if(!M(o))return;let l=Number(o.pairIndex);if(l<i)throw new Error(`scenes[${t}].steps must remain grouped in explanation stage order.`);if(i=l,o.stageId!==void 0&&R(o.stageId,`scenes[${t}].steps[${a}].stageId`),o.stageIndex!==void 0&&G(o.stageIndex,`scenes[${t}].steps[${a}].stageIndex`),o.focusIndex!==void 0&&G(o.focusIndex,`scenes[${t}].steps[${a}].focusIndex`),o.focusCount!==void 0&&Se(o.focusCount,`scenes[${t}].steps[${a}].focusCount`),o.stageIndex!==void 0&&Number(o.stageIndex)!==l)throw new Error(`scenes[${t}].steps[${a}].stageIndex must match pairIndex.`);if(o.focusIndex!==void 0&&o.focusCount!==void 0&&Number(o.focusIndex)>=Number(o.focusCount))throw new Error(`scenes[${t}].steps[${a}].focusIndex must be less than focusCount.`)});for(let o=0;o<n.length-1;o+=1){let a=n[o+1],l=e.steps.filter(m=>M(m)&&Number(m.pairIndex)===o);if(!M(a)||l.length===0)throw new Error(`scenes[${t}].steps must cover every explanation stage.`);let d=l[0],p=M(d)?d.id:void 0;if(l.some(m=>M(m)?(m.stageId??p)!==a.stageId:!0))throw new Error(`scenes[${t}].panels must align with explanation stage ids.`)}}}function on(e,t,n){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${n}].files must be non-empty.`);for(let[i,o]of e.entries()){if(!M(o))throw new Error(`scenes[${n}].files[${i}] must be an object.`);if(R(o.path,`scenes[${n}].files[${i}].path`),!Array.isArray(o.panels)||o.panels.length!==t)throw new Error(`scenes[${n}].files[${i}].panels must match panel count.`);for(let[a,l]of o.panels.entries()){if(!M(l))throw new Error(`scenes[${n}].files[${i}].panels[${a}] must be an object.`);for(let d of["id","label","content"])R(l[d],`scenes[${n}].files[${i}].panels[${a}].${d}`);if(l.path!==void 0&&R(l.path,`scenes[${n}].files[${i}].panels[${a}].path`),typeof l.exists!="boolean")throw new Error(`scenes[${n}].files[${i}].panels[${a}].exists must be boolean.`)}}}function sn(e,t,n,i){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${n}].steps must be non-empty.`);for(let[o,a]of e.entries()){if(!M(a))throw new Error(`scenes[${n}].steps[${o}] must be an object.`);for(let l of["id","title","body","file","side"])R(a[l],`scenes[${n}].steps[${o}].${l}`);if(G(a.pairIndex,`scenes[${n}].steps[${o}].pairIndex`),Number(a.pairIndex)>=t-1)throw new Error(`scenes[${n}].steps[${o}].pairIndex is outside the panels.`);if(i&&(xe(a.introducedHunks,`scenes[${n}].steps[${o}].introducedHunks`),a.introducedHunks.length===0))throw new Error(`scenes[${n}].steps[${o}].introducedHunks must be non-empty.`);if(a.side!=="left"&&a.side!=="right")throw new Error(`scenes[${n}].steps[${o}].side must be left or right.`);a.startLine!==void 0&&Se(a.startLine,`scenes[${n}].steps[${o}].startLine`),a.endLine!==void 0&&Se(a.endLine,`scenes[${n}].steps[${o}].endLine`)}}function Or(e,t){if(!M(e))throw new Error(`files[${t}] must be an object.`);if(e.kind==="text-diff"){ye(e,t);return}if(e.kind!=="omitted")throw new Error(`files[${t}].kind must be text-diff or omitted.`);for(let n of["id","title","path","changeKind","reason"])R(e[n],`files[${t}].${n}`);e.previousPath!==void 0&&R(e.previousPath,`files[${t}].previousPath`),G(e.additions,`files[${t}].additions`),G(e.deletions,`files[${t}].deletions`)}function Dr(e){let t=new Map;for(let n of e){if(n.kind==="text-diff"){t.has(n.path)||t.set(n.path,n);continue}if(n.kind==="walkthrough")for(let i of n.steps)t.has(i.diff.path)||t.set(i.diff.path,i.diff)}return[...t.values()].sort((n,i)=>n.path.localeCompare(i.path))}function at(e,t){if(!M(e))throw new Error(`${t} must be an object.`);for(let n of["id","path","revision","excerpt"])R(e[n],`${t}.${n}`);if(e.revision!=="base"&&e.revision!=="head")throw new Error(`${t}.revision must be base or head.`);if(Se(e.startLine,`${t}.startLine`),Se(e.endLine,`${t}.endLine`),Number(e.endLine)<Number(e.startLine))throw new Error(`${t}.endLine must not precede startLine.`)}function Pr(e,t){R(e.summary,`${t}.summary`),xe(e.bullets,`${t}.bullets`),xe(e.tags,`${t}.tags`),R(e.takeaway,`${t}.takeaway`)}function M(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function R(e,t){if(typeof e!="string")throw new Error(`${t} must be a string.`)}function xe(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of strings.`)}function G(e,t){if(!Number.isInteger(e)||Number(e)<0)throw new Error(`${t} must be a non-negative integer.`)}function nn(e,t){if(typeof e!="number"||!Number.isFinite(e)||e<0||e>100)throw new Error(`${t} must be a number from 0 to 100.`)}function Se(e,t){if(!Number.isInteger(e)||Number(e)<1)throw new Error(`${t} must be a positive integer.`)}var Ur=new Set(["modified-here","created-here","deleted-here"]);function ct(e,t){let n=e.panels[t],i=e.panels[t+1];return!n||!i?"unchanged-here":n.exists&&i.exists?n.content===i.content?"unchanged-here":"modified-here":!n.exists&&i.exists?"created-here":n.exists&&!i.exists?"deleted-here":e.panels.slice(0,t).some(l=>l.exists)?"already-deleted":(e.panels.slice(t+2).some(l=>l.exists),"not-created-yet")}function an(e,t,n,i){if(i!==-1&&i!==1||!n)return null;let o=e.findIndex(d=>d.path===n);if(o<0)return null;let a=e.map((d,p)=>({file:d,fileIndex:p,state:ct(d,t)})).filter(({state:d})=>Ur.has(d)),l=i<0?[...a].reverse().find(({fileIndex:d})=>d<o):a.find(({fileIndex:d})=>d>o);return l?{pairIndex:t,fileIndex:l.fileIndex,path:l.file.path}:null}function cn(e,t,n){let i=e.findIndex(d=>d.id===t),o=i>=0?i:0,a=e[o];if(!a||a.kind!=="walkthrough"&&a.kind!=="stacked-diff"&&a.kind!=="deconstructed-diff"||!n)return{sceneIndex:o,stepIndex:0};let l=a.steps.findIndex(d=>d.id===n);return{sceneIndex:o,stepIndex:l>=0?l:0}}function Pe(e,t,n){let i=e[t.sceneIndex];if(!i)return null;if(n>0)return(i.kind==="walkthrough"||i.kind==="stacked-diff"||i.kind==="deconstructed-diff")&&t.stepIndex<i.steps.length-1?{sceneIndex:t.sceneIndex,stepIndex:t.stepIndex+1}:t.sceneIndex<e.length-1?{sceneIndex:t.sceneIndex+1,stepIndex:0}:null;if((i.kind==="walkthrough"||i.kind==="stacked-diff"||i.kind==="deconstructed-diff")&&t.stepIndex>0)return{sceneIndex:t.sceneIndex,stepIndex:t.stepIndex-1};if(t.sceneIndex===0)return null;let o=e[t.sceneIndex-1];return{sceneIndex:t.sceneIndex-1,stepIndex:o.kind==="walkthrough"||o.kind==="stacked-diff"||o.kind==="deconstructed-diff"?o.steps.length-1:0}}function un(e,t,n){if(!t)return null;let i=e.map((d,p)=>({file:d,fileIndex:p})).filter(({file:d})=>d.kind==="text-diff"),o=i.findIndex(({file:d})=>d.path===t),a=o+n,l=o>=0?i[a]:null;return l?{fileIndex:l.fileIndex,path:l.file.path}:null}function dn(e,t,n){let i=e.scenes[t.sceneIndex];if(!i)return null;let o=ut(i)?Math.min(Math.max(t.stepIndex,0),i.steps.length-1):0,a={sceneIndex:t.sceneIndex,stepIndex:o},l=ut(i)?i.steps[o]:void 0,d=[],p=!l||o===0,m=!!(l&&o>0&&n.entry==="playback-start");if(p){let T=e.chapters.find(A=>A.sceneIds.includes(i.id));T&&d.push({source:{field:"chapter"},text:T.title})}(p||m)&&d.push({source:{field:"scene-title"},text:i.title}),p&&(d.push({source:{field:"summary"},text:i.summary}),i.bullets.forEach((T,A)=>{d.push({source:{field:"bullet",itemIndex:A},text:T})})),l&&(d.push({source:{field:"step-title"},text:l.title}),d.push({source:{field:"step-body"},text:l.body}),"connection"in l&&l.connection?.label&&d.push({source:{field:"connection"},text:l.connection.label})),(!l||ut(i)&&o===i.steps.length-1)&&d.push({source:{field:"takeaway"},text:i.takeaway});let f=`${i.id}:${l?.id||"scene"}`,s=n.segmentLimit??240,x=d.flatMap(T=>zr(f,T,s));return{id:f,position:a,segments:x}}function Br(e,t=240){if(!Number.isInteger(t)||t<40)throw new Error("Narration segment limit must be an integer of at least 40 characters.");return Wr(e).flatMap(i=>Gr(e,i.startOffset,i.endOffset,t))}function Hr(e){return e.replace(/https?:\/\/\S+/giu," ").replace(/\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*\d)[0-9a-f]+\b/giu," ").replace(/[`*_~]/gu,"").replace(/([\p{Ll}\d])(\p{Lu})/gu,"$1 $2").replace(/([\p{Lu}])(\p{Lu}\p{Ll})/gu,"$1 $2").replace(/\s+/gu," ").trim()}function zr(e,t,n){let i=t.source.itemIndex===void 0?t.source.field:`${t.source.field}-${t.source.itemIndex}`;return Br(t.text,n).map((o,a)=>({id:`${e}:${i}:${a}`,text:o.text,speechText:Hr(o.text),source:t.source,startOffset:o.startOffset,endOffset:o.endOffset})).filter(o=>o.speechText.length>0)}function Wr(e){let t=[],n=0;for(let i=0;i<e.length;i+=1){if(!".!?".includes(e[i]))continue;let o=i+1;for(;o<e.length&&`"'\u201D\u2019)]}`.includes(e[o]);)o+=1;o<e.length&&!/\s/u.test(e[o])||(Ue(e,t,n,o),n=o)}return Ue(e,t,n,e.length),t}function Gr(e,t,n,i){let o=[],a=t;for(;n-a>i;){let l=a+i,d=a+Math.floor(i*.55),p=ln(e,d,l,/[;,:—–-]/u);p<=a&&(p=ln(e,d,l,/\s/u)),p<=a&&(p=l),Ue(e,o,a,p),a=p}return Ue(e,o,a,n),o}function ln(e,t,n,i){for(let o=n;o>=t;o-=1)if(i.test(e[o]))return o+1;return-1}function Ue(e,t,n,i){let o=n,a=i;for(;o<a&&/\s/u.test(e[o]);)o+=1;for(;a>o&&/\s/u.test(e[a-1]);)a-=1;o<a&&t.push({text:e.slice(o,a),startOffset:o,endOffset:a})}function ut(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}var Be=class{constructor(t,n){this.engine=t;this.callbacks=n;this.generation=0;this.continuous=!0;this.currentState={kind:"idle"}}get state(){return this.currentState}get engaged(){return this.currentState.kind==="playing"||this.currentState.kind==="paused"}start(t,n=!0){if(this.resetEngine(),this.continuous=n,t.segments.length===0){this.finishUnit(t);return}this.callbacks.claimAudio(),this.setState({kind:"playing",unit:t,segmentIndex:0}),this.speakCurrent()}togglePause(){if(this.currentState.kind==="playing"){this.engine.pause();let n={kind:"paused",unit:this.currentState.unit,segmentIndex:this.currentState.segmentIndex,pendingStart:!1};this.setState(n),this.callbacks.onSegmentChange(n.unit.segments[n.segmentIndex]||null,!0);return}if(this.currentState.kind!=="paused")return;this.callbacks.claimAudio();let t=this.currentState;this.setState({kind:"playing",unit:t.unit,segmentIndex:t.segmentIndex}),t.pendingStart?this.speakCurrent():(this.engine.resume(),this.callbacks.onSegmentChange(t.unit.segments[t.segmentIndex]||null,!1))}stop(){this.resetEngine(),this.setState({kind:"idle"}),this.callbacks.onSegmentChange(null,!1)}pauseForExternalOwner(){this.currentState.kind==="playing"&&this.togglePause()}canSkipSegment(t){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return!1;let n=this.currentState.segmentIndex+t;return n>=0&&n<this.currentState.unit.segments.length?!0:this.callbacks.canNavigateUnit(this.currentState.unit,t)}skipSegment(t){if(!this.canSkipSegment(t))return!1;let n=this.currentState,i=n.kind==="paused",o=n.unit,a=n.segmentIndex+t;if(a<0||a>=o.segments.length){let l=this.callbacks.navigateUnit(o,t);if(!l||l.segments.length===0)return!1;o=l,a=t<0?o.segments.length-1:0}return this.resetEngine(),i?(this.setState({kind:"paused",unit:o,segmentIndex:a,pendingStart:!0}),this.callbacks.onSegmentChange(o.segments[a]||null,!0)):(this.setState({kind:"playing",unit:o,segmentIndex:a}),this.speakCurrent()),!0}followLinearNavigation(t){this.currentState.kind==="playing"?this.start(t,this.continuous):this.currentState.kind==="paused"&&this.preparePaused(t)}followDirectNavigation(t){this.engaged&&this.preparePaused(t)}interruptForExploration(){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return;let t=this.currentState;this.resetEngine(),this.setState({kind:"paused",unit:t.unit,segmentIndex:t.segmentIndex,pendingStart:!0}),this.callbacks.onSegmentChange(t.unit.segments[t.segmentIndex]||null,!0)}dispose(){this.stop()}preparePaused(t){this.resetEngine(),this.setState({kind:"paused",unit:t,segmentIndex:0,pendingStart:!0}),this.callbacks.onSegmentChange(t.segments[0]||null,!0)}speakCurrent(){if(this.currentState.kind!=="playing")return;let t=this.generation,n=this.currentState.unit.segments[this.currentState.segmentIndex];if(!n){this.finishUnit(this.currentState.unit);return}this.callbacks.onSegmentChange(n,!1),this.engine.speak(n,{onEnd:()=>{if(t!==this.generation||this.currentState.kind!=="playing")return;let i=this.currentState.segmentIndex+1;i<this.currentState.unit.segments.length?(this.setState({kind:"playing",unit:this.currentState.unit,segmentIndex:i}),this.speakCurrent()):this.finishUnit(this.currentState.unit)},onError:i=>{t===this.generation&&(this.setState({kind:"error",message:i}),this.callbacks.onSegmentChange(null,!1))}})}finishUnit(t){if(this.continuous){let n=this.callbacks.navigateUnit(t,1);if(n){if(this.generation+=1,n.segments.length===0){this.finishUnit(n);return}this.setState({kind:"playing",unit:n,segmentIndex:0}),this.speakCurrent();return}}this.setState({kind:"completed"}),this.callbacks.onSegmentChange(null,!1)}resetEngine(){this.generation+=1,this.engine.cancel()}setState(t){this.currentState=t,this.callbacks.onStateChange(t)}};function hn(e,t,n="all",i=300){let o=t.trim().toLocaleLowerCase();if(!o||i<=0)return[];let a=[];if(n!=="code"){let l=new Map;e.chapters.forEach(d=>d.sceneIds.forEach(p=>l.set(p,d.title))),e.scenes.forEach((d,p)=>{let m=[l.get(d.id),d.title,d.summary,...d.bullets,...d.tags,d.takeaway],f=fn(m,o);f&&a.push({kind:"narrative",sceneIndex:p,label:d.title,preview:f}),jr(d)&&d.steps.forEach((s,x)=>{let T=fn([s.title,s.body,"connection"in s?s.connection?.label:void 0],o);T&&a.push({kind:"narrative",sceneIndex:p,stepIndex:x,label:`${d.title} \xB7 ${s.title}`,preview:T})})})}if(n!=="narrative"&&a.length<i)for(let l=0;l<e.files.length;l+=1){let d=e.files[l];if(d.kind==="text-diff"){for(let[p,m]of[[0,d.leftContent],[1,d.rightContent]])for(let f of qr(m,o))if(a.push({kind:"code",fileIndex:l,sideIndex:p,label:`${d.path} \xB7 ${p===0?"base":"head"}`,...f}),a.length>=i)return a}}return a.slice(0,i)}function fn(e,t){return e.find(n=>n?.toLocaleLowerCase().includes(t))}function qr(e,t){let n=[];return e.replace(/\r\n/g,`
|
|
148
|
+
`}}function vr(e,r={}){if(!qe(e))throw new Error("review must be an object.");if(We(e,["baseOid","headOid","items"],"review"),br(e.baseOid,"review.baseOid"),br(e.headOid,"review.headOid"),!Array.isArray(e.items)||e.items.length===0)throw new Error("review.items must be a non-empty array.");if(r.expectedRange){if(Ot(e.baseOid)!==Ot(r.expectedRange.baseOid))throw new Error(`Stale review: review.baseOid ${e.baseOid} does not match the resolved range.mergeBaseOid ${r.expectedRange.baseOid}.`);if(Ot(e.headOid)!==Ot(r.expectedRange.headOid))throw new Error(`Stale review: review.headOid ${e.headOid} does not match the resolved range.headOid ${r.expectedRange.headOid}.`)}let i=new Set;for(let[a,s]of e.items.entries()){let c=`review.items[${a}]`;if(!qe(s))throw new Error(`${c} must be an object.`);if(We(s,["id","kind","title","body","evidence","nextCheck"],c),ze(s.id,`${c}.id`),i.has(s.id))throw new Error(`Duplicate review item id: ${s.id}`);if(i.add(s.id),typeof s.kind!="string"||!["concept","boundary","tradeoff","question"].includes(s.kind))throw new Error(`${c}.kind must be concept, boundary, tradeoff, or question.`);if(ze(s.title,`${c}.title`),ze(s.body,`${c}.body`),!Array.isArray(s.evidence))throw new Error(`${c}.evidence must be an array.`);if(s.kind!=="question"&&s.evidence.length===0)throw new Error(`${c}.evidence must contain at least one reference for claims.`);if(s.kind==="question"&&s.nextCheck===void 0)throw new Error(`${c}.nextCheck must be a non-empty string for question items.`);s.nextCheck!==void 0&&ze(s.nextCheck,`${c}.nextCheck`);for(let[f,p]of s.evidence.entries()){let t=`${c}.evidence[${f}]`;if(!qe(p))throw new Error(`${t} must be an object.`);if(We(p,["sceneId","stepId"],t),ze(p.sceneId,`${t}.sceneId`),ze(p.stepId,`${t}.stepId`),r.authoredWalkthroughSteps){let v=r.authoredWalkthroughSteps.get(p.sceneId);if(!v)throw new Error(`${t} references unknown authored walkthrough scene ${p.sceneId}.`);if(!v.has(p.stepId))throw new Error(`${t} references unknown authored walkthrough step ${p.sceneId}/${p.stepId}.`)}}}}function xr(e,r){if(e!==void 0){if(!qe(e))throw new Error(`${r} must be an object.`);if(We(e,["id","text","status","source","confidence"],r),Re(e.id,`${r}.id`),Re(e.text,`${r}.text`),e.status!==void 0&&!["fulfilled","gap"].includes(String(e.status)))throw new Error(`${r}.status must be fulfilled or gap.`);if(xi(e.source,`${r}.source`),e.confidence!==void 0&&!["high","medium","low"].includes(String(e.confidence)))throw new Error(`${r}.confidence must be high, medium, or low.`)}}function je(e,r,i={}){if(e!==void 0){if(!qe(e))throw new Error(`${r} must be an object.`);if(We(e,["kind","path","comparison"],r),e.kind!=="directory-diff")throw new Error(`${r}.kind must be directory-diff.`);if(e.path!==void 0&&vi(e.path,`${r}.path`),e.comparison!==void 0){if(i.allowComparison===!1)throw new Error(`${r}.comparison is not supported for walkthrough scenes; use the fixed base-to-head comparison.`);if(!qe(e.comparison))throw new Error(`${r}.comparison must be an object.`);if(We(e.comparison,["from","to"],`${r}.comparison`),Re(e.comparison.from,`${r}.comparison.from`),Re(e.comparison.to,`${r}.comparison.to`),e.comparison.from===e.comparison.to)throw new Error(`${r}.comparison.from and to must identify distinct endpoints.`);if(i.endpointIds!==void 0){for(let a of[e.comparison.from,e.comparison.to])if(!i.endpointIds.includes(a))throw new Error(`${r}.comparison endpoint ${a} is not defined by this scene.`)}}}}function vi(e,r){if(Re(e,r),e.includes("\\"))throw new Error(`${r} must use a relative POSIX directory path without backslashes.`);if(e.startsWith("/")||/^[A-Za-z]:/.test(e))throw new Error(`${r} must be relative to the repository root.`);if(e.split("/").some(i=>i===".."))throw new Error(`${r} must not contain parent-directory traversal.`)}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Re(e,r){if(typeof e!="string"||e.length===0)throw new Error(`${r} must be a non-empty string.`)}function br(e,r){if(Re(e,r),!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(e))throw new Error(`${r} must be a full 40- or 64-character hexadecimal Git OID.`)}function ze(e,r){if(typeof e!="string"||e.trim().length===0)throw new Error(`${r} must be a non-empty string.`)}function Ot(e){return e.toLowerCase()}function xi(e,r){e!==void 0&&Re(e,r)}function We(e,r,i){let a=Object.keys(e).filter(s=>!r.includes(s));if(a.length>0)throw new Error(`${i} contains unknown field${a.length===1?"":"s"}: ${a.join(", ")}`)}var pn=3;function Ir(e){if(U(e)&&Number.isInteger(e.version)&&Number(e.version)>pn)throw new Error(`This tour uses manifest format version ${e.version}, but this version of Bygone supports up to version ${pn}. Upgrade Bygone to open it.`);if(!U(e)||e.version!==1&&e.version!==2&&e.version!==pn)throw new Error("Unsupported or missing change-tour manifest version.");if(_(e.title,"title"),_(e.generatedAt,"generatedAt"),e.windowTitle!==void 0&&_(e.windowTitle,"windowTitle"),e.sourceUrl!==void 0&&_(e.sourceUrl,"sourceUrl"),!U(e.range))throw new Error("Change-tour manifest range must be an object.");for(let a of["baseRef","headRef","mergeBaseOid","headOid"])_(e.range[a],`range.${a}`);if(!U(e.summary))throw new Error("Change-tour manifest summary must be an object.");for(let a of["changedFiles","includedScenes","additions","deletions","commitCount"])Q(e.summary[a],`summary.${a}`);if(Ke(e.summary.omittedFiles,"summary.omittedFiles"),!Array.isArray(e.commits)||!Array.isArray(e.chapters)||!Array.isArray(e.scenes))throw new Error("Change-tour manifest commits, chapters, and scenes must be arrays.");if(e.files!==void 0&&!Array.isArray(e.files))throw new Error("Change-tour manifest files must be an array.");let r=new Set;for(let[a,s]of e.scenes.entries()){if(Ge(s,a,e.version),r.has(s.id))throw new Error(`Duplicate change-tour scene id: ${s.id}`);r.add(s.id)}for(let[a,s]of e.chapters.entries()){if(!U(s))throw new Error(`chapters[${a}] must be an object.`);_(s.id,`chapters[${a}].id`),_(s.title,`chapters[${a}].title`),Ke(s.sceneIds,`chapters[${a}].sceneIds`);for(let c of s.sceneIds)if(!r.has(c))throw new Error(`Chapter references unknown scene id: ${c}`)}if(e.summary.includedScenes!==e.scenes.length)throw new Error("summary.includedScenes must match the number of scenes.");let i=e.files===void 0?Ni(e.scenes):e.files.map((a,s)=>($i(a,s),a));if(e.files!==void 0&&e.summary.changedFiles!==i.length)throw new Error("summary.changedFiles must match the number of files.");if(e.authoringCoverage!==void 0&&Ii(e.authoringCoverage,e.version),e.tours!==void 0){if(e.version!==3)throw new Error("Independent tours require manifest version 3.");Si(e.tours,e.version)}if(e.version!==1&&Ci(e,e.version),e.review!==void 0){if(e.version!==3)throw new Error("Review notes require manifest version 3.");let a=e.version>=2&&U(e.zoom)&&U(e.zoom.final)?e.zoom.final.scenes:e.scenes;vr(e.review,{expectedRange:{baseOid:String(e.range.mergeBaseOid),headOid:String(e.range.headOid)},authoredWalkthroughSteps:ki(a)})}return{...e,files:i}}function ki(e){let r=new Map;if(!Array.isArray(e))return r;for(let i of e){if(!U(i)||i.kind!=="walkthrough"||!Array.isArray(i.steps)||typeof i.id!="string")continue;let a=new Set;for(let s of i.steps)U(s)&&typeof s.id=="string"&&a.add(s.id);r.set(i.id,a)}return r}function Ii(e,r){if(!U(e)||!U(e.walkthrough)||!Array.isArray(e.explanationAssignments))throw new Error("authoringCoverage must contain walkthrough and explanationAssignments.");let i=r>=2?"final":"tour";if(e.walkthrough.scope!==i)throw new Error(`authoringCoverage.walkthrough.scope must be ${i}.`);if(Q(e.walkthrough.coveredUnits,"authoringCoverage.walkthrough.coveredUnits"),Q(e.walkthrough.includedUnits,"authoringCoverage.walkthrough.includedUnits"),kr(e.walkthrough.coveragePercent,"authoringCoverage.walkthrough.coveragePercent"),e.walkthrough.coveredUnits>e.walkthrough.includedUnits)throw new Error("authoringCoverage.walkthrough.coveredUnits must not exceed includedUnits.");for(let[a,s]of e.explanationAssignments.entries()){let c=`authoringCoverage.explanationAssignments[${a}]`;if(!U(s))throw new Error(`${c} must be an object.`);if(_(s.sceneId,`${c}.sceneId`),Q(s.assignedUnits,`${c}.assignedUnits`),Q(s.excludedUnits,`${c}.excludedUnits`),Q(s.completeUnits,`${c}.completeUnits`),Q(s.totalUnits,`${c}.totalUnits`),kr(s.assignmentPercent,`${c}.assignmentPercent`),s.assignedUnits+s.excludedUnits!==s.completeUnits||s.completeUnits>s.totalUnits)throw new Error(`${c} contains inconsistent unit counts.`)}}function Si(e,r){if(!U(e))throw new Error("Change-tour manifest tours must be an object.");if(e.historical===void 0&&e.deconstructed===void 0)throw new Error("Change-tour manifest tours must contain a historical or deconstructed tour.");for(let i of["historical","deconstructed"]){let a=e[i];if(a===void 0)continue;if(!U(a)||!Array.isArray(a.chapters)||!Array.isArray(a.scenes)||a.chapters.length===0||a.scenes.length===0)throw new Error(`Change-tour manifest tours.${i} must contain non-empty chapters and scenes arrays.`);let s=new Set,c=!1;for(let[f,p]of a.scenes.entries()){if(Ge(p,f,r),s.has(p.id))throw new Error(`Duplicate ${i} tour scene id: ${p.id}`);if(s.add(p.id),p.kind==="deconstructed-diff"&&(c=!0),i==="historical"&&p.kind==="deconstructed-diff")throw new Error("Historical tours cannot contain synthetic deconstructed scenes.")}if(i==="deconstructed"&&!c)throw new Error("Deconstructed tours must contain a constructed deconstructed-diff scene.");for(let[f,p]of a.chapters.entries()){if(!U(p))throw new Error(`tours.${i}.chapters[${f}] must be an object.`);_(p.id,`tours.${i}.chapters[${f}].id`),_(p.title,`tours.${i}.chapters[${f}].title`),Ke(p.sceneIds,`tours.${i}.chapters[${f}].sceneIds`);for(let t of p.sceneIds)if(!s.has(t))throw new Error(`tours.${i} chapter references unknown scene id: ${t}`)}}}function Ci(e,r){if(!U(e.repository)||typeof e.repository.root!="string"||!e.repository.root)throw new Error("A v2 tour requires its originating repository.root.");if(!U(e.zoom)||!Array.isArray(e.zoom.revisions)||!U(e.zoom.final))throw new Error("A v2 tour requires zoom metadata and real revision evidence.");let i=e.scenes,a=e.zoom.revisions,s=new Set;for(let[g,m]of a.entries()){if(Ge(m,g,r),m.kind!=="stacked-diff")throw new Error("zoom.revisions must contain real stacked-diff scenes.");if(s.has(m.id))throw new Error(`Duplicate zoom revision scene: ${m.id}`);s.add(m.id);let w=e.range;if(m.stack[0].oid!==w.mergeBaseOid||m.stack[m.stack.length-1].oid!==w.headOid)throw new Error(`Revision scene ${m.id} endpoints must match the final diff range.`)}for(let g of i){if(g.kind!=="deconstructed-diff"&&g.kind!=="stacked-diff")continue;let m=a.find(w=>w.id===g.id);if(!m)throw new Error(`Scene ${g.id} is missing its real revision evidence.`);if(g.kind==="deconstructed-diff"&&(m.stack[0].oid!==g.realRange.baseOid||m.stack[m.stack.length-1].oid!==g.realRange.targetOid))throw new Error(`Deconstructed scene ${g.id} real stack endpoints must match its explanation range.`)}let c=i.some(g=>g.kind==="deconstructed-diff"),f=a.some(g=>g.stack.length>2),p=c?"explanation":f?"revisions":"final",t=[...c?["explanation"]:[],...f?["revisions"]:[],"final","history"];if(e.zoom.authoredDepth!==p||JSON.stringify(e.zoom.modes)!==JSON.stringify(t))throw new Error("zoom depth and modes must match the maximum authored depth.");if(!Array.isArray(e.files))throw new Error("A v2 tour requires final endpoint file evidence.");if(!Array.isArray(e.zoom.final.scenes)||!Array.isArray(e.zoom.final.chapters))throw new Error("A v2 tour requires a non-stacked final tour.");let v=new Set;for(let[g,m]of e.zoom.final.scenes.entries()){if(Ge(m,g,r),m.kind==="stacked-diff"||m.kind==="deconstructed-diff")throw new Error("zoom.final must contain only non-stacked scenes.");if(v.has(m.id))throw new Error(`Duplicate final tour scene: ${m.id}`);v.add(m.id)}for(let[g,m]of e.zoom.final.chapters.entries()){if(!U(m)||!Array.isArray(m.sceneIds))throw new Error(`zoom.final.chapters[${g}] must contain sceneIds.`);_(m.id,`zoom.final.chapters[${g}].id`),_(m.title,`zoom.final.chapters[${g}].title`);for(let w of m.sceneIds)if(_(w,`zoom.final.chapters[${g}].sceneIds`),!v.has(w))throw new Error(`Final tour chapter references unknown scene: ${w}`)}}function Ge(e,r,i){if(!U(e)||!["text-diff","discussion","walkthrough","stacked-diff","deconstructed-diff"].includes(String(e.kind)))throw new Error(`scenes[${r}] must be a text-diff, discussion, walkthrough, stacked-diff, or deconstructed-diff scene.`);for(let a of["id","title"])_(e[a],`scenes[${r}].${a}`);if(e.overview!==void 0&&i!==3)throw new Error(`scenes[${r}].overview requires manifest version 3.`);if(Ai(e,`scenes[${r}]`),e.kind==="discussion"){je(e.overview,`scenes[${r}].overview`,{allowComparison:!1});return}if(e.kind==="walkthrough"){if(je(e.overview,`scenes[${r}].overview`,{allowComparison:!1}),!Array.isArray(e.steps)||e.steps.length===0)throw new Error(`scenes[${r}].steps must be a non-empty array.`);for(let[a,s]of e.steps.entries()){let c=`scenes[${r}].steps[${a}]`;if(!U(s)||!U(s.focus)||!U(s.diff))throw new Error(`${c} must contain focus and diff objects.`);for(let f of["id","title","body"])_(s[f],`${c}.${f}`);if(s.depth!==void 0&&!["mentioned","explained","contextualized"].includes(String(s.depth)))throw new Error(`${c}.depth must be mentioned, explained, or contextualized.`);if(xr(s.requirement,`${c}.requirement`),mn(s.focus,`${c}.focus`),Ge(s.diff,r,i),s.diff.kind!=="text-diff")throw new Error(`${c}.diff must be a text-diff scene.`);if(s.connection!==void 0){if(!U(s.connection))throw new Error(`${c}.connection must be an object.`);_(s.connection.id,`${c}.connection.id`),_(s.connection.label,`${c}.connection.label`),mn(s.connection.from,`${c}.connection.from`),mn(s.connection.to,`${c}.connection.to`)}}return}if(e.kind==="stacked-diff"){Ei(e,r),je(e.overview,`scenes[${r}].overview`,{endpointIds:e.stack.map(a=>a.id)});return}if(e.kind==="deconstructed-diff"){Ti(e,r),je(e.overview,`scenes[${r}].overview`,{endpointIds:e.panels.map(a=>a.id)});return}je(e.overview,`scenes[${r}].overview`,{allowComparison:!1});for(let a of["path","leftLabel","rightLabel","leftContent","rightContent"])_(e[a],`scenes[${r}].${a}`);e.previousPath!==void 0&&_(e.previousPath,`scenes[${r}].previousPath`),_(e.changeKind,`scenes[${r}].changeKind`),Q(e.additions,`scenes[${r}].additions`),Q(e.deletions,`scenes[${r}].deletions`),e.focusChangeIndex!==void 0&&Q(e.focusChangeIndex,`scenes[${r}].focusChangeIndex`)}function Ei(e,r){if(!Array.isArray(e.stack)||e.stack.length<2||e.stack.length>6)throw new Error(`scenes[${r}].stack must contain between 2 and 6 revisions.`);for(let[i,a]of e.stack.entries()){if(!U(a))throw new Error(`scenes[${r}].stack[${i}] must be an object.`);for(let s of["id","ref","oid","label"])_(a[s],`scenes[${r}].stack[${i}].${s}`)}Sr(e.files,e.stack.length,r),Cr(e.steps,e.stack.length,r,!1)}function Ti(e,r){if(e.stageLabel!=="Explanation stages")throw new Error(`scenes[${r}].stageLabel must be Explanation stages.`);if(!U(e.realRange))throw new Error(`scenes[${r}].realRange must be an object.`);for(let a of["baseRef","targetRef","baseOid","targetOid"])_(e.realRange[a],`scenes[${r}].realRange.${a}`);if(!Array.isArray(e.panels)||e.panels.length<2||e.panels.length>13)throw new Error(`scenes[${r}].panels must contain a baseline and between 1 and 12 stages.`);let i=e.panels;for(let[a,s]of i.entries()){if(!U(s))throw new Error(`scenes[${r}].panels[${a}] must be an object.`);for(let f of["id","label","role"])_(s[f],`scenes[${r}].panels[${a}].${f}`);let c=a===0?"baseline":"stage";if(s.role!==c)throw new Error(`scenes[${r}].panels[${a}].role must be ${c}.`);a>0&&_(s.stageId,`scenes[${r}].panels[${a}].stageId`)}if(Sr(e.files,i.length,r),Cr(e.steps,i.length,r,!0),Array.isArray(e.steps)){let a=-1;e.steps.forEach((s,c)=>{if(!U(s))return;let f=Number(s.pairIndex);if(f<a)throw new Error(`scenes[${r}].steps must remain grouped in explanation stage order.`);if(a=f,s.stageId!==void 0&&_(s.stageId,`scenes[${r}].steps[${c}].stageId`),s.stageIndex!==void 0&&Q(s.stageIndex,`scenes[${r}].steps[${c}].stageIndex`),s.focusIndex!==void 0&&Q(s.focusIndex,`scenes[${r}].steps[${c}].focusIndex`),s.focusCount!==void 0&&ft(s.focusCount,`scenes[${r}].steps[${c}].focusCount`),s.stageIndex!==void 0&&Number(s.stageIndex)!==f)throw new Error(`scenes[${r}].steps[${c}].stageIndex must match pairIndex.`);if(s.focusIndex!==void 0&&s.focusCount!==void 0&&Number(s.focusIndex)>=Number(s.focusCount))throw new Error(`scenes[${r}].steps[${c}].focusIndex must be less than focusCount.`)});for(let s=0;s<i.length-1;s+=1){let c=i[s+1],f=e.steps.filter(v=>U(v)&&Number(v.pairIndex)===s);if(!U(c)||f.length===0)throw new Error(`scenes[${r}].steps must cover every explanation stage.`);let p=f[0],t=U(p)?p.id:void 0;if(f.some(v=>U(v)?(v.stageId??t)!==c.stageId:!0))throw new Error(`scenes[${r}].panels must align with explanation stage ids.`)}}}function Sr(e,r,i){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${i}].files must be non-empty.`);for(let[a,s]of e.entries()){if(!U(s))throw new Error(`scenes[${i}].files[${a}] must be an object.`);if(_(s.path,`scenes[${i}].files[${a}].path`),!Array.isArray(s.panels)||s.panels.length!==r)throw new Error(`scenes[${i}].files[${a}].panels must match panel count.`);for(let[c,f]of s.panels.entries()){if(!U(f))throw new Error(`scenes[${i}].files[${a}].panels[${c}] must be an object.`);for(let p of["id","label","content"])_(f[p],`scenes[${i}].files[${a}].panels[${c}].${p}`);if(f.path!==void 0&&_(f.path,`scenes[${i}].files[${a}].panels[${c}].path`),typeof f.exists!="boolean")throw new Error(`scenes[${i}].files[${a}].panels[${c}].exists must be boolean.`)}}}function Cr(e,r,i,a){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${i}].steps must be non-empty.`);for(let[s,c]of e.entries()){if(!U(c))throw new Error(`scenes[${i}].steps[${s}] must be an object.`);for(let f of["id","title","body","file","side"])_(c[f],`scenes[${i}].steps[${s}].${f}`);if(Q(c.pairIndex,`scenes[${i}].steps[${s}].pairIndex`),Number(c.pairIndex)>=r-1)throw new Error(`scenes[${i}].steps[${s}].pairIndex is outside the panels.`);if(a&&(Ke(c.introducedHunks,`scenes[${i}].steps[${s}].introducedHunks`),c.introducedHunks.length===0))throw new Error(`scenes[${i}].steps[${s}].introducedHunks must be non-empty.`);if(c.side!=="left"&&c.side!=="right")throw new Error(`scenes[${i}].steps[${s}].side must be left or right.`);c.startLine!==void 0&&ft(c.startLine,`scenes[${i}].steps[${s}].startLine`),c.endLine!==void 0&&ft(c.endLine,`scenes[${i}].steps[${s}].endLine`)}}function $i(e,r){if(!U(e))throw new Error(`files[${r}] must be an object.`);if(e.kind==="text-diff"){Ge(e,r,1);return}if(e.kind!=="omitted")throw new Error(`files[${r}].kind must be text-diff or omitted.`);for(let i of["id","title","path","changeKind","reason"])_(e[i],`files[${r}].${i}`);e.previousPath!==void 0&&_(e.previousPath,`files[${r}].previousPath`),Q(e.additions,`files[${r}].additions`),Q(e.deletions,`files[${r}].deletions`)}function Ni(e){let r=new Map;for(let i of e){if(i.kind==="text-diff"){r.has(i.path)||r.set(i.path,i);continue}if(i.kind==="walkthrough")for(let a of i.steps)r.has(a.diff.path)||r.set(a.diff.path,a.diff)}return[...r.values()].sort((i,a)=>i.path.localeCompare(a.path))}function mn(e,r){if(!U(e))throw new Error(`${r} must be an object.`);for(let i of["id","path","revision","excerpt"])_(e[i],`${r}.${i}`);if(e.revision!=="base"&&e.revision!=="head")throw new Error(`${r}.revision must be base or head.`);if(ft(e.startLine,`${r}.startLine`),ft(e.endLine,`${r}.endLine`),Number(e.endLine)<Number(e.startLine))throw new Error(`${r}.endLine must not precede startLine.`)}function Ai(e,r){_(e.summary,`${r}.summary`),Ke(e.bullets,`${r}.bullets`),Ke(e.tags,`${r}.tags`),_(e.takeaway,`${r}.takeaway`)}function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _(e,r){if(typeof e!="string")throw new Error(`${r} must be a string.`)}function Ke(e,r){if(!Array.isArray(e)||e.some(i=>typeof i!="string"))throw new Error(`${r} must be an array of strings.`)}function Q(e,r){if(!Number.isInteger(e)||Number(e)<0)throw new Error(`${r} must be a non-negative integer.`)}function kr(e,r){if(typeof e!="number"||!Number.isFinite(e)||e<0||e>100)throw new Error(`${r} must be a number from 0 to 100.`)}function ft(e,r){if(!Number.isInteger(e)||Number(e)<1)throw new Error(`${r} must be a positive integer.`)}var Li=new Set(["modified-here","created-here","deleted-here"]);function gn(e,r){let i=e.panels[r],a=e.panels[r+1];return!i||!a?"unchanged-here":i.exists&&a.exists?i.content===a.content?"unchanged-here":"modified-here":!i.exists&&a.exists?"created-here":i.exists&&!a.exists?"deleted-here":e.panels.slice(0,r).some(f=>f.exists)?"already-deleted":(e.panels.slice(r+2).some(f=>f.exists),"not-created-yet")}function Er(e,r,i,a){if(a!==-1&&a!==1||!i)return null;let s=e.findIndex(p=>p.path===i);if(s<0)return null;let c=e.map((p,t)=>({file:p,fileIndex:t,state:gn(p,r)})).filter(({state:p})=>Li.has(p)),f=a<0?[...c].reverse().find(({fileIndex:p})=>p<s):c.find(({fileIndex:p})=>p>s);return f?{pairIndex:r,fileIndex:f.fileIndex,path:f.file.path}:null}function yn(e,r,i){let a=e.findIndex(p=>p.id===r),s=a>=0?a:0,c=e[s];if(!c||c.kind!=="walkthrough"&&c.kind!=="stacked-diff"&&c.kind!=="deconstructed-diff"||!i)return{sceneIndex:s,stepIndex:0};let f=c.steps.findIndex(p=>p.id===i);return{sceneIndex:s,stepIndex:f>=0?f:0}}function wn(e,r,i){let a=e[r.sceneIndex];if(!a)return null;if(i>0)return(a.kind==="walkthrough"||a.kind==="stacked-diff"||a.kind==="deconstructed-diff")&&r.stepIndex<a.steps.length-1?{sceneIndex:r.sceneIndex,stepIndex:r.stepIndex+1}:r.sceneIndex<e.length-1?{sceneIndex:r.sceneIndex+1,stepIndex:0}:null;if((a.kind==="walkthrough"||a.kind==="stacked-diff"||a.kind==="deconstructed-diff")&&r.stepIndex>0)return{sceneIndex:r.sceneIndex,stepIndex:r.stepIndex-1};if(r.sceneIndex===0)return null;let s=e[r.sceneIndex-1];return{sceneIndex:r.sceneIndex-1,stepIndex:s.kind==="walkthrough"||s.kind==="stacked-diff"||s.kind==="deconstructed-diff"?s.steps.length-1:0}}function Tr(e,r,i){if(!r)return null;let a=e.map((p,t)=>({file:p,fileIndex:t})).filter(({file:p})=>p.kind==="text-diff"),s=a.findIndex(({file:p})=>p.path===r),c=s+i,f=s>=0?a[c]:null;return f?{fileIndex:f.fileIndex,path:f.file.path}:null}function Nr(e,r,i){let a=e.scenes[r.sceneIndex];if(!a)return null;let s=bn(a)?Math.min(Math.max(r.stepIndex,0),a.steps.length-1):0,c={sceneIndex:r.sceneIndex,stepIndex:s},f=bn(a)?a.steps[s]:void 0,p=[],t=!f||s===0,v=!!(f&&s>0&&i.entry==="playback-start");if(t){let I=e.chapters.find($=>$.sceneIds.includes(a.id));I&&p.push({source:{field:"chapter"},text:I.title})}(t||v)&&p.push({source:{field:"scene-title"},text:a.title}),t&&(p.push({source:{field:"summary"},text:a.summary}),a.bullets.forEach((I,$)=>{p.push({source:{field:"bullet",itemIndex:$},text:I})})),f&&(p.push({source:{field:"step-title"},text:f.title}),p.push({source:{field:"step-body"},text:f.body}),"connection"in f&&f.connection?.label&&p.push({source:{field:"connection"},text:f.connection.label})),(!f||bn(a)&&s===a.steps.length-1)&&p.push({source:{field:"takeaway"},text:a.takeaway});let g=`${a.id}:${f?.id||"scene"}`,m=i.segmentLimit??240,w=p.flatMap(I=>Oi(g,I,m));return{id:g,position:c,segments:w}}function Ri(e,r=240){if(!Number.isInteger(r)||r<40)throw new Error("Narration segment limit must be an integer of at least 40 characters.");return Di(e).flatMap(a=>Mi(e,a.startOffset,a.endOffset,r))}function Pi(e){return e.replace(/https?:\/\/\S+/giu," ").replace(/\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*\d)[0-9a-f]+\b/giu," ").replace(/[`*_~]/gu,"").replace(/([\p{Ll}\d])(\p{Lu})/gu,"$1 $2").replace(/([\p{Lu}])(\p{Lu}\p{Ll})/gu,"$1 $2").replace(/\s+/gu," ").trim()}function Oi(e,r,i){let a=r.source.itemIndex===void 0?r.source.field:`${r.source.field}-${r.source.itemIndex}`;return Ri(r.text,i).map((s,c)=>({id:`${e}:${a}:${c}`,text:s.text,speechText:Pi(s.text),source:r.source,startOffset:s.startOffset,endOffset:s.endOffset})).filter(s=>s.speechText.length>0)}function Di(e){let r=[],i=0;for(let a=0;a<e.length;a+=1){if(!".!?".includes(e[a]))continue;let s=a+1;for(;s<e.length&&`"'\u201D\u2019)]}`.includes(e[s]);)s+=1;s<e.length&&!/\s/u.test(e[s])||(Dt(e,r,i,s),i=s)}return Dt(e,r,i,e.length),r}function Mi(e,r,i,a){let s=[],c=r;for(;i-c>a;){let f=c+a,p=c+Math.floor(a*.55),t=$r(e,p,f,/[;,:—–-]/u);t<=c&&(t=$r(e,p,f,/\s/u)),t<=c&&(t=f),Dt(e,s,c,t),c=t}return Dt(e,s,c,i),s}function $r(e,r,i,a){for(let s=i;s>=r;s-=1)if(a.test(e[s]))return s+1;return-1}function Dt(e,r,i,a){let s=i,c=a;for(;s<c&&/\s/u.test(e[s]);)s+=1;for(;c>s&&/\s/u.test(e[c-1]);)c-=1;s<c&&r.push({text:e.slice(s,c),startOffset:s,endOffset:c})}function bn(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function Ar(e){let r=[{kind:"title",key:"title",sceneIndex:0,stepIndex:0}],i=new Map;for(let s of e.chapters)for(let c of s.sceneIds)i.has(c)||i.set(c,s.id);let a=new Set;return e.scenes.forEach((s,c)=>{let f=i.get(s.id);e.chapters.length>1&&f&&!a.has(f)&&(r.push({kind:"chapter",key:`chapter:${f}`,chapterId:f,sceneIndex:c,stepIndex:0}),a.add(f)),r.push({kind:"scene",key:`scene:${s.id}`,sceneIndex:c,stepIndex:0}),Fi(s)&&s.steps.forEach((p,t)=>{r.push({kind:"step",key:`step:${s.id}:${p.id}`,sceneIndex:c,stepIndex:t})})}),r}function Lr(e,r,i){if(i!==-1&&i!==1)return null;let a=e.findIndex(s=>s.key===r);return a<0?null:e[a+i]??null}function Mt(e,r,i,a=null){if(a==="tour")return e.find(c=>c.kind==="title")??null;let s=e.findIndex(c=>c.kind==="scene"&&c.sceneIndex===r);if(s<0)return null;if(a==="overview")return e[s]??null;if(a==="chapter"){for(let c=s-1;c>=0;c-=1){let f=e[c];if(f.kind==="chapter")return f;if(f.kind==="title")break}return e.find(c=>c.kind==="title")??null}return e.find(c=>c.kind==="step"&&c.sceneIndex===r&&c.stepIndex===i)??e[s]??null}function Fi(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}var Ft=class{constructor(r,i){this.engine=r;this.callbacks=i;this.generation=0;this.continuous=!0;this.currentState={kind:"idle"}}get state(){return this.currentState}get engaged(){return this.currentState.kind==="playing"||this.currentState.kind==="paused"}start(r,i=!0){if(this.resetEngine(),this.continuous=i,r.segments.length===0){this.finishUnit(r);return}this.callbacks.claimAudio(),this.setState({kind:"playing",unit:r,segmentIndex:0}),this.speakCurrent()}togglePause(){if(this.currentState.kind==="playing"){this.engine.pause();let i={kind:"paused",unit:this.currentState.unit,segmentIndex:this.currentState.segmentIndex,pendingStart:!1};this.setState(i),this.callbacks.onSegmentChange(i.unit.segments[i.segmentIndex]||null,!0);return}if(this.currentState.kind!=="paused")return;this.callbacks.claimAudio();let r=this.currentState;this.setState({kind:"playing",unit:r.unit,segmentIndex:r.segmentIndex}),r.pendingStart?this.speakCurrent():(this.engine.resume(),this.callbacks.onSegmentChange(r.unit.segments[r.segmentIndex]||null,!1))}stop(){this.resetEngine(),this.setState({kind:"idle"}),this.callbacks.onSegmentChange(null,!1)}pauseForExternalOwner(){this.currentState.kind==="playing"&&this.togglePause()}canSkipSegment(r){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return!1;let i=this.currentState.segmentIndex+r;return i>=0&&i<this.currentState.unit.segments.length?!0:this.callbacks.canNavigateUnit(this.currentState.unit,r)}skipSegment(r){if(!this.canSkipSegment(r))return!1;let i=this.currentState,a=i.kind==="paused",s=i.unit,c=i.segmentIndex+r;if(c<0||c>=s.segments.length){let f=this.callbacks.navigateUnit(s,r);if(!f||f.segments.length===0)return!1;s=f,c=r<0?s.segments.length-1:0}return this.resetEngine(),a?(this.setState({kind:"paused",unit:s,segmentIndex:c,pendingStart:!0}),this.callbacks.onSegmentChange(s.segments[c]||null,!0)):(this.setState({kind:"playing",unit:s,segmentIndex:c}),this.speakCurrent()),!0}followLinearNavigation(r){this.currentState.kind==="playing"?this.start(r,this.continuous):this.currentState.kind==="paused"&&this.preparePaused(r)}followDirectNavigation(r){this.engaged&&this.preparePaused(r)}interruptForExploration(){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return;let r=this.currentState;this.resetEngine(),this.setState({kind:"paused",unit:r.unit,segmentIndex:r.segmentIndex,pendingStart:!0}),this.callbacks.onSegmentChange(r.unit.segments[r.segmentIndex]||null,!0)}dispose(){this.stop()}preparePaused(r){this.resetEngine(),this.setState({kind:"paused",unit:r,segmentIndex:0,pendingStart:!0}),this.callbacks.onSegmentChange(r.segments[0]||null,!0)}speakCurrent(){if(this.currentState.kind!=="playing")return;let r=this.generation,i=this.currentState.unit.segments[this.currentState.segmentIndex];if(!i){this.finishUnit(this.currentState.unit);return}this.callbacks.onSegmentChange(i,!1),this.engine.speak(i,{onEnd:()=>{if(r!==this.generation||this.currentState.kind!=="playing")return;let a=this.currentState.segmentIndex+1;a<this.currentState.unit.segments.length?(this.setState({kind:"playing",unit:this.currentState.unit,segmentIndex:a}),this.speakCurrent()):this.finishUnit(this.currentState.unit)},onError:a=>{r===this.generation&&(this.setState({kind:"error",message:a}),this.callbacks.onSegmentChange(null,!1))}})}finishUnit(r){if(this.continuous){let i=this.callbacks.navigateUnit(r,1);if(i){if(this.generation+=1,i.segments.length===0){this.finishUnit(i);return}this.setState({kind:"playing",unit:i,segmentIndex:0}),this.speakCurrent();return}}this.setState({kind:"completed"}),this.callbacks.onSegmentChange(null,!1)}resetEngine(){this.generation+=1,this.engine.cancel()}setState(r){this.currentState=r,this.callbacks.onStateChange(r)}};function Pr(e,r,i="all",a=300){let s=r.trim().toLocaleLowerCase();if(!s||a<=0)return[];let c=[];if(i!=="code"){let f=new Map;e.chapters.forEach(p=>p.sceneIds.forEach(t=>f.set(t,p.title))),e.scenes.forEach((p,t)=>{let v=[f.get(p.id),p.title,p.summary,...p.bullets,...p.tags,p.takeaway],g=Rr(v,s);g&&c.push({kind:"narrative",sceneIndex:t,label:p.title,preview:g}),Ui(p)&&p.steps.forEach((m,w)=>{let I=Rr([m.title,m.body,"connection"in m?m.connection?.label:void 0],s);I&&c.push({kind:"narrative",sceneIndex:t,stepIndex:w,label:`${p.title} \xB7 ${m.title}`,preview:I})})})}if(i!=="narrative"&&c.length<a)for(let f=0;f<e.files.length;f+=1){let p=e.files[f];if(p.kind==="text-diff"){for(let[t,v]of[[0,p.leftContent],[1,p.rightContent]])for(let g of Bi(v,s))if(c.push({kind:"code",fileIndex:f,sideIndex:t,label:`${p.path} \xB7 ${t===0?"base":"head"}`,...g}),c.length>=a)return c}}return c.slice(0,a)}function Rr(e,r){return e.find(i=>i?.toLocaleLowerCase().includes(r))}function Bi(e,r){let i=[];return e.replace(/\r\n/g,`
|
|
149
149
|
`).split(`
|
|
150
|
-
`).forEach((i,o)=>{let a=i.toLocaleLowerCase(),l=0;for(;l<=a.length-t.length;){let d=a.indexOf(t,l);if(d<0)break;n.push({lineNumber:o+1,startColumn:d+1,endColumn:d+t.length+1,preview:i}),l=d+Math.max(t.length,1)}}),n}function jr(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function gn(e,t){return Vr(e,0,t)}function Vr(e,t,n){let i=e?.blocks[t],o=n==="left"?e?.leftLines:e?.rightLines;if(!i||!o?.length)return;let a=n==="left"?i.leftStart:i.rightStart,l=n==="left"?i.leftEnd:i.rightEnd,d=o.slice(a,l),p=d[0]?.lineNumber??o[Math.min(a,o.length-1)]?.lineNumber;if(Number.isInteger(p))return{startLine:p,endLine:d.at(-1)?.lineNumber??p}}function mn(e,t,n,i){let o=[];return e.scenes.forEach((a,l)=>{a.kind==="walkthrough"&&a.steps.forEach((d,p)=>{d.diff.path===t&&o.push({side:d.focus.revision==="base"?"left":"right",startLine:d.focus.startLine,endLine:d.focus.endLine,label:`${a.title} \xB7 ${d.title}: ${d.body}`,active:l===n&&p===i,jumpTarget:{sceneIndex:l,stepIndex:p}})})}),o}function pn(e,t,n,i,o){let a=[];return e.scenes.forEach((l,d)=>{d!==n||l.kind!=="stacked-diff"&&l.kind!=="deconstructed-diff"||l.steps.forEach((p,m)=>{if(p.file!==t)return;let f=p.startLine===void 0?o?.(p.pairIndex,p.side):{startLine:p.startLine,endLine:p.endLine??p.startLine};if(!f)return;let s=p.pairIndex+(p.side==="right"?1:0);a.push({pairIndex:p.pairIndex,panelIndex:s,side:p.side,startLine:f.startLine,endLine:f.endLine,label:`${l.title} \xB7 ${p.title}: ${p.body}`,active:d===n&&m===i,jumpTarget:{sceneIndex:d,stepIndex:m}})})}),a}function Kr(e,t=120){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function bn(e,t="Bygone"){let n=e?.windowTitle?.trim()||e?.title?.trim();return n?Kr(n):`${t} Tour`}var He=class{constructor(t){this.mode=t;this.cursors=new Map;this.epoch=0;this.dirty=!1;this.origin=null}navigate(){this.dirty=!0}depart(t){return this.dirty||!this.origin?(this.dirty&&this.epoch++,this.origin=t,this.cursors.set(this.mode,{location:t,epoch:this.epoch})):this.cursors.has(this.mode)||this.cursors.set(this.mode,{location:t,epoch:this.epoch}),this.dirty=!1,this.origin}enter(t,n){let i=this.cursors.get(t);return this.mode=t,this.dirty=!1,i&&(i.epoch===this.epoch||!n)?{location:i.location,restore:!0}:{location:n||{sceneIndex:0,stepIndex:0,path:null},restore:!1}}};function wn(e,t,n){let i=n.find(d=>d.path===e.path||d.previousPath===e.path),o=new Set([e.path,i?.path,i?.previousPath].filter(Boolean)),a=null,l=1/0;return t.forEach((d,p)=>{(d.steps||[{file:d.path}]).forEach((f,s)=>{let x=f.diff?.path||f.file||d.path;if(!o.has(x))return;let T=f.startLine||1,A=f.endLine||T,I=e.line||T,y=Math.max(T-I,I-A,0);y<l&&(l=y,a={sceneIndex:p,stepIndex:s,path:x??null,line:e.line,commit:e.commit})})}),!a&&i?.kind==="text-diff"?{sceneIndex:0,stepIndex:0,path:i.path??null,line:e.line,commit:e.commit}:a}(function(){let t="bygone.tourSidebarWidth",o="bygone.tourNarrativeHeight",d="bygone.tourNarrationVoice",p="bygone.tourNarrationRate",m=new Set([.75,1,1.25,1.5]),f="speechSynthesis"in window&&"SpeechSynthesisUtterance"in window,s={mode:"empty",left:null,right:null,comparisonId:0,tour:null,authoredTour:null,zoom:null,zoomSwitching:!1,historyCommit:null,historyEntries:[],activeSceneIndex:-1,activeStepIndex:0,activeTourFilePath:null,tourFocusFilePath:null,tourSidebarWidth:Nn(),tourSidebarHidden:!1,tourNarrativeHeight:An(),narrationVoiceURI:window.localStorage.getItem(d)||"",narrationRate:yn(),narrationVoices:[],renderedNarrationUnit:null},x=new Be(xn(),{claimAudio:kn,onStateChange:ze,onSegmentChange:Tn,canNavigateUnit:vn,navigateUnit:En});window.__BYGONE_HOST__={environment:"web",editorWorkerUrl:"/media/editor.worker.js",diffWorkerUrl:"/media/diff.worker.js",postMessage(r){ne(r)}},window.addEventListener("DOMContentLoaded",()=>{Ie(),Q("Browser host ready.")});function T(r){window.dispatchEvent(new window.CustomEvent("bygone:host-message",{detail:r}))}let A=0,I=new Map,y=null;function E(){s.zoomSwitching||s.zoom?.navigate()}function k(){return new Promise(r=>{let c=++A,g=h=>{I.delete(c);let b=s.tour?.scenes[s.activeSceneIndex],w=h?.activeMultiPairIndex,v=b&&ie(b)?Xe(b):[],S=h?.editorStates?.[h.activeMultiPanelId||h.activePaneSide];r({sceneIndex:s.activeSceneIndex,stepIndex:s.activeStepIndex,path:s.activeTourFilePath,line:S?.selection?.startLineNumber,commit:s.historyCommit||v[w+1]?.oid||s.authoredTour.range.headOid,navigation:h,focusId:document.activeElement?.id,narrativeScroll:document.getElementById("tour-narrative")?.scrollTop||0})},u=window.setTimeout(()=>g(null),1e3);I.set(c,h=>{window.clearTimeout(u),g(h)}),T({type:"captureNavigationState",requestId:c})})}function N(r){let c=s.authoredTour;if(r===c.zoom.authoredDepth)return c;if(r==="final")return{...c,...c.zoom.final};let g=c.zoom.revisions;return{...c,scenes:g,chapters:[{id:"zoom-revisions",title:"Revisions",sceneIds:g.map(u=>u.id)}]}}function L(){let r=document.getElementById("tour-mode-controls");if(!r||(r.hidden=!s.zoom,!s.zoom))return;let c={explanation:"Explanation stages",revisions:"Revisions",final:"Final diff",history:"Git history"},g=document.getElementById("tour-mode-select");g.replaceChildren(...s.authoredTour.zoom.modes.map(h=>{let b=document.createElement("option");return b.value=h,b.textContent=c[h],b})),g.value=s.zoom.mode;let u=s.zoom.mode==="history";document.getElementById("tour-history-select").hidden=!u,document.getElementById("tour-history-label").hidden=!u,document.body.classList.toggle("tour-derived-mode",s.zoom.mode==="revisions"||s.zoom.mode==="history")}async function F(r,c){let g=await fetch(`/history/${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),u=await g.json();if(!g.ok)throw new Error(u.error||`History request failed (${g.status}).`);return u}async function U(r,c,g=!0){if(g){let b=await F("list",{path:r,commit:c});s.historyEntries=b.entries,c=b.selectedCommit,document.getElementById("tour-mode-status").textContent=b.fallback||"",document.getElementById("tour-history-select").replaceChildren(...b.entries.map(v=>{let S=document.createElement("option");return S.value=v.commit,S.textContent=`${v.shortCommit} ${v.summary}`,S}))}if(!c)throw new Error("No file history is available for this path.");let u=s.historyEntries.find(b=>b.commit===c),h=await F("diff",{path:u?.path||r,commit:c});s.historyCommit=c,document.getElementById("tour-history-select").value=c,fe({...h,kind:"text-diff",takeaway:"",focusChangeIndex:0},[],`history-${c}-${h.path}`)}async function J(r){if(!(!s.zoom||s.zoomSwitching||r===s.zoom.mode)){s.zoomSwitching=!0;try{let c=s.zoom.depart(await k());x.pauseForExternalOwner(),s.tour=N(r);let g=wn(c,s.tour.scenes,s.tour.files),u=s.zoom.enter(r,g);if(pt(),Ee(),L(),document.getElementById("tour-mode-status").textContent=g||u.restore?"":"No corresponding location; showing the first available change.",y=u.restore?u.location:null,r==="history")await U(u.location.path||s.tour.files.find(h=>h.kind==="text-diff")?.path,u.location.commit||c.commit);else{if(s.historyCommit=null,re(Math.max(0,u.location.sceneIndex),u.location.stepIndex,{zoomLanding:!0}),u.location.path&&s.activeTourFilePath!==u.location.path){let h=s.tour.files.findIndex(b=>b.path===u.location.path);h>=0&&Ke(h)}!u.restore&&u.location.line&&T({type:"revealSearchResult",lineNumber:u.location.line})}}catch(c){document.getElementById("tour-mode-status").textContent=c instanceof Error?c.message:String(c)}finally{s.zoomSwitching=!1}}}async function ne(r){if(!(!r||typeof r!="object")){if(r.type==="navigationState"){I.get(r.requestId)?.(r.navigation);return}if(r.type==="renderComplete"&&y){let c=y;y=null,T({type:"restoreNavigationState",navigation:c.navigation});let g=document.getElementById("tour-narrative");g&&(g.scrollTop=c.narrativeScroll||0),c.focusId&&c.focusId!=="tour-mode-select"&&document.getElementById(c.focusId)?.focus({preventScroll:!0})}if(r.type==="ready"){let c=new URLSearchParams(window.location.search),g=c.get("manifest");g?Rn(g):c.get("demo")==="1"&&$t();return}if(r.type==="navigateFile"&&s.mode==="tour"){_n(r.direction==="previous"?-1:1);return}if(r.type==="navigateTourStep"&&s.mode==="tour"){let c=r.sceneIndex,g=r.stepIndex;Number.isInteger(c)&&Number.isInteger(g)&&re(c,g,{userNavigation:!0});return}r.type==="recomputeDiff"&&s.mode==="diff"&&s.left&&s.right&&(s.left.content=r.leftContent,s.right.content=r.rightContent,T({type:"showDiff",file1:s.left.name,file2:s.right.name,comparisonId:`web-${s.comparisonId}`,leftContent:s.left.content,rightContent:s.right.content,diffModel:ae(s.left.content,s.right.content),history:null}))}}function Ie(){document.getElementById("tour-mode-select")?.addEventListener("change",C=>{J(C.target.value)}),document.getElementById("tour-history-select")?.addEventListener("change",C=>{E(),U(s.activeTourFilePath,C.target.value,!1).catch($=>{document.getElementById("tour-mode-status").textContent=$.message})});for(let C of["wheel","pointerdown","keydown"])document.addEventListener(C,$=>{!$.isTrusted||$.target?.closest?.("#tour-mode-controls")||$.target?.closest?.(".monaco-editor, .diff-toolbar, #tour-narrative")&&E()},{capture:!0,passive:!0});let r=document.getElementById("web-compare-test"),c=document.getElementById("web-open-diff"),g=document.getElementById("web-open-diff3"),u=document.getElementById("web-diff-input"),h=document.getElementById("web-diff3-input"),b=document.getElementById("tour-previous"),w=document.getElementById("tour-next"),v=document.getElementById("tour-return-focus"),S=document.getElementById("tour-search-input"),O=document.getElementById("tour-search-scope"),D=document.getElementById("tour-listen"),j=document.getElementById("tour-stop"),q=document.getElementById("tour-narration-skip-back"),B=document.getElementById("tour-narration-skip-ahead"),z=document.getElementById("tour-narration-voice"),H=document.getElementById("tour-narration-rate");$n(),Ln(),ve(),r?.addEventListener("click",()=>{$t()}),c?.addEventListener("click",()=>{u.value="",u.click()}),g?.addEventListener("click",()=>{h.value="",h.click()}),u?.addEventListener("change",async()=>{let C=Array.from(u.files||[]);if(C.length!==2){Q("Select exactly 2 files for a diff.");return}await zn(C)}),h?.addEventListener("change",async()=>{let C=Array.from(h.files||[]);if(C.length<1){Q("Select one or more files.");return}await Wn(C)}),b?.addEventListener("click",()=>Ce(-1)),w?.addEventListener("click",()=>Ce(1)),v?.addEventListener("click",On),S?.addEventListener("input",Ee),O?.addEventListener("change",Ee),D?.addEventListener("click",lt),j?.addEventListener("click",()=>x.stop()),q?.addEventListener("click",()=>x.skipSegment(-1)),B?.addEventListener("click",()=>x.skipSegment(1)),z?.addEventListener("change",()=>{s.narrationVoiceURI=z.value,window.localStorage.setItem(d,s.narrationVoiceURI)}),H&&(H.value=String(s.narrationRate),H.addEventListener("change",()=>{let C=Number(H.value);s.narrationRate=m.has(C)?C:1,H.value=String(s.narrationRate),window.localStorage.setItem(p,String(s.narrationRate))})),document.getElementById("tour-search-results")?.addEventListener("click",C=>{let $=C.target instanceof Element?C.target.closest("[data-tour-search-result]"):null;$&&Cn(Number($.getAttribute("data-tour-search-result")))}),window.addEventListener("keydown",C=>{if(s.mode==="tour"&&(C.metaKey||C.ctrlKey)&&C.shiftKey&&C.key.toLocaleLowerCase()==="f"){C.preventDefault(),C.stopImmediatePropagation(),s.tourSidebarHidden&&Ge(!1),S?.focus(),S?.select();return}s.mode!=="tour"||C.metaKey||C.ctrlKey||C.altKey||Un(C.target)||(C.key==="PageUp"||C.key==="ArrowLeft"?(C.preventDefault(),Ce(-1)):(C.key==="PageDown"||C.key==="ArrowRight")&&(C.preventDefault(),Ce(1)))},!0),window.addEventListener("bygone:tour-command",C=>{C.detail==="toggleNarration"&<(),C.detail==="pauseNarration"&&x.pauseForExternalOwner()}),window.addEventListener("beforeunload",()=>x.dispose(),{once:!0}),ze(x.state)}function ve(){let r=document.getElementById("tour-narration-voice"),c=document.getElementById("tour-listen");if(!f){c&&(c.disabled=!0,c.title="Device narration is not supported by this browser."),r&&(r.disabled=!0),le("Device narration unavailable");return}let g=()=>{if(s.narrationVoices=window.speechSynthesis.getVoices().slice().sort((u,h)=>Number(h.default)-Number(u.default)||u.lang.localeCompare(h.lang)||u.name.localeCompare(h.name)),s.narrationVoiceURI&&s.narrationVoices.length>0&&!s.narrationVoices.some(u=>u.voiceURI===s.narrationVoiceURI)&&(s.narrationVoiceURI="",window.localStorage.removeItem(d)),r){let u=document.createElement("option");u.value="",u.textContent="System default voice",r.replaceChildren(u,...s.narrationVoices.map(h=>{let b=document.createElement("option");return b.value=h.voiceURI,b.textContent=`${h.name} (${h.lang})${h.default?" \u2014 default":""}`,b})),r.value=s.narrationVoiceURI,r.disabled=s.narrationVoices.length===0}};g(),window.speechSynthesis.addEventListener("voiceschanged",g)}function yn(){let r=Number(window.localStorage.getItem(p));return m.has(r)?r:1}function xn(){let r=null;return{speak(c,g){if(!f){g.onError("Device narration is not supported by this browser.");return}let u=new window.SpeechSynthesisUtterance(c.speechText),h=s.narrationVoices.find(b=>b.voiceURI===s.narrationVoiceURI);h&&(u.voice=h),u.rate=s.narrationRate,u.onend=()=>{r===u&&(r=null),g.onEnd()},u.onerror=b=>{r===u&&(r=null),g.onError(Sn(b.error))},r=u,window.speechSynthesis.speak(u)},pause(){f&&window.speechSynthesis.pause()},resume(){f&&window.speechSynthesis.resume()},cancel(){r=null,f&&window.speechSynthesis.cancel()}}}function Sn(r){return r==="not-allowed"?"Device narration needs permission to play audio.":r==="language-unavailable"||r==="voice-unavailable"?"The selected device voice is unavailable.":`Device narration failed${r?`: ${r}`:"."}`}function In(){if(!f||s.mode!=="tour")return;let r=dt("playback-start");r&&(s.renderedNarrationUnit=r,Bn(r),x.start(r,!0))}function lt(){x.state.kind==="playing"||x.state.kind==="paused"?x.togglePause():In()}function dt(r){return!s.tour||s.activeSceneIndex<0?null:dn(s.tour,{sceneIndex:s.activeSceneIndex,stepIndex:s.activeStepIndex},{entry:r})}function vn(r,c){let g=s.tour;return!!(g&&Pe(g.scenes,r.position,c))}function En(r,c){let g=s.tour;if(!g)return null;let u=Pe(g.scenes,r.position,c);return u?re(u.sceneIndex,u.stepIndex,{narrationNavigation:"controller",narrationEntry:"continuous"}):null}function kn(){fetch("/narration/claim",{method:"POST",cache:"no-store"}).catch(()=>{})}function ze(r){let c=document.getElementById("tour-listen"),g=document.getElementById("tour-stop"),u=document.getElementById("tour-narration-skip-back"),h=document.getElementById("tour-narration-skip-ahead");if(c){c.disabled=!f||s.mode!=="tour";let b=r.kind==="playing";c.querySelector(".tour-play-pause-icon")?.setAttribute("d",b?"M7 5h4v14H7zM13 5h4v14h-4z":"m8 5 11 7-11 7Z");let w=b?"Pause narration":r.kind==="paused"?"Resume narration":"Listen from the current tour item";c.title=w,c.setAttribute("aria-label",w)}if(g&&(g.disabled=r.kind!=="playing"&&r.kind!=="paused"),u&&(u.disabled=!x.canSkipSegment(-1)),h&&(h.disabled=!x.canSkipSegment(1)),r.kind==="playing"||r.kind==="paused"){let b=r.segmentIndex+1,w=r.unit.segments.length;le(`${r.kind==="paused"?"Paused":"Speaking"} \xB7 segment ${b} of ${w}`)}else r.kind==="completed"?le("Narration complete"):r.kind==="error"?le(r.message):f&&le("Device voice ready")}function le(r){let c=document.getElementById("tour-narration-status");c&&(c.textContent=r)}function Tn(r,c){if(document.querySelectorAll(".tour-narration-segment.is-speaking").forEach(w=>{w.classList.remove("is-speaking","is-paused")}),!r)return;let g=[...document.querySelectorAll("[data-narration-segment-id]")].find(w=>w.dataset.narrationSegmentId===r.id);if(!g)return;g.classList.add("is-speaking"),g.classList.toggle("is-paused",c);let u=document.getElementById("tour-narrative");if(!u)return;let h=g.getBoundingClientRect(),b=u.getBoundingClientRect();(h.top<b.top||h.bottom>b.bottom)&&g.scrollIntoView({block:"nearest"})}let de=[];function Ee(){let r=document.getElementById("tour-search-input"),c=document.getElementById("tour-search-scope"),g=document.getElementById("tour-search-status"),u=document.getElementById("tour-search-results");if(!(!s.tour||!r||!c||!g||!u)){if(de=hn(s.tour,r.value,c.value),!r.value.trim()){g.textContent="Cmd/Ctrl+Shift+F",u.replaceChildren();return}g.textContent=`${de.length} result${de.length===1?"":"s"}`,u.replaceChildren(...de.map((h,b)=>{let w=document.createElement("button");w.type="button",w.className="tour-search-result",w.setAttribute("role","option"),w.dataset.tourSearchResult=String(b),w.title=`Open ${h.kind==="code"?`${h.label}:${h.lineNumber}`:h.label}`;let v=document.createElement("span");v.className="tour-search-location",v.textContent=h.kind==="code"?`${h.label}:${h.lineNumber}`:h.label;let S=document.createElement("span");return S.className="tour-search-preview",S.textContent=h.preview.trim(),w.append(v,S),w}))}}function Cn(r){let c=de[r];if(c){if(c.kind==="narrative"){E(),re(c.sceneIndex,c.stepIndex??0);return}St(c.fileIndex)&&window.requestAnimationFrame(()=>T({type:"revealSearchResult",sideIndex:c.sideIndex,lineNumber:c.lineNumber,startColumn:c.startColumn,endColumn:c.endColumn}))}}function $n(){let r=document.getElementById("tour-shell"),c=document.getElementById("tour-sidebar-resizer"),g=document.getElementById("tour-sidebar-hide"),u=document.getElementById("tour-sidebar-show");!r||!c||!g||!u||(ht(),g.addEventListener("click",()=>Ge(!0)),u.addEventListener("click",()=>Ge(!1)),c.addEventListener("pointerdown",h=>{h.preventDefault(),document.body.classList.add("is-resizing-tour-sidebar"),c.setPointerCapture?.(h.pointerId);let b=v=>ft(v.clientX),w=()=>{document.body.classList.remove("is-resizing-tour-sidebar"),window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",w),window.removeEventListener("pointercancel",w),window.localStorage.setItem(t,String(s.tourSidebarWidth))};window.addEventListener("pointermove",b),window.addEventListener("pointerup",w),window.addEventListener("pointercancel",w)}),c.addEventListener("keydown",h=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(h.key))return;h.preventDefault();let b=s.tourSidebarWidth;h.key==="Home"?b=240:h.key==="End"?b=We():b+=h.key==="ArrowLeft"?-16:16,ft(b),window.localStorage.setItem(t,String(s.tourSidebarWidth))}))}function Nn(){let r=Number.parseInt(window.localStorage.getItem(t)||"",10);return Number.isFinite(r)?Math.min(600,Math.max(240,r)):360}function We(){return Math.max(240,Math.min(600,Math.floor(window.innerWidth*.6)))}function ft(r){s.tourSidebarWidth=Math.min(We(),Math.max(240,Math.round(r))),ht(),window.dispatchEvent(new Event("resize"))}function ht(){document.documentElement.style.setProperty("--tour-rail-width",`${s.tourSidebarWidth}px`);let r=document.getElementById("tour-sidebar-resizer");r?.setAttribute("aria-valuemax",String(We())),r?.setAttribute("aria-valuenow",String(s.tourSidebarWidth))}function Ge(r){s.tourSidebarHidden=r,document.body.classList.toggle("tour-sidebar-hidden",r);let c=document.getElementById("tour-sidebar-show");c&&(c.hidden=!r),window.dispatchEvent(new Event("resize"))}function Ln(){let r=document.getElementById("tour-narrative-resizer");r&&(qe(),r.addEventListener("pointerdown",c=>{c.preventDefault(),document.body.classList.add("is-resizing-tour-narrative"),r.setPointerCapture?.(c.pointerId),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-start"));let g=document.getElementById("tour-narrative")?.getBoundingClientRect().top||0,u=b=>gt(b.clientY-g),h=()=>{document.body.classList.remove("is-resizing-tour-narrative"),window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",h),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-end")),mt()};window.addEventListener("pointermove",u),window.addEventListener("pointerup",h),window.addEventListener("pointercancel",h)}),r.addEventListener("keydown",c=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(c.key))return;c.preventDefault();let g=c.key==="Home"?180:c.key==="End"?ke():s.tourNarrativeHeight+(c.key==="ArrowUp"?-16:16);gt(g),mt()}),window.addEventListener("resize",()=>{s.tourNarrativeHeight=Math.min(ke(),s.tourNarrativeHeight),qe()}))}function An(){let r=Number.parseInt(window.localStorage.getItem(o)||"",10);if(Number.isFinite(r))return Math.max(180,r);let c=Number.parseInt(window.getComputedStyle(document.documentElement).getPropertyValue("--tour-narrative-height"),10);return Number.isFinite(c)?c:296}function ke(){let r=document.getElementById("tour-narrative")?.getBoundingClientRect().top||0;return Math.max(180,window.innerHeight-r-180)}function gt(r){s.tourNarrativeHeight=Math.min(ke(),Math.max(180,Math.round(r))),qe(),window.dispatchEvent(new Event("resize"))}function qe(){document.documentElement.style.setProperty("--tour-narrative-height",`${s.tourNarrativeHeight}px`);let r=document.getElementById("tour-narrative-resizer");r?.setAttribute("aria-valuemax",String(ke())),r?.setAttribute("aria-valuenow",String(s.tourNarrativeHeight))}function mt(){window.localStorage.setItem(o,String(s.tourNarrativeHeight))}async function Rn(r){Q("Loading change tour\u2026");try{x.stop();let c=await fetch(r,{cache:"no-store"});if(!c.ok)throw new Error(`Manifest request failed (${c.status}).`);s.tour=rn(await c.json()),s.authoredTour=s.tour,s.zoom=s.tour.version===2?new He(s.tour.zoom.authoredDepth):null,s.mode="tour",document.body.classList.add("tour-mode"),pt(),L(),Ee();let g=new URLSearchParams(window.location.search),u=cn(s.tour.scenes,g.get("scene"),g.get("step"));re(u.sceneIndex,u.stepIndex),ze(x.state),Q("")}catch(c){Q(`Could not load change tour: ${c instanceof Error?c.message:String(c)}`)}}function pt(){let r=s.tour;if(!r)return;let c=document.getElementById("tour-shell"),g=document.getElementById("tour-title"),u=document.getElementById("tour-source"),h=document.getElementById("tour-range"),b=document.getElementById("tour-stats"),w=document.getElementById("tour-authoring-coverage"),v=document.getElementById("tour-scenes"),S=document.getElementById("tour-scene-count"),O=document.getElementById("tour-files"),D=document.getElementById("tour-file-count"),j=document.getElementById("tour-commits"),q=document.getElementById("tour-commits-summary");if(!c||!g||!u||!h||!b||!w||!v||!S||!O||!D||!j||!q)throw new Error("Presenter UI is incomplete.");c.hidden=!1,g.textContent=r.title,document.title=bn(r),r.sourceUrl?(u.href=r.sourceUrl,u.hidden=!1):(u.removeAttribute("href"),u.hidden=!0);let B=Ne(r.range.baseRef),z=Ne(r.range.headRef),H=r.range.headOid.slice(0,7);h.textContent=`${B} \u2192 ${z}${z===H?"":` \xB7 ${H}`}`,b.textContent=`${ce(r.summary.changedFiles,"file")} \xB7 +${r.summary.additions} \u2212${r.summary.deletions} \xB7 ${ce(r.summary.commitCount,"commit")}`,Mn(w,r.authoringCoverage),S.textContent=String(r.scenes.length),D.textContent=String(r.files.length),q.textContent=ce(r.summary.commitCount,"commit"),v.replaceChildren();let C=new Map(r.scenes.map($=>[$.id,$]));for(let $ of r.chapters){let K=document.createElement("h2");K.className="tour-chapter-title",K.textContent=$.title,v.append(K);for(let _ of $.sceneIds){let P=C.get(_);if(!P)continue;let V=r.scenes.indexOf(P),W=document.createElement("button");W.type="button",W.className="tour-scene",W.dataset.sceneId=P.id,P.kind==="text-diff"&&(W.dataset.filePath=P.path),W.title=`Open scene: ${P.kind==="text-diff"?P.path:P.title}`,W.addEventListener("click",()=>re(V,0,{userNavigation:!0}));let oe=document.createElement("span");oe.className="tour-scene-number",oe.textContent=String(V+1).padStart(2,"0");let Ye=document.createElement("span");Ye.className="tour-scene-copy";for(let[Gn,qn]of[["tour-scene-title",P.title],["tour-scene-path",P.kind==="text-diff"?P.path:P.kind==="deconstructed-diff"?`${ce(P.panels.length-1,"comparison stage")} \xB7 ${ce(P.steps.length,"tour slide")}`:ge(P)?ce(P.steps.length,"code step"):"Discussion"],["tour-scene-note",P.takeaway]]){let Je=document.createElement("span");Je.className=Gn,Je.textContent=qn,Ye.append(Je)}W.append(oe,Ye),v.append(W)}}O.replaceChildren(...r.files.map(($,K)=>{let _=document.createElement("button");_.type="button",_.className=`tour-file${$.kind==="omitted"?" is-omitted":""}`,_.dataset.filePath=$.path,_.disabled=$.kind==="omitted",_.title=$.kind==="omitted"?`${$.path}: ${$.reason}`:`Open file: ${$.path}`,$.kind==="text-diff"&&_.addEventListener("click",()=>Ke(K));let P=document.createElement("span");P.className="tour-file-marker",P.textContent=$.kind==="omitted"?"\xD7":It($.changeKind);let V=document.createElement("span");V.className="tour-file-copy";let W=document.createElement("span");W.className="tour-file-path",W.textContent=$.path;let oe=document.createElement("span");return oe.className="tour-file-meta",oe.textContent=$.kind==="omitted"?`Not rendered \xB7 ${$.reason}`:`${vt($.changeKind)} \xB7 +${$.additions} \u2212${$.deletions}`,V.append(W,oe),_.append(P,V),_})),j.replaceChildren(...r.commits.map($=>{let K=document.createElement("li"),_=document.createElement("span");return _.className="tour-commit-oid",_.textContent=$.shortOid,K.append(_,document.createTextNode($.summary)),K}))}function Mn(r,c){if(r.replaceChildren(),r.hidden=!c,!c)return;let g=[{metric:"walkthrough",label:c.walkthrough.scope==="final"?"Final walkthrough":"Walkthrough",covered:c.walkthrough.coveredUnits,total:c.walkthrough.includedUnits,percent:c.walkthrough.coveragePercent,description:"Distinct change hunks referenced by authored focus anchors."},...c.explanationAssignments.map(u=>({metric:"assignment",label:c.explanationAssignments.length>1?`Explanation assignment \xB7 ${u.sceneId}`:"Explanation assignment",covered:u.completeUnits,total:u.totalUnits,percent:u.assignmentPercent,description:`${u.assignedUnits} assigned, ${u.excludedUnits} explicitly excluded.`}))];for(let u of g){let h=document.createElement("div");h.className="tour-coverage-item",h.dataset.metric=u.metric,h.title=u.description;let b=document.createElement("div");b.className="tour-coverage-heading";let w=document.createElement("span");w.textContent=u.label;let v=document.createElement("strong");v.textContent=`${u.covered}/${u.total} \xB7 ${u.percent}%`,b.append(w,v);let S=document.createElement("div");S.className="tour-coverage-meter",S.setAttribute("role","progressbar"),S.setAttribute("aria-label",u.label),S.setAttribute("aria-valuemin","0"),S.setAttribute("aria-valuemax","100"),S.setAttribute("aria-valuenow",String(u.percent));let O=document.createElement("span");O.style.width=`${u.percent}%`,S.append(O),h.append(b,S),r.append(h)}}function re(r,c=0,g={}){let u=s.tour;if(!u||r<0||r>=u.scenes.length)return null;if(g.userNavigation&&E(),s.zoom?.mode==="history"&&!s.zoomSwitching){let S=u.scenes[r],O=S.path||S.steps?.[c]?.file||s.activeTourFilePath;return U(O,s.historyCommit).catch(D=>{document.getElementById("tour-mode-status").textContent=D.message}),null}let h=u.scenes[r];s.activeSceneIndex=r,s.activeStepIndex=ge(h)?Math.min(Math.max(c,0),Math.max(h.steps.length-1,0)):0,s.tourFocusFilePath=h.kind==="text-diff"?h.path:h.kind==="walkthrough"?h.steps[s.activeStepIndex]?.diff.path??null:ie(h)?h.steps[s.activeStepIndex]?.file??null:null;let b=Et(u,r);document.querySelectorAll(".tour-scene").forEach(S=>{S.classList.toggle("is-active",S.dataset.sceneId===h.id)}),document.querySelector(`.tour-scene[data-scene-id="${h.id}"]`)?.scrollIntoView({block:"nearest"});let w=dt(g.narrationEntry||"playback-start");s.renderedNarrationUnit=w,Tt(h,b,w),w&&!g.zoomLanding&&(!s.zoom||s.zoom.mode===s.authoredTour.zoom.authoredDepth||s.zoom.mode==="final")&&(g.narrationNavigation==="linear"?x.followLinearNavigation(w):g.narrationNavigation!=="controller"&&x.followDirectNavigation(w));let v=new URLSearchParams(window.location.search);return v.set("scene",h.id),ge(h)?v.set("step",h.steps[s.activeStepIndex].id):v.delete("step"),window.history.replaceState(null,"",`${window.location.pathname}?${v.toString()}`),h.kind==="discussion"?(document.body.classList.add("tour-discussion"),Ze(),w):(document.body.classList.remove("tour-discussion"),h.kind==="walkthrough"?(wt(h),w):ie(h)?(yt(h),w):(fe(h,Te(h.path)),w))}function Te(r){let c=s.tour;return!c||!r?[]:mn(c,r,s.activeSceneIndex,s.activeStepIndex)}function Fn(r,c){let g=s.tour;return!g||!r?[]:pn(g,r,s.activeSceneIndex,s.activeStepIndex,(u,h)=>gn(c?.[u]?.diffModel,h))}function je(r){return`file::${r}`}function fe(r,c=[],g=je(r.path)){if(!s.tour)return;s.activeTourFilePath=r.path,Ze();let h=ae(r.leftContent,r.rightContent),b=bt(r,r.leftLabel,"base"),w=bt(r,r.rightLabel,"head"),v=c.find(S=>S.active);T({type:"showDiff",file1:b,file2:w,comparisonId:`tour-${g}`,leftContent:r.leftContent,rightContent:r.rightContent,sourceInfo:{leftPath:r.path,rightPath:r.path},diffModel:h,history:null,fileNavigation:{canGoPrevious:!!he(-1),canGoNext:!!he(1)},editableSides:{left:!1,right:!1},comparisonSummary:`${r.path} \xB7 ${r.takeaway}`,initialChangeIndex:v?kt(h,v.side,v.startLine):r.focusChangeIndex,tourAnnotations:c})}function bt(r,c,g){let u=c.startsWith(r.path)?c.slice(r.path.length).trim():c.trim();return u?`${g} ${u}`:g}function wt(r){let c=r.steps[s.activeStepIndex];c&&fe(c.diff,Te(c.diff.path),je(c.diff.path))}function yt(r){let c=r.steps[s.activeStepIndex];c&&xt(r,c.file,c)}function xt(r,c,g){let u=$e(r,c);if(!g||!u)return;s.activeTourFilePath=u.path,Ze();let h=u.panels.map((B,z)=>({id:`${r.id}-${u.path}-${B.id}`,label:B.label,path:B.path||u.path,content:B.content,savedContent:B.content,dirty:!1,editable:!1,stackId:Xe(r)[z].id})),b=h.slice(0,-1).map((B,z)=>({leftIndex:z,rightIndex:z+1,diffModel:ae(B.content,h[z+1].content)})),w=Fn(u.path,b),v=w.find(B=>B.active),S=v?.pairIndex??g.pairIndex,O=v?.side??g.side,D=v?.startLine??g.startLine,j=b[S]?.diffModel,q=j&&D?kt(j,O,D):0;T({type:"showMultiDiff",panels:h,pairs:b,activePanelId:h[S+(O==="right"?1:0)]?.id,activePairIndex:S,initialChangeIndex:q,revealFirstChangeInEachPanel:r.kind==="deconstructed-diff",history:null,fileNavigation:{canGoPrevious:!!he(-1),canGoNext:!!he(1)},mutationEnabled:!1,comparisonSummary:r.kind==="deconstructed-diff"?`${r.stageLabel} \xB7 ${u.path} \xB7 ${Ne(r.realRange.baseRef)} \u2192 ${Ne(r.realRange.targetRef)}`:`${u.path} \xB7 ${r.takeaway}`,tourAnnotations:w})}function Ve(r){let c=s.tour;return!c||r!==-1&&r!==1?null:Pe(c.scenes,{sceneIndex:s.activeSceneIndex,stepIndex:s.activeStepIndex},r)}function Ce(r){let c=Ve(r);return c?(re(c.sceneIndex,c.stepIndex,{userNavigation:!0,narrationNavigation:"linear",narrationEntry:"playback-start"}),!0):!1}function he(r){let c=s.tour;if(!c||r!==-1&&r!==1)return null;let g=c.scenes[s.activeSceneIndex];if(ie(g)){let u=g.steps[s.activeStepIndex]?.pairIndex;if(!Number.isInteger(u))return null;let h=c.files.flatMap(v=>{if(v.kind!=="text-diff")return[];let S=$e(g,v.path);return S?[S]:[]}),b=an(h,u,s.activeTourFilePath,r);if(!b)return null;let w=c.files.findIndex(v=>v.kind==="text-diff"&&v.path===b.path);return w>=0?{fileIndex:w,path:b.path}:null}return un(c.files,s.activeTourFilePath,r)}function _n(r){let c=he(r);return c?Ke(c.fileIndex):!1}function St(r,c=!0){let g=s.tour?.files[r];return!g||g.kind!=="text-diff"?!1:(c&&x.interruptForExploration(),fe(g,Te(g.path),je(g.path)),!0)}function Ke(r){let c=s.tour?.files[r];if(!c||c.kind!=="text-diff")return!1;if(E(),s.zoom?.mode==="history")return U(c.path,s.historyCommit).catch(u=>{document.getElementById("tour-mode-status").textContent=u.message}),!0;s.zoomSwitching||x.interruptForExploration();let g=s.tour?.scenes[s.activeSceneIndex];if(ie(g)){let u=g.steps[s.activeStepIndex];return u&&$e(g,c.path)?(xt(g,c.path,u),!0):!1}return St(r,!1)}function $e(r,c){let g=r?.files?.find(b=>b.path===c);if(g||r?.kind!=="deconstructed-diff")return g;let u=s.tour?.files.find(b=>b.kind==="text-diff"&&b.path===c);if(!u||u.kind!=="text-diff")return null;let h=u.changeKind!=="deleted";return{path:u.path,panels:Xe(r).map(b=>({id:b.id,label:`${b.label} / ${u.path}${h?"":" (absent)"}`,path:h?u.path:void 0,content:h?u.rightContent:"",exists:h}))}}function On(){let r=s.tour?.scenes[s.activeSceneIndex];if(!r||!s.tourFocusFilePath)return!1;if(r.kind==="walkthrough")wt(r);else if(ie(r))yt(r);else if(r.kind==="text-diff")fe(r,Te(r.path));else return!1;return!0}function Ze(){let r=s.tour?.scenes[s.activeSceneIndex],c=ie(r)?r.steps[s.activeStepIndex]:null;document.querySelectorAll(".tour-file").forEach(u=>{let h=u.dataset.filePath;u.classList.toggle("is-active",h===s.activeTourFilePath),u.classList.toggle("is-tour-focus",h===s.tourFocusFilePath),u.classList.remove("is-comparison-changed","is-comparison-empty"),delete u.dataset.comparisonState;let b=s.tour?.files.find(S=>S.path===h),w=u.querySelector(".tour-file-marker"),v=u.querySelector(".tour-file-meta");if(c&&b?.kind==="text-diff"){let S=$e(r,h);if(S){let O=ct(S,c.pairIndex),D=Dn(O);u.dataset.comparisonState=O,u.classList.add(D.changed?"is-comparison-changed":"is-comparison-empty"),u.setAttribute("title",`${b.path} \xB7 ${D.label}`),u.setAttribute("aria-label",`${b.path}, ${D.label}`),w&&(w.textContent=D.marker),v&&(v.textContent=D.label);return}}if(b){let S=b.kind==="omitted"?`${b.path}: ${b.reason}`:`Open file: ${b.path}`;u.setAttribute("title",S),u.setAttribute("aria-label",S),w&&(w.textContent=b.kind==="omitted"?"\xD7":It(b.changeKind)),v&&(v.textContent=b.kind==="omitted"?`Not rendered \xB7 ${b.reason}`:`${vt(b.changeKind)} \xB7 +${b.additions} \u2212${b.deletions}`)}}),document.querySelector(".tour-file.is-active")?.scrollIntoView({block:"nearest"});let g=document.getElementById("tour-return-focus");if(g){let u=!s.zoom||s.zoom.mode===s.authoredTour.zoom.authoredDepth||s.zoom.mode==="final";g.hidden=!u||!s.tourFocusFilePath||s.activeTourFilePath===s.tourFocusFilePath}}function Dn(r){return{"modified-here":{label:"Modified here",marker:"\u2022",changed:!0},"created-here":{label:"Created here",marker:"+",changed:!0},"deleted-here":{label:"Deleted here",marker:"\u2212",changed:!0},"unchanged-here":{label:"Unchanged here",marker:"\u25CB",changed:!1},"not-created-yet":{label:"Not created yet",marker:"\u2026",changed:!1},"already-deleted":{label:"Already deleted",marker:"\xD7",changed:!1}}[r]}function ge(r){return r.kind==="walkthrough"||r.kind==="stacked-diff"||r.kind==="deconstructed-diff"}function ie(r){return r?.kind==="stacked-diff"||r?.kind==="deconstructed-diff"}function Xe(r){return r.kind==="deconstructed-diff"?r.panels:r.stack}function It(r){return{added:"+",deleted:"\u2212",renamed:"\u2192",modified:"\u2022"}[r]||"\u2022"}function vt(r){return`${r.charAt(0).toUpperCase()}${r.slice(1)}`}function Et(r,c){let g=r.scenes[c],u=r.chapters.findIndex(v=>v.sceneIds.includes(g.id)),h=u>=0?r.chapters[u]:null,b=h?h.sceneIds.indexOf(g.id)+1:c+1,w=h?h.sceneIds.length:r.scenes.length;return{chapter:h,chapterIndex:u,chapterNumber:u>=0?u+1:c+1,sceneInChapter:b,scenesInChapter:w}}function Pn(r,c,g){let u=[`Ch ${r.chapterNumber}`,`Scene ${r.sceneInChapter}/${r.scenesInChapter}`];return ge(c)&&u.push(`Step ${g+1}/${c.steps.length}`),u.join(" \xB7 ")}function kt(r,c,g){let h=(c==="left"?r.leftLines:r.rightLines).findIndex(D=>D.lineNumber===g);if(h<0)return 0;let b=c==="left"?"leftStart":"rightStart",w=c==="left"?"leftEnd":"rightEnd",v=r.blocks.findIndex(D=>h>=D[b]&&h<D[w]);if(v>=0)return v;let S=0,O=Number.POSITIVE_INFINITY;return r.blocks.forEach((D,j)=>{let q=Math.min(Math.abs(h-D[b]),Math.abs(h-D[w]));q<O&&(S=j,O=q)}),S}function Ne(r){return/^[0-9a-f]{40}$/i.test(r)?r.slice(0,7):r}function ce(r,c){return`${r} ${r===1?c:`${c}s`}`}function Un(r){return r instanceof Element&&!!r.closest('a, button, input, select, summary, textarea, [contenteditable="true"], [role="textbox"], .monaco-editor')}function Bn(r){let c=s.tour?.scenes[s.activeSceneIndex];!s.tour||!c||Tt(c,Et(s.tour,s.activeSceneIndex),r)}function Tt(r,c,g){let u=document.getElementById("tour-narrative"),h=document.getElementById("tour-breadcrumb"),b=document.getElementById("tour-narrative-chapter"),w=document.getElementById("tour-narrative-title"),v=document.getElementById("tour-narrative-summary"),S=document.getElementById("tour-narrative-bullets"),O=document.getElementById("tour-narrative-tags"),D=document.getElementById("tour-narrative-takeaway"),j=document.getElementById("tour-step"),q=document.getElementById("tour-step-title"),B=document.getElementById("tour-step-body"),z=document.getElementById("tour-step-requirement"),H=document.getElementById("tour-connection"),C=document.getElementById("tour-previous"),$=document.getElementById("tour-next");if(!u||!h||!b||!w||!v||!S||!O||!D||!j||!q||!B||!z||!H||!C||!$)throw new Error("Tour narrative UI is incomplete.");u.hidden=!1,h.textContent=Pn(c,r,s.activeStepIndex);let K=c.chapter?.title||"Change tour";te(b,K,{field:"chapter"},g,{suffix:r.kind==="deconstructed-diff"?` \xB7 ${r.stageLabel}`:""}),te(w,r.title,{field:"scene-title"},g),te(v,r.summary,{field:"summary"},g),S.replaceChildren(...r.bullets.map((P,V)=>{let W=document.createElement("li");return te(W,P,{field:"bullet",itemIndex:V},g),W})),O.replaceChildren(...r.tags.map(P=>{let V=document.createElement("span");return V.textContent=P,V})),te(D,r.takeaway,{field:"takeaway"},g);let _=ge(r)?r.steps[s.activeStepIndex]:null;j.hidden=!_,_?(te(q,_.title,{field:"step-title"},g,{prefix:r.kind==="deconstructed-diff"?`Stage ${(_.stageIndex??_.pairIndex)+1}: `:""}),te(B,_.body,{field:"step-body"},g),Ct(z,"requirement"in _?_.requirement:null),"connection"in _&&_.connection?(H.hidden=!1,te(H,_.connection.label,{field:"connection"},g,{prefix:`${_.connection.from.path} \u2192 ${_.connection.to.path} \xB7 `})):(H.hidden=!0,H.textContent="")):(q.textContent="",B.textContent="",Ct(z,null),H.hidden=!0,H.textContent=""),C.disabled=!Ve(-1),$.disabled=!Ve(1)}function Hn(r){let c=[];return r.source&&c.push(r.source),r.confidence&&c.push(`${r.confidence} confidence`),c.join(" \xB7 ")}function Ct(r,c){if(!c){r.hidden=!0,r.replaceChildren(),r.removeAttribute("title");return}let g=document.createElement("span");g.className="tour-requirement-chip",g.dataset.status=c.status||"unspecified",g.textContent=c.status?`${c.id} \xB7 ${c.status}`:c.id;let u=document.createElement("span");u.className="tour-requirement-text",u.textContent=c.text;let h=[g,u],b=Hn(c);if(b){let w=document.createElement("span");w.className="tour-requirement-meta",w.textContent=b,h.push(w)}r.replaceChildren(...h),r.title=[`${c.id}: ${c.text}`,b].filter(Boolean).join(" \u2014 "),r.hidden=!1}function te(r,c,g,u,h={}){let b=u?.segments.filter(S=>S.source.field===g.field&&S.source.itemIndex===g.itemIndex)||[];if(b.length===0){r.textContent=`${h.prefix||""}${c}${h.suffix||""}`;return}let w=[];h.prefix&&w.push(document.createTextNode(h.prefix));let v=0;for(let S of b){S.startOffset>v&&w.push(document.createTextNode(c.slice(v,S.startOffset)));let O=document.createElement("span");O.className="tour-narration-segment",O.dataset.narrationSegmentId=S.id,O.textContent=c.slice(S.startOffset,S.endOffset),w.push(O),v=S.endOffset}v<c.length&&w.push(document.createTextNode(c.slice(v))),h.suffix&&w.push(document.createTextNode(h.suffix)),r.replaceChildren(...w)}function $t(){x.stop();let r=en();s.mode="diff",s.comparisonId+=1,s.left={name:r.leftFileName,content:r.leftContent},s.right={name:r.rightFileName,content:r.rightContent},Q("Loaded sample diff."),T({type:"showDiff",file1:s.left.name,file2:s.right.name,comparisonId:`web-${s.comparisonId}`,leftContent:s.left.content,rightContent:s.right.content,diffModel:ae(s.left.content,s.right.content),history:null})}async function zn(r){x.stop();let[c,g]=r,[u,h]=await Promise.all([c.text(),g.text()]);s.mode="diff",s.comparisonId+=1,s.left={name:c.name,content:u},s.right={name:g.name,content:h},Q(`Loaded ${c.name} and ${g.name}.`),T({type:"showDiff",file1:c.name,file2:g.name,comparisonId:`web-${s.comparisonId}`,leftContent:u,rightContent:h,diffModel:ae(u,h),history:null})}async function Wn(r){x.stop();let c=await Promise.all(r.map(async(g,u)=>{let h=await g.text();return{id:`web-panel-${u}`,label:g.name,content:h,savedContent:h,dirty:!1,editable:!0}}));s.mode="multi-diff",Q(`Loaded ${c.length}-panel diff for ${c.map(g=>g.label).join(", ")}.`),T({type:"showMultiDiff",panels:c,pairs:c.slice(0,-1).map((g,u)=>({leftIndex:u,rightIndex:u+1,diffModel:ae(g.content,c[u+1].content)}))})}function Q(r){let c=document.getElementById("web-status");c&&(c.textContent=r)}})();})();
|
|
150
|
+
`).forEach((a,s)=>{let c=a.toLocaleLowerCase(),f=0;for(;f<=c.length-r.length;){let p=c.indexOf(r,f);if(p<0)break;i.push({lineNumber:s+1,startColumn:p+1,endColumn:p+r.length+1,preview:a}),f=p+Math.max(r.length,1)}}),i}function Ui(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function vn(e,r){return _i(e,0,r)}function _i(e,r,i){let a=e?.blocks[r],s=i==="left"?e?.leftLines:e?.rightLines;if(!a||!s?.length)return;let c=i==="left"?a.leftStart:a.rightStart,f=i==="left"?a.leftEnd:a.rightEnd,p=s.slice(c,f),t=p[0]?.lineNumber??s[Math.min(c,s.length-1)]?.lineNumber;if(Number.isInteger(t))return{startLine:t,endLine:p.at(-1)?.lineNumber??t}}function Or(e,r,i,a){let s=[];return e.scenes.forEach((c,f)=>{c.kind==="walkthrough"&&c.steps.forEach((p,t)=>{p.diff.path===r&&s.push({side:p.focus.revision==="base"?"left":"right",startLine:p.focus.startLine,endLine:p.focus.endLine,label:`${c.title} \xB7 ${p.title}: ${p.body}`,active:f===i&&t===a,jumpTarget:{sceneIndex:f,stepIndex:t}})})}),s}function Dr(e,r,i,a,s){let c=[];return e.scenes.forEach((f,p)=>{p!==i||f.kind!=="stacked-diff"&&f.kind!=="deconstructed-diff"||f.steps.forEach((t,v)=>{if(t.file!==r)return;let g=t.startLine===void 0?s?.(t.pairIndex,t.side):{startLine:t.startLine,endLine:t.endLine??t.startLine};if(!g)return;let m=t.pairIndex+(t.side==="right"?1:0);c.push({pairIndex:t.pairIndex,panelIndex:m,side:t.side,startLine:g.startLine,endLine:g.endLine,label:`${f.title} \xB7 ${t.title}: ${t.body}`,active:p===i&&v===a,jumpTarget:{sceneIndex:p,stepIndex:v}})})}),c}function Hi(e,r=120){return e.length<=r?e:`${e.slice(0,r-1)}\u2026`}function Mr(e,r="Bygone"){let i=e?.windowTitle?.trim()||e?.title?.trim();return i?Hi(i):`${r} Tour`}function Fr(e,r){let i="overview"in r?r.overview:void 0,a=(i?.path||"").split("/").filter(m=>m&&m!==".").join("/"),s=m=>!a||m.startsWith(`${a}/`),c=[e.range.baseRef,e.range.headRef],f,p=[];if(r.kind==="stacked-diff"||r.kind==="deconstructed-diff"){let m=r.kind==="stacked-diff"?r.stack:r.panels,w=i?.comparison?m.findIndex($=>$.id===i.comparison?.from):0,I=i?.comparison?m.findIndex($=>$.id===i.comparison?.to):m.length-1;if(!m[w]||!m[I]||w===I)throw new Error(`Scene ${r.id} has invalid overview comparison endpoints.`);c=[m[w].label,m[I].label],f=r.files.flatMap($=>{if(!s($.path))return[];let x=$.panels[w],S=$.panels[I];if(!x||!S)return[];if(x.exists===S.exists&&x.content===S.content)return[];let E=x.exists?S.exists?"modified":"deleted":"added";return[{id:`${r.id}-overview-${$.path}`,kind:"text-diff",title:$.path,path:$.path,changeKind:E,leftContent:x.content,rightContent:S.content,leftLabel:c[0],rightLabel:c[1],summary:"",bullets:[],tags:[],takeaway:"",additions:0,deletions:0}]})}else f=e.files.filter(m=>m.kind==="text-diff"&&s(m.path)),p=e.files.filter(m=>m.kind==="omitted"&&s(m.path));let t=new Map;for(let m of[...f,...p]){let w=[m.changeKind!=="added",m.changeKind!=="deleted"],I=m.path.split("/");for(let $=0;$<I.length-1;$++){let x=I.slice(0,$+1).join("/"),S=t.get(x);S?S.sides=S.sides.map((E,N)=>E||w[N]):t.set(x,{relativePath:x,displayName:I[$],depth:$,isDirectory:!0,status:"modified",sides:[...w]})}t.set(m.path,{relativePath:m.path,displayName:I[I.length-1],depth:I.length-1,isDirectory:!1,sides:w,status:w[0]?w[1]?"modified":"left-only":"right-only",gitChangeKind:m.changeKind,...m.previousPath?{previousPath:m.previousPath}:{},...m.kind==="omitted"?{relationSummary:`Unavailable: ${m.reason}`}:{}})}for(let m of t.values())m.isDirectory&&(m.status=m.sides[0]?m.sides[1]?"modified":"left-only":"right-only");let v=[...t.values()].sort((m,w)=>{let I=m.relativePath.split("/"),$=w.relativePath.split("/");for(let x=0;x<Math.min(I.length,$.length);x++){if(I[x]===$[x])continue;let S=x<I.length-1||m.isDirectory,E=x<$.length-1||w.isDirectory;return Number(E)-Number(S)||I[x].localeCompare($[x])}return I.length-$.length}),g=a?` / ${a}/`:"";return{entries:v,files:f,labels:[c[0]+g,c[1]+g],omitted:p}}function zi(){return{sceneIndex:0,stepIndex:0,path:null}}var Bt=class{constructor(r){this.mode=r;this.cursors=new Map}depart(r){return this.cursors.set(this.mode,r),r}enter(r,i){this.mode=r;let a=this.cursors.get(r);return a?{location:a,restore:!0}:{location:i??zi(),restore:!1}}};function Br(e,r){let i=new Map;for(let f of r)i.has(f)||i.set(f,i.size);let a=e?.commits,s=Array.isArray(a)?a:[e?.from,e?.to],c=[...new Set(s.filter(f=>typeof f=="string"&&i.has(f)))];if(c.length<2)throw new Error("Select at least two revisions to compare.");return c.sort((f,p)=>i.get(f)-i.get(p)),{commits:c,...typeof e?.path=="string"&&e.path?{path:e.path}:{}}}var qi=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i,Wi="bygone-tour-skill.md";function _r(e,r={},i={}){let a=e==="deconstructed"?"deconstructed":"historical",s=xn(r.repository),c=Ur(r.paths),p=s!==void 0&&Array.isArray(r.paths)&&r.paths.length===0?["."]:c.length>0?c:null,t=Ur(r.revisions),v=ji(s,t,r.rangeStatus),g=r.rangeStatus||"unavailable",m=[Gi(i),`Create a v3 ${a} tour.`,`Repository: ${JSON.stringify(s??null)}`,`Selected paths: ${JSON.stringify(p)}`,`Base: ${JSON.stringify(v?t[0]:null)}`,`Head: ${JSON.stringify(v?t[1]:null)}`,"Additional context: (optional)"];return v||m.push(`Warning: range status ${JSON.stringify(g)} is not an exact committed range; choose revisions in Compare. Do not silently substitute a merge-base, swap endpoints, or drop revisions.`,`All revisions: ${JSON.stringify(t)}`),m.join(`
|
|
151
|
+
`)}function ji(e,r,i){return i==="exact"&&!!e&&r.length===2&&r.every(a=>qi.test(a))}function Gi(e){let r=xn(e.path);if(r)return`Read and follow the Bygone tour skill at ${JSON.stringify(r)}.`;let i=xn(e.name)||Wi;return`Read and follow the Bygone tour skill in attached ${JSON.stringify(i)}.`}function Ur(e){return Array.isArray(e)?e.filter(r=>typeof r=="string").filter(r=>r.length>0):[]}function xn(e){return typeof e=="string"&&e.trim().length>0?e:void 0}var kn=`---
|
|
152
|
+
name: pr-tour-guide
|
|
153
|
+
description: Act as a PR Tour Guide by generating, validating, compiling, and presenting evidence-grounded Bygone code-change tours from Git ranges. Use for requests such as "Tour this commit for me," or whenever an AI coding agent should explain a pull request, branch, commit, or code change as a guided walkthrough; create or repair a .bygone file; produce an LLM-ready Bygone change context; connect narrative claims to exact source evidence; or turn a diff into a browser-presentable review or demo. Always print the exact \`bygone\` CLI command to open the resulting diff, review, tour, or history view.
|
|
154
|
+
---
|
|
155
|
+
|
|
156
|
+
# PR Tour Guide
|
|
157
|
+
|
|
158
|
+
Use Bygone as the deterministic evidence and rendering layer. Treat the language model as the narrative planner, never as the authority on Git ranges or source locations.
|
|
159
|
+
|
|
160
|
+
## Install this skill
|
|
161
|
+
|
|
162
|
+
Install with the [skills CLI](https://skills.sh). Prefer **project** scope (default) or name agents explicitly on **global** installs \u2014 bare \`-g\` fans out to every detected host, and PromptScript only supports project-level skills, which produces a spurious failure line.
|
|
163
|
+
|
|
164
|
+
**This repo / PromptScript / team-shared (project scope):**
|
|
165
|
+
|
|
166
|
+
\`\`\`sh
|
|
167
|
+
npx skills add davidmashburn/bygone -s pr-tour-guide -y
|
|
168
|
+
\`\`\`
|
|
169
|
+
|
|
170
|
+
Installs to \`.agents/skills/pr-tour-guide\` (or your agent's project skills directory).
|
|
171
|
+
|
|
172
|
+
**Global, all projects (pick your agents):**
|
|
173
|
+
|
|
174
|
+
\`\`\`sh
|
|
175
|
+
npx skills add davidmashburn/bygone -s pr-tour-guide -g -y -a cursor codex claude-code
|
|
176
|
+
\`\`\`
|
|
177
|
+
|
|
178
|
+
Add or remove agent names for the tools you use. Omit \`-a\` only if you accept PromptScript possibly printing \`does not support global skill installation\` even when other agents succeeded.
|
|
179
|
+
|
|
180
|
+
**PromptScript only:**
|
|
181
|
+
|
|
182
|
+
\`\`\`sh
|
|
183
|
+
npx skills add davidmashburn/bygone -s pr-tour-guide -y -a promptscript
|
|
184
|
+
\`\`\`
|
|
185
|
+
|
|
186
|
+
List without installing:
|
|
187
|
+
|
|
188
|
+
\`\`\`sh
|
|
189
|
+
npx skills add davidmashburn/bygone --list
|
|
190
|
+
\`\`\`
|
|
191
|
+
|
|
192
|
+
From a Bygone source checkout, install the local copy instead:
|
|
193
|
+
|
|
194
|
+
\`\`\`sh
|
|
195
|
+
npx skills add ./skills/pr-tour-guide -y
|
|
196
|
+
\`\`\`
|
|
197
|
+
|
|
198
|
+
## Install Bygone
|
|
199
|
+
|
|
200
|
+
This skill requires the \`bygone\` CLI with \`tour context\`, \`tour schema\`, \`tour validate\`, and \`tour compile\`. Install only when the user asks or when the task cannot proceed without it.
|
|
201
|
+
|
|
202
|
+
**macOS (desktop app + CLI, recommended):**
|
|
203
|
+
|
|
204
|
+
\`\`\`sh
|
|
205
|
+
brew tap davidmashburn/bygone
|
|
206
|
+
brew install --cask bygone-desktop
|
|
207
|
+
\`\`\`
|
|
208
|
+
|
|
209
|
+
First install may require \`brew trust davidmashburn/bygone\`.
|
|
210
|
+
|
|
211
|
+
**CLI only (Node.js required):**
|
|
212
|
+
|
|
213
|
+
\`\`\`sh
|
|
214
|
+
npm install -g @davmash/bygone
|
|
215
|
+
\`\`\`
|
|
216
|
+
|
|
217
|
+
**macOS without Homebrew:** download the DMG from [GitHub Releases](https://github.com/davidmashburn/bygone/releases), then choose **Help \u2192 Install Command Line Tools\u2026** in the app.
|
|
218
|
+
|
|
219
|
+
If macOS reports the app is **damaged**, the build is likely unsigned. Clear quarantine and open once:
|
|
220
|
+
|
|
221
|
+
\`\`\`sh
|
|
222
|
+
xattr -cr /Applications/Bygone.app
|
|
223
|
+
open /Applications/Bygone.app
|
|
224
|
+
\`\`\`
|
|
225
|
+
|
|
226
|
+
**From a Bygone source checkout:**
|
|
227
|
+
|
|
228
|
+
\`\`\`sh
|
|
229
|
+
npm install
|
|
230
|
+
npm run dev:sync
|
|
231
|
+
\`\`\`
|
|
232
|
+
|
|
233
|
+
## Locate and verify Bygone
|
|
234
|
+
|
|
235
|
+
Run \`bygone --help\`. In a Bygone source checkout whose installed command is stale, use \`node ./bin/bygone.js\` instead.
|
|
236
|
+
|
|
237
|
+
Verify tour support before authoring:
|
|
238
|
+
|
|
239
|
+
\`\`\`sh
|
|
240
|
+
bygone tour schema >/dev/null
|
|
241
|
+
\`\`\`
|
|
242
|
+
|
|
243
|
+
If neither \`bygone\` nor \`node ./bin/bygone.js\` exposes the \`tour\` subcommands, stop, share the install commands above, and report that the toolchain is unavailable rather than guessing.
|
|
244
|
+
|
|
245
|
+
Do not rebuild, commit, push, publish, or open a browser unless the user requests it or the surrounding task clearly requires it.
|
|
246
|
+
|
|
247
|
+
## Build the evidence context
|
|
248
|
+
|
|
249
|
+
Determine the intended head and base from the request and repository state. Prefer an explicit base; do not guess when different bases would materially change the explanation.
|
|
250
|
+
|
|
251
|
+
Treat workspace paths named by the request as the explicit scope. The context
|
|
252
|
+
does not provide a path filter, so do not silently narrow or broaden that scope
|
|
253
|
+
based on which files seem easiest to explain; surface any scope ambiguity.
|
|
254
|
+
|
|
255
|
+
For a hosted review, resolve both immutable endpoint OIDs from provider metadata. Never assume the current checkout is the requested review head. For GitHub:
|
|
256
|
+
|
|
257
|
+
\`\`\`sh
|
|
258
|
+
PR_JSON="$(gh pr view <n> --json baseRefOid,headRefOid)"
|
|
259
|
+
BASE_OID="$(jq -r .baseRefOid <<<"$PR_JSON")"
|
|
260
|
+
HEAD_OID="$(jq -r .headRefOid <<<"$PR_JSON")"
|
|
261
|
+
test -n "$BASE_OID" && test "$BASE_OID" != null
|
|
262
|
+
test -n "$HEAD_OID" && test "$HEAD_OID" != null
|
|
263
|
+
bygone tour context "$HEAD_OID" --base "$BASE_OID" --output /tmp/change-context.json
|
|
264
|
+
\`\`\`
|
|
265
|
+
|
|
266
|
+
Use the equivalent API or CLI fields for other providers. If the requested
|
|
267
|
+
endpoints are unresolved, reversed, divergent, or have multiple candidates,
|
|
268
|
+
stop and report the ambiguity. Never silently invent an endpoint, choose among
|
|
269
|
+
candidates, or substitute a merge-base. If you are not reviewing a hosted
|
|
270
|
+
change, compute the merge-base only when the intended integration branch is
|
|
271
|
+
explicit, and pass that exact base OID or ref.
|
|
272
|
+
|
|
273
|
+
Use immutable commit IDs in the eventual tour. Dirty working-tree changes and
|
|
274
|
+
unsaved buffers are reported separately but excluded from committed-range
|
|
275
|
+
context, authored evidence, and compiled source.
|
|
276
|
+
|
|
277
|
+
Inspect progressively instead of loading every patch immediately:
|
|
278
|
+
|
|
279
|
+
\`\`\`sh
|
|
280
|
+
jq '{range,summary,commits,files:[.files[]|{path,previousPath,changeKind,role,additions,deletions,binary,patchOmittedReason,symbolHints}]}' /tmp/change-context.json
|
|
281
|
+
\`\`\`
|
|
282
|
+
|
|
283
|
+
Then read patches only for likely narrative-bearing files. Account explicitly for every \`patchOmittedReason\`; never claim to understand omitted binary or oversized evidence.
|
|
284
|
+
|
|
285
|
+
Compiled tours and context dossiers are large because they embed source snapshots. Inspect them progressively and do not load every patch unless the narrative really needs it.
|
|
286
|
+
|
|
287
|
+
## Plan the explanation
|
|
288
|
+
|
|
289
|
+
Identify the smallest set of reviewer questions that makes the change understandable. Organize by conceptual dependency rather than filename order. Usually move through:
|
|
290
|
+
|
|
291
|
+
1. motivation, contract, or invariant;
|
|
292
|
+
2. core implementation;
|
|
293
|
+
3. integration or side effects;
|
|
294
|
+
4. failure behavior and proof.
|
|
295
|
+
|
|
296
|
+
Keep secondary, generated, dependency, and mechanical files in Bygone's complete Files rail unless they alter a reviewer conclusion.
|
|
297
|
+
|
|
298
|
+
Let the change determine the hierarchy. A chapter is a named conceptual arc containing one or more related scenes; a scene answers one reviewer question or advances one thesis. Do not target a fixed chapter count, and do not create a chapter merely to wrap each scene. Repeated one-scene chapters usually indicate that headings are being generated from a template instead of the change's actual structure.
|
|
299
|
+
|
|
300
|
+
Scale the structure proportionally:
|
|
301
|
+
|
|
302
|
+
- A small commit may need one chapter and one scene.
|
|
303
|
+
- A normal pull request often needs one to three chapters with one or more scenes in each.
|
|
304
|
+
- A broad release or long-lived branch may need several chapters, but each boundary must mark a real conceptual transition.
|
|
305
|
+
- Prefer merging adjacent chapters when their scenes form one argument; split a chapter only when its scenes answer materially different reviewer questions.
|
|
306
|
+
|
|
307
|
+
These are pacing heuristics, not quotas. Preserve asymmetry when one capability deserves substantially more explanation than another.
|
|
308
|
+
|
|
309
|
+
Use these narrative constraints:
|
|
310
|
+
|
|
311
|
+
- State one reviewer question or thesis per scene.
|
|
312
|
+
- Give every chapter a coherent multi-scene arc when the material supports one; allow a single-scene chapter only when that scene is independently substantial.
|
|
313
|
+
- Decompose scenes by conceptual need, not a fixed template; do not force every scene to use the same step count.
|
|
314
|
+
- Prefer three to seven steps per scene.
|
|
315
|
+
- Explain why focused code matters instead of paraphrasing syntax.
|
|
316
|
+
- Keep summaries, bullets, annotations, and takeaways distinct; bullets that merely restate the summary are a defect.
|
|
317
|
+
- Avoid intent, safety, performance, or runtime claims unsupported by the evidence.
|
|
318
|
+
- Do not imply that the authored tour exhaustively reviews every changed file.
|
|
319
|
+
|
|
320
|
+
## Author the source
|
|
321
|
+
|
|
322
|
+
Retrieve the current contract:
|
|
323
|
+
|
|
324
|
+
\`\`\`sh
|
|
325
|
+
bygone tour schema > /tmp/change-tour-source.schema.json
|
|
326
|
+
\`\`\`
|
|
327
|
+
|
|
328
|
+
Write a version 3 \`.bygone\` file for new tours. The legacy \`.bygone.yaml\`
|
|
329
|
+
spelling remains valid when generic YAML tooling requires it. Treat the
|
|
330
|
+
authored source and its compiled \`.tour.json\` as Git-backed, non-portable
|
|
331
|
+
artifacts: pin \`range.base\` and \`range.head\` to the exact OIDs from the
|
|
332
|
+
context, and keep them with the corresponding repository so Bygone can resolve
|
|
333
|
+
those objects and live history. Versions 1 and 2 remain readable for legacy
|
|
334
|
+
inputs; v3 is the format for independent authored modes, directory overviews,
|
|
335
|
+
and review notes.
|
|
336
|
+
|
|
337
|
+
Set optional \`windowTitle\` when the tour should appear in the native window
|
|
338
|
+
title \u2014 for example a pull request number (\`PR-1234\`) so multiple open tours
|
|
339
|
+
stay distinguishable. When omitted, the presenter falls back to \`title\`.
|
|
340
|
+
|
|
341
|
+
### Choose the authored modes
|
|
342
|
+
|
|
343
|
+
The root \`chapters\` is required and is the compatibility tour. It shares the
|
|
344
|
+
top-level \`range\`, \`anchors\`, and \`connections\` with any independent modes.
|
|
345
|
+
When the source supplies them, \`tours.historical.chapters\` and
|
|
346
|
+
\`tours.deconstructed.chapters\` are separate authored tours; keep their chapter,
|
|
347
|
+
scene, and step order independent rather than expecting Bygone to match content
|
|
348
|
+
across modes.
|
|
349
|
+
|
|
350
|
+
- **Historical** explains real revision states. Its scenes may be walkthroughs
|
|
351
|
+
or \`stacked-diff\` scenes, never \`deconstructed-diff\` scenes. Every stacked
|
|
352
|
+
panel must resolve to a real Git revision; an explicitly authored Historical
|
|
353
|
+
stack may contain two to six revisions, but its first and last panels must be
|
|
354
|
+
the resolved review base and head.
|
|
355
|
+
- **Deconstructed** explains the change through synthetic cumulative stages. It
|
|
356
|
+
must contain at least one \`deconstructed-diff\` scene and may include
|
|
357
|
+
walkthrough scenes for context or proof. A mode-specific deconstructed scene
|
|
358
|
+
may omit \`stack\` and endpoint \`steps\`: its stages, not Git history, define the
|
|
359
|
+
explanation panels.
|
|
360
|
+
- If a mode is omitted, v3 derives it from the root chapters by scene identity
|
|
361
|
+
and order. Root walkthroughs and real stacks supply Historical; root
|
|
362
|
+
deconstructed scenes supply Deconstructed. A root deconstructed scene enters
|
|
363
|
+
Historical only when it also has explicit endpoint walkthrough \`steps\`; a
|
|
364
|
+
real revision \`stack\` by itself is not that walkthrough. No cross-mode
|
|
365
|
+
correspondence is inferred from filenames or narrative text.
|
|
366
|
+
|
|
367
|
+
For a root v3 \`deconstructed-diff\` scene, provide both an explicit real
|
|
368
|
+
revision \`stack\` and regular endpoint \`steps\`. The stack is used for the real
|
|
369
|
+
Historical/Final fallback and must have the same base and final endpoints as
|
|
370
|
+
the source range; the synthetic stages remain separate. A
|
|
371
|
+
mode-specific Deconstructed scene may omit those fields as described above.
|
|
372
|
+
|
|
373
|
+
For every walkthrough step:
|
|
374
|
+
|
|
375
|
+
- make one concise explanatory claim;
|
|
376
|
+
- focus an anchor in \`base\` or \`head\` evidence;
|
|
377
|
+
- prefer changed lines, using unchanged context only when it establishes a required boundary;
|
|
378
|
+
- use the shortest snippet that is unique within that file and revision;
|
|
379
|
+
- connect behavior to tests, error handling, or other concrete proof;
|
|
380
|
+
- add a connection only when the relationship between two locations materially improves understanding.
|
|
381
|
+
|
|
382
|
+
For every \`stacked-diff\` step, use a real changed file and a \`pair\` of adjacent
|
|
383
|
+
stack entry IDs; use \`side\` or \`lines\` only to refine the focus. For every
|
|
384
|
+
deconstructed stage, assign concrete change-unit (hunk) IDs through \`changes\`
|
|
385
|
+
and build a cumulative teaching order. Assign each changed hunk exactly once,
|
|
386
|
+
or exclude it explicitly with a reason; unsupported, binary, and rename-path
|
|
387
|
+
changes generally need whole-file exclusions. Do not infer a real stack from
|
|
388
|
+
the synthetic stages or describe an explanation panel as a commit.
|
|
389
|
+
|
|
390
|
+
Keep deconstructed-tour coordinates distinct:
|
|
391
|
+
|
|
392
|
+
- A **stage** is an authored synthetic phase and cumulative comparison state;
|
|
393
|
+
it is not a Git revision.
|
|
394
|
+
- The presenter derives one or more navigable Deconstructed tour steps from a
|
|
395
|
+
stage's introduced changes. A root deconstructed scene's endpoint \`steps\`
|
|
396
|
+
are ordinary anchor-based walkthrough items for the real range, not those
|
|
397
|
+
synthetic stage steps.
|
|
398
|
+
- Do not refer to either by an unqualified ordinal such as "Stage 2" or "Step 11" in authored titles, summaries, narration, or takeaways. Prefer the stable descriptive title so the reference survives edits.
|
|
399
|
+
- When an ordinal is necessary, qualify the coordinate: "stage 2 of 4" versus "tour step 11 of 46."
|
|
400
|
+
- Treat presenter-generated labels as UI context; do not repeat them in authored prose unless the distinction itself needs explanation.
|
|
401
|
+
|
|
402
|
+
Version 3 scenes may include a directory Overview:
|
|
403
|
+
|
|
404
|
+
\`\`\`yaml
|
|
405
|
+
overview:
|
|
406
|
+
kind: directory-diff
|
|
407
|
+
path: web
|
|
408
|
+
\`\`\`
|
|
409
|
+
|
|
410
|
+
Keep \`path\` relative and POSIX-style; omit it or use \`.\` for the repository
|
|
411
|
+
root. Stacked and Deconstructed scenes may set \`overview.comparison\` to two
|
|
412
|
+
distinct stack-entry IDs or to \`explanation-baseline\` and
|
|
413
|
+
\`explanation-stage-<stage-id>\`. Walkthrough overviews always use the review's
|
|
414
|
+
base-to-head comparison and reject an explicit comparison.
|
|
415
|
+
|
|
416
|
+
Use the optional v3 top-level \`review\` block for evidence-linked concepts,
|
|
417
|
+
boundaries, tradeoffs, and unresolved questions instead of presenting open
|
|
418
|
+
questions as settled scene narration. Pin \`review.baseOid\` and \`review.headOid\`
|
|
419
|
+
to the resolved range. \`concept\`, \`boundary\`, and \`tradeoff\` items need at
|
|
420
|
+
least one link to a root authored walkthrough scene and step; a \`question\` may
|
|
421
|
+
have empty evidence but must provide \`nextCheck\`. Do not add an ad hoc \`notes\`
|
|
422
|
+
key. See \`examples/bygone-history.bygone\` for review notes and
|
|
423
|
+
\`examples/navigation-lab.bygone.yaml\` for independently authored v3 modes.
|
|
424
|
+
|
|
425
|
+
Never emit generated line numbers or hunk indexes. Verify candidate snippets against the pinned object when uncertain:
|
|
426
|
+
|
|
427
|
+
\`\`\`sh
|
|
428
|
+
git show HEAD_OID:path/to/file | rg -F -n 'exact snippet'
|
|
429
|
+
\`\`\`
|
|
430
|
+
|
|
431
|
+
Use \`occurrence\` only when repetition is intentional and stable. Treat rename identity as evidence rather than describing a rename as unrelated deletion and addition.
|
|
432
|
+
|
|
433
|
+
## Validate and repair
|
|
434
|
+
|
|
435
|
+
Always run validation before presenting or handing off:
|
|
436
|
+
|
|
437
|
+
\`\`\`sh
|
|
438
|
+
bygone tour validate review.bygone --json
|
|
439
|
+
\`\`\`
|
|
440
|
+
|
|
441
|
+
Repair every error. Do not weaken, delete, or redirect an anchor merely to make validation pass. If evidence no longer exists, revise the claim or report the broken premise.
|
|
442
|
+
|
|
443
|
+
After structural validation, check that:
|
|
444
|
+
|
|
445
|
+
Treat this as a required self-audit, not a claim the validator can prove. For each item, cite concrete evidence you actually opened or mark it not applicable; the hand-off must distinguish verified findings from interpretation.
|
|
446
|
+
|
|
447
|
+
- the first step establishes enough context for later steps;
|
|
448
|
+
- chapter boundaries follow conceptual transitions rather than a fixed count or one-scene-per-chapter pattern;
|
|
449
|
+
- important production behavior is not hidden in the complete Files rail;
|
|
450
|
+
- tests are connected to the behavior they prove;
|
|
451
|
+
- connections express causal, contractual, data-flow, ordering, or proof relationships;
|
|
452
|
+
- binary files and omitted patches are surfaced explicitly;
|
|
453
|
+
- every Historical tour excludes synthetic deconstructed scenes, and every
|
|
454
|
+
Deconstructed tour contains at least one deconstructed scene;
|
|
455
|
+
- deconstructed stages cover every included change unit exactly once or record
|
|
456
|
+
an explicit exclusion, contain no unqualified "Stage N" or "Step N"
|
|
457
|
+
references, and keep comparison stages distinct from navigable tour steps;
|
|
458
|
+
- root deconstructed scenes have the required real stack and endpoint
|
|
459
|
+
walkthrough evidence, while mode-specific synthetic scenes do not claim
|
|
460
|
+
that evidence exists;
|
|
461
|
+
- v3 review-note OIDs match the resolved range and evidence links resolve to
|
|
462
|
+
authored root walkthrough steps;
|
|
463
|
+
- the final step supplies proof or a clear reviewer conclusion.
|
|
464
|
+
|
|
465
|
+
## Always print the open command
|
|
466
|
+
|
|
467
|
+
Whenever you create, validate, compile, recommend, or open a diff, review, tour, history view, or Git comparison, **always** print the exact one-line \`bygone\` command the user can paste to open it in the desktop app.
|
|
468
|
+
|
|
469
|
+
Do this even when you also run the command yourself, when presentation was not requested, and when handing off artifacts. Use the real paths and refs from the work; prefer absolute paths when a tour or file lives outside the current directory.
|
|
470
|
+
|
|
471
|
+
| Goal | Command template |
|
|
472
|
+
| --- | --- |
|
|
473
|
+
| Authored tour | \`bygone -C <repository> present --tour <path/to/review.bygone>\` |
|
|
474
|
+
| Branch review (change set) | \`bygone review <head> --base <base>\` |
|
|
475
|
+
| App-hosted range tour (no authored file) | \`bygone present <head> --base <base>\` |
|
|
476
|
+
| Two-way file or directory compare | \`bygone <left> <right>\` |
|
|
477
|
+
| Explicit diff mode | \`bygone --diff <left> <right>\` |
|
|
478
|
+
| Multi-panel compare | \`bygone <path1> <path2> <path3> [...]\` |
|
|
479
|
+
| Git refs compare | \`bygone --git-diff <ref1> <ref2> [<ref3>...]\` |
|
|
480
|
+
| File or directory history | \`bygone --history <path>\` |
|
|
481
|
+
| Repo directory history | \`bygone\` (from inside the Git repo) |
|
|
482
|
+
|
|
483
|
+
Tour tooling that does not open the app (\`tour context\`, \`tour validate\`, \`tour compile\`, \`tour coverage\`) still warrants the matching open command when a human should inspect the result visually.
|
|
484
|
+
|
|
485
|
+
## Compile or present
|
|
486
|
+
|
|
487
|
+
Compile a repository-bound manifest when the user needs an artifact:
|
|
488
|
+
|
|
489
|
+
\`\`\`sh
|
|
490
|
+
bygone tour compile review.bygone --output review.tour.json
|
|
491
|
+
\`\`\`
|
|
492
|
+
|
|
493
|
+
Open the interactive browser only when requested or useful for verifying the result:
|
|
494
|
+
|
|
495
|
+
\`\`\`sh
|
|
496
|
+
bygone -C /absolute/path/to/repository present --tour review.bygone
|
|
497
|
+
\`\`\`
|
|
498
|
+
|
|
499
|
+
Always print that same command with the real repository and tour paths, even if you do not run it. \`-C\` gives Bygone an explicit working directory without changing the user's shell directory.
|
|
500
|
+
|
|
501
|
+
Compiled manifests contain source snapshots. Do not publish or upload them without explicit authorization.
|
|
502
|
+
|
|
503
|
+
## Hand off
|
|
504
|
+
|
|
505
|
+
Report:
|
|
506
|
+
|
|
507
|
+
- the exact base and head OIDs;
|
|
508
|
+
- the **open command** for the primary artifact (\`bygone present --tour \u2026\`, \`bygone review \u2026\`, \`bygone --git-diff \u2026\`, etc.);
|
|
509
|
+
- the source and compiled artifact paths;
|
|
510
|
+
- authored root and Historical/Deconstructed chapter, scene, step, and stage
|
|
511
|
+
counts, plus compiled counts when generated complete-change or per-mode
|
|
512
|
+
scenes change them;
|
|
513
|
+
- omitted or unread evidence;
|
|
514
|
+
- validation and visual verification performed;
|
|
515
|
+
- whether generated files are temporary, uncommitted, committed, or pushed.
|
|
516
|
+
|
|
517
|
+
Distinguish syntactic grounding from interpretive correctness: Bygone proves that cited evidence exists at the pinned revision, not that the narrative's interpretation is unquestionably correct.
|
|
518
|
+
`;var Ut=["history","compare","historical","deconstructed"],In={history:"History",compare:"Compare",historical:"Historical tour",deconstructed:"Deconstructed tour"},Hr={historical:"No Historical tour is available. Copy a prompt for your coding agent and read or customize its Markdown instructions.",deconstructed:"No Deconstructed tour is available. Copy a prompt for your coding agent and read or customize its Markdown instructions."},Vi=new Set(["exact","none","multiple","uncommitted","reversed","divergent","unavailable"]),Xi=0;function jr({container:e,send:r}={}){if(!e||typeof e.appendChild!="function")throw new TypeError("createWorkspaceControls requires a DOM container.");let i=e.ownerDocument||globalThis.document;if(!i||typeof i.createElement!="function")throw new TypeError("createWorkspaceControls requires a browser document.");let a=typeof r=="function"?r:()=>{},s=++Xi,c=i.createElement("section");c.className="workspace-controls",c.setAttribute("data-workspace-controls","true");let f=i.createElement("nav");f.className="workspace-mode-strip",f.setAttribute("aria-label","Workspace modes"),c.appendChild(f);let p=i.createElement("div");p.className="workspace-mode-descriptions",p.setAttribute("aria-hidden","true"),c.appendChild(p);let t=new Map,v=new Map;for(let C of Ut){let P=i.createElement("button");P.type="button",P.className="workspace-mode-button",P.setAttribute("data-workspace-mode",C),P.textContent=In[C];let q=i.createElement("span");q.className="workspace-mode-description visually-hidden";let te=`bygone-workspace-${s}-${C}-description`;q.id=te,p.appendChild(q),P.setAttribute("aria-describedby",te),t.set(C,P),v.set(C,q),f.appendChild(P)}let g=i.createElement("button");g.type="button",g.className="workspace-back-button",g.textContent="Back to comparison",g.title="Return to the comparison that opened this workspace",g.setAttribute("aria-label","Back to comparison"),g.setAttribute("data-workspace-back","true"),c.appendChild(g);let m=i.createElement("div");m.className="workspace-status",m.setAttribute("role","status"),m.setAttribute("aria-live","polite"),m.setAttribute("aria-atomic","true"),c.appendChild(m);let w=Ji(i,s);c.appendChild(w.dialog),e.appendChild(c);let I=zr(),$=!1,x=null,S=null,E=!1,N="",A=new Map,L=new Map;for(let[C,P]of t)P.addEventListener("click",()=>{if($||P.disabled)return;let q=qr(C,I);if((C==="historical"||C==="deconstructed")&&!q){me(C,P);return}a({type:"workspaceMode",mode:C})});return g.addEventListener("click",()=>{!$&&!g.disabled&&a({type:"workspaceBack"})}),w.textarea.addEventListener("input",()=>{if(!x)return;let C=De(x);C.text=w.textarea.value,C.edited=!0}),w.copyButton.addEventListener("click",()=>{if(!x)return;let C=Oe(x);_t(C.text)}),w.resetButton.addEventListener("click",()=>{if(!x)return;let C=De(x,{reset:!0});w.textarea.value=C.text,ge(),w.textarea.focus()}),w.saveSkillButton.addEventListener("click",()=>{if(I.nativeSkillFiles){a({type:"workspaceSkillSave"});return}let C=oe(),P=URL.createObjectURL(new Blob([C.text],{type:"text/markdown;charset=utf-8"})),q=i.createElement("a");q.href=P,q.download=C.name||"bygone-tour-skill.md",q.click(),setTimeout(()=>URL.revokeObjectURL(P),1e3),ke("Markdown downloaded. Edit your copy, then choose Use my copy. Attach it alongside the prompt when your agent cannot read local files.")}),w.chooseSkillButton.addEventListener("click",()=>{I.nativeSkillFiles?a({type:"workspaceSkillChoose"}):w.skillFile.click()}),w.skillFile.addEventListener("change",async()=>{let C=w.skillFile.files?.[0],P=I.sessionId;if(w.skillFile.value="",!!C)try{if(!C.name.toLowerCase().endsWith(".md")||C.size>1024*1024)throw new Error("Choose a Markdown file smaller than 1 MiB.");let q=await C.text();if(!q.trim())throw new Error("The instructions file is empty.");if(L.set(P,{name:C.name,text:q}),$||I.sessionId!==P)return;ge(),ke("Custom instructions selected. Attach this Markdown file with the prompt.")}catch(q){!$&&I.sessionId===P&&ke(`Could not load instructions: ${q.message}`)}}),w.openExistingButton.addEventListener("click",()=>{if(!x)return;Oe(x);let C=x;Y(),a({type:"workspaceOpenTour",kind:C})}),w.chooseCompareButton.addEventListener("click",()=>{x&&(Oe(x),Y(),a({type:"workspaceMode",mode:"compare"}))}),w.closeButton.addEventListener("click",()=>Y()),w.dialog.addEventListener("cancel",C=>{C.preventDefault(),Y()}),w.dialog.addEventListener("close",()=>{x=null,N="",E||Ve()}),H(),{update:H,destroy:G};function H(C){if($)return;let P=zr(C);P.sessionId!==I.sessionId&&Z()&&Y(),ne(P),x&&P.status!==I.status&&(N=P.status),I=P,V(),J(),x&&ge()}function G(){$||($=!0,Y(),typeof c.remove=="function"?c.remove():c.parentNode?.removeChild(c),t.clear(),v.clear(),A.clear(),L.clear())}function V(){for(let C of Ut){let P=t.get(C),q=v.get(C),te=qr(C,I),ye=te&&I.mode===C,Xe=(C==="historical"||C==="deconstructed")&&!te,Je=C==="history"&&I.history.enabled===!1,Ze=C==="compare"&&I.compare.enabled===!1,we=C==="history"?I.history.label:C==="compare"?I.compare.label:I.modeLabels[C]||In[C],de=Xe?`${Hr[C]} Opens a prompt dialog without changing the current mode.`:Je?I.history.reason||"History is unavailable for this workspace.":Ze?I.compare.reason||"Compare is unavailable for this workspace.":ye?`${we} is the current workspace mode.`:`Switch to ${we}.`;P.textContent=we,P.title=de,P.setAttribute("aria-label",we),P.setAttribute("aria-description",de),q.textContent=de,P.classList.toggle("is-active",ye),P.classList.toggle("is-missing",Xe),P.classList.toggle("is-unavailable",Je||Ze),P.disabled=Je||Ze,Xe?P.removeAttribute("aria-pressed"):P.setAttribute("aria-pressed",String(ye))}g.hidden=I.canReturn!==!0,g.disabled=I.canReturn!==!0}function J(){m.textContent=I.status||"",m.hidden=!I.status}function me(C,P){if(!($||C!=="historical"&&C!=="deconstructed")){if(x=C,S=P,N=I.status||"",ge(),typeof w.dialog.showModal=="function")try{w.dialog.showModal()}catch{w.dialog.setAttribute("open","")}else w.dialog.setAttribute("open","");w.textarea.focus()}}function Y(){if(!Z()){x=null,Ve();return}E=!0;try{typeof w.dialog.close=="function"?w.dialog.close():w.dialog.removeAttribute("open"),x=null,N=""}finally{E=!1,Ve()}}function Ve(){let C=S;if(S=null,!(!C||typeof C.focus!="function")&&C.isConnected!==!1)try{C.focus()}catch{}}function Z(){return w.dialog.open===!0||w.dialog.hasAttribute("open")}function ge(){if(!x)return;let C=De(x),P=oe();w.title.textContent=`${In[x]} prompt`,w.description.textContent=Hr[x],w.context.textContent=`Current context: ${Wr(I.promptContext)}`,C.skillKey!==ce()?(w.draftNotice.hidden=!1,w.draftNotice.textContent="The selected instructions changed. Your edited prompt was preserved; use Reset prompt to reference the selected file, or update its reference yourself."):C.contextKey!==Sn(I.promptContext)?(w.draftNotice.hidden=!1,w.draftNotice.textContent=`This draft is based on earlier workspace context: ${C.contextSummary}. Review the repository, revision boundaries, and selected paths before copying.`):(w.draftNotice.hidden=!0,w.draftNotice.textContent=""),w.textarea.value=C.text,w.skillText.value=P.text,w.skillReference.textContent=P.path?`Instructions: ${P.path}. Local agents can read this path; for browser chats, save and attach a copy.`:`Instructions: ${P.name||"bygone-tour-skill.md"} (attachment). Download and attach it with the prompt; browsers do not expose its full local path.`,w.status.textContent=N,w.status.hidden=!N}function _t(C){let P=i.defaultView?.navigator?.clipboard||globalThis.navigator?.clipboard;if(!P||typeof P.writeText!="function"){ke("Could not copy the prompt: clipboard access is unavailable.");return}Promise.resolve().then(()=>P.writeText(C)).then(()=>ke("Prompt copied to the clipboard.")).catch(q=>{let te=q instanceof Error&&q.message?` ${q.message}`:"";ke(`Could not copy the prompt.${te}`)})}function ke(C){N=C,w.status.textContent=C,w.status.hidden=!C}function Oe(C){let P=De(C);return P.text=w.textarea.value,P.edited=!0,P}function De(C,{reset:P=!1}={}){let q=A.get(I.sessionId)||new Map;A.set(I.sessionId,q);let te=q.get(C);return(P||!te||!te.edited&&te.skillKey!==ce())&&q.set(C,{text:_r(C,I.promptContext,oe()),skillKey:ce(),contextKey:Sn(I.promptContext),contextSummary:Wr(I.promptContext),edited:!1}),q.get(C)}function oe(){return I.tourSkill||L.get(I.sessionId)||{name:"bygone-tour-skill.md",text:kn}}function ce(){let C=oe();return JSON.stringify([C.path||"",C.name||"",C.text])}function ne(C){let P=A.get(C.sessionId);if(P)for(let q of P.values())q.contextChanged=q.contextKey!==Sn(C.promptContext)}}function Ji(e,r){let i=e.createElement("dialog");i.className="workspace-prompt-dialog",i.setAttribute("aria-modal","true");let a=e.createElement("h2");a.id=`bygone-workspace-${r}-prompt-title`,i.setAttribute("aria-labelledby",a.id),i.appendChild(a);let s=e.createElement("p");s.className="workspace-prompt-description",s.id=`bygone-workspace-${r}-prompt-description`,i.setAttribute("aria-describedby",s.id),i.appendChild(s);let c=e.createElement("p");c.className="workspace-prompt-context",i.appendChild(c);let f=e.createElement("p");f.className="workspace-prompt-draft-notice",f.setAttribute("role","status"),f.hidden=!0,i.appendChild(f);let p=e.createElement("label");p.className="workspace-prompt-label";let t=e.createElement("textarea");t.id=`bygone-workspace-${r}-prompt-textarea`,t.rows=9,t.spellcheck=!1,t.setAttribute("aria-label","Tour authoring prompt draft"),p.textContent="Prompt draft",p.appendChild(t),i.appendChild(p);let v=e.createElement("p");v.className="workspace-prompt-context",i.appendChild(v);let g=e.createElement("details"),m=e.createElement("summary");m.textContent="Read instructions (Markdown)";let w=e.createElement("textarea");w.readOnly=!0,w.rows=12,w.setAttribute("aria-label","Tour skill Markdown instructions"),g.append(m,w),i.appendChild(g);let I=e.createElement("div");I.className="workspace-prompt-actions";let $=Pe(e,"Save an editable copy","workspace-skill-save"),x=Pe(e,"Use my copy","workspace-skill-choose"),S=e.createElement("input");S.type="file",S.accept=".md,text/markdown",S.hidden=!0,I.append($,x,S),i.appendChild(I);let E=e.createElement("p");E.className="workspace-prompt-status",E.setAttribute("role","status"),E.setAttribute("aria-live","polite"),E.setAttribute("aria-atomic","true"),E.hidden=!0,i.appendChild(E);let N=e.createElement("div");N.className="workspace-prompt-actions";let A=Pe(e,"Copy prompt","workspace-prompt-copy"),L=Pe(e,"Reset prompt","workspace-prompt-reset"),H=Pe(e,"Open existing tour","workspace-prompt-open"),G=Pe(e,"Choose revisions in Compare","workspace-prompt-compare"),V=Pe(e,"Close","workspace-prompt-close");return N.append(A,L,H,G,V),i.appendChild(N),{dialog:i,title:a,description:s,context:c,draftNotice:f,textarea:t,skillText:w,skillReference:v,saveSkillButton:$,chooseSkillButton:x,skillFile:S,status:E,copyButton:A,resetButton:L,openExistingButton:H,chooseCompareButton:G,closeButton:V}}function Pe(e,r,i){let a=e.createElement("button");return a.type="button",a.textContent=r,a.title=r,a.setAttribute("data-workspace-prompt-action",i),a}function zr(e={}){let r=Ut.includes(e?.mode)?e.mode:"compare",i=e?.history&&typeof e.history=="object"?{enabled:e.history.enabled!==!1,label:ht(e.history.label,"History"),reason:ht(e.history.reason,"")}:{enabled:!0,label:"History",reason:""},a=e?.compare&&typeof e.compare=="object"?{enabled:e.compare.enabled!==!1,label:ht(e.compare.label,"Compare"),reason:ht(e.compare.reason,"")}:{enabled:!0,label:"Compare",reason:""},s=Array.isArray(e?.availableTours)?e.availableTours.filter(c=>c==="historical"||c==="deconstructed"):null;return{sessionId:Yi(e?.sessionId),mode:r,modeLabels:e?.modeLabels&&typeof e.modeLabels=="object"?Object.fromEntries(Ut.filter(c=>typeof e.modeLabels[c]=="string").map(c=>[c,e.modeLabels[c]])):{},history:i,compare:a,availableTours:s,nativeSkillFiles:e?.nativeSkillFiles===!0,tourSkill:e?.tourSkill&&typeof e.tourSkill.path=="string"?{path:e.tourSkill.path,text:typeof e.tourSkill.text=="string"?e.tourSkill.text:kn}:null,promptContext:Zi(e?.promptContext),canReturn:e?.canReturn===!0,status:ht(e?.status,"")}}function Zi(e){let r=e&&typeof e=="object"?e:{};return{...typeof r.repository=="string"?{repository:r.repository}:{},...Array.isArray(r.paths)?{paths:r.paths.filter(i=>typeof i=="string")}:{},...Array.isArray(r.revisions)?{revisions:r.revisions.filter(i=>typeof i=="string")}:{},...Vi.has(r.rangeStatus)?{rangeStatus:r.rangeStatus}:{},...typeof r.reason=="string"?{reason:r.reason}:{}}}function qr(e,r){return e==="history"?r.history.enabled!==!1:e==="compare"?r.compare.enabled!==!1:r.availableTours?r.availableTours.includes(e):r.mode===e}function Sn(e){return JSON.stringify({repository:e.repository||"",paths:Array.isArray(e.paths)?e.paths:[],revisions:Array.isArray(e.revisions)?e.revisions:[],rangeStatus:e.rangeStatus||"",reason:e.reason||""})}function Wr(e){let r=e.repository||"(not resolved)",i=Array.isArray(e.paths)&&e.paths.length>0?e.paths.join(", "):e.repository&&Array.isArray(e.paths)?". (repository root; full requested scope)":"(scope not supplied)",a=Array.isArray(e.revisions)&&e.revisions.length>0?e.revisions.join(", "):"(none reported)";return`repository ${r}; paths ${i}; revisions ${a}; range ${e.rangeStatus||"unavailable"}`}function Yi(e){return typeof e=="string"||typeof e=="number"?String(e):"default"}function ht(e,r){return typeof e=="string"?e:r}(function(){let r="bygone.tourSidebarWidth",s="bygone.tourNarrationVoice",c="bygone.tourNarrationRate",f=new Set([.75,1,1.25,1.5]),p="speechSynthesis"in window&&"SpeechSynthesisUtterance"in window,t={mode:"empty",left:null,right:null,comparisonId:0,tour:null,authoredTour:null,zoom:null,zoomSwitching:!1,historyCommit:null,historyEntries:[],fileHistoryCache:new Map,displayedPanels:[],historyPath:null,historyPanels:[],historyFocus:null,historyDiff:null,compare:null,comparisonFocus:null,comparisonCommits:[],comparisonDraftCommits:[],activeSceneIndex:-1,activeStepIndex:0,sceneIntroVisible:!1,narrativeParent:null,readingKey:"title",directoryEvidence:null,activeTourFilePath:null,tourFocusFilePath:null,tourSidebarWidth:go(),tourSidebarHidden:!1,tourNavigatorTab:"tour",narrationVoiceURI:window.localStorage.getItem(s)||"",narrationRate:io(),narrationVoices:[],renderedNarrationUnit:null,workspacePromptStatus:"",historyPrefix:"/history/"},v=null,g=null,m=null,w=[],I=new Map,$=new Set,x=null,S=null,E=new URLSearchParams(window.location.search).get("workspaceEmbedded")==="1",N=null,A=new Ft(so(),{claimAudio:fo,onStateChange:jt,onSegmentChange:ho,canNavigateUnit:lo,navigateUnit:uo});window.__BYGONE_HOST__={environment:"web",editorWorkerUrl:"/media/editor.worker.js",diffWorkerUrl:"/media/diff.worker.js",postMessage(n){no(n)}},window.addEventListener("message",n=>{if(!E||n.source!==window.parent||n.origin!=="null")return;let o=n.data;!o||typeof o!="object"||o.type!=="bygoneWorkspaceTourMode"||o.mode!=="historical"&&o.mode!=="deconstructed"||(N=o.mode,!(!t.zoom||t.zoom.mode===o.mode||!ce().includes(o.mode))&&$e(o.mode).catch(ie))}),window.addEventListener("DOMContentLoaded",()=>{if(ro(),E){let n=document.getElementById("tour-mode-tabs"),o=document.getElementById("tour-mode-description");n&&(n.hidden=!0),o&&(o.hidden=!0)}ve("Browser host ready.")});function L(n){(n.type==="showDiff"||n.type==="showMultiDiff"||n.type==="showDirectoryDiff")&&(n={...n,renderRequestId:++J},t.mode==="tour"&&(t.displayedPanels=n.type==="showMultiDiff"?n.panels:Zr(),n.history||(n.history=Tn()),ye()),V&&(me=n.renderRequestId)),window.dispatchEvent(new window.CustomEvent("bygone:host-message",{detail:n}))}let H=0,G=new Map,V=null,J=0,me=null;function Y(){t.zoomSwitching||(V=null)}function Ve(){return new Promise(n=>{let o=++H,d=u=>{G.delete(o);let h=t.tour?.scenes[t.activeSceneIndex],y=u?.activeMultiPairIndex,b=h&&le(h)?ot(h):[],k=u?.editorStates?.[u.activeMultiPanelId||u.activePaneSide];n({sceneIndex:t.activeSceneIndex,stepIndex:t.activeStepIndex,path:t.activeTourFilePath,line:k?.selection?.startLineNumber,commit:(t.zoom?.mode==="history"?t.historyCommit:b[y+1]?.oid)||t.authoredTour.range.headOid,navigation:u,focusId:document.activeElement?.id,narrativeParent:t.narrativeParent,sceneIntroVisible:t.sceneIntroVisible,narrativeScroll:document.getElementById("tour-narrative-content")?.scrollTop||0,readingKey:t.readingKey,navigatorTab:t.tourNavigatorTab})},l=window.setTimeout(()=>d(null),1e3);G.set(o,u=>{window.clearTimeout(l),d(u)}),L({type:"captureNavigationState",requestId:o})})}let Z=0;function ge(n=t.authoredTour){if(n.tours||!n.scenes.some(d=>d.kind==="deconstructed-diff"))return null;let o=n.zoom?.final;return o?.scenes.some(d=>d.kind==="walkthrough")?o:null}let _t={history:"History",compare:"Compare",historical:"Historical tour",deconstructed:"Deconstructed tour"},ke={history:"Explore commits and choose revisions to compare.",compare:"Inspect the changes between selected revisions.",historical:"Actual revisions, with explanations of updates, reversals, and decisions.",deconstructed:"The change broken into constructed stages for explanation."};function Oe(n){return n==="historical"&&ge()?"Final tour":_t[n]}function De(n){return n==="historical"&&ge()?"The authored walkthrough of the completed endpoint diff.":ke[n]}function oe(n=t.authoredTour){if(n.tours)return n.tours;if(!n.scenes.some(l=>l.kind==="deconstructed-diff"))return{historical:{scenes:n.scenes,chapters:n.chapters}};let d=ge(n);return{...d?{historical:d}:{},deconstructed:{scenes:n.scenes,chapters:n.chapters}}}function ce(){return[...ne()?["history","compare"]:[],...Object.keys(oe()).filter(n=>oe()[n])]}function ne(n=t.authoredTour){return Number(n?.version)>=2}function C(){return"History is unavailable for legacy v1 tours; open a version 2 tour to browse commit history."}function P(){return"Compare is unavailable for legacy v1 tours because this tour has no history backend."}function q(){if(v)return;let n=document.getElementById("tour-mode-controls");if(!n)return;let o=document.getElementById("tour-mode-tabs"),d=document.getElementById("tour-mode-description"),l=document.getElementById("tour-mode-status");o&&(o.hidden=!0),d&&(d.hidden=!0),l&&(l.hidden=!0),g=document.createElement("div"),g.id="workspace-mode-controls",n.prepend(g),v=jr({container:g,send:te})}function te(n){if(!(!n||typeof n!="object")){if(n.type==="workspaceMode"&&["history","compare","historical","deconstructed"].includes(n.mode)){$e(n.mode).catch(ie);return}n.type==="workspaceOpenTour"&&(n.kind==="historical"||n.kind==="deconstructed")&&Jr()}}function ye(){if(!t.zoom||(q(),!v))return;g.hidden=E;let n=document.getElementById("tour-mode-tabs"),o=document.getElementById("tour-mode-description");n&&(n.dataset.workspaceModeLabel=Oe(t.zoom.mode)),o&&(o.textContent=De(t.zoom.mode));let d=ne();v.update({sessionId:Xe(),mode:t.zoom.mode,modeLabels:{historical:Oe("historical")},history:{enabled:d,label:"History",...d?{}:{reason:C()}},compare:{enabled:d,label:"Compare",...d?{}:{reason:P()}},availableTours:Object.keys(oe()).filter(l=>l==="historical"||l==="deconstructed"),promptContext:Je(),status:t.workspacePromptStatus})}function Xe(){let n=t.authoredTour;return[n?.repository?.root||"",n?.range?.mergeBaseOid||"",n?.range?.headOid||""].join("\0")||"browser-workspace"}function Je(){let n=t.authoredTour,o=n?.range,d=Array.isArray(t.displayedPanels)?t.displayedPanels:[],l=we(d.map(k=>k?.commit)),u=d.length>0?l:we([o?.mergeBaseOid,o?.headOid]),h=we(d.map(k=>k?.path)),y=h.length>0?h:we(t.tour?.files?.map(k=>k?.path)),b=Ze(u,n);return{...typeof n?.repository?.root=="string"?{repository:n.repository.root}:{},...y.length>0?{paths:y}:{},...u.length>0?{revisions:u}:{},rangeStatus:b.status,...b.reason?{reason:b.reason}:{}}}function Ze(n,o){if(n.length===0)return{status:"none",reason:"The browser view has no selected committed revisions."};if(n.length>2)return{status:"multiple",reason:"The displayed comparison contains more than two revision panels."};if(n.length!==2)return{status:"unavailable",reason:"The browser view could not resolve both comparison boundaries."};if(n.some(u=>/^(WORKTREE|INDEX)$/i.test(u)))return{status:"uncommitted",reason:"The browser comparison includes a live working or staged state."};if(!n.every(u=>/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(u)))return{status:"unavailable",reason:"The browser comparison does not expose two full revision identifiers."};let d=o?.range?.mergeBaseOid,l=o?.range?.headOid;return n[0]===d&&n[1]===l?{status:"exact",reason:"The manifest validates its merge-base/head range."}:n[0]===l&&n[1]===d?{status:"reversed",reason:"The selected revisions reverse the manifest merge-base/head range."}:{status:"unavailable",reason:"The browser manifest validates only its merge-base/head pair; this displayed pair needs deliberate Compare selection or backend Git validation."}}function we(n){return[...new Set(n.filter(o=>typeof o=="string"&&o.trim()).map(o=>o.trim()))]}function de(n){t.workspacePromptStatus=n,ye()}function Gr(n){try{let o=new URL(n,window.location.href).pathname,d="/tour.json";if(o.endsWith(d))return`${o.slice(0,-d.length)||""}/history/`}catch{}return"/history/"}function Kr(){return new Promise(n=>{let o=document.createElement("input");o.type="file",o.accept=".bygone,.yaml,.yml,application/yaml,text/yaml",o.hidden=!0,document.body.appendChild(o);let d=l=>{o.remove(),n(l||null)};o.addEventListener("change",()=>d(o.files?.[0])),o.addEventListener("cancel",()=>d(null)),o.click()})}function Vr(n){let o=t.authoredTour;if(!o)return!1;let d=o.repository?.root,l=o.range?.mergeBaseOid,u=o.range?.headOid,h=typeof n.repository=="string"?n.repository:"",y=typeof n.range?.mergeBaseOid=="string"?n.range.mergeBaseOid:"",b=typeof n.range?.headOid=="string"?n.range.headOid:"";return!!(d&&h&&d!==h||l&&y&&l!==y||u&&b&&u!==b)}function Xr(n){let o=typeof n.repository=="string"&&n.repository?n.repository:"(server-selected repository)",d=typeof n.range?.mergeBaseOid=="string"&&n.range.mergeBaseOid?n.range.mergeBaseOid:"(unknown base)",l=typeof n.range?.headOid=="string"&&n.range.headOid?n.range.headOid:"(unknown head)",u=t.authoredTour?.repository?.root||"(current repository unavailable)",h=t.authoredTour?.range?.mergeBaseOid||"(unknown base)",y=t.authoredTour?.range?.headOid||"(unknown head)";return["Open this authored tour from the server?",`Repository: ${o}`,`Range: ${d} \u2192 ${l}`,`Current browser range: ${u}, ${h} \u2192 ${y}`,"This loads the server-validated tour and does not change a local repository."].join(`
|
|
519
|
+
`)}async function Jr(){try{let n=await Kr();if(!n)return;if(n.size>1024*1024)throw new Error("Choose an authored .bygone or .yaml file no larger than 1 MiB.");let o=typeof n.name=="string"?n.name.toLowerCase():"";if(!/\.(?:bygone|ya?ml)$/.test(o))throw new Error("Choose an authored .bygone or .yaml file.");let d=await n.text(),l=await fetch("/tour/open",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:d})}),u=await l.json().catch(()=>({}));if(!l.ok)throw new Error(u.error||`Tour upload failed (${l.status}).`);if(!u||typeof u.manifestUrl!="string"||!u.manifestUrl)throw new Error("Tour upload did not return a manifest URL.");if(Vr(u)&&!window.confirm(Xr(u))){de("Kept the current tour.");return}if(!await Dn(u.manifestUrl)){de("Could not load the uploaded tour.");return}de("")}catch(n){de(`Could not open existing tour: ${n instanceof Error?n.message:String(n)}`)}}function ee(){return!t.zoom||t.zoom.mode==="historical"||t.zoom.mode==="deconstructed"}function Ye(n){let o=t.authoredTour;return oe()[n]?{...o,...oe()[n]}:{...o,scenes:[],chapters:[],files:n==="compare"&&t.compare?t.compare.files:o.files}}function Me(){let n=document.getElementById("tour-mode-controls");if(n.hidden=!t.zoom||E,!t.zoom)return;ye();let o=document.getElementById("tour-mode-tabs"),d=document.getElementById("tour-mode-description");o&&(o.hidden=!0),d&&(d.hidden=!0);let l=t.zoom.mode==="history",u=ne();document.getElementById("tour-history-controls").hidden=!u||t.zoom.mode==="compare",document.getElementById("tour-compare-controls").hidden=!u||t.zoom.mode!=="compare",document.body.classList.toggle("tour-derived-mode",!ee()),ee()||document.body.classList.remove("tour-discussion");for(let h of["tour-history-parent","tour-history-base"])document.getElementById(h).hidden=!l;pt()}function pt(){let n=t.comparisonDraftCommits.length,o=document.getElementById("tour-history-compare");o.textContent=`Compare selected (${n})`,o.disabled=n<2||!ne();let d=document.getElementById("tour-compare-apply");d.textContent=`Update comparison (${n})`,d.disabled=n<2||!ne(),document.getElementById("tour-compare-scope").textContent=t.compare?.path?`File: ${t.compare.path}`:"All changed files",document.getElementById("tour-compare-all").hidden=!t.compare?.path;for(let l of["tour-history-parent","tour-history-base"])document.getElementById(l).disabled=!ne()||!t.historyCommit}function Ht(){return[...new Set([...[...t.historyEntries].reverse().map(n=>n.commit),t.authoredTour.range.mergeBaseOid,...t.authoredTour.commits.map(n=>n.oid),t.authoredTour.range.headOid])]}function Cn(n){return Br(n,Ht())}async function Ie(n,o,d=t.historyPrefix,l=t.authoredTour){if(!ne(l))throw new Error(C());let u=await fetch(`${d||"/history/"}${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),h=await u.json();if(!u.ok)throw new Error(h.error||`History request failed (${u.status}).`);return h}function ie(n){let o=n instanceof Error?n.message:String(n),d=document.getElementById("tour-mode-status");d&&(d.textContent=o),v&&de(o)}function En(){return t.displayedPanels.map(n=>n.commit).filter(Boolean)}function Zr(){let n=t.tour?.scenes[t.activeSceneIndex],o=t.zoom?.mode==="compare"?t.comparisonCommits:[t.authoredTour.range.mergeBaseOid,t.authoredTour.range.headOid];if(t.directoryEvidence&&le(n)){let d=ot(n),l=n.overview?.comparison;o=n.kind==="deconstructed-diff"?[]:[(l?d.find(u=>u.id===l.from):d[0])?.oid,(l?d.find(u=>u.id===l.to):d.at(-1))?.oid]}return["left","right"].map((d,l)=>({id:d,commit:o[l]}))}function Tn(){let n=t.displayedPanels.map(o=>o.commit);return{...gt(qt({commits:En()},null),n,null),navigatorOnly:!0}}async function Yr(n){if(!n||!t.zoom||!ne())return[];if(!t.fileHistoryCache.has(n)){let o=Ie("list",{path:n,commit:t.authoredTour.range.headOid}).then(d=>d.entries);t.fileHistoryCache.set(n,o),o.catch(()=>t.fileHistoryCache.delete(n))}return t.fileHistoryCache.get(n)}async function Qr(n,o){try{let d=await Yr(n);if(o!==J)return;L({type:"updateCommitMarkers",changedCommits:d.map(l=>l.commit),path:n})}catch(d){o===J&&ie(d)}}async function Fe(n,o,d=!0){let l=++Z,u=t.historyEntries;if(o=o||t.historyCommit||t.authoredTour.range.headOid,!n)throw new Error("Choose a text file to explore its revisions.");let h=u.find(B=>B.commit===o);if(t.historyPath===n&&t.historyCommit===o&&t.historyPanels.length){yt();return}let y=await Ie("diff",{path:n,commit:o,head:t.authoredTour.range.headOid});if(l!==Z||t.zoom.mode!=="history")return;if(d&&t.historyPanels.length&&t.historyCommit===o){let B=await Promise.all(t.historyPanels.map(async K=>{let D=K.commit?await Ie("diff",{path:n,commit:K.commit,head:t.authoredTour.range.headOid}):{rightContent:"",path:n};return{...K,content:D.rightContent,path:D.path}}));if(l!==Z||t.zoom.mode!=="history")return;t.historyPanels=B,t.historyPath=n,t.historyDiff=y,yt(),ue();return}let b=u.findIndex(B=>B.commit===o),R=(b>=0?u[b+1]:null)?.commit||y.parentCommit,M=R&&R!==y.parentCommit?(await Ie("diff",{path:n,commit:R,head:t.authoredTour.range.headOid})).rightContent:y.leftContent;if(l!==Z||t.zoom.mode!=="history")return;t.historyPath=n,t.historyCommit=o;let W=Math.max(2,t.historyPanels.length);t.historyDiff=y;let z=(B,K,D)=>({id:`history-${B||"empty"}`,commit:B,content:K,label:D,path:y.path,editable:!1});for(t.historyPanels=[z(R,M,R?.slice(0,7)||"Empty tree"),z(o,y.rightContent,h?`${h.shortCommit} ${h.summary}`:o.slice(0,7))],t.historyFocus=`history-${o}`;t.historyPanels.length<W;){let B=mt(t.historyPanels[0],"left");if(!B)break;let K=await Ie("diff",{path:n,commit:B.commit,head:t.authoredTour.range.headOid});if(l!==Z||t.zoom.mode!=="history")return;t.historyPanels.unshift(z(B.commit,K.rightContent,`${B.shortCommit} ${B.summary}`))}yt(),document.getElementById("tour-mode-status").textContent="",pt(),ue()}function eo(n,o,d){let l=n.findIndex(h=>h.commit===o),u=n[l];return{fileName:(t.historyPath||d.path).split("/").pop(),canGoBack:l>=0&&l<n.length-1,canGoForward:l>0,positionLabel:`${l+1} / ${n.length}`,leftCommitLabel:t.historyPanels[0]?.commit?.slice(0,7)||"Empty tree",leftTimestamp:"",rightCommitLabel:t.historyPanels.at(-1)?.label||(u?`${u.shortCommit} ${u.summary}`.trim():o.slice(0,7)),rightTimestamp:u?.timestamp||"",workingTreeControls:!1,rail:{activeTabId:"history",tabs:[{id:"history",label:"History"}],itemsByTab:{history:n.map((h,y)=>({label:`${h.shortCommit} ${h.summary}`.trim(),meta:h.timestamp,active:y===l,selected:t.comparisonDraftCommits.includes(h.commit),kind:"history-entry",index:y}))}}}}function mt(n,o){let d=Ht(),l=d.indexOf(n.commit);if(l<0)return null;let u=new Set(t.historyPanels.map(b=>b.commit)),y=(o==="left"?d.slice(0,l).reverse():d.slice(l+1)).find(b=>!u.has(b)&&t.historyEntries.some(k=>k.commit===b));return t.historyEntries.find(b=>b.commit===y)}function gt(n,o,d){let l=n.rail.itemsByTab.history;for(let u of l){u.commit=t.historyEntries[u.index]?.commit;let h=t.historyEntries[u.index];u.inTour=t.authoredTour?.commits.some(y=>y.oid===u.commit),u.selectionEnabled=!!t.zoom,h?.parents?.length>1&&(u.meta+=` \xB7 Merge: ${h.parents.map(y=>y.slice(0,7)).join(", ")}`),u.panelNumber=o.indexOf(u.commit)+1||null,u.active=u.commit===d}return o.forEach((u,h)=>{u!==void 0&&(l.some(y=>y.commit===u)||l.push({label:u?`${u.slice(0,7)} \xB7 Parent/base revision`:"Empty tree",commit:u,selected:t.comparisonDraftCommits.includes(u),selectionEnabled:!!t.zoom,panelNumber:h+1,active:u===d,kind:"panel-revision",index:-h-1}))}),n}function yt(){let n=t.historyPanels.map(d=>({...d,addLeftEnabled:!!mt(d,"left"),addRightEnabled:!!mt(d,"right"),removeEnabled:t.historyPanels.length>2})),o=n.find(d=>d.id===t.historyFocus)?.commit;t.activeTourFilePath=t.historyPath,Ae(),L({type:"showMultiDiff",panels:n,pairs:n.slice(0,-1).map((d,l)=>({leftIndex:l,rightIndex:l+1,diffModel:ae(d.content,n[l+1].content)})),activePanelId:t.historyFocus,mutationEnabled:!0,fileNavigation:{canGoPrevious:!!be(-1),canGoNext:!!be(1)},history:gt(eo(t.historyEntries,t.historyCommit,t.historyDiff),n.map(d=>d.commit),o)})}async function to(n){let o=t.historyPanels.find(d=>d.id===(n.anchorPanelId||n.panelId));if(o){if(n.type==="multiRemovePanel"){if(t.historyPanels.length<=2)return;++Z,t.historyPanels=t.historyPanels.filter(d=>d!==o),t.historyFocus===o.id&&(t.historyFocus=t.historyPanels.at(-1).id)}else{let d=mt(o,n.side);if(!d)return;let l=++Z,u=await Ie("diff",{path:t.historyPath,commit:d.commit,head:t.authoredTour.range.headOid});if(l!==Z||t.zoom.mode!=="history")return;let h={id:`history-${d.commit}`,commit:d.commit,content:u.rightContent,label:`${d.shortCommit} ${d.summary}`,path:u.path,editable:!1};t.historyPanels.push(h);let y=Ht();t.historyPanels.sort((b,k)=>y.indexOf(b.commit)-y.indexOf(k.commit)),t.historyFocus=h.id}yt()}}function zt(n){let o=t.historyEntries.findIndex(l=>l.commit===t.historyCommit),d=t.historyEntries[o+n];if(d)return Fe(t.historyPath,d.commit,!1)}function qt(n,o){return{fileName:(n.path||t.activeTourFilePath||"Comparison").split("/").pop(),canGoBack:!1,canGoForward:!1,positionLabel:`${n.commits.length} loaded panels`,leftCommitLabel:n.commits[0]?.slice(0,7)||"",leftTimestamp:"",rightCommitLabel:n.commits.at(-1)?.slice(0,7)||"",rightTimestamp:"",workingTreeControls:!1,rail:{activeTabId:"history",tabs:[{id:"history",label:"History"}],itemsByTab:{history:t.historyEntries.map((d,l)=>({label:`${d.shortCommit} ${d.summary}`.trim(),meta:d.timestamp,active:d.commit===o,selected:t.comparisonDraftCommits.includes(d.commit),panelNumber:n.commits.indexOf(d.commit)+1||null,kind:"history-entry",index:l}))}}}}function $n(n,o=null){if(!n||n.kind!=="text-diff")return!1;let d=n.comparisonPanels;o=o||t.comparisonFocus,t.comparisonFocus=o;let l=d.slice(0,-1).map((u,h)=>({leftIndex:h,rightIndex:h+1,diffModel:ae(u.content,d[h+1].content)}));return t.activeTourFilePath=n.path,Ae(),L({type:"showMultiDiff",panels:d,pairs:l,activePanelId:o?`compare-${o}`:null,history:gt(qt(t.compare,o),t.compare.commits,o),fileNavigation:{canGoPrevious:!!be(-1),canGoNext:!!be(1)},mutationEnabled:!1}),ue(),!0}async function Nn(n,o,d=null){n=Cn(n);let l=++Z,u=await Ie("compare-many",n);if(l!==Z||t.zoom.mode!=="compare")return;let h=u.files;t.comparisonCommits=n.commits,t.compare={...n,files:h},t.tour=Ye("compare"),t.activeSceneIndex=-1,t.tourFocusFilePath=null,Be(),Me(),Ne();let y=h.find(b=>b.kind==="text-diff"&&b.path===o)||h.find(b=>b.kind==="text-diff");if(y)$n(y,d);else{t.activeTourFilePath=null;let b=n.commits.map(k=>({id:`compare-${k}`,commit:k,path:"No text changes",content:"",label:k.slice(0,7),editable:!1}));L({type:"showMultiDiff",panels:b,pairs:b.slice(0,-1).map((k,R)=>({leftIndex:R,rightIndex:R+1,diffModel:ae("","")})),mutationEnabled:!1,history:gt(qt(n,null),n.commits,null)}),t.activeTourFilePath=null,V=null}document.getElementById("tour-mode-status").textContent=h.length?y?"":"Changed files cannot be displayed as text. See the file list for details.":"No changes between these revisions.",ue()}async function Te(n){if(!ne()){de(P());return}t.zoomSwitching||(t.zoom.mode!=="compare"?await $e("compare",n):await Nn(n,t.activeTourFilePath),xt("commits"))}function Wt(){return{commits:[t.authoredTour.range.mergeBaseOid,t.authoredTour.range.headOid]}}function An(){return t.historyEntries.find(n=>n.commit===t.historyCommit)?.path||t.historyPath}async function $e(n,o,d){if(!t.zoom||t.zoomSwitching||n===t.zoom.mode||!ce().includes(n))return;t.zoomSwitching=!0,++Z;let l=t.zoom.mode,u;try{u=await Ve(),t.zoom.depart(u),A.pauseForExternalOwner();let h=t.zoom.enter(n,n==="history"?u:null);if(t.tourNavigatorTab=h.restore?h.location.navigatorTab||"commits":ee()?"tour":"commits",t.activeSceneIndex=-1,t.activeStepIndex=0,t.narrativeParent=null,t.directoryEvidence=null,t.sceneIntroVisible=!1,t.tourFocusFilePath=null,t.tour=Ye(n),Be(),Ne(),Me(),document.getElementById("tour-mode-status").textContent="",V=h.restore&&!o?h.location:null,n==="history")await Fe(t.historyPath||h.location.path||t.tour.files.find(y=>y.kind==="text-diff")?.path,t.historyCommit||h.location.commit);else if(n==="compare")await Nn(o||t.compare||Wt(),d||h.location.path||u.path);else if(se(Math.max(0,h.location.sceneIndex),h.location.stepIndex,{zoomLanding:!0,showIntro:h.restore?h.location.sceneIntroVisible:!0,readingKey:h.restore?h.location.readingKey:"title"}),h.location.path&&t.activeTourFilePath!==h.location.path){let y=t.tour.files.findIndex(b=>b.path===h.location.path);y>=0&&nt(y)}ue()}catch(h){V=null,t.zoom.enter(l),t.tour=Ye(l),u&&(t.activeSceneIndex=u.sceneIndex,t.activeStepIndex=u.stepIndex,t.activeTourFilePath=u.path,t.narrativeParent=u.narrativeParent,t.sceneIntroVisible=u.sceneIntroVisible,t.tourNavigatorTab=u.navigatorTab),Be(),Me(),Ne(),u&&ee()&&(V=u,se(u.sceneIndex,u.stepIndex,{zoomLanding:!0,showIntro:u.sceneIntroVisible,readingKey:u.readingKey}),u.path&&t.activeTourFilePath!==u.path&&nt(t.tour.files.findIndex(y=>y.path===u.path))),Ae(),ue(),ie(h)}finally{t.zoomSwitching=!1}}async function no(n){if(!(!n||typeof n!="object")){if(n.type==="navigationState"){G.get(n.requestId)?.(n.navigation);return}if(n.type==="renderComplete"&&t.mode==="tour"&&n.renderRequestId===J&&Qr(t.activeTourFilePath,J),n.type==="renderComplete"&&V&&n.renderRequestId===me){let o=V;V=null,L({type:"restoreNavigationState",navigation:o.navigation});let d=document.getElementById("tour-narrative-content");d&&(d.scrollTop=o.narrativeScroll||0,x=d.scrollTop),o.focusId&&document.getElementById(o.focusId)?.focus({preventScroll:!0})}if(n.type==="ready"){let o=new URLSearchParams(window.location.search),d=o.get("manifest");d?Dn(d):o.get("demo")==="1"&&Gn();return}if(t.mode==="tour"&&t.directoryEvidence&&ee()){if(n.type==="openDirectoryEntry"){Xt(n.relativePath);return}if(n.type==="returnToDirectory"){bt();return}}if(t.mode==="tour"){if(t.zoom?.mode==="history"&&["multiAddPanel","multiRemovePanel"].includes(n.type)){to(n).catch(ie);return}if(n.type==="multiSetActivePair"||n.type==="multiSetActivePanel"){t.zoom?.mode==="history"?t.historyFocus=n.type==="multiSetActivePanel"?n.panelId:t.historyPanels[n.pairIndex]?.id||t.historyFocus:t.zoom?.mode==="compare"&&(t.comparisonFocus=n.type==="multiSetActivePanel"?n.panelId.replace(/^compare-/,""):t.comparisonCommits[n.pairIndex]);return}if(n.type==="historyBack"||n.type==="historyForward"){if(t.zoom?.mode!=="history")return;let o=zt(n.type==="historyBack"?1:-1);o&&o.catch(ie);return}if(n.type==="toggleHistorySelection"&&Number.isInteger(n.index)){let o=t.displayedPanels.map(u=>u.commit),d=n.index<0?{commit:o[-n.index-1]}:t.historyEntries[n.index];if(!d?.commit)return;let l=t.comparisonDraftCommits.includes(d.commit)?t.comparisonDraftCommits.filter(u=>u!==d.commit):[...t.comparisonDraftCommits,d.commit];t.comparisonDraftCommits=l.length>=2?Cn({commits:l}).commits:l,pt();return}if(n.type==="selectHistoryEntry"&&Number.isInteger(n.index)){let o=t.historyEntries[n.index];if(o&&t.zoom?.mode==="history"){let d=t.historyPanels.find(l=>l.commit===o.commit);d?(t.historyFocus=d.id,L({type:"focusHistoryPanel",panelId:d.id})):Fe(t.historyPath,o.commit,!1).catch(ie)}if(o&&t.zoom?.mode!=="history"){let d=t.displayedPanels.find(l=>l.commit===o.commit);d?L({type:"focusHistoryPanel",panelId:d.id}):document.getElementById("tour-mode-status").textContent=`${o.shortCommit} ${o.summary} \xB7 ${o.timestamp}${o.parents?.length?` \xB7 Parents: ${o.parents.map(l=>l.slice(0,7)).join(", ")}`:""}. Select its checkbox to include it in a comparison.`}return}}if(n.type==="navigateFile"&&t.mode==="tour"){Un(n.direction==="previous"?-1:1);return}if(n.type==="navigateTourStep"&&t.mode==="tour"){let o=n.sceneIndex,d=n.stepIndex;Number.isInteger(o)&&Number.isInteger(d)&&se(o,d,{userNavigation:!0,showIntro:!1});return}n.type==="recomputeDiff"&&t.mode==="diff"&&t.left&&t.right&&(t.left.content=n.leftContent,t.right.content=n.rightContent,L({type:"showDiff",file1:t.left.name,file2:t.right.name,comparisonId:`web-${t.comparisonId}`,leftContent:t.left.content,rightContent:t.right.content,diffModel:ae(t.left.content,t.right.content),history:null}))}}function ro(){document.getElementById("tour-review-toggle")?.addEventListener("click",()=>{wt(document.getElementById("tour-review").hidden)}),document.getElementById("tour-review-close")?.addEventListener("click",()=>wt(!1)),document.getElementById("tour-review")?.addEventListener("keydown",T=>{T.key==="Escape"&&(T.preventDefault(),wt(!1))});let n=(T,j)=>document.getElementById(T)?.addEventListener("click",()=>{Promise.resolve().then(j).catch(ie)});n("tour-history-compare",()=>Te({commits:t.comparisonDraftCommits})),n("tour-compare-apply",()=>Te({commits:t.comparisonDraftCommits,path:t.compare?.path})),n("tour-history-parent",()=>{let T=t.historyEntries.find(j=>j.commit===t.historyCommit)?.parentCommit;if(!T){ie("This is the first commit; History already shows its comparison with the empty tree.");return}return Te({commits:[T,t.historyCommit],path:An()})}),n("tour-history-base",()=>Te({commits:[t.authoredTour.range.mergeBaseOid,t.historyCommit],path:An()})),n("tour-history-final",()=>Te(Wt())),n("tour-compare-final",()=>Te(Wt())),n("tour-compare-all",()=>Te({commits:t.compare.commits}));let o=T=>{t.comparisonDraftCommits=T.filter(Boolean),pt(),L({type:"updateHistorySelection",commits:t.comparisonDraftCommits})};for(let T of["history","compare"])n(`tour-${T}-clear`,()=>o([])),n(`tour-${T}-reset`,()=>o(En()));for(let T of["wheel","pointerdown","keydown"])document.addEventListener(T,j=>{!j.isTrusted||j.target?.closest?.("#tour-mode-controls")||j.target?.closest?.(".monaco-editor, .diff-toolbar, #tour-narrative")&&Y()},{capture:!0,passive:!0});let d=document.getElementById("web-compare-test"),l=document.getElementById("web-open-diff"),u=document.getElementById("web-open-diff3"),h=document.getElementById("web-diff-input"),y=document.getElementById("web-diff3-input"),b=document.getElementById("tour-narration"),k=document.getElementById("tour-return-focus"),R=document.getElementById("tour-search-input"),M=document.getElementById("tour-search-scope"),W=document.getElementById("tour-listen"),z=document.getElementById("tour-stop"),B=document.getElementById("tour-narration-skip-back"),K=document.getElementById("tour-narration-skip-ahead"),D=document.getElementById("tour-narration-voice"),F=document.getElementById("tour-narration-rate");mo(),yo(),oo(),document.getElementById("tour-navigator-tabs")?.addEventListener("click",T=>{let j=T.target instanceof Element?T.target.closest("[data-tour-navigator]"):null;j?.dataset.tourNavigator&&xt(j.dataset.tourNavigator)}),d?.addEventListener("click",()=>{Gn()}),l?.addEventListener("click",()=>{h.value="",h.click()}),u?.addEventListener("click",()=>{y.value="",y.click()}),h?.addEventListener("change",async()=>{let T=Array.from(h.files||[]);if(T.length!==2){ve("Select exactly 2 files for a diff.");return}await Oo(T)}),y?.addEventListener("change",async()=>{let T=Array.from(y.files||[]);if(T.length<1){ve("Select one or more files.");return}await Do(T)}),document.getElementById("tour-title")?.addEventListener("click",()=>St("tour")),document.getElementById("tour-narrative-content")?.addEventListener("scroll",Ao,{passive:!0}),b?.addEventListener("click",()=>To()),k?.addEventListener("click",ko),document.getElementById("tour-directory-root")?.addEventListener("click",()=>{St("scene"),document.getElementById("tour-directory-root").focus({preventScroll:!0})}),R?.addEventListener("input",Ne),M?.addEventListener("change",Ne),W?.addEventListener("click",Ln),z?.addEventListener("click",()=>A.stop()),B?.addEventListener("click",()=>A.skipSegment(-1)),K?.addEventListener("click",()=>A.skipSegment(1)),D?.addEventListener("change",()=>{t.narrationVoiceURI=D.value,window.localStorage.setItem(s,t.narrationVoiceURI)}),F&&(F.value=String(t.narrationRate),F.addEventListener("change",()=>{let T=Number(F.value);t.narrationRate=f.has(T)?T:1,F.value=String(t.narrationRate),window.localStorage.setItem(c,String(t.narrationRate))})),document.getElementById("tour-search-results")?.addEventListener("click",T=>{let j=T.target instanceof Element?T.target.closest("[data-tour-search-result]"):null;j&&po(Number(j.getAttribute("data-tour-search-result")))}),window.addEventListener("keydown",T=>{if(t.mode==="tour"&&(T.metaKey||T.ctrlKey)&&T.shiftKey&&T.key.toLocaleLowerCase()==="f"){T.preventDefault(),T.stopImmediatePropagation(),t.tourSidebarHidden&&Kt(!1),xt("tour"),document.querySelector(".tour-search-disclosure")?.setAttribute("open",""),R?.focus(),R?.select();return}t.mode!=="tour"||T.metaKey||T.ctrlKey||T.altKey||Co(T.target)||T.target.closest?.("#tour-review")||(T.key==="PageUp"||T.key==="ArrowLeft"?(T.preventDefault(),t.zoom?.mode==="history"?zt(1)?.catch(ie):Bn(-1)):T.key==="PageDown"||T.key==="ArrowRight"?(T.preventDefault(),t.zoom?.mode==="history"?zt(-1)?.catch(ie):Bn(1)):t.zoom?.mode==="history"&&["ArrowUp","ArrowDown"].includes(T.key)&&(T.preventDefault(),Un(T.key==="ArrowUp"?-1:1)))},!0),window.addEventListener("bygone:tour-command",T=>{T.detail==="toggleNarration"&&Ln(),T.detail==="pauseNarration"&&A.pauseForExternalOwner()}),window.addEventListener("beforeunload",()=>A.dispose(),{once:!0}),jt(A.state)}function oo(){let n=document.getElementById("tour-narration-voice"),o=document.getElementById("tour-listen");if(!p){o&&(o.disabled=!0,o.title="Device narration is not supported by this browser."),n&&(n.disabled=!0),Qe("Device narration unavailable");return}let d=()=>{if(t.narrationVoices=window.speechSynthesis.getVoices().slice().sort((l,u)=>Number(u.default)-Number(l.default)||l.lang.localeCompare(u.lang)||l.name.localeCompare(u.name)),t.narrationVoiceURI&&t.narrationVoices.length>0&&!t.narrationVoices.some(l=>l.voiceURI===t.narrationVoiceURI)&&(t.narrationVoiceURI="",window.localStorage.removeItem(s)),n){let l=document.createElement("option");l.value="",l.textContent="System default voice",n.replaceChildren(l,...t.narrationVoices.map(u=>{let h=document.createElement("option");return h.value=u.voiceURI,h.textContent=`${u.name} (${u.lang})${u.default?" \u2014 default":""}`,h})),n.value=t.narrationVoiceURI,n.disabled=t.narrationVoices.length===0}};d(),window.speechSynthesis.addEventListener("voiceschanged",d)}function io(){let n=Number(window.localStorage.getItem(c));return f.has(n)?n:1}function so(){let n=null;return{speak(o,d){if(!p){d.onError("Device narration is not supported by this browser.");return}let l=new window.SpeechSynthesisUtterance(o.speechText),u=t.narrationVoices.find(h=>h.voiceURI===t.narrationVoiceURI);u&&(l.voice=u),l.rate=t.narrationRate,l.onend=()=>{n===l&&(n=null),d.onEnd()},l.onerror=h=>{n===l&&(n=null),d.onError(ao(h.error))},n=l,window.speechSynthesis.speak(l)},pause(){p&&window.speechSynthesis.pause()},resume(){p&&window.speechSynthesis.resume()},cancel(){n=null,p&&window.speechSynthesis.cancel()}}}function ao(n){return n==="not-allowed"?"Device narration needs permission to play audio.":n==="language-unavailable"||n==="voice-unavailable"?"The selected device voice is unavailable.":`Device narration failed${n?`: ${n}`:"."}`}function co(){if(!p||t.mode!=="tour")return;let n=Rn("playback-start");if(!n)return;let o=n.segments[0];It(!!(o&&["chapter","scene-title","summary","bullet","takeaway"].includes(o.source.field))),t.renderedNarrationUnit=n,Eo(n),A.start(n,!0)}function Ln(){A.state.kind==="playing"||A.state.kind==="paused"?A.togglePause():co()}function Rn(n){return!t.tour||t.activeSceneIndex<0?null:Nr(t.tour,{sceneIndex:t.activeSceneIndex,stepIndex:t.activeStepIndex},{entry:n})}function lo(n,o){let d=t.tour;return!!(d&&wn(d.scenes,n.position,o))}function uo(n,o){let d=t.tour;if(!d)return null;let l=wn(d.scenes,n.position,o);return l?se(l.sceneIndex,l.stepIndex,{narrationNavigation:"controller",narrationEntry:"continuous",showIntro:!1}):null}function fo(){fetch("/narration/claim",{method:"POST",cache:"no-store"}).catch(()=>{})}function jt(n){let o=document.getElementById("tour-listen"),d=document.getElementById("tour-stop"),l=document.getElementById("tour-narration-skip-back"),u=document.getElementById("tour-narration-skip-ahead");if(o){o.disabled=!p||t.mode!=="tour";let h=n.kind==="playing";o.querySelector(".tour-play-pause-icon")?.setAttribute("d",h?"M7 5h4v14H7zM13 5h4v14h-4z":"m8 5 11 7-11 7Z");let y=h?"Pause narration":n.kind==="paused"?"Resume narration":"Listen from the current tour item";o.title=y,o.setAttribute("aria-label",y),document.getElementById("tour-listen-label").textContent=h?"Pause":n.kind==="paused"?"Resume":"Listen"}if(d&&(d.disabled=n.kind!=="playing"&&n.kind!=="paused"),l&&(l.disabled=!A.canSkipSegment(-1)),u&&(u.disabled=!A.canSkipSegment(1)),n.kind==="playing"||n.kind==="paused"){let h=n.segmentIndex+1,y=n.unit.segments.length;Qe(`${n.kind==="paused"?"Paused":"Speaking"} \xB7 segment ${h} of ${y}`)}else n.kind==="completed"?Qe("Narration complete"):n.kind==="error"?Qe(n.message):p&&Qe("Device voice ready")}function Qe(n){let o=document.getElementById("tour-narration-status");o&&(o.textContent=n)}function ho(n,o){if(document.querySelectorAll(".tour-narration-segment.is-speaking").forEach(b=>{b.classList.remove("is-speaking","is-paused")}),!n)return;let d=[...document.querySelectorAll("[data-narration-segment-id]")].find(b=>b.dataset.narrationSegmentId===n.id);if(!d||(d.classList.add("is-speaking"),d.classList.toggle("is-paused",o),o))return;let l=d.closest("[data-reading-kind]");if(l?.dataset.readingKind==="scene"){let b=["chapter","scene-title","summary","bullet","takeaway"].includes(n.source.field);It(b)}else l?.dataset.readingKind==="step"&&It(!1);let u=document.getElementById("tour-narrative-content");if(!u)return;let h=d.getBoundingClientRect(),y=u.getBoundingClientRect();(h.top<y.top||h.bottom>y.bottom)&&(d.scrollIntoView({block:"nearest"}),x=u.scrollTop)}let et=[];function Ne(){let n=document.getElementById("tour-search-input"),o=document.getElementById("tour-search-scope"),d=document.getElementById("tour-search-status"),l=document.getElementById("tour-search-results");if(!(!t.tour||!n||!o||!d||!l)){if(et=Pr(t.tour,n.value,o.value),!n.value.trim()){d.textContent="Cmd/Ctrl+Shift+F",l.replaceChildren();return}d.textContent=`${et.length} result${et.length===1?"":"s"}`,l.replaceChildren(...et.map((u,h)=>{let y=document.createElement("button");y.type="button",y.className="tour-search-result",y.setAttribute("role","option"),y.dataset.tourSearchResult=String(h),y.title=`Open ${u.kind==="code"?`${u.label}:${u.lineNumber}`:u.label}`;let b=document.createElement("span");b.className="tour-search-location",b.textContent=u.kind==="code"?`${u.label}:${u.lineNumber}`:u.label;let k=document.createElement("span");return k.className="tour-search-preview",k.textContent=u.preview.trim(),y.append(b,k),y}))}}function po(n){let o=et[n];if(o){if(o.kind==="narrative"){Y(),se(o.sceneIndex,o.stepIndex??0,{showIntro:o.stepIndex===void 0});return}Qt(o.fileIndex)&&(It(!1),window.requestAnimationFrame(()=>L({type:"revealSearchResult",sideIndex:o.sideIndex,lineNumber:o.lineNumber,startColumn:o.startColumn,endColumn:o.endColumn})))}}function mo(){let n=document.getElementById("tour-shell"),o=document.getElementById("tour-sidebar-resizer"),d=document.getElementById("tour-sidebar-hide"),l=document.getElementById("tour-sidebar-show");!n||!o||!d||!l||(On(),d.addEventListener("click",()=>Kt(!0)),l.addEventListener("click",()=>Kt(!1)),o.addEventListener("pointerdown",u=>{u.preventDefault(),document.body.classList.add("is-resizing-tour-sidebar"),o.setPointerCapture?.(u.pointerId);let h=b=>Pn(b.clientX),y=()=>{document.body.classList.remove("is-resizing-tour-sidebar"),window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),window.localStorage.setItem(r,String(t.tourSidebarWidth))};window.addEventListener("pointermove",h),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)}),o.addEventListener("keydown",u=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(u.key))return;u.preventDefault();let h=t.tourSidebarWidth;u.key==="Home"?h=240:u.key==="End"?h=Gt():h+=u.key==="ArrowLeft"?-16:16,Pn(h),window.localStorage.setItem(r,String(t.tourSidebarWidth))}))}function go(){let n=Number.parseInt(window.localStorage.getItem(r)||"",10);return Number.isFinite(n)?Math.min(600,Math.max(240,n)):300}function Gt(){return Math.max(240,Math.min(600,Math.floor(window.innerWidth*.6)))}function Pn(n){t.tourSidebarWidth=Math.min(Gt(),Math.max(240,Math.round(n))),On(),window.dispatchEvent(new Event("resize"))}function On(){document.documentElement.style.setProperty("--tour-rail-width",`${t.tourSidebarWidth}px`);let n=document.getElementById("tour-sidebar-resizer");n?.setAttribute("aria-valuemax",String(Gt())),n?.setAttribute("aria-valuenow",String(t.tourSidebarWidth))}function Kt(n){t.tourSidebarHidden=n,document.body.classList.toggle("tour-sidebar-hidden",n);let o=document.getElementById("tour-sidebar-show");o&&(o.hidden=!n),window.dispatchEvent(new Event("resize"))}function yo(){let n=document.getElementById("tour-narrative");if(!n)return;let o=()=>{let d=n.hidden?0:Math.ceil(n.getBoundingClientRect().height);document.documentElement.style.setProperty("--tour-narrative-height",`${d}px`);let l=document.getElementById("tour-narrative-content");l?.style.setProperty("--tour-reading-viewport",`${l.clientHeight}px`),window.dispatchEvent(new Event("resize"))};new ResizeObserver(o).observe(n),o()}async function Dn(n){ve("Loading change tour\u2026");let o=Gr(n),d={...t,historyEntries:[...t.historyEntries],fileHistoryCache:new Map(t.fileHistoryCache),displayedPanels:[...t.displayedPanels],historyPanels:[...t.historyPanels],comparisonCommits:[...t.comparisonCommits],comparisonDraftCommits:[...t.comparisonDraftCommits]},l=document.body.className,u=document.getElementById("tour-shell")?.hidden,h=document.getElementById("tour-narrative")?.hidden,y=document.getElementById("tour-mode-controls")?.hidden,b=J,k=V,R=me,M=Z;try{A.stop();let W=await fetch(n,{cache:"no-store"});if(!W.ok)throw new Error(`Manifest request failed (${W.status}).`);let z=Ir(await W.json()),K=oe(z).deconstructed?"deconstructed":"historical",D=ne(z)?(await Ie("list",{commit:z.range.headOid},o,z)).entries:[];t.tour=z,t.authoredTour=z,t.historyPrefix=o,t.zoom=new Bt(K),t.historyEntries=D,t.zoom&&(t.tour=Ye(K)),t.mode="tour",document.body.classList.add("tour-mode"),Be(),Me(),Ne();let F=new URLSearchParams(window.location.search),T=yn(t.tour.scenes,F.get("scene"),F.get("step"));if(se(T.sceneIndex,T.stepIndex,{showIntro:F.get("view")==="overview"||!F.get("step"),readingKey:!F.get("scene")&&!F.get("step")?"title":void 0}),["tour","chapter"].includes(F.get("view"))&&St(F.get("view")),t.zoom){let O={explanation:"deconstructed",revisions:"historical",final:ge()?"historical":"compare"}[F.get("mode")]||F.get("mode");if(O==="history"&&ce().includes("history"))t.historyPath=F.get("file"),t.tourNavigatorTab="commits",t.zoom.enter("history"),t.tour=Ye("history"),Be(),Me(),await Fe(t.historyPath||t.tour.files.find(X=>X.kind==="text-diff")?.path,F.get("commit"));else if(O==="compare"&&ce().includes("compare")){let X=F.get("commits")?.split(",").filter(Boolean);await $e("compare",{commits:X?.length?X:[F.get("from")||t.authoredTour.range.mergeBaseOid,F.get("to")||t.authoredTour.range.headOid],...F.get("scope")?{path:F.get("scope")}:{}},F.get("file"))}else if(O&&O!==t.zoom.mode&&ce().includes(O)){await $e(O);let X=yn(t.tour.scenes,F.get("scene"),F.get("step"));se(X.sceneIndex,X.stepIndex,{showIntro:F.get("view")==="overview"||!F.get("step"),readingKey:!F.get("scene")&&!F.get("step")?"title":void 0}),["tour","chapter"].includes(F.get("view"))&&St(F.get("view"))}let re=N;N=null,E&&re&&re!==t.zoom.mode&&ce().includes(re)&&await $e(re)}return t.directoryEvidence&&F.get("file")&&Xt(F.get("file")),jt(A.state),t.workspacePromptStatus="",ye(),ve(""),!0}catch(W){Object.assign(t,d),J=b,V=k,me=R,Z=M,document.body.className=l;let z=document.getElementById("tour-shell");z&&u!==void 0&&(z.hidden=u);let B=document.getElementById("tour-narrative");B&&h!==void 0&&(B.hidden=h);let K=document.getElementById("tour-mode-controls");return K&&y!==void 0&&(K.hidden=y),t.mode==="tour"&&t.tour&&(Be(),Me(),Ne(),ye()),ve(`Could not load change tour: ${W instanceof Error?W.message:String(W)}`),!1}}function Be(){kt();let n=t.tour;if(!n)return;let o=document.getElementById("tour-shell"),d=document.getElementById("tour-title"),l=document.getElementById("tour-source"),u=document.getElementById("tour-range"),h=document.getElementById("tour-stats"),y=document.getElementById("tour-authoring-coverage"),b=document.getElementById("tour-scenes"),k=document.getElementById("tour-scene-count"),R=document.getElementById("tour-files"),M=document.getElementById("tour-file-count");if(!o||!d||!l||!u||!h||!y||!b||!k||!R||!M)throw new Error("Presenter UI is incomplete.");o.hidden=!1,d.textContent=n.title,document.title=Mr(n),n.sourceUrl?(l.href=n.sourceUrl,l.hidden=!1):(l.removeAttribute("href"),l.hidden=!0);let W=Ue(n.range.baseRef),z=Ue(n.range.headRef),B=n.range.headOid.slice(0,7);u.textContent=`${W} \u2192 ${z}${z===B?"":` \xB7 ${B}`}`,h.textContent=`${it(n.summary.changedFiles,"file")} \xB7 +${n.summary.additions} \u2212${n.summary.deletions} \xB7 ${it(n.summary.commitCount,"commit")}`,vo(y,n.authoringCoverage),wo(),k.textContent=String(n.scenes.length),M.textContent=String(n.files.length),b.replaceChildren(),ee()&&on();let K=new Map(n.scenes.map(D=>[D.id,D]));for(let D of n.chapters){let F=zn(`chapter:${D.id}`,D.title,"tour-chapter-link",()=>{let j=w.find(O=>O.kind==="chapter"&&O.chapterId===D.id)||w.find(O=>O.kind==="scene"&&D.sceneIds.includes(n.scenes[O.sceneIndex]?.id));j&&st(j)}),T=n.chapters.length>1?F.children:b;n.chapters.length>1&&b.append(F.group);for(let j of D.sceneIds){let O=K.get(j);if(!O)continue;let re=n.scenes.indexOf(O),X=zn(`scene:${O.id}`,O.title,"tour-scene",()=>se(re,0,{userNavigation:!0,showIntro:!0})),Ct=X.link;Ct.replaceChildren(),Ct.dataset.sceneId=O.id,O.kind==="text-diff"&&(Ct.dataset.filePath=O.path),X.link.title=`Open scene: ${O.kind==="text-diff"?O.path:O.title}`;let sn=document.createElement("span");sn.className="tour-scene-number",sn.textContent=String(re+1).padStart(2,"0");let an=document.createElement("span");an.className="tour-scene-copy";for(let[at,_e]of[["tour-scene-title",O.title],["tour-scene-path",O.kind==="text-diff"?O.path:O.kind==="deconstructed-diff"?`${it(O.panels.length-1,"comparison stage")} \xB7 ${it(O.steps.length,"tour slide")}`:Se(O)?it(O.steps.length,"code step"):"Discussion"],["tour-scene-note",O.takeaway]]){let Ce=document.createElement("span");Ce.className=at,Ce.textContent=_e,an.append(Ce)}if(Ct.append(sn,an),T.append(X.group),Se(O)){let at=X.children;at.classList.add("tour-outline-steps"),at.dataset.sceneId=O.id,O.steps.forEach((_e,Ce)=>{let Ee=document.createElement("button");Ee.type="button",Ee.className="tour-outline-step",Ee.dataset.sceneId=O.id,Ee.dataset.stepIndex=String(Ce);let Mo=O.kind==="deconstructed-diff"?`Stage ${(_e.stageIndex??_e.pairIndex)+1}: `:"";Ee.textContent=`${Ce+1}. ${Mo}${_e.title}`,Ee.title=`Open step ${Ce+1}: ${_e.title}`,Ee.addEventListener("click",()=>se(re,Ce,{userNavigation:!0,showIntro:!1})),at.append(Ee)})}else X.toggle.hidden=!0}}R.replaceChildren(...n.files.map((D,F)=>{let T=document.createElement("button");T.type="button",T.className=`tour-file${D.kind==="omitted"?" is-omitted":""}`,T.dataset.filePath=D.path,T.disabled=D.kind==="omitted",T.title=D.kind==="omitted"?`${D.path}: ${D.reason}`:`Open file: ${D.path}`,D.kind==="text-diff"&&T.addEventListener("click",()=>nt(F));let j=document.createElement("span");j.className="tour-file-marker",j.textContent=D.kind==="omitted"?"\xD7":en(D.changeKind);let O=document.createElement("span");O.className="tour-file-copy";let re=document.createElement("span");re.className="tour-file-path",re.textContent=D.path;let X=document.createElement("span");return X.className="tour-file-meta",X.textContent=D.kind==="omitted"?`Not rendered \xB7 ${D.reason}`:`${tn(D.changeKind)} \xB7 +${D.additions} \u2212${D.deletions}`,O.append(re,X),T.append(j,O),T})),xt(t.tourNavigatorTab)}function wt(n){document.getElementById("tour-review").hidden=!n;let o=document.getElementById("tour-review-toggle");o.setAttribute("aria-expanded",String(n)),(n?document.getElementById("tour-review-close"):o).focus()}function wo(){let n=t.authoredTour,o=n?.review,d=document.getElementById("tour-review-toggle"),l=document.getElementById("tour-review-content");if(d.hidden=!o,l.replaceChildren(),!o){document.getElementById("tour-review").hidden=!0,d.setAttribute("aria-expanded","false");return}d.textContent=`Review notes (${o.items.length})`;let u=document.createElement("p");u.className="tour-review-provenance",u.textContent="Authored interpretations. Linked evidence is checked; conclusions and external checks are not verified.";let h=document.createElement("p");h.className="tour-review-range",h.textContent=`Reviewed snapshot: ${o.baseOid.slice(0,7)} \u2192 ${o.headOid.slice(0,7)}. Evidence opens this range\u2019s final diff.`,h.title=`${o.baseOid} \u2192 ${o.headOid}`,l.append(u,h);let y=n.zoom?.final.scenes||n.scenes;for(let[b,k]of[["concept","Concepts and invariants"],["boundary","Boundaries and prerequisites"],["tradeoff","Complexity tradeoffs"],["question","Open questions"]]){let R=o.items.filter(W=>W.kind===b);if(!R.length)continue;let M=document.createElement("h3");M.textContent=k,l.append(M);for(let W of R){let z=document.createElement("article");z.className="tour-review-item";let B=document.createElement("h4");B.textContent=W.title;let K=document.createElement("p");K.textContent=W.body,z.append(B,K);for(let D of W.evidence){let T=y.find(O=>O.id===D.sceneId).steps.find(O=>O.id===D.stepId),j=document.createElement("button");j.type="button",j.className="tour-review-evidence",j.textContent=`${T.title} \xB7 ${T.focus.path}:${T.focus.startLine} (${T.focus.revision})`,j.title=`Open evidence in the reviewed snapshot: ${T.title}`,j.addEventListener("click",()=>{bo(D)}),z.append(j)}if(W.nextCheck){let D=document.createElement("p");D.className="tour-review-next",D.textContent=`Next check: ${W.nextCheck}`,z.append(D)}l.append(z)}}}async function bo(n){let o=document.getElementById("tour-review-status");if(o.textContent="",t.zoomSwitching){o.textContent="Wait for the current mode change, then open the evidence again.";return}t.zoom&&t.zoom.mode!=="final"&&await $e("final");let d=t.tour.scenes.findIndex(h=>h.id===n.sceneId),l=t.tour.scenes[d],u=l?.kind==="walkthrough"?l.steps.findIndex(h=>h.id===n.stepId):-1;if(t.zoom&&t.zoom.mode!=="final"||u<0){o.textContent="Could not open the reviewed snapshot. Try switching to Final diff first.";return}V=null,se(d,u,{userNavigation:!0}),wt(!1)}function vo(n,o){if(n.replaceChildren(),n.hidden=!o,!o)return;let d=[{metric:"walkthrough",label:"Anchored diff hunks",covered:o.walkthrough.coveredUnits,total:o.walkthrough.includedUnits,percent:o.walkthrough.coveragePercent,description:"Distinct change hunks referenced by authored base/head focus anchors. Revision-stack steps are not counted."},...o.explanationAssignments.map(l=>({metric:"assignment",label:o.explanationAssignments.length>1?`Deconstructed assignment \xB7 ${l.sceneId}`:"Deconstructed assignment",covered:l.completeUnits,total:l.totalUnits,percent:l.assignmentPercent,description:`${l.assignedUnits} assigned, ${l.excludedUnits} explicitly excluded.`}))];for(let l of d){let u=document.createElement("div");u.className="tour-coverage-item",u.dataset.metric=l.metric,u.title=l.description;let h=document.createElement("div");h.className="tour-coverage-heading";let y=document.createElement("span");y.textContent=l.label;let b=document.createElement("strong");b.textContent=`${l.covered}/${l.total} \xB7 ${l.percent}%`,h.append(y,b);let k=document.createElement("div");k.className="tour-coverage-meter",k.setAttribute("role","progressbar"),k.setAttribute("aria-label",l.label),k.setAttribute("aria-valuemin","0"),k.setAttribute("aria-valuemax","100"),k.setAttribute("aria-valuenow",String(l.percent));let R=document.createElement("span");R.style.width=`${l.percent}%`,k.append(R),u.append(h,k),n.append(u)}}function se(n,o=0,d={}){let l=t.tour;if(!l||n<0||n>=l.scenes.length)return null;if(d.userNavigation&&Y(),t.zoom?.mode==="history"&&!t.zoomSwitching){let k=l.scenes[n],R=k.path||k.steps?.[o]?.file||t.activeTourFilePath;return Fe(R,t.historyCommit).catch(M=>{document.getElementById("tour-mode-status").textContent=M.message}),null}t.directoryEvidence=null,kt(),on();let u=w.find(k=>k.key===d.readingKey)||Mt(w,n,o,d.showIntro?"overview":null);u&&(n=u.sceneIndex,o=u.stepIndex);let h=l.scenes[n];t.readingKey=u?.key||"title",t.sceneIntroVisible=u?.kind!=="step",t.narrativeParent=u?.kind==="title"?"tour":u?.kind==="chapter"?"chapter":null,t.activeSceneIndex=n,t.activeStepIndex=Se(h)?Math.min(Math.max(o,0),Math.max(h.steps.length-1,0)):0,t.tourFocusFilePath=h.kind==="text-diff"?h.path:h.kind==="walkthrough"?h.steps[t.activeStepIndex]?.diff.path??null:le(h)?h.steps[t.activeStepIndex]?.file??null:null;let y=_n(l,n);jn();let b=Rn(d.narrationEntry||"playback-start");return t.renderedNarrationUnit=b,Wn(h,y,b),d.fromReadingScroll||No(t.readingKey),b&&!d.zoomLanding&&(!t.zoom||ee())&&(d.narrationNavigation==="linear"?A.followLinearNavigation(b):d.narrationNavigation!=="controller"&&A.followDirectNavigation(b)),ue(),t.sceneIntroVisible&&bt()?b:h.kind==="discussion"?(++J,t.displayedPanels=[],t.activeTourFilePath=null,L({type:"updateCommitHistory",history:Tn()}),document.body.classList.add("tour-discussion"),Ae(),b):(document.body.classList.remove("tour-discussion"),h.kind==="walkthrough"?(Zt(h),b):le(h)?(Yt(h),b):(tt(h,vt(h.path)),b))}function Vt(n){let o=document.getElementById("status-banner");o.textContent=n,o.hidden=!n}function bt(){let n=t.tour?.scenes[t.activeSceneIndex];if(!ee()||!n||!t.narrativeParent&&n.kind==="text-diff")return!1;let o=t.narrativeParent==="tour"?{...n,kind:"discussion",overview:void 0}:n,d=Fr(t.tour,o);return t.directoryEvidence=d,t.activeTourFilePath=null,Ae(),document.body.classList.remove("tour-discussion"),L({type:"showDirectoryDiff",leftLabel:d.labels[0],rightLabel:d.labels[1],labels:d.labels,entries:d.entries,canMutate:!1}),Vt(d.entries.length?"":"No changed files in this directory for the selected comparison."),ue(),!0}function Xt(n){let o=t.directoryEvidence;if(!o)return!1;let d=o.files.find(l=>l.path===n);if(!d){let l=o.omitted.find(u=>u.path===n);return Vt(l?`${n}: ${l.reason}`:"This file has no change in the overview comparison."),!1}return Y(),Vt(""),tt(d,[],`directory-${t.tour.scenes[t.activeSceneIndex].id}-${n}`),ue(),!0}function vt(n){let o=t.tour;return!o||!n?[]:Or(o,n,t.activeSceneIndex,t.activeStepIndex)}function xo(n,o){let d=t.tour;return!d||!n?[]:Dr(d,n,t.activeSceneIndex,t.activeStepIndex,(l,u)=>vn(o?.[l]?.diffModel,u))}function Jt(n){return`file::${n}`}function tt(n,o=[],d=Jt(n.path),l=null){if(!t.tour)return;t.activeTourFilePath=t.zoom?.mode==="history"&&t.historyPath||n.path,Ae();let h=ae(n.leftContent,n.rightContent),y=Mn(n,n.leftLabel,t.zoom?.mode==="compare"?"from":"base"),b=Mn(n,n.rightLabel,t.zoom?.mode==="compare"?"to":"head"),k=o.find(M=>M.active),R=n.changeKind==="added"?{left:!1,right:!0}:n.changeKind==="deleted"?{left:!0,right:!1}:{left:!0,right:!0};L({type:"showDiff",file1:`1. ${y}`,file2:`2. ${b}`,comparisonId:`tour-${d}`,leftContent:n.leftContent,rightContent:n.rightContent,canReturnToDirectory:!!t.directoryEvidence,sourceInfo:{leftPath:n.previousPath||n.path,rightPath:n.path},fileExists:R,diffModel:h,history:l,fileNavigation:{canGoPrevious:!!be(-1),canGoNext:!!be(1)},editableSides:{left:!1,right:!1},comparisonSummary:n.takeaway?`${n.path} \xB7 ${n.takeaway}`:n.path,initialChangeIndex:k?Hn(h,k.side,k.startLine):n.focusChangeIndex,tourAnnotations:o})}function Mn(n,o,d){if(t.zoom?.mode==="history")return o;let l=o.startsWith(n.path)?o.slice(n.path.length).trim():o.trim();return l?`${d} ${l}`:d}function Zt(n){let o=n.steps[t.activeStepIndex];o&&tt(o.diff,vt(o.diff.path),Jt(o.diff.path))}function Yt(n){let o=n.steps[t.activeStepIndex];o&&Fn(n,o.file,o)}function Fn(n,o,d){let l=rt(n,o);if(!d||!l)return;t.activeTourFilePath=l.path,Ae();let u=l.panels.map((B,K)=>({id:`${n.id}-${l.path}-${B.id}`,commit:n.kind==="stacked-diff"?ot(n)[K].oid:void 0,label:B.label,path:B.path||l.path,content:B.content,savedContent:B.content,dirty:!1,editable:!1,stackId:ot(n)[K].id})),h=u.slice(0,-1).map((B,K)=>({leftIndex:K,rightIndex:K+1,diffModel:ae(B.content,u[K+1].content)})),y=xo(l.path,h),b=y.find(B=>B.active),k=b?.pairIndex??d.pairIndex,R=b?.side??d.side,M=b?.startLine??d.startLine,W=h[k]?.diffModel,z=W&&M?Hn(W,R,M):0;L({type:"showMultiDiff",panels:u,pairs:h,activePanelId:u[k+(R==="right"?1:0)]?.id,activePairIndex:k,initialChangeIndex:z,revealFirstChangeInEachPanel:n.kind==="deconstructed-diff",history:null,fileNavigation:{canGoPrevious:!!be(-1),canGoNext:!!be(1)},mutationEnabled:!1,comparisonSummary:n.kind==="deconstructed-diff"?`${n.stageLabel} \xB7 ${l.path} \xB7 ${Ue(n.realRange.baseRef)} \u2192 ${Ue(n.realRange.targetRef)}`:`${l.path} \xB7 ${n.takeaway}`,tourAnnotations:y})}function Bn(n){if(!ee())return!1;let o=Lr(w,t.readingKey,n);return o?(st(o),!0):!1}function be(n){let o=t.tour;if(!o||n!==-1&&n!==1)return null;let d=o.scenes[t.activeSceneIndex];if(t.directoryEvidence){let l=t.directoryEvidence.files,u=l.findIndex(b=>b.path===t.activeTourFilePath),h=l[u+n],y=h?o.files.findIndex(b=>b.path===h.path):-1;return y>=0?{fileIndex:y,path:h.path}:null}if(le(d)){let l=d.steps[t.activeStepIndex]?.pairIndex;if(!Number.isInteger(l))return null;let u=o.files.flatMap(b=>{if(b.kind!=="text-diff")return[];let k=rt(d,b.path);return k?[k]:[]}),h=Er(u,l,t.activeTourFilePath,n);if(!h)return null;let y=o.files.findIndex(b=>b.kind==="text-diff"&&b.path===h.path);return y>=0?{fileIndex:y,path:h.path}:null}return Tr(o.files,t.activeTourFilePath,n)}function Un(n){let o=be(n);return o?nt(o.fileIndex):!1}function Qt(n,o=!0){let d=t.tour?.files[n];return!d||d.kind!=="text-diff"?!1:(o&&A.interruptForExploration(),tt(d,vt(d.path),Jt(d.path)),!0)}function nt(n){let o=t.tour?.files[n];if(!o||o.kind!=="text-diff")return!1;if(Y(),t.zoom?.mode==="history")return Fe(o.path,t.historyCommit).catch(l=>{document.getElementById("tour-mode-status").textContent=l.message}),!0;if(t.zoom?.mode==="compare")return $n(o);if(t.directoryEvidence&&ee())return Xt(o.path);t.zoomSwitching||A.interruptForExploration();let d=t.tour?.scenes[t.activeSceneIndex];if(le(d)){let l=d.steps[t.activeStepIndex];return l&&rt(d,o.path)?(Fn(d,o.path,l),!0):!1}return Qt(n,!1)}function rt(n,o){let d=n?.files?.find(h=>h.path===o);if(d||n?.kind!=="deconstructed-diff")return d;let l=t.tour?.files.find(h=>h.kind==="text-diff"&&h.path===o);if(!l||l.kind!=="text-diff")return null;let u=l.changeKind!=="deleted";return{path:l.path,panels:ot(n).map(h=>({id:h.id,label:`${h.label} / ${l.path}${u?"":" (absent)"}`,path:u?l.path:void 0,content:u?l.rightContent:"",exists:u}))}}function ko(){if(t.directoryEvidence)return bt();let n=t.tour?.scenes[t.activeSceneIndex];if(!n||!t.tourFocusFilePath)return!1;if(n.kind==="walkthrough")Zt(n);else if(le(n))Yt(n);else if(n.kind==="text-diff")tt(n,vt(n.path));else return!1;return!0}function xt(n){["tour","files","commits"].includes(n)&&(t.tourNavigatorTab=n,document.querySelectorAll("[data-tour-navigator]").forEach(o=>{let d=o.dataset.tourNavigator===n;o.classList.toggle("is-active",d),o.setAttribute("aria-selected",String(d)),o.tabIndex=d?0:-1}),document.querySelectorAll("[data-tour-navigator-panel]").forEach(o=>{o.hidden=o.dataset.tourNavigatorPanel!==n}),window.dispatchEvent(new CustomEvent("bygone:present-navigator-change",{detail:{tab:n}})),window.dispatchEvent(new Event("resize")))}function kt(){let n=!!(t.directoryEvidence&&ee()),o=n?t.activeTourFilePath:null;document.body.classList.toggle("tour-directory-overview",n),document.body.classList.toggle("tour-directory-file-open",!!o),document.getElementById("tour-directory-breadcrumb").hidden=!n;let d=document.getElementById("tour-directory-root");o?d.removeAttribute("aria-current"):d.setAttribute("aria-current","location"),document.getElementById("tour-directory-separator").hidden=!o;let l=document.getElementById("tour-directory-file");l.textContent=o||"",l.hidden=!o;let u=document.getElementById("tour-directory-narration-context");u.hidden=!o,u.textContent=`Narration describes the ${t.narrativeParent||"overview"}`}function Ae(){kt();let n=t.tour?.scenes[t.activeSceneIndex],o=le(n)?n.steps[t.activeStepIndex]:null;document.querySelectorAll(".tour-file").forEach(l=>{let u=l.dataset.filePath;l.classList.toggle("is-active",u===t.activeTourFilePath),l.classList.toggle("is-tour-focus",!t.directoryEvidence&&u===t.tourFocusFilePath),l.disabled=!!(t.directoryEvidence&&!t.directoryEvidence.files.some(k=>k.path===u)),l.classList.remove("is-comparison-changed","is-comparison-empty"),delete l.dataset.comparisonState;let h=t.tour?.files.find(k=>k.path===u),y=l.querySelector(".tour-file-marker"),b=l.querySelector(".tour-file-meta");if(t.directoryEvidence&&l.disabled&&h?.kind==="text-diff"){let k="Not in this overview comparison";l.setAttribute("title",`${u} \xB7 ${k}`),l.setAttribute("aria-label",`${u}, ${k}`),b&&(b.textContent=k),y&&(y.textContent="\u25CB");return}if(t.directoryEvidence&&h?.kind==="text-diff"){let k=t.directoryEvidence.files.find(M=>M.path===u),R=`${tn(k.changeKind)} in overview`;l.setAttribute("title",`${u} \xB7 ${R}`),l.setAttribute("aria-label",`${u}, ${R}`),b&&(b.textContent=R),y&&(y.textContent=en(k.changeKind));return}if(o&&h?.kind==="text-diff"){let k=rt(n,u);if(k){let R=gn(k,o.pairIndex),M=Io(R);l.dataset.comparisonState=R,l.classList.add(M.changed?"is-comparison-changed":"is-comparison-empty"),l.setAttribute("title",`${h.path} \xB7 ${M.label}`),l.setAttribute("aria-label",`${h.path}, ${M.label}`),y&&(y.textContent=M.marker),b&&(b.textContent=M.label);return}}if(h){let k=h.kind==="omitted"?`${h.path}: ${h.reason}`:`Open file: ${h.path}`;l.setAttribute("title",k),l.setAttribute("aria-label",k),y&&(y.textContent=h.kind==="omitted"?"\xD7":en(h.changeKind)),b&&(b.textContent=h.kind==="omitted"?`Not rendered \xB7 ${h.reason}`:`${tn(h.changeKind)} \xB7 +${h.additions} \u2212${h.deletions}`)}}),document.querySelector(".tour-file.is-active")?.scrollIntoView({block:"nearest"});let d=document.getElementById("tour-return-focus");if(d){let l=ee();d.hidden=!l||!!t.directoryEvidence||!t.tourFocusFilePath||t.activeTourFilePath===t.tourFocusFilePath}}function Io(n){return{"modified-here":{label:"Modified here",marker:"\u2022",changed:!0},"created-here":{label:"Created here",marker:"+",changed:!0},"deleted-here":{label:"Deleted here",marker:"\u2212",changed:!0},"unchanged-here":{label:"Unchanged here",marker:"\u25CB",changed:!1},"not-created-yet":{label:"Not created yet",marker:"\u2026",changed:!1},"already-deleted":{label:"Already deleted",marker:"\xD7",changed:!1}}[n]}function Se(n){return n.kind==="walkthrough"||n.kind==="stacked-diff"||n.kind==="deconstructed-diff"}function le(n){return n?.kind==="stacked-diff"||n?.kind==="deconstructed-diff"}function ot(n){return n.kind==="deconstructed-diff"?n.panels:n.stack}function en(n){return{added:"+",deleted:"\u2212",renamed:"\u2192",modified:"\u2022"}[n]||"\u2022"}function tn(n){return`${n.charAt(0).toUpperCase()}${n.slice(1)}`}function _n(n,o){let d=n.scenes[o],l=n.chapters.findIndex(b=>b.sceneIds.includes(d.id)),u=l>=0?n.chapters[l]:null,h=u?u.sceneIds.indexOf(d.id)+1:o+1,y=u?u.sceneIds.length:n.scenes.length;return{chapter:u,chapterIndex:l,chapterNumber:l>=0?l+1:o+1,sceneInChapter:h,scenesInChapter:y,sceneNumber:o+1,sceneCount:n.scenes.length}}function So(n,o,d){return Se(o)?`Scene ${n.sceneNumber} of ${n.sceneCount} \xB7 Step ${d+1} of ${o.steps.length}`:`Scene ${n.sceneNumber} of ${n.sceneCount}`}function Hn(n,o,d){let u=(o==="left"?n.leftLines:n.rightLines).findIndex(M=>M.lineNumber===d);if(u<0)return 0;let h=o==="left"?"leftStart":"rightStart",y=o==="left"?"leftEnd":"rightEnd",b=n.blocks.findIndex(M=>u>=M[h]&&u<M[y]);if(b>=0)return b;let k=0,R=Number.POSITIVE_INFINITY;return n.blocks.forEach((M,W)=>{let z=Math.min(Math.abs(u-M[h]),Math.abs(u-M[y]));z<R&&(k=W,R=z)}),k}function Ue(n){return/^[0-9a-f]{40}$/i.test(n)?n.slice(0,7):n}function it(n,o){return`${n} ${n===1?o:`${o}s`}`}function Co(n){return n instanceof Element&&!!n.closest('a, button, input, select, summary, textarea, [contenteditable="true"], [role="textbox"], .monaco-editor')}function Eo(n){let o=t.tour?.scenes[t.activeSceneIndex];!t.tour||!o||Wn(o,_n(t.tour,t.activeSceneIndex),n)}function It(n){let o=t.tour?.scenes[t.activeSceneIndex];if(!o)return;t.narrativeParent=null,t.sceneIntroVisible=n;let d=Mt(w,t.activeSceneIndex,t.activeStepIndex,n?"overview":null);d&&(t.readingKey=d.key),jn(),rn(),t.sceneIntroVisible&&!t.directoryEvidence?bt():!t.sceneIntroVisible&&t.directoryEvidence&&(t.directoryEvidence=null,o.kind==="walkthrough"?Zt(o):le(o)&&Yt(o)),ue()}function St(n){let o=Mt(w,t.activeSceneIndex,t.activeStepIndex,n==="scene"?"overview":n==="step"?null:n);o&&st(o)}function nn(n,o,d){let l=document.createElement("button");return l.type="button",l.textContent=n,l.title=o,l.addEventListener("click",d),l}function zn(n,o,d,l){let u=document.createElement("div");u.className="tour-outline-group",u.dataset.readingGroup=n;let h=document.createElement("div");h.className="tour-outline-heading";let y=document.createElement("div");y.className="tour-outline-children",y.id=`outline-${encodeURIComponent(n)}`;let b=`${t.zoom?.mode||"tour"}:${n}`,k=nn("\u25BE",`Expand or collapse ${o}`,()=>{$.has(b)?$.delete(b):$.add(b),R()});k.className="tour-outline-toggle",k.setAttribute("aria-controls",y.id);let R=()=>{y.hidden=$.has(b),k.setAttribute("aria-expanded",String(!y.hidden)),k.textContent=y.hidden?"\u25B8":"\u25BE"};R();let M=nn(o,`Read ${o}`,l);return M.className=d,M.dataset.readingLink=n,h.append(k,M),u.append(h,y),{group:u,children:y,link:M,toggle:k}}function To(){let n=document.getElementById("tour-audio-settings");n&&(n.hidden=!n.hidden,rn())}function rn(){kt();let n=document.getElementById("tour-narration"),o=document.getElementById("tour-audio-settings");if(n){let d=!!(o&&!o.hidden);n.setAttribute("aria-expanded",String(d)),n.textContent=d?"\u203A":"\u2039 Narration",n.title=d?"Hide narration controls":"Show narration controls",n.setAttribute("aria-label",n.title)}}function ue(){let n=t.tour?.scenes[t.activeSceneIndex],o=new URLSearchParams(window.location.search);for(let l of["from","to","commits","scope","commit","file"])o.delete(l);if(t.zoom&&o.set("mode",t.zoom.mode),t.zoom&&!ee()){for(let l of["scene","step","view"])o.delete(l);t.zoom.mode==="compare"&&t.compare&&(o.set("commits",t.compare.commits.join(",")),t.compare.path&&o.set("scope",t.compare.path)),t.zoom.mode==="history"&&t.historyCommit&&o.set("commit",t.historyCommit),t.activeTourFilePath&&o.set("file",t.zoom.mode==="history"?t.historyPath:t.activeTourFilePath),window.history.replaceState(null,"",`${window.location.pathname}?${o.toString()}`);return}if(!n)return;o.set("scene",n.id);let d=Se(n)?n.steps[t.activeStepIndex]:null;d?o.set("step",d.id):o.delete("step"),t.directoryEvidence&&t.activeTourFilePath?o.set("file",t.activeTourFilePath):o.delete("file"),t.narrativeParent?o.set("view",t.narrativeParent):d&&t.sceneIntroVisible?o.set("view","overview"):o.delete("view"),window.history.replaceState(null,"",`${window.location.pathname}?${o.toString()}`)}function qn(n=t.tour?.scenes[t.activeSceneIndex],o=t.activeStepIndex){if(!n||!Se(n))return null;let d=n.steps[o];if(!d)return null;if(n.kind==="walkthrough"){let u=d.focus;return!u?.path||!Number.isInteger(u.startLine)?null:{filePath:u.path,sideIndex:u.revision==="base"?0:1,lineNumber:u.startLine,label:`${u.path}:${u.startLine}`}}let l=d.startLine;if(!Number.isInteger(l)){let u=rt(n,d.file),h=u?.panels?.[d.pairIndex],y=u?.panels?.[d.pairIndex+1];if(h&&y){let b=ae(h.content,y.content);l=vn(b,d.side)?.startLine}}return!d.file||!Number.isInteger(l)?null:{filePath:d.file,sideIndex:d.pairIndex+(d.side==="right"?1:0),lineNumber:l,label:`${d.file}:${l}`}}function $o(){let n=qn(),o=t.tour?.scenes[t.activeSceneIndex];if(t.sceneIntroVisible||!n||!o)return!1;if(A.interruptForExploration(),t.activeTourFilePath!==n.filePath){let d=t.tour.files.findIndex(u=>u.kind==="text-diff"&&u.path===n.filePath);if(d<0||!(le(o)?nt(d):Qt(d,!1)))return!1}return window.requestAnimationFrame(()=>L({type:"revealSearchResult",sideIndex:n.sideIndex,lineNumber:n.lineNumber,startColumn:1,endColumn:1})),!0}function Wn(n,o,d){on(),document.getElementById("tour-narrative").hidden=!1,document.getElementById("tour-breadcrumb").textContent=t.narrativeParent==="tour"?t.tour.title:t.narrativeParent==="chapter"?o.chapter?.title||"Chapter":t.sceneIntroVisible?`Scene ${o.sceneNumber} of ${o.sceneCount} \xB7 Overview`:So(o,n,t.activeStepIndex);let l=I.get(`scene:${n.id}`),u=Se(n)?n.steps[t.activeStepIndex]:null,h=u&&I.get(`step:${n.id}:${u.id}`);for(let y of[l,h].filter(Boolean))y.querySelectorAll("[data-reading-field]").forEach(b=>{Po(b,b.dataset.readingText,{field:b.dataset.readingField,...b.dataset.itemIndex!==void 0?{itemIndex:Number(b.dataset.itemIndex)}:{}},d)});rn()}function on(){if(m===t.tour)return;m=t.tour,w=Ar(t.tour),I.clear();let n=document.getElementById("tour-narrative-content"),o=(l,u,h,y,b,k)=>{let R=document.createElement(u);return R.className=h,R.textContent=y||"",b&&(R.dataset.readingField=b,R.dataset.readingText=y||"",k!==void 0&&(R.dataset.itemIndex=String(k))),l.append(R),R},d=(l,u,h)=>{if(o(l,"p","tour-narrative-summary",u.summary,h?"summary":null),u.bullets.length){let y=document.createElement("ul");y.className="tour-narrative-bullets",u.bullets.forEach((b,k)=>o(y,"li","",b,h?"bullet":null,k)),l.append(y)}u.takeaway&&o(l,"p","tour-narrative-takeaway",u.takeaway,h?"takeaway":null)};for(let l of w){let u=document.createElement("section");u.className="tour-reading-item",u.dataset.readingKey=l.key,u.dataset.readingKind=l.kind,u.dataset.sceneIndex=String(l.sceneIndex),u.dataset.stepIndex=String(l.stepIndex);let h=t.tour.scenes[l.sceneIndex];if(l.kind==="title")o(u,"h1","tour-document-title",t.tour.title),o(u,"p","tour-document-meta",`${Ue(t.tour.range.mergeBaseOid)} \u2192 ${Ue(t.tour.range.headOid)}`);else if(l.kind==="chapter")o(u,"h2","tour-document-chapter",t.tour.chapters.find(y=>y.id===l.chapterId)?.title);else if(l.kind==="scene"){o(u,"h2","tour-scene-heading",h.title,"scene-title"),d(u,h,!0);let y=o(u,"div","tour-narrative-tags","");h.tags.forEach(b=>o(y,"span","",b))}else{let y=h.steps[l.stepIndex],b=document.createElement("details");b.className="tour-step-context",o(b,"summary","",`Scene context \xB7 ${h.title}`);let k=o(b,"div","tour-step-context-body","");d(k,h,!1),u.append(b);let R=h.kind==="deconstructed-diff"?`Stage ${(y.stageIndex??y.pairIndex)+1} \xB7 `:"";R&&o(u,"div","tour-narrative-chapter",R),o(u,"h3","tour-step-title",y.title,"step-title"),o(u,"p","tour-step-body",y.body,"step-body");let M=o(u,"div","tour-step-requirement","");Ro(M,y.requirement),y.connection&&(o(u,"p","tour-connection",`${y.connection.from.path} \u2192 ${y.connection.to.path}`),o(u,"p","tour-connection",y.connection.label,"connection"));let W=qn(h,l.stepIndex);if(W){let z=o(u,"div","tour-step-code","");o(z,"span","tour-step-code-location",W.label);let B=nn("Show in code",`Show ${W.label}`,()=>{st(l),$o()});B.className="tour-show-in-code",z.append(B)}}I.set(l.key,u)}n.replaceChildren(...I.values()),x=n.scrollTop}function jn(){for(let[d,l]of I)l.classList.toggle("is-active",d===t.readingKey);document.querySelectorAll("[data-reading-link], .tour-outline-step, #tour-title").forEach(d=>{let l=t.tour?.scenes[t.activeSceneIndex],u=l&&Se(l)?l.steps[Number(d.dataset.stepIndex)]:null,y=(d.id==="tour-title"?"title":d.dataset.readingLink||(u&&d.dataset.sceneId===l.id?`step:${l.id}:${u.id}`:null))===t.readingKey;d.classList.toggle("is-active",y),y?d.setAttribute("aria-current","location"):d.removeAttribute("aria-current")}),document.querySelectorAll(".tour-outline-group").forEach(d=>{d.classList.toggle("has-active",!!d.querySelector('[aria-current="location"]'))});let n=document.getElementById("tour-scenes"),o=n?.querySelector('[aria-current="location"]');for(;o&&!o.getClientRects().length;)o=o.closest(".tour-outline-children[hidden]")?.parentElement.querySelector(":scope > .tour-outline-heading [data-reading-link]");if(o&&n.clientHeight){let d=n.getBoundingClientRect(),l=o.getBoundingClientRect();l.top<d.top?n.scrollTop+=l.top-d.top:l.bottom>d.bottom&&(n.scrollTop+=l.bottom-d.bottom)}}function No(n){let o=document.getElementById("tour-narrative-content"),d=I.get(n);!o||!d||(o.scrollTop+=d.getBoundingClientRect().top-o.getBoundingClientRect().top,x=o.scrollTop)}function st(n,o=!1){return se(n.sceneIndex,n.stepIndex,{readingKey:n.key,showIntro:n.kind!=="step",userNavigation:!0,fromReadingScroll:o})}function Ao(){S===null&&(S=window.requestAnimationFrame(()=>{if(S=null,!ee()||t.zoomSwitching)return;let n=document.getElementById("tour-narrative-content");if(x!==null&&Math.abs(n.scrollTop-x)<2)return;x=null;let o=n.getBoundingClientRect().top+24,d=w[0];for(let l of w){if(I.get(l.key).getBoundingClientRect().top>o)break;d=l}d&&d.key!==t.readingKey&&st(d,!0)}))}function Lo(n){let o=[];return n.source&&o.push(n.source),n.confidence&&o.push(`${n.confidence} confidence`),o.join(" \xB7 ")}function Ro(n,o){if(!o){n.hidden=!0,n.replaceChildren(),n.removeAttribute("title");return}let d=document.createElement("span");d.className="tour-requirement-chip",d.dataset.status=o.status||"unspecified",d.textContent=o.status?`${o.id} \xB7 ${o.status}`:o.id;let l=document.createElement("span");l.className="tour-requirement-text",l.textContent=o.text;let u=[d,l],h=Lo(o);if(h){let y=document.createElement("span");y.className="tour-requirement-meta",y.textContent=h,u.push(y)}n.replaceChildren(...u),n.title=[`${o.id}: ${o.text}`,h].filter(Boolean).join(" \u2014 "),n.hidden=!1}function Po(n,o,d,l,u={}){let h=l?.segments.filter(k=>k.source.field===d.field&&k.source.itemIndex===d.itemIndex)||[];if(h.length===0){n.textContent=`${u.prefix||""}${o}${u.suffix||""}`;return}let y=[];u.prefix&&y.push(document.createTextNode(u.prefix));let b=0;for(let k of h){k.startOffset>b&&y.push(document.createTextNode(o.slice(b,k.startOffset)));let R=document.createElement("span");R.className="tour-narration-segment",R.dataset.narrationSegmentId=k.id,R.textContent=o.slice(k.startOffset,k.endOffset),y.push(R),b=k.endOffset}b<o.length&&y.push(document.createTextNode(o.slice(b))),u.suffix&&y.push(document.createTextNode(u.suffix)),n.replaceChildren(...y)}function Gn(){A.stop();let n=wr();t.mode="diff",t.comparisonId+=1,t.left={name:n.leftFileName,content:n.leftContent},t.right={name:n.rightFileName,content:n.rightContent},ve("Loaded sample diff."),L({type:"showDiff",file1:t.left.name,file2:t.right.name,comparisonId:`web-${t.comparisonId}`,leftContent:t.left.content,rightContent:t.right.content,diffModel:ae(t.left.content,t.right.content),history:null})}async function Oo(n){A.stop();let[o,d]=n,[l,u]=await Promise.all([o.text(),d.text()]);t.mode="diff",t.comparisonId+=1,t.left={name:o.name,content:l},t.right={name:d.name,content:u},ve(`Loaded ${o.name} and ${d.name}.`),L({type:"showDiff",file1:o.name,file2:d.name,comparisonId:`web-${t.comparisonId}`,leftContent:l,rightContent:u,diffModel:ae(l,u),history:null})}async function Do(n){A.stop();let o=await Promise.all(n.map(async(d,l)=>{let u=await d.text();return{id:`web-panel-${l}`,label:d.name,content:u,savedContent:u,dirty:!1,editable:!0}}));t.mode="multi-diff",ve(`Loaded ${o.length}-panel diff for ${o.map(d=>d.label).join(", ")}.`),L({type:"showMultiDiff",panels:o,pairs:o.slice(0,-1).map((d,l)=>({leftIndex:l,rightIndex:l+1,diffModel:ae(d.content,o[l+1].content)}))})}function ve(n){let o=document.getElementById("web-status");o&&(o.textContent=n)}})();})();
|
|
151
520
|
//# sourceMappingURL=web-host.js.map
|