@davmash/bygone 0.9.7 → 0.9.8
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 +9 -0
- package/docs/change-tour-format.md +2 -0
- package/out/standalone-main.js +3 -3
- package/package.json +1 -1
- package/web/presenter.css +7 -0
- package/web/web-host.js +8 -8
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.9.8
|
|
6
|
+
|
|
7
|
+
- Rendered Markdown links as clickable links in tour narrative prose
|
|
8
|
+
- Kept Scene context visible at the top of the reading pane while scrolling through each step
|
|
9
|
+
- Updated extension packaging tooling and cache dependencies to resolve high-severity advisories
|
|
10
|
+
|
|
11
|
+
macOS desktop downloads are unsigned and not notarized. If Gatekeeper reports
|
|
12
|
+
the app as damaged, run `xattr -cr /Applications/Bygone.app`, then reopen it.
|
|
13
|
+
|
|
5
14
|
## 0.9.7
|
|
6
15
|
|
|
7
16
|
- Published the tour text/code resizing fix and expanded ticket, project, and PR context guidance introduced in 0.9.6
|
|
@@ -205,6 +205,8 @@ including why the focused code matters and any rationale or tradeoff that the
|
|
|
205
205
|
source supports. Keeping that explanation beside `focus` lets the reader assess
|
|
206
206
|
the claim while the code is visible and avoids repeating it in scene framing.
|
|
207
207
|
|
|
208
|
+
Narrative text supports inline Markdown links such as `[ticket](https://example.com/ticket)`. HTTP and HTTPS destinations open outside the tour; link labels remain visible and clickable during narration highlighting. Authored HTML, other URL schemes, and local-file destinations are treated as plain text. This is link support, not a general Markdown renderer.
|
|
209
|
+
|
|
208
210
|
The source schema has no ad hoc `notes` field. In v3, use the top-level `review`
|
|
209
211
|
block below for evidence-linked review observations and unresolved questions;
|
|
210
212
|
do not present those questions as settled step rationale.
|
package/out/standalone-main.js
CHANGED
|
@@ -18785,7 +18785,7 @@ var require_package = __commonJS({
|
|
|
18785
18785
|
displayName: "Bygone",
|
|
18786
18786
|
desktopName: "com.davidmashburn.bygone.desktop",
|
|
18787
18787
|
description: "See how change happened. Visual diff and file history for VS Code.",
|
|
18788
|
-
version: "0.9.
|
|
18788
|
+
version: "0.9.8",
|
|
18789
18789
|
author: "David Mashburn",
|
|
18790
18790
|
license: "MIT",
|
|
18791
18791
|
private: false,
|
|
@@ -19002,7 +19002,7 @@ var require_package = __commonJS({
|
|
|
19002
19002
|
lint: "eslint . --max-warnings=0",
|
|
19003
19003
|
"lint:fix": "eslint . --fix",
|
|
19004
19004
|
watch: "tsc -watch -p ./",
|
|
19005
|
-
test: "npm run compile && node ./test/runTests.js && node --test ./test/tourReading.test.js ./test/tourZoomSession.test.js ./test/tourComparison.test.js ./test/tourHistory.test.js ./test/changeTourAuthoredModes.test.js ./test/renderCompleteToken.test.js ./test/tourDirectoryOverview.test.js ./test/tourDirectoryEvidence.test.js ./test/reviewNotes.test.js ./test/workspace*.test.js"
|
|
19005
|
+
test: "npm run compile && node ./test/runTests.js && node --test ./test/tourProse.test.js ./test/tourReading.test.js ./test/tourZoomSession.test.js ./test/tourComparison.test.js ./test/tourHistory.test.js ./test/changeTourAuthoredModes.test.js ./test/renderCompleteToken.test.js ./test/tourDirectoryOverview.test.js ./test/tourDirectoryEvidence.test.js ./test/reviewNotes.test.js ./test/workspace*.test.js"
|
|
19006
19006
|
},
|
|
19007
19007
|
build: {
|
|
19008
19008
|
appId: "com.davidmashburn.bygone",
|
|
@@ -19091,7 +19091,7 @@ var require_package = __commonJS({
|
|
|
19091
19091
|
"@eslint/js": "^10.0.1",
|
|
19092
19092
|
"@types/node": "16.x",
|
|
19093
19093
|
"@types/vscode": "1.74.0",
|
|
19094
|
-
"@vscode/vsce": "^
|
|
19094
|
+
"@vscode/vsce": "^4.0.0",
|
|
19095
19095
|
electron: "^43.7.6",
|
|
19096
19096
|
"electron-builder": "^26.15.3",
|
|
19097
19097
|
esbuild: "^0.28.1",
|
package/package.json
CHANGED
package/web/presenter.css
CHANGED
|
@@ -920,7 +920,11 @@ body.tour-derived-mode .tour-narrative-resizer {
|
|
|
920
920
|
.tour-step-body { margin: 8px 0 0; max-width: 85ch; color: var(--tour-body); font-size: 15px; line-height: 1.6; }
|
|
921
921
|
|
|
922
922
|
.tour-step-context {
|
|
923
|
+
position: sticky;
|
|
924
|
+
top: 0;
|
|
925
|
+
z-index: 1;
|
|
923
926
|
margin: 0 0 9px;
|
|
927
|
+
background: #151821;
|
|
924
928
|
}
|
|
925
929
|
|
|
926
930
|
.tour-step-context > summary {
|
|
@@ -965,6 +969,8 @@ body.tour-derived-mode .tour-narrative-resizer {
|
|
|
965
969
|
}
|
|
966
970
|
|
|
967
971
|
.tour-step-context-body {
|
|
972
|
+
max-height: calc(var(--tour-reading-viewport, 200px) / 2);
|
|
973
|
+
overflow-y: auto;
|
|
968
974
|
margin: 2px 0 8px;
|
|
969
975
|
padding: 7px 0 3px 12px;
|
|
970
976
|
color: var(--tour-muted);
|
|
@@ -1074,6 +1080,7 @@ body.tour-derived-mode .tour-narrative-resizer {
|
|
|
1074
1080
|
.tour-narrative-content {
|
|
1075
1081
|
flex: 1 1 auto;
|
|
1076
1082
|
min-height: 0;
|
|
1083
|
+
overflow-anchor: none;
|
|
1077
1084
|
overflow-x: hidden;
|
|
1078
1085
|
overflow-y: auto;
|
|
1079
1086
|
padding-right: 8px;
|
package/web/web-host.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";(()=>{function ge(){}ge.prototype={diff:function(r,i){var a
|
|
2
|
-
`));var r=[],i=e.split(/(\n|\r\n)/);i[i.length-1]||i.pop();for(var
|
|
1
|
+
"use strict";(()=>{function ge(){}ge.prototype={diff:function(r,i){var s,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},c=a.callback;typeof a=="function"&&(c=a,a={}),this.options=a;var f=this;function p(O){return c?(setTimeout(function(){c(void 0,O)},0),!0):O}r=this.castInput(r),i=this.castInput(i),r=this.removeEmpty(this.tokenize(r)),i=this.removeEmpty(this.tokenize(i));var g=i.length,w=r.length,m=1,t=g+w;a.maxEditLength&&(t=Math.min(t,a.maxEditLength));var b=(s=a.timeout)!==null&&s!==void 0?s:1/0,I=Date.now()+b,N=[{oldPos:-1,lastComponent:void 0}],x=this.extractCommon(N[0],i,r,0);if(N[0].oldPos+1>=w&&x+1>=g)return p([{value:this.join(i),count:i.length}]);var S=-1/0,C=1/0;function $(){for(var O=Math.max(S,-m);O<=Math.min(C,m);O+=2){var z=void 0,R=N[O-1],W=N[O+1];R&&(N[O-1]=void 0);var fe=!1;if(W){var ye=W.oldPos-O;fe=W&&0<=ye&&ye<g}var X=R&&R.oldPos+1<w;if(!fe&&!X){N[O]=void 0;continue}if(!X||fe&&R.oldPos+1<W.oldPos?z=f.addToPath(W,!0,void 0,0):z=f.addToPath(R,void 0,!0,1),x=f.extractCommon(z,i,r,O),z.oldPos+1>=w&&x+1>=g)return p(Ko(f,z.lastComponent,i,r,f.useLongestToken));N[O]=z,z.oldPos+1>=w&&(C=Math.min(C,O-1)),x+1>=g&&(S=Math.max(S,O+1))}m++}if(c)(function O(){setTimeout(function(){if(m>t||Date.now()>I)return c();$()||O()},0)})();else for(;m<=t&&Date.now()<=I;){var P=$();if(P)return P}},addToPath:function(r,i,s,a){var c=r.lastComponent;return c&&c.added===i&&c.removed===s?{oldPos:r.oldPos+a,lastComponent:{count:c.count+1,added:i,removed:s,previousComponent:c.previousComponent}}:{oldPos:r.oldPos+a,lastComponent:{count:1,added:i,removed:s,previousComponent:c}}},extractCommon:function(r,i,s,a){for(var c=i.length,f=s.length,p=r.oldPos,g=p-a,w=0;g+1<c&&p+1<f&&this.equals(i[g+1],s[p+1]);)g++,p++,w++;return w&&(r.lastComponent={count:w,previousComponent:r.lastComponent}),r.oldPos=p,g},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=[],s=0;s<r.length;s++)r[s]&&i.push(r[s]);return i},castInput:function(r){return r},tokenize:function(r){return r.split("")},join:function(r){return r.join("")}};function Ko(e,r,i,s,a){for(var c=[],f;r;)c.push(r),f=r.previousComponent,delete r.previousComponent,r=f;c.reverse();for(var p=0,g=c.length,w=0,m=0;p<g;p++){var t=c[p];if(t.removed){if(t.value=e.join(s.slice(m,m+t.count)),m+=t.count,p&&c[p-1].added){var I=c[p-1];c[p-1]=c[p],c[p]=I}}else{if(!t.added&&a){var b=i.slice(w,w+t.count);b=b.map(function(x,S){var C=s[m+S];return C.length>x.length?C:x}),t.value=e.join(b)}else t.value=e.join(i.slice(w,w+t.count));w+=t.count,t.added||(m+=t.count)}}var N=c[g-1];return g>1&&typeof N.value=="string"&&(N.added||N.removed)&&e.equals("",N.value)&&(c[g-2].value+=N.value,c.pop()),c}var Vo=new ge;function nr(e,r,i){return Vo.diff(e,r,i)}var er=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,tr=/\S/,hn=new ge;hn.equals=function(e,r){return this.options.ignoreCase&&(e=e.toLowerCase(),r=r.toLowerCase()),e===r||this.options.ignoreWhitespace&&!tr.test(e)&&!tr.test(r)};hn.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]&&er.test(r[i])&&er.test(r[i+2])&&(r[i]+=r[i+2],r.splice(i+1,2),i--);return r};function rr(e,r,i){return hn.diff(e,r,i)}var or=new ge;or.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 s=0;s<i.length;s++){var a=i[s];s%2&&!this.options.newlineIsToken?r[r.length-1]+=a:(this.options.ignoreWhitespace&&(a=a.trim()),r.push(a))}return r};var Xo=new ge;Xo.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var Jo=new ge;Jo.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function Tt(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Tt=function(r){return typeof r}:Tt=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Tt(e)}var Yo=Object.prototype.toString,ct=new ge;ct.useLongestToken=!0;ct.tokenize=or.tokenize;ct.castInput=function(e){var r=this.options,i=r.undefinedReplacement,s=r.stringifyReplacer,a=s===void 0?function(c,f){return typeof f>"u"?i:f}:s;return typeof e=="string"?e:JSON.stringify(fn(e,null,null,a),a," ")};ct.equals=function(e,r){return ge.prototype.equals.call(ct,e.replace(/,([\r\n])/g,"$1"),r.replace(/,([\r\n])/g,"$1"))};function fn(e,r,i,s,a){r=r||[],i=i||[],s&&(e=s(a,e));var c;for(c=0;c<r.length;c+=1)if(r[c]===e)return i[c];var f;if(Yo.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]=fn(e[c],r,i,s,a);return r.pop(),i.pop(),f}if(e&&e.toJSON&&(e=e.toJSON()),Tt(e)==="object"&&e!==null){r.push(e),f={},i.push(f);var p=[],g;for(g in e)e.hasOwnProperty(g)&&p.push(g);for(p.sort(),c=0;c<p.length;c+=1)g=p[c],f[g]=fn(e[g],r,i,s,g);r.pop(),i.pop()}else f=e;return f}var $t=new ge;$t.tokenize=function(e){return e.slice()};$t.join=$t.removeEmpty=function(e){return e};function ir(e,r,i){return $t.diff(e,r,i)}var Qo=500,ei=100,sr=Sr("BYGONE_MAX_INLINE_HIGHLIGHT_LINE_LENGTH",Qo),ti=Sr("BYGONE_DIFF_TIMEOUT_MS",ei);function ie(e,r,i={}){let s=ar(e),a=ar(r);if(e===r)return ri(s);let c=ni(s,a),f=ir(c.left,c.right,{timeout:i.timeoutMs??ti});if(!f)return oi(s,a);let p=f.map(x=>({...x,value:x.value.map(S=>c.lines[S])})),g=[],w=[],m=[],t=[],b=1,I=1;for(let x=0;x<p.length;x++){let S=p[x],C=S.removed?S.value:[],$=S.added?S.value:[];if(!S.added&&!S.removed){for(let P of S.value)w.push(le("context",P,b)),m.push(le("context",P,I)),g.push($e(de("context",P,b++),de("context",P,I++)));continue}if(S.removed&&x+1<p.length&&p[x+1].added){let P=p[x+1],O=ii(C,P.value,b,I,g,w,m,t);b=O.left,I=O.right,x++;continue}if(S.removed){let P=w.length,O=m.length;for(let z of C)w.push(le("removed",z,b)),g.push($e(de("removed",z,b++),ze()));t.push(Pt("delete",P,w.length,O,m.length));continue}if(S.added){let P=w.length,O=m.length;for(let z of $)m.push(le("added",z,I)),g.push($e(ze(),de("added",z,I++)));t.push(Pt("insert",P,w.length,O,m.length))}}let N=g.some(x=>x.left.kind!=="context"||x.right.kind!=="context");return{rows:g,leftLines:w,rightLines:m,blocks:t,hasChanges:N,quality:"exact"}}function ni(e,r){let i=new Map,s=[],a=c=>{let f=i.get(c);if(f!==void 0)return f;let p=s.length;return i.set(c,p),s.push(c),p};return{left:e.map(a),right:r.map(a),lines:s}}function ri(e){return{rows:e.map((r,i)=>$e(de("context",r,i+1),de("context",r,i+1))),leftLines:e.map((r,i)=>le("context",r,i+1)),rightLines:e.map((r,i)=>le("context",r,i+1)),blocks:[],hasChanges:!1,quality:"exact"}}function oi(e,r){let i=e.map((f,p)=>le("removed",f,p+1)),s=r.map((f,p)=>le("added",f,p+1)),a=[...e.map((f,p)=>$e(de("removed",f,p+1),ze())),...r.map((f,p)=>$e(ze(),de("added",f,p+1)))],c="replace";return e.length===0?c="insert":r.length===0&&(c="delete"),{rows:a,leftLines:i,rightLines:s,blocks:a.length===0?[]:[Pt(c,0,e.length,0,r.length)],hasChanges:a.length>0,quality:"fallback"}}function ar(e){if(e.length===0)return[];let r=e.replace(/\r\n/g,`
|
|
3
3
|
`).split(`
|
|
4
|
-
`);return r[r.length-1]===""&&r.pop(),r}function ri(e,r,i,a,s,d,h,p){let y=vr(e,r),b=y.filter($=>$.left!==void 0&&$.right!==void 0&&mn($.left,$.right)).length,m=ii(e,r,b),t=y.flatMap($=>$.left===void 0||$.right===void 0||mn($.left,$.right)?[$]:[{left:$.left},{right:$.right}]),v=i,I=a,N,x=d.length,S=h.length,E=()=>{N&&p.push(Pt(N,x,d.length,S,h.length))};for(let{left:$,right:P}of t){let O=m||$!==void 0&&P!==void 0?"replace":$!==void 0?"delete":"insert";N!==O&&(E(),N=O,x=d.length,S=h.length);let z,R;$!==void 0&&(z=le("removed",$,v),d.push(z)),P!==void 0&&(R=le("added",P,I),h.push(R)),z&&R?Ei(z,R):m&&(z&&gr(z),R&&gr(R)),s.push($e($===void 0?ze():de("removed",$,v++),P===void 0?ze():de("added",P,I++)))}return E(),{left:v,right:I}}function mn(e,r){if(Ot(e,r).eligible)return!0;let a=dt(e);if(a&&a===dt(r))return!0;let s=new Set(ut(ue(e)).filter(sr));return ut(ue(r)).some(d=>s.has(d)&&sr(d))}var oi=new Set(["and","are","for","from","into","that","the","this","to","with"]);function sr(e){return e.length>=3&&/^[\p{L}\p{N}_$]+$/u.test(e)&&!oi.has(e)}function ii(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(si);return s[0]!==null&&s.every(d=>d===s[0])}function si(e){let r=e.trimStart();return/^[-*+]\s+/.test(r)?"bullet":/^\d+[.)]\s+/.test(r)?"ordered":/^>\s+/.test(r)?"quote":null}var yr=1e4,ar=2e3,ai=.52,ci=.35,wr=.38,di=.33,br=.86,Rt=.08,Nt=.05,At=-.12,cr=5e3,li=2e3,ui=5e7,dr=4,fi=8,pn=4;function vr(e,r){if(e.length===0)return r.map(m=>({right:m}));if(r.length===0)return e.map(m=>({left:m}));let i=e.reduce((m,t)=>m+t.length,0),a=r.reduce((m,t)=>m+t.length,0);if(i*a>ui)return[...e.map(m=>({left:m})),...r.map(m=>({right:m}))];if(e.length===1&&r.length===1){let m=Ot(e[0],r[0]);return(m.eligible||m.score>=ci)&&mn(e[0],r[0])&&yn(e[0],r[0])&<(ue(e[0]))&<(ue(r[0]))?[{left:e[0],right:r[0]}]:[{left:e[0]},{right:r[0]}]}if(e.length*r.length>yr)return yi(e,r);let s=hi(e,r),d=Array.from({length:e.length+1},()=>new Array(r.length+1).fill(Number.NEGATIVE_INFINITY)),h=Array.from({length:e.length+1},()=>new Array(r.length+1).fill(null));d[0][0]=0;for(let m=1;m<=e.length;m++)d[m][0]=d[m-1][0]+At,h[m][0]="left";for(let m=1;m<=r.length;m++)d[0][m]=d[0][m-1]+At,h[0][m]="right";for(let m=1;m<=e.length;m++)for(let t=1;t<=r.length;t++){let v=s[m-1][t-1],N=[{move:"left",score:d[m-1][t]+At},{move:"right",score:d[m][t-1]+At},{move:"match",score:v===null?Number.NEGATIVE_INFINITY:d[m-1][t-1]+v}].reduce((x,S)=>S.score>x.score?S:x);d[m][t]=N.score,h[m][t]=N.move}let p=[],y=e.length,b=r.length;for(;y>0||b>0;){let m=h[y][b];m==="match"?p.push({left:e[--y],right:r[--b]}):m==="left"?p.push({left:e[--y]}):p.push({right:r[--b]})}return p.reverse()}function Ot(e,r){let i=ue(e),a=ue(r),s=lt(i),d=lt(a);if(!s||!d||i.length>ar||a.length>ar)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 h=ut(i),p=ut(a),y=Ci(i,a),b=Ii(h,p),m=Math.min(i.length,a.length)/Math.max(i.length,a.length),t=Si(h,p),v=y*.52+b*.32+m*.1+t*.06,I=y>=.52||b>=.45||y>=.48&&b>=.28;return{score:v,eligible:I&&v>=ai,characterSimilarity:y,tokenSimilarity:b,lengthSimilarity:m}}function hi(e,r){let i=e.map(x=>r.map(S=>Ot(x,S))),a=xr(e,r),s=i.map(x=>gn(x)),d=r.map((x,S)=>gn(i.map(E=>E[S]))),h=i.map((x,S)=>x.map((E,$)=>{if(a.has(`${S}:${$}`))return Math.max(E.score,1);if(!E.eligible)return null;let P=s[S],O=d[$],z=E.score===P.best&&E.score===O.best,R=E.score>=br?Rt/2:Rt,W=P.best-P.second>=R,fe=O.best-O.second>=R;return z&&W&&fe?E.score:null}));if(Math.max(e.length,r.length)>fi||Math.abs(e.length-r.length)>pn)return h;let p=(x,S,E)=>x.score>=wr&&yn(e[S],r[E])&&Math.abs(S-E)<=pn,y=i.map((x,S)=>Lt(x,(E,$)=>p(E,S,$))),b=r.map((x,S)=>Lt(i.map(E=>E[S]),(E,$)=>p(E,$,S))),m=(x,S,E)=>x.score>=di&&yn(e[S],r[E])&&Math.abs(S-E)<=pn,t=i.map((x,S)=>Lt(x,(E,$)=>m(E,S,$))),v=r.map((x,S)=>Lt(i.map(E=>E[S]),(E,$)=>m(E,$,S))),I=(x,S)=>{let E=i[x][S];if(!p(E,x,S))return!1;let $=y[x],P=b[S];return E.score===$.best&&E.score===P.best&&$.best-$.second>=Nt&&P.best-P.second>=Nt},N=(x,S)=>{let E=i[x][S];if(!m(E,x,S))return!1;let $=t[x],P=v[S];return E.score===$.best&&E.score===P.best&&$.best-$.second>=Nt&&P.best-P.second>=Nt};return h.map((x,S)=>x.map((E,$)=>{if(E!==null)return E;let P=I(S,$)&&(pi(h,S,$)||mi(i,S,$,I)),O=gi(i,S,$,(z,R)=>m(i[z][R],z,R),N);return!P&&!O?null:i[S][$].score}))}function pi(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 mi(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 gi(e,r,i,a,s){let d=r,h=i;for(;d>0&&h>0&&a(d-1,h-1);)d--,h--;let p=r,y=i,b=e[r][i].score,m=1;for(;p+1<e.length&&y+1<e[p+1].length&&a(p+1,y+1);)p++,y++,b+=e[p][y].score,m++;for(let t=r-1,v=i-1;t>=d&&v>=h;t--,v--)b+=e[t][v].score,m++;return m>=3&&b/m>=wr&&s(d,h)&&s(p,y)}function Lt(e,r){let i=Number.NEGATIVE_INFINITY,a=Number.NEGATIVE_INFINITY;return e.forEach((s,d)=>{r(s,d)&&(s.score>i?(a=i,i=s.score):s.score>a&&(a=s.score))}),{best:i,second:a}}function gn(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 yi(e,r){let i=wi(e,r),a=[],s=0,d=0;for(let h of i)pr(a,e.slice(s,h.leftIndex),r.slice(d,h.rightIndex)),a.push({left:e[h.leftIndex],right:r[h.rightIndex]}),s=h.leftIndex+1,d=h.rightIndex+1;return pr(a,e.slice(s),r.slice(d)),a}function wi(e,r){let i=bi(e,r);if(i===null)return[];let a=xr(e,r),s=i.map(({leftIndex:b,rightIndex:m,exact:t})=>({leftIndex:b,rightIndex:m,exact:t,structural:a.has(`${b}:${m}`),match:Ot(e[b],r[m])})).filter(b=>b.exact||b.structural||b.match.eligible),d=fr(s,"leftIndex"),h=fr(s,"rightIndex"),p=s.filter(b=>{if(b.exact||b.structural)return!0;let m=d.get(b.leftIndex),t=h.get(b.rightIndex);if(!m||!t||b.match.score!==m.best||b.match.score!==t.best)return!1;let v=b.match.score>=br?Rt/2:Rt;return m.best-m.second>=v&&t.best-t.second>=v}),y=xi(p,r.length);return y.length<=li?y:[]}function bi(e,r){let i=lr(e,ue),a=lr(r,ue),s=new Map;for(let[p,y]of i){let b=a.get(p);if(!lt(p)||y.length!==1||b?.length!==1)continue;let m=y[0],t=b[0];if(s.set(`${m}:${t}`,{leftIndex:m,rightIndex:t,exact:!0}),s.size>cr)return null}let d=ur(e),h=ur(r);for(let[p,y]of d){let b=h.get(p);if(!(!b||y.length>dr||b.length>dr))for(let m of y)for(let t of b){let v=`${m}:${t}`;if(!s.has(v)&&(s.set(v,{leftIndex:m,rightIndex:t,exact:!1}),s.size>cr))return null}}return[...s.values()]}function lr(e,r){let i=new Map;return e.forEach((a,s)=>{let d=r(a),h=i.get(d)??[];h.push(s),i.set(d,h)}),i}function ur(e){let r=new Map;return e.forEach((i,a)=>{let s=new Set(ut(ue(i)).filter(vi));for(let d of s){let h=r.get(d)??[];h.push(a),r.set(d,h)}}),r}function vi(e){return e.length>=2&&/[\p{L}\p{N}_$]/u.test(e)}function fr(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,gn(s)]))}function xi(e,r){let i=[...e].sort((b,m)=>b.leftIndex-m.leftIndex||b.rightIndex-m.rightIndex),a=new Array(r+2).fill(0),s=new Array(r+2).fill(-1),d=new Array(i.length).fill(0),h=new Array(i.length).fill(-1);for(let b=0;b<i.length;){let m=b+1;for(;m<i.length&&i[m].leftIndex===i[b].leftIndex;)m++;for(let t=b;t<m;t++){let v=hr(a,s,i[t].rightIndex),I=i[t].exact||i[t].structural?.5:0;d[t]=v.score+i[t].match.score+I,h[t]=v.candidateIndex}for(let t=b;t<m;t++)ki(a,s,i[t].rightIndex+1,d[t],t);b=m}let p=hr(a,s,r+1),y=[];for(let b=p.candidateIndex;b>=0;b=h[b])y.push({leftIndex:i[b].leftIndex,rightIndex:i[b].rightIndex});return y.reverse()}function hr(e,r,i){let a=0,s=-1;for(let d=i;d>0;d-=d&-d)e[d]>a&&(a=e[d],s=r[d]);return{score:a,candidateIndex:s}}function ki(e,r,i,a,s){for(let d=i;d<e.length;d+=d&-d)a>e[d]&&(e[d]=a,r[d]=s)}function pr(e,r,i){if(r.length*i.length<=yr){e.push(...vr(r,i));return}e.push(...r.map(a=>({left:a}))),e.push(...i.map(a=>({right:a})))}function ue(e){return e.trim().replace(/\s+/g," ")}function xr(e,r){let i=mr(e),a=mr(r),s=new Set;for(let[d,h]of i){let p=a.get(d);h.length===1&&p?.length===1&&s.add(`${h[0]}:${p[0]}`)}return s}function mr(e){let r=new Map;return e.forEach((i,a)=>{let s=dt(i);if(!s)return;let d=r.get(s)??[];d.push(a),r.set(s,d)}),r}function yn(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=ue(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 d=r.match(s);if(d)return`${a}:${d[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 Ii(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 d=i.get(s)??0;d>0&&(a++,i.set(s,d-1))}return 2*a/(e.length+r.length)}function Si(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 Ci(e,r){let i=e.length+r.length;return i===0?1:2*er(e,r).filter(s=>!s.added&&!s.removed).reduce((s,d)=>s+d.value.length,0)/i}function Ei(e,r){if(e.content.length>or||r.content.length>or)return;let{leftSegments:i,rightSegments:a,hasInlineChanges:s}=Ti(e.content,r.content);s&&(e.segments=i,r.segments=a)}function gr(e){/[^\s]/.test(e.content)&&(e.segments=[{kind:e.kind,text:e.content,emphasis:!0}])}function Ti(e,r){let i=tr(e,r),a=[],s=[],d=!1;for(let h of i){let p=h.value;if(!h.added&&!h.removed){let b={kind:"context",text:p,emphasis:!1};a.push(b),s.push(b);continue}let y=/[^\s]/.test(p);d=d||y,h.removed&&a.push({kind:"removed",text:p,emphasis:y}),h.added&&s.push({kind:"added",text:p,emphasis:y})}return{leftSegments:a,rightSegments:s,hasInlineChanges:d}}function ze(){return{kind:"placeholder",content:"",lineNumber:null}}function de(e,r,i){return{kind:e,content:r,lineNumber:i}}function le(e,r,i){return{kind:e,content:r,lineNumber:i}}function $e(e,r){return{left:e,right:r}}function Pt(e,r,i,a,s){return{kind:e,leftStart:r,leftEnd:i,rightStart:a,rightEnd:s}}function kr(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 Ir(){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 ii(e,r,i,s,a,c,f,p){let g=kr(e,r),w=g.filter($=>$.left!==void 0&&$.right!==void 0&&mn($.left,$.right)).length,m=ai(e,r,w),t=g.flatMap($=>$.left===void 0||$.right===void 0||mn($.left,$.right)?[$]:[{left:$.left},{right:$.right}]),b=i,I=s,N,x=c.length,S=f.length,C=()=>{N&&p.push(Pt(N,x,c.length,S,f.length))};for(let{left:$,right:P}of t){let O=m||$!==void 0&&P!==void 0?"replace":$!==void 0?"delete":"insert";N!==O&&(C(),N=O,x=c.length,S=f.length);let z,R;$!==void 0&&(z=le("removed",$,b),c.push(z)),P!==void 0&&(R=le("added",P,I),f.push(R)),z&&R?$i(z,R):m&&(z&&wr(z),R&&wr(R)),a.push($e($===void 0?ze():de("removed",$,b++),P===void 0?ze():de("added",P,I++)))}return C(),{left:b,right:I}}function mn(e,r){if(Ot(e,r).eligible)return!0;let s=dt(e);if(s&&s===dt(r))return!0;let a=new Set(ut(ue(e)).filter(cr));return ut(ue(r)).some(c=>a.has(c)&&cr(c))}var si=new Set(["and","are","for","from","into","that","the","this","to","with"]);function cr(e){return e.length>=3&&/^[\p{L}\p{N}_$]+$/u.test(e)&&!si.has(e)}function ai(e,r,i){if(i===0)return!1;let s=Math.max(e.length,r.length);if(s<=2||i*2>=s)return!0;let a=[...e,...r].map(ci);return a[0]!==null&&a.every(c=>c===a[0])}function ci(e){let r=e.trimStart();return/^[-*+]\s+/.test(r)?"bullet":/^\d+[.)]\s+/.test(r)?"ordered":/^>\s+/.test(r)?"quote":null}var br=1e4,dr=2e3,di=.52,li=.35,vr=.38,ui=.33,xr=.86,Rt=.08,Nt=.05,At=-.12,lr=5e3,fi=2e3,hi=5e7,ur=4,pi=8,pn=4;function kr(e,r){if(e.length===0)return r.map(m=>({right:m}));if(r.length===0)return e.map(m=>({left:m}));let i=e.reduce((m,t)=>m+t.length,0),s=r.reduce((m,t)=>m+t.length,0);if(i*s>hi)return[...e.map(m=>({left:m})),...r.map(m=>({right:m}))];if(e.length===1&&r.length===1){let m=Ot(e[0],r[0]);return(m.eligible||m.score>=li)&&mn(e[0],r[0])&&yn(e[0],r[0])&<(ue(e[0]))&<(ue(r[0]))?[{left:e[0],right:r[0]}]:[{left:e[0]},{right:r[0]}]}if(e.length*r.length>br)return bi(e,r);let a=mi(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 m=1;m<=e.length;m++)c[m][0]=c[m-1][0]+At,f[m][0]="left";for(let m=1;m<=r.length;m++)c[0][m]=c[0][m-1]+At,f[0][m]="right";for(let m=1;m<=e.length;m++)for(let t=1;t<=r.length;t++){let b=a[m-1][t-1],N=[{move:"left",score:c[m-1][t]+At},{move:"right",score:c[m][t-1]+At},{move:"match",score:b===null?Number.NEGATIVE_INFINITY:c[m-1][t-1]+b}].reduce((x,S)=>S.score>x.score?S:x);c[m][t]=N.score,f[m][t]=N.move}let p=[],g=e.length,w=r.length;for(;g>0||w>0;){let m=f[g][w];m==="match"?p.push({left:e[--g],right:r[--w]}):m==="left"?p.push({left:e[--g]}):p.push({right:r[--w]})}return p.reverse()}function Ot(e,r){let i=ue(e),s=ue(r),a=lt(i),c=lt(s);if(!a||!c||i.length>dr||s.length>dr)return{score:0,eligible:!1,characterSimilarity:0,tokenSimilarity:0,lengthSimilarity:0};if(i===s)return{score:1,eligible:!0,characterSimilarity:1,tokenSimilarity:1,lengthSimilarity:1};let f=ut(i),p=ut(s),g=Ti(i,s),w=Ei(f,p),m=Math.min(i.length,s.length)/Math.max(i.length,s.length),t=Ci(f,p),b=g*.52+w*.32+m*.1+t*.06,I=g>=.52||w>=.45||g>=.48&&w>=.28;return{score:b,eligible:I&&b>=di,characterSimilarity:g,tokenSimilarity:w,lengthSimilarity:m}}function mi(e,r){let i=e.map(x=>r.map(S=>Ot(x,S))),s=Ir(e,r),a=i.map(x=>gn(x)),c=r.map((x,S)=>gn(i.map(C=>C[S]))),f=i.map((x,S)=>x.map((C,$)=>{if(s.has(`${S}:${$}`))return Math.max(C.score,1);if(!C.eligible)return null;let P=a[S],O=c[$],z=C.score===P.best&&C.score===O.best,R=C.score>=xr?Rt/2:Rt,W=P.best-P.second>=R,fe=O.best-O.second>=R;return z&&W&&fe?C.score:null}));if(Math.max(e.length,r.length)>pi||Math.abs(e.length-r.length)>pn)return f;let p=(x,S,C)=>x.score>=vr&&yn(e[S],r[C])&&Math.abs(S-C)<=pn,g=i.map((x,S)=>Lt(x,(C,$)=>p(C,S,$))),w=r.map((x,S)=>Lt(i.map(C=>C[S]),(C,$)=>p(C,$,S))),m=(x,S,C)=>x.score>=ui&&yn(e[S],r[C])&&Math.abs(S-C)<=pn,t=i.map((x,S)=>Lt(x,(C,$)=>m(C,S,$))),b=r.map((x,S)=>Lt(i.map(C=>C[S]),(C,$)=>m(C,$,S))),I=(x,S)=>{let C=i[x][S];if(!p(C,x,S))return!1;let $=g[x],P=w[S];return C.score===$.best&&C.score===P.best&&$.best-$.second>=Nt&&P.best-P.second>=Nt},N=(x,S)=>{let C=i[x][S];if(!m(C,x,S))return!1;let $=t[x],P=b[S];return C.score===$.best&&C.score===P.best&&$.best-$.second>=Nt&&P.best-P.second>=Nt};return f.map((x,S)=>x.map((C,$)=>{if(C!==null)return C;let P=I(S,$)&&(gi(f,S,$)||yi(i,S,$,I)),O=wi(i,S,$,(z,R)=>m(i[z][R],z,R),N);return!P&&!O?null:i[S][$].score}))}function gi(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 yi(e,r,i,s){return r>0&&i>0&&s(r-1,i-1)||r+1<e.length&&i+1<e[r+1].length&&s(r+1,i+1)}function wi(e,r,i,s,a){let c=r,f=i;for(;c>0&&f>0&&s(c-1,f-1);)c--,f--;let p=r,g=i,w=e[r][i].score,m=1;for(;p+1<e.length&&g+1<e[p+1].length&&s(p+1,g+1);)p++,g++,w+=e[p][g].score,m++;for(let t=r-1,b=i-1;t>=c&&b>=f;t--,b--)w+=e[t][b].score,m++;return m>=3&&w/m>=vr&&a(c,f)&&a(p,g)}function Lt(e,r){let i=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY;return e.forEach((a,c)=>{r(a,c)&&(a.score>i?(s=i,i=a.score):a.score>s&&(s=a.score))}),{best:i,second:s}}function gn(e){let r=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let s of e)s.eligible&&(s.score>r?(i=r,r=s.score):s.score>i&&(i=s.score));return{best:r,second:i}}function bi(e,r){let i=vi(e,r),s=[],a=0,c=0;for(let f of i)gr(s,e.slice(a,f.leftIndex),r.slice(c,f.rightIndex)),s.push({left:e[f.leftIndex],right:r[f.rightIndex]}),a=f.leftIndex+1,c=f.rightIndex+1;return gr(s,e.slice(a),r.slice(c)),s}function vi(e,r){let i=xi(e,r);if(i===null)return[];let s=Ir(e,r),a=i.map(({leftIndex:w,rightIndex:m,exact:t})=>({leftIndex:w,rightIndex:m,exact:t,structural:s.has(`${w}:${m}`),match:Ot(e[w],r[m])})).filter(w=>w.exact||w.structural||w.match.eligible),c=pr(a,"leftIndex"),f=pr(a,"rightIndex"),p=a.filter(w=>{if(w.exact||w.structural)return!0;let m=c.get(w.leftIndex),t=f.get(w.rightIndex);if(!m||!t||w.match.score!==m.best||w.match.score!==t.best)return!1;let b=w.match.score>=xr?Rt/2:Rt;return m.best-m.second>=b&&t.best-t.second>=b}),g=Ii(p,r.length);return g.length<=fi?g:[]}function xi(e,r){let i=fr(e,ue),s=fr(r,ue),a=new Map;for(let[p,g]of i){let w=s.get(p);if(!lt(p)||g.length!==1||w?.length!==1)continue;let m=g[0],t=w[0];if(a.set(`${m}:${t}`,{leftIndex:m,rightIndex:t,exact:!0}),a.size>lr)return null}let c=hr(e),f=hr(r);for(let[p,g]of c){let w=f.get(p);if(!(!w||g.length>ur||w.length>ur))for(let m of g)for(let t of w){let b=`${m}:${t}`;if(!a.has(b)&&(a.set(b,{leftIndex:m,rightIndex:t,exact:!1}),a.size>lr))return null}}return[...a.values()]}function fr(e,r){let i=new Map;return e.forEach((s,a)=>{let c=r(s),f=i.get(c)??[];f.push(a),i.set(c,f)}),i}function hr(e){let r=new Map;return e.forEach((i,s)=>{let a=new Set(ut(ue(i)).filter(ki));for(let c of a){let f=r.get(c)??[];f.push(s),r.set(c,f)}}),r}function ki(e){return e.length>=2&&/[\p{L}\p{N}_$]/u.test(e)}function pr(e,r){let i=new Map;for(let s of e){let a=i.get(s[r])??[];a.push(s.match),i.set(s[r],a)}return new Map([...i].map(([s,a])=>[s,gn(a)]))}function Ii(e,r){let i=[...e].sort((w,m)=>w.leftIndex-m.leftIndex||w.rightIndex-m.rightIndex),s=new Array(r+2).fill(0),a=new Array(r+2).fill(-1),c=new Array(i.length).fill(0),f=new Array(i.length).fill(-1);for(let w=0;w<i.length;){let m=w+1;for(;m<i.length&&i[m].leftIndex===i[w].leftIndex;)m++;for(let t=w;t<m;t++){let b=mr(s,a,i[t].rightIndex),I=i[t].exact||i[t].structural?.5:0;c[t]=b.score+i[t].match.score+I,f[t]=b.candidateIndex}for(let t=w;t<m;t++)Si(s,a,i[t].rightIndex+1,c[t],t);w=m}let p=mr(s,a,r+1),g=[];for(let w=p.candidateIndex;w>=0;w=f[w])g.push({leftIndex:i[w].leftIndex,rightIndex:i[w].rightIndex});return g.reverse()}function mr(e,r,i){let s=0,a=-1;for(let c=i;c>0;c-=c&-c)e[c]>s&&(s=e[c],a=r[c]);return{score:s,candidateIndex:a}}function Si(e,r,i,s,a){for(let c=i;c<e.length;c+=c&-c)s>e[c]&&(e[c]=s,r[c]=a)}function gr(e,r,i){if(r.length*i.length<=br){e.push(...kr(r,i));return}e.push(...r.map(s=>({left:s}))),e.push(...i.map(s=>({right:s})))}function ue(e){return e.trim().replace(/\s+/g," ")}function Ir(e,r){let i=yr(e),s=yr(r),a=new Set;for(let[c,f]of i){let p=s.get(c);f.length===1&&p?.length===1&&a.add(`${f[0]}:${p[0]}`)}return a}function yr(e){let r=new Map;return e.forEach((i,s)=>{let a=dt(i);if(!a)return;let c=r.get(a)??[];c.push(s),r.set(a,c)}),r}function yn(e,r){let i=dt(e),s=dt(r);return!i||!s?i===s:i.split(":",1)[0]===s.split(":",1)[0]}function dt(e){let r=ue(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[s,a]of i){let c=r.match(a);if(c)return`${s}:${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 Ei(e,r){if(e.length+r.length===0)return 1;let i=new Map;e.forEach(a=>i.set(a,(i.get(a)??0)+1));let s=0;for(let a of r){let c=i.get(a)??0;c>0&&(s++,i.set(a,c-1))}return 2*s/(e.length+r.length)}function Ci(e,r){if(e.length===0||r.length===0)return 0;let i=e[0]===r[0]?.5:0,s=e[e.length-1]===r[r.length-1]?.5:0;return i+s}function Ti(e,r){let i=e.length+r.length;return i===0?1:2*nr(e,r).filter(a=>!a.added&&!a.removed).reduce((a,c)=>a+c.value.length,0)/i}function $i(e,r){if(e.content.length>sr||r.content.length>sr)return;let{leftSegments:i,rightSegments:s,hasInlineChanges:a}=Ni(e.content,r.content);a&&(e.segments=i,r.segments=s)}function wr(e){/[^\s]/.test(e.content)&&(e.segments=[{kind:e.kind,text:e.content,emphasis:!0}])}function Ni(e,r){let i=rr(e,r),s=[],a=[],c=!1;for(let f of i){let p=f.value;if(!f.added&&!f.removed){let w={kind:"context",text:p,emphasis:!1};s.push(w),a.push(w);continue}let g=/[^\s]/.test(p);c=c||g,f.removed&&s.push({kind:"removed",text:p,emphasis:g}),f.added&&a.push({kind:"added",text:p,emphasis:g})}return{leftSegments:s,rightSegments:a,hasInlineChanges:c}}function ze(){return{kind:"placeholder",content:"",lineNumber:null}}function de(e,r,i){return{kind:e,content:r,lineNumber:i}}function le(e,r,i){return{kind:e,content:r,lineNumber:i}}function $e(e,r){return{left:e,right:r}}function Pt(e,r,i,s,a){return{kind:e,leftStart:r,leftEnd:i,rightStart:s,rightEnd:a}}function Sr(e,r){let i=typeof process<"u"?process.env?.[e]:void 0,s=Number.parseInt(i??"",10);return Number.isFinite(s)&&s>0?s:r}function Er(){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,10 +145,10 @@ if (require.main === module) {
|
|
|
145
145
|
}
|
|
146
146
|
|
|
147
147
|
module.exports = FileProcessor;
|
|
148
|
-
`}}function Cr(e,r={}){if(!We(e))throw new Error("review must be an object.");if(je(e,["baseOid","headOid","items"],"review"),Sr(e.baseOid,"review.baseOid"),Sr(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(Dt(e.baseOid)!==Dt(r.expectedRange.baseOid))throw new Error(`Stale review: review.baseOid ${e.baseOid} does not match the resolved range.mergeBaseOid ${r.expectedRange.baseOid}.`);if(Dt(e.headOid)!==Dt(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 d=`review.items[${a}]`;if(!We(s))throw new Error(`${d} must be an object.`);if(je(s,["id","kind","title","body","evidence","nextCheck"],d),qe(s.id,`${d}.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(`${d}.kind must be concept, boundary, tradeoff, or question.`);if(qe(s.title,`${d}.title`),qe(s.body,`${d}.body`),!Array.isArray(s.evidence))throw new Error(`${d}.evidence must be an array.`);if(s.kind!=="question"&&s.evidence.length===0)throw new Error(`${d}.evidence must contain at least one reference for claims.`);if(s.kind==="question"&&s.nextCheck===void 0)throw new Error(`${d}.nextCheck must be a non-empty string for question items.`);s.nextCheck!==void 0&&qe(s.nextCheck,`${d}.nextCheck`);for(let[h,p]of s.evidence.entries()){let y=`${d}.evidence[${h}]`;if(!We(p))throw new Error(`${y} must be an object.`);if(je(p,["sceneId","stepId"],y),qe(p.sceneId,`${y}.sceneId`),qe(p.stepId,`${y}.stepId`),r.authoredWalkthroughSteps){let b=r.authoredWalkthroughSteps.get(p.sceneId);if(!b)throw new Error(`${y} references unknown authored walkthrough scene ${p.sceneId}.`);if(!b.has(p.stepId))throw new Error(`${y} references unknown authored walkthrough step ${p.sceneId}/${p.stepId}.`)}}}}function Er(e,r){if(e!==void 0){if(!We(e))throw new Error(`${r} must be an object.`);if(je(e,["id","text","status","source","confidence"],r),Ne(e.id,`${r}.id`),Ne(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(Ni(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 Ge(e,r,i={}){if(e!==void 0){if(!We(e))throw new Error(`${r} must be an object.`);if(je(e,["kind","path","comparison"],r),e.kind!=="directory-diff")throw new Error(`${r}.kind must be directory-diff.`);if(e.path!==void 0&&$i(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(!We(e.comparison))throw new Error(`${r}.comparison must be an object.`);if(je(e.comparison,["from","to"],`${r}.comparison`),Ne(e.comparison.from,`${r}.comparison.from`),Ne(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 $i(e,r){if(Ne(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 We(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e,r){if(typeof e!="string"||e.length===0)throw new Error(`${r} must be a non-empty string.`)}function Sr(e,r){if(Ne(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 qe(e,r){if(typeof e!="string"||e.trim().length===0)throw new Error(`${r} must be a non-empty string.`)}function Dt(e){return e.toLowerCase()}function Ni(e,r){e!==void 0&&Ne(e,r)}function je(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 wn=3;function $r(e){if(H(e)&&Number.isInteger(e.version)&&Number(e.version)>wn)throw new Error(`This tour uses manifest format version ${e.version}, but this version of Bygone supports up to version ${wn}. Upgrade Bygone to open it.`);if(!H(e)||e.version!==1&&e.version!==2&&e.version!==wn)throw new Error("Unsupported or missing change-tour manifest version.");if(q(e.title,"title"),q(e.generatedAt,"generatedAt"),e.windowTitle!==void 0&&q(e.windowTitle,"windowTitle"),e.sourceUrl!==void 0&&q(e.sourceUrl,"sourceUrl"),!H(e.range))throw new Error("Change-tour manifest range must be an object.");for(let a of["baseRef","headRef","mergeBaseOid","headOid"])q(e.range[a],`range.${a}`);if(!H(e.summary))throw new Error("Change-tour manifest summary must be an object.");for(let a of["changedFiles","includedScenes","additions","deletions","commitCount"])Z(e.summary[a],`summary.${a}`);if(Ve(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(Ke(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(!H(s))throw new Error(`chapters[${a}] must be an object.`);q(s.id,`chapters[${a}].id`),q(s.title,`chapters[${a}].title`),Ve(s.sceneIds,`chapters[${a}].sceneIds`);for(let d of s.sceneIds)if(!r.has(d))throw new Error(`Chapter references unknown scene id: ${d}`)}if(e.summary.includedScenes!==e.scenes.length)throw new Error("summary.includedScenes must match the number of scenes.");let i=e.files===void 0?Fi(e.scenes):e.files.map((a,s)=>(Mi(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&&Li(e.authoringCoverage,e.version),e.tours!==void 0){if(e.version!==3)throw new Error("Independent tours require manifest version 3.");Ri(e.tours,e.version)}if(e.version!==1&&Pi(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&&H(e.zoom)&&H(e.zoom.final)?e.zoom.final.scenes:e.scenes;Cr(e.review,{expectedRange:{baseOid:String(e.range.mergeBaseOid),headOid:String(e.range.headOid)},authoredWalkthroughSteps:Ai(a)})}return{...e,files:i}}function Ai(e){let r=new Map;if(!Array.isArray(e))return r;for(let i of e){if(!H(i)||i.kind!=="walkthrough"||!Array.isArray(i.steps)||typeof i.id!="string")continue;let a=new Set;for(let s of i.steps)H(s)&&typeof s.id=="string"&&a.add(s.id);r.set(i.id,a)}return r}function Li(e,r){if(!H(e)||!H(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(Z(e.walkthrough.coveredUnits,"authoringCoverage.walkthrough.coveredUnits"),Z(e.walkthrough.includedUnits,"authoringCoverage.walkthrough.includedUnits"),Tr(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 d=`authoringCoverage.explanationAssignments[${a}]`;if(!H(s))throw new Error(`${d} must be an object.`);if(q(s.sceneId,`${d}.sceneId`),Z(s.assignedUnits,`${d}.assignedUnits`),Z(s.excludedUnits,`${d}.excludedUnits`),Z(s.completeUnits,`${d}.completeUnits`),Z(s.totalUnits,`${d}.totalUnits`),Tr(s.assignmentPercent,`${d}.assignmentPercent`),s.assignedUnits+s.excludedUnits!==s.completeUnits||s.completeUnits>s.totalUnits)throw new Error(`${d} contains inconsistent unit counts.`)}}function Ri(e,r){if(!H(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(!H(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,d=!1;for(let[h,p]of a.scenes.entries()){if(Ke(p,h,r),s.has(p.id))throw new Error(`Duplicate ${i} tour scene id: ${p.id}`);if(s.add(p.id),p.kind==="deconstructed-diff"&&(d=!0),i==="historical"&&p.kind==="deconstructed-diff")throw new Error("Historical tours cannot contain synthetic deconstructed scenes.")}if(i==="deconstructed"&&!d)throw new Error("Deconstructed tours must contain a constructed deconstructed-diff scene.");for(let[h,p]of a.chapters.entries()){if(!H(p))throw new Error(`tours.${i}.chapters[${h}] must be an object.`);q(p.id,`tours.${i}.chapters[${h}].id`),q(p.title,`tours.${i}.chapters[${h}].title`),Ve(p.sceneIds,`tours.${i}.chapters[${h}].sceneIds`);for(let y of p.sceneIds)if(!s.has(y))throw new Error(`tours.${i} chapter references unknown scene id: ${y}`)}}}function Pi(e,r){if(!H(e.repository)||typeof e.repository.root!="string"||!e.repository.root)throw new Error("A v2 tour requires its originating repository.root.");if(!H(e.zoom)||!Array.isArray(e.zoom.revisions)||!H(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[m,t]of a.entries()){if(Ke(t,m,r),t.kind!=="stacked-diff")throw new Error("zoom.revisions must contain real stacked-diff scenes.");if(s.has(t.id))throw new Error(`Duplicate zoom revision scene: ${t.id}`);s.add(t.id);let v=e.range;if(t.stack[0].oid!==v.mergeBaseOid||t.stack[t.stack.length-1].oid!==v.headOid)throw new Error(`Revision scene ${t.id} endpoints must match the final diff range.`)}for(let m of i){if(m.kind!=="deconstructed-diff"&&m.kind!=="stacked-diff")continue;let t=a.find(v=>v.id===m.id);if(!t)throw new Error(`Scene ${m.id} is missing its real revision evidence.`);if(m.kind==="deconstructed-diff"&&(t.stack[0].oid!==m.realRange.baseOid||t.stack[t.stack.length-1].oid!==m.realRange.targetOid))throw new Error(`Deconstructed scene ${m.id} real stack endpoints must match its explanation range.`)}let d=i.some(m=>m.kind==="deconstructed-diff"),h=a.some(m=>m.stack.length>2),p=d?"explanation":h?"revisions":"final",y=[...d?["explanation"]:[],...h?["revisions"]:[],"final","history"];if(e.zoom.authoredDepth!==p||JSON.stringify(e.zoom.modes)!==JSON.stringify(y))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 b=new Set;for(let[m,t]of e.zoom.final.scenes.entries()){if(Ke(t,m,r),t.kind==="stacked-diff"||t.kind==="deconstructed-diff")throw new Error("zoom.final must contain only non-stacked scenes.");if(b.has(t.id))throw new Error(`Duplicate final tour scene: ${t.id}`);b.add(t.id)}for(let[m,t]of e.zoom.final.chapters.entries()){if(!H(t)||!Array.isArray(t.sceneIds))throw new Error(`zoom.final.chapters[${m}] must contain sceneIds.`);q(t.id,`zoom.final.chapters[${m}].id`),q(t.title,`zoom.final.chapters[${m}].title`);for(let v of t.sceneIds)if(q(v,`zoom.final.chapters[${m}].sceneIds`),!b.has(v))throw new Error(`Final tour chapter references unknown scene: ${v}`)}}function Ke(e,r,i){if(!H(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"])q(e[a],`scenes[${r}].${a}`);if(e.overview!==void 0&&i!==3)throw new Error(`scenes[${r}].overview requires manifest version 3.`);if(Bi(e,`scenes[${r}]`),e.kind==="discussion"){Ge(e.overview,`scenes[${r}].overview`,{allowComparison:!1});return}if(e.kind==="walkthrough"){if(Ge(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 d=`scenes[${r}].steps[${a}]`;if(!H(s)||!H(s.focus)||!H(s.diff))throw new Error(`${d} must contain focus and diff objects.`);for(let h of["id","title","body"])q(s[h],`${d}.${h}`);if(s.depth!==void 0&&!["mentioned","explained","contextualized"].includes(String(s.depth)))throw new Error(`${d}.depth must be mentioned, explained, or contextualized.`);if(Er(s.requirement,`${d}.requirement`),bn(s.focus,`${d}.focus`),Ke(s.diff,r,i),s.diff.kind!=="text-diff")throw new Error(`${d}.diff must be a text-diff scene.`);if(s.connection!==void 0){if(!H(s.connection))throw new Error(`${d}.connection must be an object.`);q(s.connection.id,`${d}.connection.id`),q(s.connection.label,`${d}.connection.label`),bn(s.connection.from,`${d}.connection.from`),bn(s.connection.to,`${d}.connection.to`)}}return}if(e.kind==="stacked-diff"){Oi(e,r),Ge(e.overview,`scenes[${r}].overview`,{endpointIds:e.stack.map(a=>a.id)});return}if(e.kind==="deconstructed-diff"){Di(e,r),Ge(e.overview,`scenes[${r}].overview`,{endpointIds:e.panels.map(a=>a.id)});return}Ge(e.overview,`scenes[${r}].overview`,{allowComparison:!1});for(let a of["path","leftLabel","rightLabel","leftContent","rightContent"])q(e[a],`scenes[${r}].${a}`);e.previousPath!==void 0&&q(e.previousPath,`scenes[${r}].previousPath`),q(e.changeKind,`scenes[${r}].changeKind`),Z(e.additions,`scenes[${r}].additions`),Z(e.deletions,`scenes[${r}].deletions`),e.focusChangeIndex!==void 0&&Z(e.focusChangeIndex,`scenes[${r}].focusChangeIndex`)}function Oi(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(!H(a))throw new Error(`scenes[${r}].stack[${i}] must be an object.`);for(let s of["id","ref","oid","label"])q(a[s],`scenes[${r}].stack[${i}].${s}`)}Nr(e.files,e.stack.length,r),Ar(e.steps,e.stack.length,r,!1)}function Di(e,r){if(e.stageLabel!=="Explanation stages")throw new Error(`scenes[${r}].stageLabel must be Explanation stages.`);if(!H(e.realRange))throw new Error(`scenes[${r}].realRange must be an object.`);for(let a of["baseRef","targetRef","baseOid","targetOid"])q(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(!H(s))throw new Error(`scenes[${r}].panels[${a}] must be an object.`);for(let h of["id","label","role"])q(s[h],`scenes[${r}].panels[${a}].${h}`);let d=a===0?"baseline":"stage";if(s.role!==d)throw new Error(`scenes[${r}].panels[${a}].role must be ${d}.`);a>0&&q(s.stageId,`scenes[${r}].panels[${a}].stageId`)}if(Nr(e.files,i.length,r),Ar(e.steps,i.length,r,!0),Array.isArray(e.steps)){let a=-1;e.steps.forEach((s,d)=>{if(!H(s))return;let h=Number(s.pairIndex);if(h<a)throw new Error(`scenes[${r}].steps must remain grouped in explanation stage order.`);if(a=h,s.stageId!==void 0&&q(s.stageId,`scenes[${r}].steps[${d}].stageId`),s.stageIndex!==void 0&&Z(s.stageIndex,`scenes[${r}].steps[${d}].stageIndex`),s.focusIndex!==void 0&&Z(s.focusIndex,`scenes[${r}].steps[${d}].focusIndex`),s.focusCount!==void 0&&ft(s.focusCount,`scenes[${r}].steps[${d}].focusCount`),s.stageIndex!==void 0&&Number(s.stageIndex)!==h)throw new Error(`scenes[${r}].steps[${d}].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[${d}].focusIndex must be less than focusCount.`)});for(let s=0;s<i.length-1;s+=1){let d=i[s+1],h=e.steps.filter(b=>H(b)&&Number(b.pairIndex)===s);if(!H(d)||h.length===0)throw new Error(`scenes[${r}].steps must cover every explanation stage.`);let p=h[0],y=H(p)?p.id:void 0;if(h.some(b=>H(b)?(b.stageId??y)!==d.stageId:!0))throw new Error(`scenes[${r}].panels must align with explanation stage ids.`)}}}function Nr(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(!H(s))throw new Error(`scenes[${i}].files[${a}] must be an object.`);if(q(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[d,h]of s.panels.entries()){if(!H(h))throw new Error(`scenes[${i}].files[${a}].panels[${d}] must be an object.`);for(let p of["id","label","content"])q(h[p],`scenes[${i}].files[${a}].panels[${d}].${p}`);if(h.path!==void 0&&q(h.path,`scenes[${i}].files[${a}].panels[${d}].path`),typeof h.exists!="boolean")throw new Error(`scenes[${i}].files[${a}].panels[${d}].exists must be boolean.`)}}}function Ar(e,r,i,a){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${i}].steps must be non-empty.`);for(let[s,d]of e.entries()){if(!H(d))throw new Error(`scenes[${i}].steps[${s}] must be an object.`);for(let h of["id","title","body","file","side"])q(d[h],`scenes[${i}].steps[${s}].${h}`);if(Z(d.pairIndex,`scenes[${i}].steps[${s}].pairIndex`),Number(d.pairIndex)>=r-1)throw new Error(`scenes[${i}].steps[${s}].pairIndex is outside the panels.`);if(a&&(Ve(d.introducedHunks,`scenes[${i}].steps[${s}].introducedHunks`),d.introducedHunks.length===0))throw new Error(`scenes[${i}].steps[${s}].introducedHunks must be non-empty.`);if(d.side!=="left"&&d.side!=="right")throw new Error(`scenes[${i}].steps[${s}].side must be left or right.`);d.startLine!==void 0&&ft(d.startLine,`scenes[${i}].steps[${s}].startLine`),d.endLine!==void 0&&ft(d.endLine,`scenes[${i}].steps[${s}].endLine`)}}function Mi(e,r){if(!H(e))throw new Error(`files[${r}] must be an object.`);if(e.kind==="text-diff"){Ke(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"])q(e[i],`files[${r}].${i}`);e.previousPath!==void 0&&q(e.previousPath,`files[${r}].previousPath`),Z(e.additions,`files[${r}].additions`),Z(e.deletions,`files[${r}].deletions`)}function Fi(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 bn(e,r){if(!H(e))throw new Error(`${r} must be an object.`);for(let i of["id","path","revision","excerpt"])q(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 Bi(e,r){q(e.summary,`${r}.summary`),Ve(e.bullets,`${r}.bullets`),Ve(e.tags,`${r}.tags`),q(e.takeaway,`${r}.takeaway`)}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function q(e,r){if(typeof e!="string")throw new Error(`${r} must be a string.`)}function Ve(e,r){if(!Array.isArray(e)||e.some(i=>typeof i!="string"))throw new Error(`${r} must be an array of strings.`)}function Z(e,r){if(!Number.isInteger(e)||Number(e)<0)throw new Error(`${r} must be a non-negative integer.`)}function Tr(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 _i=new Set(["modified-here","created-here","deleted-here"]);function vn(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(h=>h.exists)?"already-deleted":(e.panels.slice(r+2).some(h=>h.exists),"not-created-yet")}function Lr(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 d=e.map((p,y)=>({file:p,fileIndex:y,state:vn(p,r)})).filter(({state:p})=>_i.has(p)),h=a<0?[...d].reverse().find(({fileIndex:p})=>p<s):d.find(({fileIndex:p})=>p>s);return h?{pairIndex:r,fileIndex:h.fileIndex,path:h.file.path}:null}function xn(e,r,i){let a=e.findIndex(p=>p.id===r),s=a>=0?a:0,d=e[s];if(!d||d.kind!=="walkthrough"&&d.kind!=="stacked-diff"&&d.kind!=="deconstructed-diff"||!i)return{sceneIndex:s,stepIndex:0};let h=d.steps.findIndex(p=>p.id===i);return{sceneIndex:s,stepIndex:h>=0?h:0}}function kn(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 Rr(e,r,i){if(!r)return null;let a=e.map((p,y)=>({file:p,fileIndex:y})).filter(({file:p})=>p.kind==="text-diff"),s=a.findIndex(({file:p})=>p.path===r),d=s+i,h=s>=0?a[d]:null;return h?{fileIndex:h.fileIndex,path:h.file.path}:null}function Or(e,r,i){let a=e.scenes[r.sceneIndex];if(!a)return null;let s=In(a)?Math.min(Math.max(r.stepIndex,0),a.steps.length-1):0,d={sceneIndex:r.sceneIndex,stepIndex:s},h=In(a)?a.steps[s]:void 0,p=[],y=!h||s===0,b=!!(h&&s>0&&i.entry==="playback-start");if(y){let I=e.chapters.find(N=>N.sceneIds.includes(a.id));I&&p.push({source:{field:"chapter"},text:I.title})}(y||b)&&p.push({source:{field:"scene-title"},text:a.title}),y&&(p.push({source:{field:"summary"},text:a.summary}),a.bullets.forEach((I,N)=>{p.push({source:{field:"bullet",itemIndex:N},text:I})})),h&&(p.push({source:{field:"step-title"},text:h.title}),p.push({source:{field:"step-body"},text:h.body}),"connection"in h&&h.connection?.label&&p.push({source:{field:"connection"},text:h.connection.label})),(!h||In(a)&&s===a.steps.length-1)&&p.push({source:{field:"takeaway"},text:a.takeaway});let m=`${a.id}:${h?.id||"scene"}`,t=i.segmentLimit??240,v=p.flatMap(I=>zi(m,I,t));return{id:m,position:d,segments:v}}function Ui(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 qi(e).flatMap(a=>Wi(e,a.startOffset,a.endOffset,r))}function Hi(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 zi(e,r,i){let a=r.source.itemIndex===void 0?r.source.field:`${r.source.field}-${r.source.itemIndex}`;return Ui(r.text,i).map((s,d)=>({id:`${e}:${a}:${d}`,text:s.text,speechText:Hi(s.text),source:r.source,startOffset:s.startOffset,endOffset:s.endOffset})).filter(s=>s.speechText.length>0)}function qi(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])||(Mt(e,r,i,s),i=s)}return Mt(e,r,i,e.length),r}function Wi(e,r,i,a){let s=[],d=r;for(;i-d>a;){let h=d+a,p=d+Math.floor(a*.55),y=Pr(e,p,h,/[;,:—–-]/u);y<=d&&(y=Pr(e,p,h,/\s/u)),y<=d&&(y=h),Mt(e,s,d,y),d=y}return Mt(e,s,d,i),s}function Pr(e,r,i,a){for(let s=i;s>=r;s-=1)if(a.test(e[s]))return s+1;return-1}function Mt(e,r,i,a){let s=i,d=a;for(;s<d&&/\s/u.test(e[s]);)s+=1;for(;d>s&&/\s/u.test(e[d-1]);)d-=1;s<d&&r.push({text:e.slice(s,d),startOffset:s,endOffset:d})}function In(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function Dr(e){let r=[{kind:"title",key:"title",sceneIndex:0,stepIndex:0}],i=new Map;for(let s of e.chapters)for(let d of s.sceneIds)i.has(d)||i.set(d,s.id);let a=new Set;return e.scenes.forEach((s,d)=>{let h=i.get(s.id);e.chapters.length>1&&h&&!a.has(h)&&(r.push({kind:"chapter",key:`chapter:${h}`,chapterId:h,sceneIndex:d,stepIndex:0}),a.add(h)),r.push({kind:"scene",key:`scene:${s.id}`,sceneIndex:d,stepIndex:0}),ji(s)&&s.steps.forEach((p,y)=>{r.push({kind:"step",key:`step:${s.id}:${p.id}`,sceneIndex:d,stepIndex:y})})}),r}function Mr(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 Ft(e,r,i,a=null){if(a==="tour")return e.find(d=>d.kind==="title")??null;let s=e.findIndex(d=>d.kind==="scene"&&d.sceneIndex===r);if(s<0)return null;if(a==="overview")return e[s]??null;if(a==="chapter"){for(let d=s-1;d>=0;d-=1){let h=e[d];if(h.kind==="chapter")return h;if(h.kind==="title")break}return e.find(d=>d.kind==="title")??null}return e.find(d=>d.kind==="step"&&d.sceneIndex===r&&d.stepIndex===i)??e[s]??null}function ji(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}var Bt=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,d=i.segmentIndex+r;if(d<0||d>=s.segments.length){let h=this.callbacks.navigateUnit(s,r);if(!h||h.segments.length===0)return!1;s=h,d=r<0?s.segments.length-1:0}return this.resetEngine(),a?(this.setState({kind:"paused",unit:s,segmentIndex:d,pendingStart:!0}),this.callbacks.onSegmentChange(s.segments[d]||null,!0)):(this.setState({kind:"playing",unit:s,segmentIndex:d}),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 Br(e,r,i="all",a=300){let s=r.trim().toLocaleLowerCase();if(!s||a<=0)return[];let d=[];if(i!=="code"){let h=new Map;e.chapters.forEach(p=>p.sceneIds.forEach(y=>h.set(y,p.title))),e.scenes.forEach((p,y)=>{let b=[h.get(p.id),p.title,p.summary,...p.bullets,...p.tags,p.takeaway],m=Fr(b,s);m&&d.push({kind:"narrative",sceneIndex:y,label:p.title,preview:m}),Ki(p)&&p.steps.forEach((t,v)=>{let I=Fr([t.title,t.body,"connection"in t?t.connection?.label:void 0],s);I&&d.push({kind:"narrative",sceneIndex:y,stepIndex:v,label:`${p.title} \xB7 ${t.title}`,preview:I})})})}if(i!=="narrative"&&d.length<a)for(let h=0;h<e.files.length;h+=1){let p=e.files[h];if(p.kind==="text-diff"){for(let[y,b]of[[0,p.leftContent],[1,p.rightContent]])for(let m of Gi(b,s))if(d.push({kind:"code",fileIndex:h,sideIndex:y,label:`${p.path} \xB7 ${y===0?"base":"head"}`,...m}),d.length>=a)return d}}return d.slice(0,a)}function Fr(e,r){return e.find(i=>i?.toLocaleLowerCase().includes(r))}function Gi(e,r){let i=[];return e.replace(/\r\n/g,`
|
|
148
|
+
`}}function Tr(e,r={}){if(!We(e))throw new Error("review must be an object.");if(je(e,["baseOid","headOid","items"],"review"),Cr(e.baseOid,"review.baseOid"),Cr(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(Mt(e.baseOid)!==Mt(r.expectedRange.baseOid))throw new Error(`Stale review: review.baseOid ${e.baseOid} does not match the resolved range.mergeBaseOid ${r.expectedRange.baseOid}.`);if(Mt(e.headOid)!==Mt(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[s,a]of e.items.entries()){let c=`review.items[${s}]`;if(!We(a))throw new Error(`${c} must be an object.`);if(je(a,["id","kind","title","body","evidence","nextCheck"],c),qe(a.id,`${c}.id`),i.has(a.id))throw new Error(`Duplicate review item id: ${a.id}`);if(i.add(a.id),typeof a.kind!="string"||!["concept","boundary","tradeoff","question"].includes(a.kind))throw new Error(`${c}.kind must be concept, boundary, tradeoff, or question.`);if(qe(a.title,`${c}.title`),qe(a.body,`${c}.body`),!Array.isArray(a.evidence))throw new Error(`${c}.evidence must be an array.`);if(a.kind!=="question"&&a.evidence.length===0)throw new Error(`${c}.evidence must contain at least one reference for claims.`);if(a.kind==="question"&&a.nextCheck===void 0)throw new Error(`${c}.nextCheck must be a non-empty string for question items.`);a.nextCheck!==void 0&&qe(a.nextCheck,`${c}.nextCheck`);for(let[f,p]of a.evidence.entries()){let g=`${c}.evidence[${f}]`;if(!We(p))throw new Error(`${g} must be an object.`);if(je(p,["sceneId","stepId"],g),qe(p.sceneId,`${g}.sceneId`),qe(p.stepId,`${g}.stepId`),r.authoredWalkthroughSteps){let w=r.authoredWalkthroughSteps.get(p.sceneId);if(!w)throw new Error(`${g} references unknown authored walkthrough scene ${p.sceneId}.`);if(!w.has(p.stepId))throw new Error(`${g} references unknown authored walkthrough step ${p.sceneId}/${p.stepId}.`)}}}}function $r(e,r){if(e!==void 0){if(!We(e))throw new Error(`${r} must be an object.`);if(je(e,["id","text","status","source","confidence"],r),Ne(e.id,`${r}.id`),Ne(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(Li(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 Ge(e,r,i={}){if(e!==void 0){if(!We(e))throw new Error(`${r} must be an object.`);if(je(e,["kind","path","comparison"],r),e.kind!=="directory-diff")throw new Error(`${r}.kind must be directory-diff.`);if(e.path!==void 0&&Ai(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(!We(e.comparison))throw new Error(`${r}.comparison must be an object.`);if(je(e.comparison,["from","to"],`${r}.comparison`),Ne(e.comparison.from,`${r}.comparison.from`),Ne(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 s of[e.comparison.from,e.comparison.to])if(!i.endpointIds.includes(s))throw new Error(`${r}.comparison endpoint ${s} is not defined by this scene.`)}}}}function Ai(e,r){if(Ne(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 We(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e,r){if(typeof e!="string"||e.length===0)throw new Error(`${r} must be a non-empty string.`)}function Cr(e,r){if(Ne(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 qe(e,r){if(typeof e!="string"||e.trim().length===0)throw new Error(`${r} must be a non-empty string.`)}function Mt(e){return e.toLowerCase()}function Li(e,r){e!==void 0&&Ne(e,r)}function je(e,r,i){let s=Object.keys(e).filter(a=>!r.includes(a));if(s.length>0)throw new Error(`${i} contains unknown field${s.length===1?"":"s"}: ${s.join(", ")}`)}var wn=3;function Ar(e){if(H(e)&&Number.isInteger(e.version)&&Number(e.version)>wn)throw new Error(`This tour uses manifest format version ${e.version}, but this version of Bygone supports up to version ${wn}. Upgrade Bygone to open it.`);if(!H(e)||e.version!==1&&e.version!==2&&e.version!==wn)throw new Error("Unsupported or missing change-tour manifest version.");if(q(e.title,"title"),q(e.generatedAt,"generatedAt"),e.windowTitle!==void 0&&q(e.windowTitle,"windowTitle"),e.sourceUrl!==void 0&&q(e.sourceUrl,"sourceUrl"),!H(e.range))throw new Error("Change-tour manifest range must be an object.");for(let s of["baseRef","headRef","mergeBaseOid","headOid"])q(e.range[s],`range.${s}`);if(!H(e.summary))throw new Error("Change-tour manifest summary must be an object.");for(let s of["changedFiles","includedScenes","additions","deletions","commitCount"])Z(e.summary[s],`summary.${s}`);if(Ve(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[s,a]of e.scenes.entries()){if(Ke(a,s,e.version),r.has(a.id))throw new Error(`Duplicate change-tour scene id: ${a.id}`);r.add(a.id)}for(let[s,a]of e.chapters.entries()){if(!H(a))throw new Error(`chapters[${s}] must be an object.`);q(a.id,`chapters[${s}].id`),q(a.title,`chapters[${s}].title`),Ve(a.sceneIds,`chapters[${s}].sceneIds`);for(let c of a.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?_i(e.scenes):e.files.map((s,a)=>(Bi(s,a),s));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&&Pi(e.authoringCoverage,e.version),e.tours!==void 0){if(e.version!==3)throw new Error("Independent tours require manifest version 3.");Oi(e.tours,e.version)}if(e.version!==1&&Mi(e,e.version),e.review!==void 0){if(e.version!==3)throw new Error("Review notes require manifest version 3.");let s=e.version>=2&&H(e.zoom)&&H(e.zoom.final)?e.zoom.final.scenes:e.scenes;Tr(e.review,{expectedRange:{baseOid:String(e.range.mergeBaseOid),headOid:String(e.range.headOid)},authoredWalkthroughSteps:Ri(s)})}return{...e,files:i}}function Ri(e){let r=new Map;if(!Array.isArray(e))return r;for(let i of e){if(!H(i)||i.kind!=="walkthrough"||!Array.isArray(i.steps)||typeof i.id!="string")continue;let s=new Set;for(let a of i.steps)H(a)&&typeof a.id=="string"&&s.add(a.id);r.set(i.id,s)}return r}function Pi(e,r){if(!H(e)||!H(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(Z(e.walkthrough.coveredUnits,"authoringCoverage.walkthrough.coveredUnits"),Z(e.walkthrough.includedUnits,"authoringCoverage.walkthrough.includedUnits"),Nr(e.walkthrough.coveragePercent,"authoringCoverage.walkthrough.coveragePercent"),e.walkthrough.coveredUnits>e.walkthrough.includedUnits)throw new Error("authoringCoverage.walkthrough.coveredUnits must not exceed includedUnits.");for(let[s,a]of e.explanationAssignments.entries()){let c=`authoringCoverage.explanationAssignments[${s}]`;if(!H(a))throw new Error(`${c} must be an object.`);if(q(a.sceneId,`${c}.sceneId`),Z(a.assignedUnits,`${c}.assignedUnits`),Z(a.excludedUnits,`${c}.excludedUnits`),Z(a.completeUnits,`${c}.completeUnits`),Z(a.totalUnits,`${c}.totalUnits`),Nr(a.assignmentPercent,`${c}.assignmentPercent`),a.assignedUnits+a.excludedUnits!==a.completeUnits||a.completeUnits>a.totalUnits)throw new Error(`${c} contains inconsistent unit counts.`)}}function Oi(e,r){if(!H(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 s=e[i];if(s===void 0)continue;if(!H(s)||!Array.isArray(s.chapters)||!Array.isArray(s.scenes)||s.chapters.length===0||s.scenes.length===0)throw new Error(`Change-tour manifest tours.${i} must contain non-empty chapters and scenes arrays.`);let a=new Set,c=!1;for(let[f,p]of s.scenes.entries()){if(Ke(p,f,r),a.has(p.id))throw new Error(`Duplicate ${i} tour scene id: ${p.id}`);if(a.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 s.chapters.entries()){if(!H(p))throw new Error(`tours.${i}.chapters[${f}] must be an object.`);q(p.id,`tours.${i}.chapters[${f}].id`),q(p.title,`tours.${i}.chapters[${f}].title`),Ve(p.sceneIds,`tours.${i}.chapters[${f}].sceneIds`);for(let g of p.sceneIds)if(!a.has(g))throw new Error(`tours.${i} chapter references unknown scene id: ${g}`)}}}function Mi(e,r){if(!H(e.repository)||typeof e.repository.root!="string"||!e.repository.root)throw new Error("A v2 tour requires its originating repository.root.");if(!H(e.zoom)||!Array.isArray(e.zoom.revisions)||!H(e.zoom.final))throw new Error("A v2 tour requires zoom metadata and real revision evidence.");let i=e.scenes,s=e.zoom.revisions,a=new Set;for(let[m,t]of s.entries()){if(Ke(t,m,r),t.kind!=="stacked-diff")throw new Error("zoom.revisions must contain real stacked-diff scenes.");if(a.has(t.id))throw new Error(`Duplicate zoom revision scene: ${t.id}`);a.add(t.id);let b=e.range;if(t.stack[0].oid!==b.mergeBaseOid||t.stack[t.stack.length-1].oid!==b.headOid)throw new Error(`Revision scene ${t.id} endpoints must match the final diff range.`)}for(let m of i){if(m.kind!=="deconstructed-diff"&&m.kind!=="stacked-diff")continue;let t=s.find(b=>b.id===m.id);if(!t)throw new Error(`Scene ${m.id} is missing its real revision evidence.`);if(m.kind==="deconstructed-diff"&&(t.stack[0].oid!==m.realRange.baseOid||t.stack[t.stack.length-1].oid!==m.realRange.targetOid))throw new Error(`Deconstructed scene ${m.id} real stack endpoints must match its explanation range.`)}let c=i.some(m=>m.kind==="deconstructed-diff"),f=s.some(m=>m.stack.length>2),p=c?"explanation":f?"revisions":"final",g=[...c?["explanation"]:[],...f?["revisions"]:[],"final","history"];if(e.zoom.authoredDepth!==p||JSON.stringify(e.zoom.modes)!==JSON.stringify(g))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 w=new Set;for(let[m,t]of e.zoom.final.scenes.entries()){if(Ke(t,m,r),t.kind==="stacked-diff"||t.kind==="deconstructed-diff")throw new Error("zoom.final must contain only non-stacked scenes.");if(w.has(t.id))throw new Error(`Duplicate final tour scene: ${t.id}`);w.add(t.id)}for(let[m,t]of e.zoom.final.chapters.entries()){if(!H(t)||!Array.isArray(t.sceneIds))throw new Error(`zoom.final.chapters[${m}] must contain sceneIds.`);q(t.id,`zoom.final.chapters[${m}].id`),q(t.title,`zoom.final.chapters[${m}].title`);for(let b of t.sceneIds)if(q(b,`zoom.final.chapters[${m}].sceneIds`),!w.has(b))throw new Error(`Final tour chapter references unknown scene: ${b}`)}}function Ke(e,r,i){if(!H(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 s of["id","title"])q(e[s],`scenes[${r}].${s}`);if(e.overview!==void 0&&i!==3)throw new Error(`scenes[${r}].overview requires manifest version 3.`);if(Ui(e,`scenes[${r}]`),e.kind==="discussion"){Ge(e.overview,`scenes[${r}].overview`,{allowComparison:!1});return}if(e.kind==="walkthrough"){if(Ge(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[s,a]of e.steps.entries()){let c=`scenes[${r}].steps[${s}]`;if(!H(a)||!H(a.focus)||!H(a.diff))throw new Error(`${c} must contain focus and diff objects.`);for(let f of["id","title","body"])q(a[f],`${c}.${f}`);if(a.depth!==void 0&&!["mentioned","explained","contextualized"].includes(String(a.depth)))throw new Error(`${c}.depth must be mentioned, explained, or contextualized.`);if($r(a.requirement,`${c}.requirement`),bn(a.focus,`${c}.focus`),Ke(a.diff,r,i),a.diff.kind!=="text-diff")throw new Error(`${c}.diff must be a text-diff scene.`);if(a.connection!==void 0){if(!H(a.connection))throw new Error(`${c}.connection must be an object.`);q(a.connection.id,`${c}.connection.id`),q(a.connection.label,`${c}.connection.label`),bn(a.connection.from,`${c}.connection.from`),bn(a.connection.to,`${c}.connection.to`)}}return}if(e.kind==="stacked-diff"){Di(e,r),Ge(e.overview,`scenes[${r}].overview`,{endpointIds:e.stack.map(s=>s.id)});return}if(e.kind==="deconstructed-diff"){Fi(e,r),Ge(e.overview,`scenes[${r}].overview`,{endpointIds:e.panels.map(s=>s.id)});return}Ge(e.overview,`scenes[${r}].overview`,{allowComparison:!1});for(let s of["path","leftLabel","rightLabel","leftContent","rightContent"])q(e[s],`scenes[${r}].${s}`);e.previousPath!==void 0&&q(e.previousPath,`scenes[${r}].previousPath`),q(e.changeKind,`scenes[${r}].changeKind`),Z(e.additions,`scenes[${r}].additions`),Z(e.deletions,`scenes[${r}].deletions`),e.focusChangeIndex!==void 0&&Z(e.focusChangeIndex,`scenes[${r}].focusChangeIndex`)}function Di(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,s]of e.stack.entries()){if(!H(s))throw new Error(`scenes[${r}].stack[${i}] must be an object.`);for(let a of["id","ref","oid","label"])q(s[a],`scenes[${r}].stack[${i}].${a}`)}Lr(e.files,e.stack.length,r),Rr(e.steps,e.stack.length,r,!1)}function Fi(e,r){if(e.stageLabel!=="Explanation stages")throw new Error(`scenes[${r}].stageLabel must be Explanation stages.`);if(!H(e.realRange))throw new Error(`scenes[${r}].realRange must be an object.`);for(let s of["baseRef","targetRef","baseOid","targetOid"])q(e.realRange[s],`scenes[${r}].realRange.${s}`);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[s,a]of i.entries()){if(!H(a))throw new Error(`scenes[${r}].panels[${s}] must be an object.`);for(let f of["id","label","role"])q(a[f],`scenes[${r}].panels[${s}].${f}`);let c=s===0?"baseline":"stage";if(a.role!==c)throw new Error(`scenes[${r}].panels[${s}].role must be ${c}.`);s>0&&q(a.stageId,`scenes[${r}].panels[${s}].stageId`)}if(Lr(e.files,i.length,r),Rr(e.steps,i.length,r,!0),Array.isArray(e.steps)){let s=-1;e.steps.forEach((a,c)=>{if(!H(a))return;let f=Number(a.pairIndex);if(f<s)throw new Error(`scenes[${r}].steps must remain grouped in explanation stage order.`);if(s=f,a.stageId!==void 0&&q(a.stageId,`scenes[${r}].steps[${c}].stageId`),a.stageIndex!==void 0&&Z(a.stageIndex,`scenes[${r}].steps[${c}].stageIndex`),a.focusIndex!==void 0&&Z(a.focusIndex,`scenes[${r}].steps[${c}].focusIndex`),a.focusCount!==void 0&&ft(a.focusCount,`scenes[${r}].steps[${c}].focusCount`),a.stageIndex!==void 0&&Number(a.stageIndex)!==f)throw new Error(`scenes[${r}].steps[${c}].stageIndex must match pairIndex.`);if(a.focusIndex!==void 0&&a.focusCount!==void 0&&Number(a.focusIndex)>=Number(a.focusCount))throw new Error(`scenes[${r}].steps[${c}].focusIndex must be less than focusCount.`)});for(let a=0;a<i.length-1;a+=1){let c=i[a+1],f=e.steps.filter(w=>H(w)&&Number(w.pairIndex)===a);if(!H(c)||f.length===0)throw new Error(`scenes[${r}].steps must cover every explanation stage.`);let p=f[0],g=H(p)?p.id:void 0;if(f.some(w=>H(w)?(w.stageId??g)!==c.stageId:!0))throw new Error(`scenes[${r}].panels must align with explanation stage ids.`)}}}function Lr(e,r,i){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${i}].files must be non-empty.`);for(let[s,a]of e.entries()){if(!H(a))throw new Error(`scenes[${i}].files[${s}] must be an object.`);if(q(a.path,`scenes[${i}].files[${s}].path`),!Array.isArray(a.panels)||a.panels.length!==r)throw new Error(`scenes[${i}].files[${s}].panels must match panel count.`);for(let[c,f]of a.panels.entries()){if(!H(f))throw new Error(`scenes[${i}].files[${s}].panels[${c}] must be an object.`);for(let p of["id","label","content"])q(f[p],`scenes[${i}].files[${s}].panels[${c}].${p}`);if(f.path!==void 0&&q(f.path,`scenes[${i}].files[${s}].panels[${c}].path`),typeof f.exists!="boolean")throw new Error(`scenes[${i}].files[${s}].panels[${c}].exists must be boolean.`)}}}function Rr(e,r,i,s){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${i}].steps must be non-empty.`);for(let[a,c]of e.entries()){if(!H(c))throw new Error(`scenes[${i}].steps[${a}] must be an object.`);for(let f of["id","title","body","file","side"])q(c[f],`scenes[${i}].steps[${a}].${f}`);if(Z(c.pairIndex,`scenes[${i}].steps[${a}].pairIndex`),Number(c.pairIndex)>=r-1)throw new Error(`scenes[${i}].steps[${a}].pairIndex is outside the panels.`);if(s&&(Ve(c.introducedHunks,`scenes[${i}].steps[${a}].introducedHunks`),c.introducedHunks.length===0))throw new Error(`scenes[${i}].steps[${a}].introducedHunks must be non-empty.`);if(c.side!=="left"&&c.side!=="right")throw new Error(`scenes[${i}].steps[${a}].side must be left or right.`);c.startLine!==void 0&&ft(c.startLine,`scenes[${i}].steps[${a}].startLine`),c.endLine!==void 0&&ft(c.endLine,`scenes[${i}].steps[${a}].endLine`)}}function Bi(e,r){if(!H(e))throw new Error(`files[${r}] must be an object.`);if(e.kind==="text-diff"){Ke(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"])q(e[i],`files[${r}].${i}`);e.previousPath!==void 0&&q(e.previousPath,`files[${r}].previousPath`),Z(e.additions,`files[${r}].additions`),Z(e.deletions,`files[${r}].deletions`)}function _i(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 s of i.steps)r.has(s.diff.path)||r.set(s.diff.path,s.diff)}return[...r.values()].sort((i,s)=>i.path.localeCompare(s.path))}function bn(e,r){if(!H(e))throw new Error(`${r} must be an object.`);for(let i of["id","path","revision","excerpt"])q(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 Ui(e,r){q(e.summary,`${r}.summary`),Ve(e.bullets,`${r}.bullets`),Ve(e.tags,`${r}.tags`),q(e.takeaway,`${r}.takeaway`)}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function q(e,r){if(typeof e!="string")throw new Error(`${r} must be a string.`)}function Ve(e,r){if(!Array.isArray(e)||e.some(i=>typeof i!="string"))throw new Error(`${r} must be an array of strings.`)}function Z(e,r){if(!Number.isInteger(e)||Number(e)<0)throw new Error(`${r} must be a non-negative integer.`)}function Nr(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 Hi=new Set(["modified-here","created-here","deleted-here"]);function vn(e,r){let i=e.panels[r],s=e.panels[r+1];return!i||!s?"unchanged-here":i.exists&&s.exists?i.content===s.content?"unchanged-here":"modified-here":!i.exists&&s.exists?"created-here":i.exists&&!s.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 Pr(e,r,i,s){if(s!==-1&&s!==1||!i)return null;let a=e.findIndex(p=>p.path===i);if(a<0)return null;let c=e.map((p,g)=>({file:p,fileIndex:g,state:vn(p,r)})).filter(({state:p})=>Hi.has(p)),f=s<0?[...c].reverse().find(({fileIndex:p})=>p<a):c.find(({fileIndex:p})=>p>a);return f?{pairIndex:r,fileIndex:f.fileIndex,path:f.file.path}:null}function xn(e,r,i){let s=e.findIndex(p=>p.id===r),a=s>=0?s:0,c=e[a];if(!c||c.kind!=="walkthrough"&&c.kind!=="stacked-diff"&&c.kind!=="deconstructed-diff"||!i)return{sceneIndex:a,stepIndex:0};let f=c.steps.findIndex(p=>p.id===i);return{sceneIndex:a,stepIndex:f>=0?f:0}}function kn(e,r,i){let s=e[r.sceneIndex];if(!s)return null;if(i>0)return(s.kind==="walkthrough"||s.kind==="stacked-diff"||s.kind==="deconstructed-diff")&&r.stepIndex<s.steps.length-1?{sceneIndex:r.sceneIndex,stepIndex:r.stepIndex+1}:r.sceneIndex<e.length-1?{sceneIndex:r.sceneIndex+1,stepIndex:0}:null;if((s.kind==="walkthrough"||s.kind==="stacked-diff"||s.kind==="deconstructed-diff")&&r.stepIndex>0)return{sceneIndex:r.sceneIndex,stepIndex:r.stepIndex-1};if(r.sceneIndex===0)return null;let a=e[r.sceneIndex-1];return{sceneIndex:r.sceneIndex-1,stepIndex:a.kind==="walkthrough"||a.kind==="stacked-diff"||a.kind==="deconstructed-diff"?a.steps.length-1:0}}function Or(e,r,i){if(!r)return null;let s=e.map((p,g)=>({file:p,fileIndex:g})).filter(({file:p})=>p.kind==="text-diff"),a=s.findIndex(({file:p})=>p.path===r),c=a+i,f=a>=0?s[c]:null;return f?{fileIndex:f.fileIndex,path:f.file.path}:null}function Dr(e,r,i){let s=e.scenes[r.sceneIndex];if(!s)return null;let a=In(s)?Math.min(Math.max(r.stepIndex,0),s.steps.length-1):0,c={sceneIndex:r.sceneIndex,stepIndex:a},f=In(s)?s.steps[a]:void 0,p=[],g=!f||a===0,w=!!(f&&a>0&&i.entry==="playback-start");if(g){let I=e.chapters.find(N=>N.sceneIds.includes(s.id));I&&p.push({source:{field:"chapter"},text:I.title})}(g||w)&&p.push({source:{field:"scene-title"},text:s.title}),g&&(p.push({source:{field:"summary"},text:s.summary}),s.bullets.forEach((I,N)=>{p.push({source:{field:"bullet",itemIndex:N},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||In(s)&&a===s.steps.length-1)&&p.push({source:{field:"takeaway"},text:s.takeaway});let m=`${s.id}:${f?.id||"scene"}`,t=i.segmentLimit??240,b=p.flatMap(I=>Wi(m,I,t));return{id:m,position:c,segments:b}}function zi(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 ji(e).flatMap(s=>Gi(e,s.startOffset,s.endOffset,r))}function qi(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 Wi(e,r,i){let s=r.source.itemIndex===void 0?r.source.field:`${r.source.field}-${r.source.itemIndex}`;return zi(r.text,i).map((a,c)=>({id:`${e}:${s}:${c}`,text:a.text,speechText:qi(a.text),source:r.source,startOffset:a.startOffset,endOffset:a.endOffset})).filter(a=>a.speechText.length>0)}function ji(e){let r=[],i=0;for(let s=0;s<e.length;s+=1){if(!".!?".includes(e[s]))continue;let a=s+1;for(;a<e.length&&`"'\u201D\u2019)]}`.includes(e[a]);)a+=1;a<e.length&&!/\s/u.test(e[a])||(Dt(e,r,i,a),i=a)}return Dt(e,r,i,e.length),r}function Gi(e,r,i,s){let a=[],c=r;for(;i-c>s;){let f=c+s,p=c+Math.floor(s*.55),g=Mr(e,p,f,/[;,:—–-]/u);g<=c&&(g=Mr(e,p,f,/\s/u)),g<=c&&(g=f),Dt(e,a,c,g),c=g}return Dt(e,a,c,i),a}function Mr(e,r,i,s){for(let a=i;a>=r;a-=1)if(s.test(e[a]))return a+1;return-1}function Dt(e,r,i,s){let a=i,c=s;for(;a<c&&/\s/u.test(e[a]);)a+=1;for(;c>a&&/\s/u.test(e[c-1]);)c-=1;a<c&&r.push({text:e.slice(a,c),startOffset:a,endOffset:c})}function In(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function Fr(e){let r=[{kind:"title",key:"title",sceneIndex:0,stepIndex:0}],i=new Map;for(let a of e.chapters)for(let c of a.sceneIds)i.has(c)||i.set(c,a.id);let s=new Set;return e.scenes.forEach((a,c)=>{let f=i.get(a.id);e.chapters.length>1&&f&&!s.has(f)&&(r.push({kind:"chapter",key:`chapter:${f}`,chapterId:f,sceneIndex:c,stepIndex:0}),s.add(f)),r.push({kind:"scene",key:`scene:${a.id}`,sceneIndex:c,stepIndex:0}),Ki(a)&&a.steps.forEach((p,g)=>{r.push({kind:"step",key:`step:${a.id}:${p.id}`,sceneIndex:c,stepIndex:g})})}),r}function Br(e,r,i){if(i!==-1&&i!==1)return null;let s=e.findIndex(a=>a.key===r);return s<0?null:e[s+i]??null}function Ft(e,r,i,s=null){if(s==="tour")return e.find(c=>c.kind==="title")??null;let a=e.findIndex(c=>c.kind==="scene"&&c.sceneIndex===r);if(a<0)return null;if(s==="overview")return e[a]??null;if(s==="chapter"){for(let c=a-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[a]??null}function Ki(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}var Bt=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,s=i.kind==="paused",a=i.unit,c=i.segmentIndex+r;if(c<0||c>=a.segments.length){let f=this.callbacks.navigateUnit(a,r);if(!f||f.segments.length===0)return!1;a=f,c=r<0?a.segments.length-1:0}return this.resetEngine(),s?(this.setState({kind:"paused",unit:a,segmentIndex:c,pendingStart:!0}),this.callbacks.onSegmentChange(a.segments[c]||null,!0)):(this.setState({kind:"playing",unit:a,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 s=this.currentState.segmentIndex+1;s<this.currentState.unit.segments.length?(this.setState({kind:"playing",unit:this.currentState.unit,segmentIndex:s}),this.speakCurrent()):this.finishUnit(this.currentState.unit)},onError:s=>{r===this.generation&&(this.setState({kind:"error",message:s}),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 Ur(e,r,i="all",s=300){let a=r.trim().toLocaleLowerCase();if(!a||s<=0)return[];let c=[];if(i!=="code"){let f=new Map;e.chapters.forEach(p=>p.sceneIds.forEach(g=>f.set(g,p.title))),e.scenes.forEach((p,g)=>{let w=[f.get(p.id),p.title,p.summary,...p.bullets,...p.tags,p.takeaway],m=_r(w,a);m&&c.push({kind:"narrative",sceneIndex:g,label:p.title,preview:m}),Xi(p)&&p.steps.forEach((t,b)=>{let I=_r([t.title,t.body,"connection"in t?t.connection?.label:void 0],a);I&&c.push({kind:"narrative",sceneIndex:g,stepIndex:b,label:`${p.title} \xB7 ${t.title}`,preview:I})})})}if(i!=="narrative"&&c.length<s)for(let f=0;f<e.files.length;f+=1){let p=e.files[f];if(p.kind==="text-diff"){for(let[g,w]of[[0,p.leftContent],[1,p.rightContent]])for(let m of Vi(w,a))if(c.push({kind:"code",fileIndex:f,sideIndex:g,label:`${p.path} \xB7 ${g===0?"base":"head"}`,...m}),c.length>=s)return c}}return c.slice(0,s)}function _r(e,r){return e.find(i=>i?.toLocaleLowerCase().includes(r))}function Vi(e,r){let i=[];return e.replace(/\r\n/g,`
|
|
149
149
|
`).split(`
|
|
150
|
-
`).forEach((a
|
|
151
|
-
`)}function
|
|
150
|
+
`).forEach((s,a)=>{let c=s.toLocaleLowerCase(),f=0;for(;f<=c.length-r.length;){let p=c.indexOf(r,f);if(p<0)break;i.push({lineNumber:a+1,startColumn:p+1,endColumn:p+r.length+1,preview:s}),f=p+Math.max(r.length,1)}}),i}function Xi(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function Sn(e,r){return Ji(e,0,r)}function Ji(e,r,i){let s=e?.blocks[r],a=i==="left"?e?.leftLines:e?.rightLines;if(!s||!a?.length)return;let c=i==="left"?s.leftStart:s.rightStart,f=i==="left"?s.leftEnd:s.rightEnd,p=a.slice(c,f),g=p[0]?.lineNumber??a[Math.min(c,a.length-1)]?.lineNumber;if(Number.isInteger(g))return{startLine:g,endLine:p.at(-1)?.lineNumber??g}}function Hr(e,r,i,s){let a=[];return e.scenes.forEach((c,f)=>{c.kind==="walkthrough"&&c.steps.forEach((p,g)=>{p.diff.path===r&&a.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&&g===s,jumpTarget:{sceneIndex:f,stepIndex:g}})})}),a}function zr(e,r,i,s,a){let c=[];return e.scenes.forEach((f,p)=>{p!==i||f.kind!=="stacked-diff"&&f.kind!=="deconstructed-diff"||f.steps.forEach((g,w)=>{if(g.file!==r)return;let m=g.startLine===void 0?a?.(g.pairIndex,g.side):{startLine:g.startLine,endLine:g.endLine??g.startLine};if(!m)return;let t=g.pairIndex+(g.side==="right"?1:0);c.push({pairIndex:g.pairIndex,panelIndex:t,side:g.side,startLine:m.startLine,endLine:m.endLine,label:`${f.title} \xB7 ${g.title}: ${g.body}`,active:p===i&&w===s,jumpTarget:{sceneIndex:p,stepIndex:w}})})}),c}function Yi(e,r=120){return e.length<=r?e:`${e.slice(0,r-1)}\u2026`}function qr(e,r="Bygone"){let i=e?.windowTitle?.trim()||e?.title?.trim();return i?Yi(i):`${r} Tour`}function Wr(e,r){let i="overview"in r?r.overview:void 0,s=(i?.path||"").split("/").filter(t=>t&&t!==".").join("/"),a=t=>!s||t.startsWith(`${s}/`),c=[e.range.baseRef,e.range.headRef],f,p=[];if(r.kind==="stacked-diff"||r.kind==="deconstructed-diff"){let t=r.kind==="stacked-diff"?r.stack:r.panels,b=i?.comparison?t.findIndex(N=>N.id===i.comparison?.from):0,I=i?.comparison?t.findIndex(N=>N.id===i.comparison?.to):t.length-1;if(!t[b]||!t[I]||b===I)throw new Error(`Scene ${r.id} has invalid overview comparison endpoints.`);c=[t[b].label,t[I].label],f=r.files.flatMap(N=>{if(!a(N.path))return[];let x=N.panels[b],S=N.panels[I];if(!x||!S)return[];if(x.exists===S.exists&&x.content===S.content)return[];let C=x.exists?S.exists?"modified":"deleted":"added";return[{id:`${r.id}-overview-${N.path}`,kind:"text-diff",title:N.path,path:N.path,changeKind:C,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(t=>t.kind==="text-diff"&&a(t.path)),p=e.files.filter(t=>t.kind==="omitted"&&a(t.path));let g=new Map;for(let t of[...f,...p]){let b=[t.changeKind!=="added",t.changeKind!=="deleted"],I=t.path.split("/");for(let N=0;N<I.length-1;N++){let x=I.slice(0,N+1).join("/"),S=g.get(x);S?S.sides=S.sides.map((C,$)=>C||b[$]):g.set(x,{relativePath:x,displayName:I[N],depth:N,isDirectory:!0,status:"modified",sides:[...b]})}g.set(t.path,{relativePath:t.path,displayName:I[I.length-1],depth:I.length-1,isDirectory:!1,sides:b,status:b[0]?b[1]?"modified":"left-only":"right-only",gitChangeKind:t.changeKind,...t.previousPath?{previousPath:t.previousPath}:{},...t.kind==="omitted"?{relationSummary:`Unavailable: ${t.reason}`}:{}})}for(let t of g.values())t.isDirectory&&(t.status=t.sides[0]?t.sides[1]?"modified":"left-only":"right-only");let w=[...g.values()].sort((t,b)=>{let I=t.relativePath.split("/"),N=b.relativePath.split("/");for(let x=0;x<Math.min(I.length,N.length);x++){if(I[x]===N[x])continue;let S=x<I.length-1||t.isDirectory,C=x<N.length-1||b.isDirectory;return Number(C)-Number(S)||I[x].localeCompare(N[x])}return I.length-N.length}),m=s?` / ${s}/`:"";return{entries:w,files:f,labels:[c[0]+m,c[1]+m],omitted:p}}function Zi(){return{sceneIndex:0,stepIndex:0,path:null}}var _t=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 s=this.cursors.get(r);return s?{location:s,restore:!0}:{location:i??Zi(),restore:!1}}};function jr(e,r){let i=new Map;for(let f of r)i.has(f)||i.set(f,i.size);let s=e?.commits,a=Array.isArray(s)?s:[e?.from,e?.to],c=[...new Set(a.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,es="bygone-tour-skill.md";function Kr(e,r={},i={}){let s=e==="deconstructed"?"deconstructed":"historical",a=En(r.repository),c=Gr(r.paths),p=a!==void 0&&Array.isArray(r.paths)&&r.paths.length===0?["."]:c.length>0?c:null,g=Gr(r.revisions),w=ts(a,g,r.rangeStatus),m=r.rangeStatus||"unavailable",t=[ns(i),`Create a v3 ${s} tour.`,`Repository: ${JSON.stringify(a??null)}`,`Selected paths: ${JSON.stringify(p)}`,`Base: ${JSON.stringify(w?g[0]:null)}`,`Head: ${JSON.stringify(w?g[1]:null)}`,"Additional context: (optional)"];return w||t.push(`Warning: range status ${JSON.stringify(m)} 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(g)}`),t.join(`
|
|
151
|
+
`)}function ts(e,r,i){return i==="exact"&&!!e&&r.length===2&&r.every(s=>Qi.test(s))}function ns(e){let r=En(e.path);if(r)return`Read and follow the Bygone tour skill at ${JSON.stringify(r)}.`;let i=En(e.name)||es;return`Read and follow the Bygone tour skill in attached ${JSON.stringify(i)}.`}function Gr(e){return Array.isArray(e)?e.filter(r=>typeof r=="string").filter(r=>r.length>0):[]}function En(e){return typeof e=="string"&&e.trim().length>0?e:void 0}var Cn=`---
|
|
152
152
|
name: pr-tour-guide
|
|
153
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
154
|
---
|
|
@@ -561,6 +561,6 @@ Report:
|
|
|
561
561
|
- whether generated files are temporary, uncommitted, committed, or pushed.
|
|
562
562
|
|
|
563
563
|
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.
|
|
564
|
-
`;var Ut=["history","compare","historical","deconstructed"],Tn={history:"History",compare:"Compare",historical:"Historical tour",deconstructed:"Deconstructed tour"},Gr={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."},ns=new Set(["exact","none","multiple","uncommitted","reversed","divergent","unavailable"]),rs=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=++rs,d=i.createElement("section");d.className="workspace-controls",d.setAttribute("data-workspace-controls","true");let h=i.createElement("nav");h.className="workspace-mode-strip",h.setAttribute("aria-label","Workspace modes"),d.appendChild(h);let p=i.createElement("div");p.className="workspace-mode-descriptions",p.setAttribute("aria-hidden","true"),d.appendChild(p);let y=new Map,b=new Map;for(let C of Ut){let A=i.createElement("button");A.type="button",A.className="workspace-mode-button",A.setAttribute("data-workspace-mode",C),A.textContent=Tn[C];let B=i.createElement("span");B.className="workspace-mode-description visually-hidden";let Q=`bygone-workspace-${s}-${C}-description`;B.id=Q,p.appendChild(B),A.setAttribute("aria-describedby",Q),y.set(C,A),b.set(C,B),h.appendChild(A)}let m=i.createElement("button");m.type="button",m.className="workspace-back-button",m.textContent="Back to comparison",m.title="Return to the comparison that opened this workspace",m.setAttribute("aria-label","Back to comparison"),m.setAttribute("data-workspace-back","true"),d.appendChild(m);let t=i.createElement("div");t.className="workspace-status",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),d.appendChild(t);let v=os(i,s);d.appendChild(v.dialog),e.appendChild(d);let I=Kr(),N=!1,x=null,S=null,E=!1,$="",P=new Map,O=new Map;for(let[C,A]of y)A.addEventListener("click",()=>{if(N||A.disabled)return;let B=Vr(C,I);if((C==="historical"||C==="deconstructed")&&!B){ye(C,A);return}a({type:"workspaceMode",mode:C})});return m.addEventListener("click",()=>{!N&&!m.disabled&&a({type:"workspaceBack"})}),v.textarea.addEventListener("input",()=>{if(!x)return;let C=Le(x);C.text=v.textarea.value,C.edited=!0}),v.copyButton.addEventListener("click",()=>{if(!x)return;let C=we(x);Ht(C.text)}),v.resetButton.addEventListener("click",()=>{if(!x)return;let C=Le(x,{reset:!0});v.textarea.value=C.text,se(),v.textarea.focus()}),v.saveSkillButton.addEventListener("click",()=>{if(I.nativeSkillFiles){a({type:"workspaceSkillSave"});return}let C=Re(),A=URL.createObjectURL(new Blob([C.text],{type:"text/markdown;charset=utf-8"})),B=i.createElement("a");B.href=A,B.download=C.name||"bygone-tour-skill.md",B.click(),setTimeout(()=>URL.revokeObjectURL(A),1e3),J("Markdown downloaded. Edit your copy, then choose Use my copy. Attach it alongside the prompt when your agent cannot read local files.")}),v.chooseSkillButton.addEventListener("click",()=>{I.nativeSkillFiles?a({type:"workspaceSkillChoose"}):v.skillFile.click()}),v.skillFile.addEventListener("change",async()=>{let C=v.skillFile.files?.[0],A=I.sessionId;if(v.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 B=await C.text();if(!B.trim())throw new Error("The instructions file is empty.");if(O.set(A,{name:C.name,text:B}),N||I.sessionId!==A)return;se(),J("Custom instructions selected. Attach this Markdown file with the prompt.")}catch(B){!N&&I.sessionId===A&&J(`Could not load instructions: ${B.message}`)}}),v.openExistingButton.addEventListener("click",()=>{if(!x)return;we(x);let C=x;X(),a({type:"workspaceOpenTour",kind:C})}),v.chooseCompareButton.addEventListener("click",()=>{x&&(we(x),X(),a({type:"workspaceMode",mode:"compare"}))}),v.closeButton.addEventListener("click",()=>X()),v.dialog.addEventListener("cancel",C=>{C.preventDefault(),X()}),v.dialog.addEventListener("close",()=>{x=null,$="",E||ne()}),z(),{update:z,destroy:R};function z(C){if(N)return;let A=Kr(C);A.sessionId!==I.sessionId&&Ce()&&X(),zt(A),x&&A.status!==I.status&&($=A.status),I=A,W(),fe(),x&&se()}function R(){N||(N=!0,X(),typeof d.remove=="function"?d.remove():d.parentNode?.removeChild(d),y.clear(),b.clear(),P.clear(),O.clear())}function W(){for(let C of Ut){let A=y.get(C),B=b.get(C),Q=Vr(C,I),Oe=Q&&I.mode===C,Xe=(C==="historical"||C==="deconstructed")&&!Q,Je=C==="history"&&I.history.enabled===!1,he=C==="compare"&&I.compare.enabled===!1,De=C==="history"?I.history.label:C==="compare"?I.compare.label:I.modeLabels[C]||Tn[C],Ye=Xe?`${Gr[C]} Opens a prompt dialog without changing the current mode.`:Je?I.history.reason||"History is unavailable for this workspace.":he?I.compare.reason||"Compare is unavailable for this workspace.":Oe?`${De} is the current workspace mode.`:`Switch to ${De}.`;A.textContent=De,A.title=Ye,A.setAttribute("aria-label",De),A.setAttribute("aria-description",Ye),B.textContent=Ye,A.classList.toggle("is-active",Oe),A.classList.toggle("is-missing",Xe),A.classList.toggle("is-unavailable",Je||he),A.disabled=Je||he,Xe?A.removeAttribute("aria-pressed"):A.setAttribute("aria-pressed",String(Oe))}m.hidden=I.canReturn!==!0,m.disabled=I.canReturn!==!0}function fe(){t.textContent=I.status||"",t.hidden=!I.status}function ye(C,A){if(!(N||C!=="historical"&&C!=="deconstructed")){if(x=C,S=A,$=I.status||"",se(),typeof v.dialog.showModal=="function")try{v.dialog.showModal()}catch{v.dialog.setAttribute("open","")}else v.dialog.setAttribute("open","");v.textarea.focus()}}function X(){if(!Ce()){x=null,ne();return}E=!0;try{typeof v.dialog.close=="function"?v.dialog.close():v.dialog.removeAttribute("open"),x=null,$=""}finally{E=!1,ne()}}function ne(){let C=S;if(S=null,!(!C||typeof C.focus!="function")&&C.isConnected!==!1)try{C.focus()}catch{}}function Ce(){return v.dialog.open===!0||v.dialog.hasAttribute("open")}function se(){if(!x)return;let C=Le(x),A=Re();v.title.textContent=`${Tn[x]} prompt`,v.description.textContent=Gr[x],v.context.textContent=`Current context: ${Xr(I.promptContext)}`,C.skillKey!==Pe()?(v.draftNotice.hidden=!1,v.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!==$n(I.promptContext)?(v.draftNotice.hidden=!1,v.draftNotice.textContent=`This draft is based on earlier workspace context: ${C.contextSummary}. Review the repository, revision boundaries, and selected paths before copying.`):(v.draftNotice.hidden=!0,v.draftNotice.textContent=""),v.textarea.value=C.text,v.skillText.value=A.text,v.skillReference.textContent=A.path?`Instructions: ${A.path}. Local agents can read this path; for browser chats, save and attach a copy.`:`Instructions: ${A.name||"bygone-tour-skill.md"} (attachment). Download and attach it with the prompt; browsers do not expose its full local path.`,v.status.textContent=$,v.status.hidden=!$}function Ht(C){let A=i.defaultView?.navigator?.clipboard||globalThis.navigator?.clipboard;if(!A||typeof A.writeText!="function"){J("Could not copy the prompt: clipboard access is unavailable.");return}Promise.resolve().then(()=>A.writeText(C)).then(()=>J("Prompt copied to the clipboard.")).catch(B=>{let Q=B instanceof Error&&B.message?` ${B.message}`:"";J(`Could not copy the prompt.${Q}`)})}function J(C){$=C,v.status.textContent=C,v.status.hidden=!C}function we(C){let A=Le(C);return A.text=v.textarea.value,A.edited=!0,A}function Le(C,{reset:A=!1}={}){let B=P.get(I.sessionId)||new Map;P.set(I.sessionId,B);let Q=B.get(C);return(A||!Q||!Q.edited&&Q.skillKey!==Pe())&&B.set(C,{text:jr(C,I.promptContext,Re()),skillKey:Pe(),contextKey:$n(I.promptContext),contextSummary:Xr(I.promptContext),edited:!1}),B.get(C)}function Re(){return I.tourSkill||O.get(I.sessionId)||{name:"bygone-tour-skill.md",text:En}}function Pe(){let C=Re();return JSON.stringify([C.path||"",C.name||"",C.text])}function zt(C){let A=P.get(C.sessionId);if(A)for(let B of A.values())B.contextChanged=B.contextKey!==$n(C.promptContext)}}function os(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 d=e.createElement("p");d.className="workspace-prompt-context",i.appendChild(d);let h=e.createElement("p");h.className="workspace-prompt-draft-notice",h.setAttribute("role","status"),h.hidden=!0,i.appendChild(h);let p=e.createElement("label");p.className="workspace-prompt-label";let y=e.createElement("textarea");y.id=`bygone-workspace-${r}-prompt-textarea`,y.rows=9,y.spellcheck=!1,y.setAttribute("aria-label","Tour authoring prompt draft"),p.textContent="Prompt draft",p.appendChild(y),i.appendChild(p);let b=e.createElement("p");b.className="workspace-prompt-context",i.appendChild(b);let m=e.createElement("details"),t=e.createElement("summary");t.textContent="Read instructions (Markdown)";let v=e.createElement("textarea");v.readOnly=!0,v.rows=12,v.setAttribute("aria-label","Tour skill Markdown instructions"),m.append(t,v),i.appendChild(m);let I=e.createElement("div");I.className="workspace-prompt-actions";let N=Ae(e,"Save an editable copy","workspace-skill-save"),x=Ae(e,"Use my copy","workspace-skill-choose"),S=e.createElement("input");S.type="file",S.accept=".md,text/markdown",S.hidden=!0,I.append(N,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 $=e.createElement("div");$.className="workspace-prompt-actions";let P=Ae(e,"Copy prompt","workspace-prompt-copy"),O=Ae(e,"Reset prompt","workspace-prompt-reset"),z=Ae(e,"Open existing tour","workspace-prompt-open"),R=Ae(e,"Choose revisions in Compare","workspace-prompt-compare"),W=Ae(e,"Close","workspace-prompt-close");return $.append(P,O,z,R,W),i.appendChild($),{dialog:i,title:a,description:s,context:d,draftNotice:h,textarea:y,skillText:v,skillReference:b,saveSkillButton:N,chooseSkillButton:x,skillFile:S,status:E,copyButton:P,resetButton:O,openExistingButton:z,chooseCompareButton:R,closeButton:W}}function Ae(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 Kr(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(d=>d==="historical"||d==="deconstructed"):null;return{sessionId:ss(e?.sessionId),mode:r,modeLabels:e?.modeLabels&&typeof e.modeLabels=="object"?Object.fromEntries(Ut.filter(d=>typeof e.modeLabels[d]=="string").map(d=>[d,e.modeLabels[d]])):{},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:En}:null,promptContext:is(e?.promptContext),canReturn:e?.canReturn===!0,status:ht(e?.status,"")}}function is(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")}:{},...ns.has(r.rangeStatus)?{rangeStatus:r.rangeStatus}:{},...typeof r.reason=="string"?{reason:r.reason}:{}}}function Vr(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 $n(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 Xr(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 ss(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.tourNarrativeHeight",p="bygone.tourNarrationVoice",y="bygone.tourNarrationRate",b=new Set([.75,1,1.25,1.5]),m="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:ko(),tourSidebarHidden:!1,tourNarrativeHeight:So(),tourNavigatorTab:"tour",narrationVoiceURI:window.localStorage.getItem(p)||"",narrationRate:fo(),narrationVoices:[],renderedNarrationUnit:null,workspacePromptStatus:"",historyPrefix:"/history/"},v=null,I=null,N=null,x=[],S=new Map,E=new Set,$=null,P=null,O=new URLSearchParams(window.location.search).get("workspaceEmbedded")==="1",z=null,R=new Bt(ho(),{claimAudio:wo,onStateChange:Kt,onSegmentChange:bo,canNavigateUnit:go,navigateUnit:yo});window.__BYGONE_HOST__={environment:"web",editorWorkerUrl:"/media/editor.worker.js",diffWorkerUrl:"/media/diff.worker.js",postMessage(n){co(n)}},window.addEventListener("message",n=>{if(!O||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"||(z=o.mode,!(!t.zoom||t.zoom.mode===o.mode||!A().includes(o.mode))&&xe(o.mode).catch(te))}),window.addEventListener("DOMContentLoaded",()=>{if(lo(),O){let n=document.getElementById("tour-mode-tabs"),o=document.getElementById("tour-mode-description");n&&(n.hidden=!0),o&&(o.hidden=!0)}me("Browser host ready.")});function W(n){(n.type==="showDiff"||n.type==="showMultiDiff"||n.type==="showDirectoryDiff")&&(n={...n,renderRequestId:++ne},t.mode==="tour"&&(t.displayedPanels=n.type==="showMultiDiff"?n.panels:ro(),n.history||(n.history=Ln()),he()),X&&(Ce=n.renderRequestId)),window.dispatchEvent(new window.CustomEvent("bygone:host-message",{detail:n}))}let fe=0,ye=new Map,X=null,ne=0,Ce=null;function se(){t.zoomSwitching||(X=null)}function Ht(){return new Promise(n=>{let o=++fe,c=u=>{ye.delete(o);let f=t.tour?.scenes[t.activeSceneIndex],g=u?.activeMultiPairIndex,w=f&&ae(f)?ot(f):[],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:w[g+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(()=>c(null),1e3);ye.set(o,u=>{window.clearTimeout(l),c(u)}),W({type:"captureNavigationState",requestId:o})})}let J=0;function we(n=t.authoredTour){if(n.tours||!n.scenes.some(c=>c.kind==="deconstructed-diff"))return null;let o=n.zoom?.final;return o?.scenes.some(c=>c.kind==="walkthrough")?o:null}let Le={history:"History",compare:"Compare",historical:"Historical tour",deconstructed:"Deconstructed tour"},Re={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 Pe(n){return n==="historical"&&we()?"Final tour":Le[n]}function zt(n){return n==="historical"&&we()?"The authored walkthrough of the completed endpoint diff.":Re[n]}function C(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 c=we(n);return{...c?{historical:c}:{},deconstructed:{scenes:n.scenes,chapters:n.chapters}}}function A(){return[...B()?["history","compare"]:[],...Object.keys(C()).filter(n=>C()[n])]}function B(n=t.authoredTour){return Number(n?.version)>=2}function Q(){return"History is unavailable for legacy v1 tours; open a version 2 tour to browse commit history."}function Oe(){return"Compare is unavailable for legacy v1 tours because this tour has no history backend."}function Xe(){if(v)return;let n=document.getElementById("tour-mode-controls");if(!n)return;let o=document.getElementById("tour-mode-tabs"),c=document.getElementById("tour-mode-description"),l=document.getElementById("tour-mode-status");o&&(o.hidden=!0),c&&(c.hidden=!0),l&&(l.hidden=!0),I=document.createElement("div"),I.id="workspace-mode-controls",n.prepend(I),v=Jr({container:I,send:Je})}function Je(n){if(!(!n||typeof n!="object")){if(n.type==="workspaceMode"&&["history","compare","historical","deconstructed"].includes(n.mode)){xe(n.mode).catch(te);return}n.type==="workspaceOpenTour"&&(n.kind==="historical"||n.kind==="deconstructed")&&no()}}function he(){if(!t.zoom||(Xe(),!v))return;I.hidden=O;let n=document.getElementById("tour-mode-tabs"),o=document.getElementById("tour-mode-description");n&&(n.dataset.workspaceModeLabel=Pe(t.zoom.mode)),o&&(o.textContent=zt(t.zoom.mode));let c=B();v.update({sessionId:De(),mode:t.zoom.mode,modeLabels:{historical:Pe("historical")},history:{enabled:c,label:"History",...c?{}:{reason:Q()}},compare:{enabled:c,label:"Compare",...c?{}:{reason:Oe()}},availableTours:Object.keys(C()).filter(l=>l==="historical"||l==="deconstructed"),promptContext:Ye(),status:t.workspacePromptStatus})}function De(){let n=t.authoredTour;return[n?.repository?.root||"",n?.range?.mergeBaseOid||"",n?.range?.headOid||""].join("\0")||"browser-workspace"}function Ye(){let n=t.authoredTour,o=n?.range,c=Array.isArray(t.displayedPanels)?t.displayedPanels:[],l=pt(c.map(k=>k?.commit)),u=c.length>0?l:pt([o?.mergeBaseOid,o?.headOid]),f=pt(c.map(k=>k?.path)),g=f.length>0?f:pt(t.tour?.files?.map(k=>k?.path)),w=Yr(u,n);return{...typeof n?.repository?.root=="string"?{repository:n.repository.root}:{},...g.length>0?{paths:g}:{},...u.length>0?{revisions:u}:{},rangeStatus:w.status,...w.reason?{reason:w.reason}:{}}}function Yr(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 c=o?.range?.mergeBaseOid,l=o?.range?.headOid;return n[0]===c&&n[1]===l?{status:"exact",reason:"The manifest validates its merge-base/head range."}:n[0]===l&&n[1]===c?{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 pt(n){return[...new Set(n.filter(o=>typeof o=="string"&&o.trim()).map(o=>o.trim()))]}function Me(n){t.workspacePromptStatus=n,he()}function Zr(n){try{let o=new URL(n,window.location.href).pathname,c="/tour.json";if(o.endsWith(c))return`${o.slice(0,-c.length)||""}/history/`}catch{}return"/history/"}function Qr(){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 c=l=>{o.remove(),n(l||null)};o.addEventListener("change",()=>c(o.files?.[0])),o.addEventListener("cancel",()=>c(null)),o.click()})}function eo(n){let o=t.authoredTour;if(!o)return!1;let c=o.repository?.root,l=o.range?.mergeBaseOid,u=o.range?.headOid,f=typeof n.repository=="string"?n.repository:"",g=typeof n.range?.mergeBaseOid=="string"?n.range.mergeBaseOid:"",w=typeof n.range?.headOid=="string"?n.range.headOid:"";return!!(c&&f&&c!==f||l&&g&&l!==g||u&&w&&u!==w)}function to(n){let o=typeof n.repository=="string"&&n.repository?n.repository:"(server-selected repository)",c=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)",f=t.authoredTour?.range?.mergeBaseOid||"(unknown base)",g=t.authoredTour?.range?.headOid||"(unknown head)";return["Open this authored tour from the server?",`Repository: ${o}`,`Range: ${c} \u2192 ${l}`,`Current browser range: ${u}, ${f} \u2192 ${g}`,"This loads the server-validated tour and does not change a local repository."].join(`
|
|
565
|
-
`)}async function no(){try{let n=await Qr();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 c=await n.text(),l=await fetch("/tour/open",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:c})}),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(eo(u)&&!window.confirm(to(u))){Me("Kept the current tour.");return}if(!await Un(u.manifestUrl)){Me("Could not load the uploaded tour.");return}Me("")}catch(n){Me(`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 Ze(n){let o=t.authoredTour;return C()[n]?{...o,...C()[n]}:{...o,scenes:[],chapters:[],files:n==="compare"&&t.compare?t.compare.files:o.files}}function Fe(){let n=document.getElementById("tour-mode-controls");if(n.hidden=!t.zoom||O,!t.zoom)return;he();let o=document.getElementById("tour-mode-tabs"),c=document.getElementById("tour-mode-description");o&&(o.hidden=!0),c&&(c.hidden=!0);let l=t.zoom.mode==="history",u=B();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 f of["tour-history-parent","tour-history-base"])document.getElementById(f).hidden=!l;mt()}function mt(){let n=t.comparisonDraftCommits.length,o=document.getElementById("tour-history-compare");o.textContent=`Compare selected (${n})`,o.disabled=n<2||!B();let c=document.getElementById("tour-compare-apply");c.textContent=`Update comparison (${n})`,c.disabled=n<2||!B(),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=!B()||!t.historyCommit}function qt(){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 Nn(n){return qr(n,qt())}async function be(n,o,c=t.historyPrefix,l=t.authoredTour){if(!B(l))throw new Error(Q());let u=await fetch(`${c||"/history/"}${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),f=await u.json();if(!u.ok)throw new Error(f.error||`History request failed (${u.status}).`);return f}function te(n){let o=n instanceof Error?n.message:String(n),c=document.getElementById("tour-mode-status");c&&(c.textContent=o),v&&Me(o)}function An(){return t.displayedPanels.map(n=>n.commit).filter(Boolean)}function ro(){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&&ae(n)){let c=ot(n),l=n.overview?.comparison;o=n.kind==="deconstructed-diff"?[]:[(l?c.find(u=>u.id===l.from):c[0])?.oid,(l?c.find(u=>u.id===l.to):c.at(-1))?.oid]}return["left","right"].map((c,l)=>({id:c,commit:o[l]}))}function Ln(){let n=t.displayedPanels.map(o=>o.commit);return{...yt(jt({commits:An()},null),n,null),navigatorOnly:!0}}async function oo(n){if(!n||!t.zoom||!B())return[];if(!t.fileHistoryCache.has(n)){let o=be("list",{path:n,commit:t.authoredTour.range.headOid}).then(c=>c.entries);t.fileHistoryCache.set(n,o),o.catch(()=>t.fileHistoryCache.delete(n))}return t.fileHistoryCache.get(n)}async function io(n,o){try{let c=await oo(n);if(o!==ne)return;W({type:"updateCommitMarkers",changedCommits:c.map(l=>l.commit),path:n})}catch(c){o===ne&&te(c)}}async function Be(n,o,c=!0){let l=++J,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 f=u.find(U=>U.commit===o);if(t.historyPath===n&&t.historyCommit===o&&t.historyPanels.length){wt();return}let g=await be("diff",{path:n,commit:o,head:t.authoredTour.range.headOid});if(l!==J||t.zoom.mode!=="history")return;if(c&&t.historyPanels.length&&t.historyCommit===o){let U=await Promise.all(t.historyPanels.map(async V=>{let M=V.commit?await be("diff",{path:n,commit:V.commit,head:t.authoredTour.range.headOid}):{rightContent:"",path:n};return{...V,content:M.rightContent,path:M.path}}));if(l!==J||t.zoom.mode!=="history")return;t.historyPanels=U,t.historyPath=n,t.historyDiff=g,wt(),ce();return}let w=u.findIndex(U=>U.commit===o),L=(w>=0?u[w+1]:null)?.commit||g.parentCommit,F=L&&L!==g.parentCommit?(await be("diff",{path:n,commit:L,head:t.authoredTour.range.headOid})).rightContent:g.leftContent;if(l!==J||t.zoom.mode!=="history")return;t.historyPath=n,t.historyCommit=o;let G=Math.max(2,t.historyPanels.length);t.historyDiff=g;let j=(U,V,M)=>({id:`history-${U||"empty"}`,commit:U,content:V,label:M,path:g.path,editable:!1});for(t.historyPanels=[j(L,F,L?.slice(0,7)||"Empty tree"),j(o,g.rightContent,f?`${f.shortCommit} ${f.summary}`:o.slice(0,7))],t.historyFocus=`history-${o}`;t.historyPanels.length<G;){let U=gt(t.historyPanels[0],"left");if(!U)break;let V=await be("diff",{path:n,commit:U.commit,head:t.authoredTour.range.headOid});if(l!==J||t.zoom.mode!=="history")return;t.historyPanels.unshift(j(U.commit,V.rightContent,`${U.shortCommit} ${U.summary}`))}wt(),document.getElementById("tour-mode-status").textContent="",mt(),ce()}function so(n,o,c){let l=n.findIndex(f=>f.commit===o),u=n[l];return{fileName:(t.historyPath||c.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((f,g)=>({label:`${f.shortCommit} ${f.summary}`.trim(),meta:f.timestamp,commit:f.commit,summary:f.summary,timestamp:f.timestamp,author:f.author,authorEmail:f.authorEmail,message:f.message,parents:f.parents,active:g===l,selected:t.comparisonDraftCommits.includes(f.commit),kind:"history-entry",index:g}))}}}}function gt(n,o){let c=qt(),l=c.indexOf(n.commit);if(l<0)return null;let u=new Set(t.historyPanels.map(w=>w.commit)),g=(o==="left"?c.slice(0,l).reverse():c.slice(l+1)).find(w=>!u.has(w)&&t.historyEntries.some(k=>k.commit===w));return t.historyEntries.find(w=>w.commit===g)}function yt(n,o,c){let l=n.rail.itemsByTab.history;for(let u of l){u.commit=t.historyEntries[u.index]?.commit;let f=t.historyEntries[u.index];u.inTour=t.authoredTour?.commits.some(g=>g.oid===u.commit),u.selectionEnabled=!!t.zoom,f?.parents?.length>1&&(u.meta+=` \xB7 Merge: ${f.parents.map(g=>g.slice(0,7)).join(", ")}`),u.panelNumber=o.indexOf(u.commit)+1||null,u.active=u.commit===c}return o.forEach((u,f)=>{u!==void 0&&(l.some(g=>g.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:f+1,active:u===c,kind:"panel-revision",index:-f-1}))}),n}function wt(){let n=t.historyPanels.map(c=>({...c,addLeftEnabled:!!gt(c,"left"),addRightEnabled:!!gt(c,"right"),removeEnabled:t.historyPanels.length>2})),o=n.find(c=>c.id===t.historyFocus)?.commit;t.activeTourFilePath=t.historyPath,Te(),W({type:"showMultiDiff",panels:n,pairs:n.slice(0,-1).map((c,l)=>({leftIndex:l,rightIndex:l+1,diffModel:ie(c.content,n[l+1].content)})),activePanelId:t.historyFocus,mutationEnabled:!0,fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(1)},history:yt(so(t.historyEntries,t.historyCommit,t.historyDiff),n.map(c=>c.commit),o)})}async function ao(n){let o=t.historyPanels.find(c=>c.id===(n.anchorPanelId||n.panelId));if(o){if(n.type==="multiRemovePanel"){if(t.historyPanels.length<=2)return;++J,t.historyPanels=t.historyPanels.filter(c=>c!==o),t.historyFocus===o.id&&(t.historyFocus=t.historyPanels.at(-1).id)}else{let c=gt(o,n.side);if(!c)return;let l=++J,u=await be("diff",{path:t.historyPath,commit:c.commit,head:t.authoredTour.range.headOid});if(l!==J||t.zoom.mode!=="history")return;let f={id:`history-${c.commit}`,commit:c.commit,content:u.rightContent,label:`${c.shortCommit} ${c.summary}`,path:u.path,editable:!1};t.historyPanels.push(f);let g=qt();t.historyPanels.sort((w,k)=>g.indexOf(w.commit)-g.indexOf(k.commit)),t.historyFocus=f.id}wt()}}function Wt(n){let o=t.historyEntries.findIndex(l=>l.commit===t.historyCommit),c=t.historyEntries[o+n];if(c)return Be(t.historyPath,c.commit,!1)}function jt(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((c,l)=>({label:`${c.shortCommit} ${c.summary}`.trim(),meta:c.timestamp,commit:c.commit,summary:c.summary,timestamp:c.timestamp,author:c.author,authorEmail:c.authorEmail,message:c.message,parents:c.parents,active:c.commit===o,selected:t.comparisonDraftCommits.includes(c.commit),panelNumber:n.commits.indexOf(c.commit)+1||null,kind:"history-entry",index:l}))}}}}function Rn(n,o=null){if(!n||n.kind!=="text-diff")return!1;let c=n.comparisonPanels;o=o||t.comparisonFocus,t.comparisonFocus=o;let l=c.slice(0,-1).map((u,f)=>({leftIndex:f,rightIndex:f+1,diffModel:ie(u.content,c[f+1].content)}));return t.activeTourFilePath=n.path,Te(),W({type:"showMultiDiff",panels:c,pairs:l,activePanelId:o?`compare-${o}`:null,history:yt(jt(t.compare,o),t.compare.commits,o),fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(1)},mutationEnabled:!1}),ce(),!0}async function Pn(n,o,c=null){n=Nn(n);let l=++J,u=await be("compare-many",n);if(l!==J||t.zoom.mode!=="compare")return;let f=u.files;t.comparisonCommits=n.commits,t.compare={...n,files:f},t.tour=Ze("compare"),t.activeSceneIndex=-1,t.tourFocusFilePath=null,_e(),Fe(),Ee();let g=f.find(w=>w.kind==="text-diff"&&w.path===o)||f.find(w=>w.kind==="text-diff");if(g)Rn(g,c);else{t.activeTourFilePath=null;let w=n.commits.map(k=>({id:`compare-${k}`,commit:k,path:"No text changes",content:"",label:k.slice(0,7),editable:!1}));W({type:"showMultiDiff",panels:w,pairs:w.slice(0,-1).map((k,L)=>({leftIndex:L,rightIndex:L+1,diffModel:ie("","")})),mutationEnabled:!1,history:yt(jt(n,null),n.commits,null)}),t.activeTourFilePath=null,X=null}document.getElementById("tour-mode-status").textContent=f.length?g?"":"Changed files cannot be displayed as text. See the file list for details.":"No changes between these revisions.",ce()}async function ve(n){if(!B()){Me(Oe());return}t.zoomSwitching||(t.zoom.mode!=="compare"?await xe("compare",n):await Pn(n,t.activeTourFilePath),kt("commits"))}function Gt(){return{commits:[t.authoredTour.range.mergeBaseOid,t.authoredTour.range.headOid]}}function On(){return t.historyEntries.find(n=>n.commit===t.historyCommit)?.path||t.historyPath}async function xe(n,o,c){if(!t.zoom||t.zoomSwitching||n===t.zoom.mode||!A().includes(n))return;t.zoomSwitching=!0,++J;let l=t.zoom.mode,u;try{u=await Ht(),t.zoom.depart(u),R.pauseForExternalOwner();let f=t.zoom.enter(n,n==="history"?u:null);if(t.tourNavigatorTab=f.restore?f.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=Ze(n),_e(),Ee(),Fe(),document.getElementById("tour-mode-status").textContent="",X=f.restore&&!o?f.location:null,n==="history")await Be(t.historyPath||f.location.path||t.tour.files.find(g=>g.kind==="text-diff")?.path,t.historyCommit||f.location.commit);else if(n==="compare")await Pn(o||t.compare||Gt(),c||f.location.path||u.path);else if(oe(Math.max(0,f.location.sceneIndex),f.location.stepIndex,{zoomLanding:!0,showIntro:f.restore?f.location.sceneIntroVisible:!0,readingKey:f.restore?f.location.readingKey:"title"}),f.location.path&&t.activeTourFilePath!==f.location.path){let g=t.tour.files.findIndex(w=>w.path===f.location.path);g>=0&&nt(g)}ce()}catch(f){X=null,t.zoom.enter(l),t.tour=Ze(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),_e(),Fe(),Ee(),u&&ee()&&(X=u,oe(u.sceneIndex,u.stepIndex,{zoomLanding:!0,showIntro:u.sceneIntroVisible,readingKey:u.readingKey}),u.path&&t.activeTourFilePath!==u.path&&nt(t.tour.files.findIndex(g=>g.path===u.path))),Te(),ce(),te(f)}finally{t.zoomSwitching=!1}}async function co(n){if(!(!n||typeof n!="object")){if(n.type==="navigationState"){ye.get(n.requestId)?.(n.navigation);return}if(n.type==="renderComplete"&&t.mode==="tour"&&n.renderRequestId===ne&&io(t.activeTourFilePath,ne),n.type==="renderComplete"&&X&&n.renderRequestId===Ce){let o=X;X=null,W({type:"restoreNavigationState",navigation:o.navigation});let c=document.getElementById("tour-narrative-content");c&&(c.scrollTop=o.narrativeScroll||0,$=c.scrollTop),o.focusId&&document.getElementById(o.focusId)?.focus({preventScroll:!0})}if(n.type==="ready"){let o=new URLSearchParams(window.location.search),c=o.get("manifest");c?Un(c):o.get("demo")==="1"&&Yn();return}if(t.mode==="tour"&&t.directoryEvidence&&ee()){if(n.type==="openDirectoryEntry"){Qt(n.relativePath);return}if(n.type==="returnToDirectory"){vt();return}}if(t.mode==="tour"){if(t.zoom?.mode==="history"&&["multiAddPanel","multiRemovePanel"].includes(n.type)){ao(n).catch(te);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=Wt(n.type==="historyBack"?1:-1);o&&o.catch(te);return}if(n.type==="toggleHistorySelection"&&Number.isInteger(n.index)){let o=t.displayedPanels.map(u=>u.commit),c=n.index<0?{commit:o[-n.index-1]}:t.historyEntries[n.index];if(!c?.commit)return;let l=t.comparisonDraftCommits.includes(c.commit)?t.comparisonDraftCommits.filter(u=>u!==c.commit):[...t.comparisonDraftCommits,c.commit];t.comparisonDraftCommits=l.length>=2?Nn({commits:l}).commits:l,mt();return}if(n.type==="compareHistoryEntry"&&Number.isInteger(n.index)){let o=t.historyEntries[n.index];o?.parentCommit&&ve({commits:[o.parentCommit,o.commit],path:t.activeTourFilePath}).catch(te);return}if(n.type==="selectHistoryEntry"&&Number.isInteger(n.index)){let o=t.historyEntries[n.index];if(o&&t.zoom?.mode==="history"){let c=t.historyPanels.find(l=>l.commit===o.commit);c?(t.historyFocus=c.id,W({type:"focusHistoryPanel",panelId:c.id})):Be(t.historyPath,o.commit,!1).catch(te)}if(o&&t.zoom?.mode!=="history"){let c=t.displayedPanels.find(l=>l.commit===o.commit);c?W({type:"focusHistoryPanel",panelId:c.id}):(t.historyCommit=o.commit,t.historyPath=t.activeTourFilePath||t.historyPath,xe("history").catch(te))}return}}if(n.type==="navigateFile"&&t.mode==="tour"){Wn(n.direction==="previous"?-1:1);return}if(n.type==="navigateTourStep"&&t.mode==="tour"){let o=n.sceneIndex,c=n.stepIndex;Number.isInteger(o)&&Number.isInteger(c)&&oe(o,c,{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,W({type:"showDiff",file1:t.left.name,file2:t.right.name,comparisonId:`web-${t.comparisonId}`,leftContent:t.left.content,rightContent:t.right.content,diffModel:ie(t.left.content,t.right.content),history:null}))}}function lo(){document.getElementById("tour-review-toggle")?.addEventListener("click",()=>{bt(document.getElementById("tour-review").hidden)}),document.getElementById("tour-review-close")?.addEventListener("click",()=>bt(!1)),document.getElementById("tour-review")?.addEventListener("keydown",T=>{T.key==="Escape"&&(T.preventDefault(),bt(!1))});let n=(T,K)=>document.getElementById(T)?.addEventListener("click",()=>{Promise.resolve().then(K).catch(te)});n("tour-history-compare",()=>ve({commits:t.comparisonDraftCommits})),n("tour-compare-apply",()=>ve({commits:t.comparisonDraftCommits,path:t.compare?.path})),n("tour-history-parent",()=>{let T=t.historyEntries.find(K=>K.commit===t.historyCommit)?.parentCommit;if(!T){te("This is the first commit; History already shows its comparison with the empty tree.");return}return ve({commits:[T,t.historyCommit],path:On()})}),n("tour-history-base",()=>ve({commits:[t.authoredTour.range.mergeBaseOid,t.historyCommit],path:On()})),n("tour-history-final",()=>ve(Gt())),n("tour-compare-final",()=>ve(Gt())),n("tour-compare-all",()=>ve({commits:t.compare.commits}));let o=T=>{t.comparisonDraftCommits=T.filter(Boolean),mt(),W({type:"updateHistorySelection",commits:t.comparisonDraftCommits})};for(let T of["history","compare"])n(`tour-${T}-clear`,()=>o([])),n(`tour-${T}-reset`,()=>o(An()));for(let T of["wheel","pointerdown","keydown"])document.addEventListener(T,K=>{!K.isTrusted||K.target?.closest?.("#tour-mode-controls")||K.target?.closest?.(".monaco-editor, .diff-toolbar, #tour-narrative")&&se()},{capture:!0,passive:!0});let c=document.getElementById("web-compare-test"),l=document.getElementById("web-open-diff"),u=document.getElementById("web-open-diff3"),f=document.getElementById("web-diff-input"),g=document.getElementById("web-diff3-input"),w=document.getElementById("tour-narration"),k=document.getElementById("tour-return-focus"),L=document.getElementById("tour-search-input"),F=document.getElementById("tour-search-scope"),G=document.getElementById("tour-listen"),j=document.getElementById("tour-stop"),U=document.getElementById("tour-narration-skip-back"),V=document.getElementById("tour-narration-skip-ahead"),M=document.getElementById("tour-narration-voice"),_=document.getElementById("tour-narration-rate");xo(),Io(),Co(),uo(),document.getElementById("tour-navigator-tabs")?.addEventListener("click",T=>{let K=T.target instanceof Element?T.target.closest("[data-tour-navigator]"):null;K?.dataset.tourNavigator&&kt(K.dataset.tourNavigator)}),c?.addEventListener("click",()=>{Yn()}),l?.addEventListener("click",()=>{f.value="",f.click()}),u?.addEventListener("click",()=>{g.value="",g.click()}),f?.addEventListener("change",async()=>{let T=Array.from(f.files||[]);if(T.length!==2){me("Select exactly 2 files for a diff.");return}await zo(T)}),g?.addEventListener("change",async()=>{let T=Array.from(g.files||[]);if(T.length<1){me("Select one or more files.");return}await qo(T)}),document.getElementById("tour-title")?.addEventListener("click",()=>Ct("tour")),document.getElementById("tour-narrative-content")?.addEventListener("scroll",Bo,{passive:!0}),w?.addEventListener("click",()=>Do()),k?.addEventListener("click",Ao),document.getElementById("tour-directory-root")?.addEventListener("click",()=>{Ct("scene"),document.getElementById("tour-directory-root").focus({preventScroll:!0})}),L?.addEventListener("input",Ee),F?.addEventListener("change",Ee),G?.addEventListener("click",Dn),j?.addEventListener("click",()=>R.stop()),U?.addEventListener("click",()=>R.skipSegment(-1)),V?.addEventListener("click",()=>R.skipSegment(1)),M?.addEventListener("change",()=>{t.narrationVoiceURI=M.value,window.localStorage.setItem(p,t.narrationVoiceURI)}),_&&(_.value=String(t.narrationRate),_.addEventListener("change",()=>{let T=Number(_.value);t.narrationRate=b.has(T)?T:1,_.value=String(t.narrationRate),window.localStorage.setItem(y,String(t.narrationRate))})),document.getElementById("tour-search-results")?.addEventListener("click",T=>{let K=T.target instanceof Element?T.target.closest("[data-tour-search-result]"):null;K&&vo(Number(K.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&&Xt(!1),kt("tour"),document.querySelector(".tour-search-disclosure")?.setAttribute("open",""),L?.focus(),L?.select();return}t.mode!=="tour"||T.metaKey||T.ctrlKey||T.altKey||Po(T.target)||T.target.closest?.("#tour-review")||(T.key==="PageUp"||T.key==="ArrowLeft"?(T.preventDefault(),t.zoom?.mode==="history"?Wt(1)?.catch(te):qn(-1)):T.key==="PageDown"||T.key==="ArrowRight"?(T.preventDefault(),t.zoom?.mode==="history"?Wt(-1)?.catch(te):qn(1)):t.zoom?.mode==="history"&&["ArrowUp","ArrowDown"].includes(T.key)&&(T.preventDefault(),Wn(T.key==="ArrowUp"?-1:1)))},!0),window.addEventListener("bygone:tour-command",T=>{T.detail==="toggleNarration"&&Dn(),T.detail==="pauseNarration"&&R.pauseForExternalOwner()}),window.addEventListener("beforeunload",()=>R.dispose(),{once:!0}),Kt(R.state)}function uo(){let n=document.getElementById("tour-narration-voice"),o=document.getElementById("tour-listen");if(!m){o&&(o.disabled=!0,o.title="Device narration is not supported by this browser."),n&&(n.disabled=!0),Qe("Device narration unavailable");return}let c=()=>{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(p)),n){let l=document.createElement("option");l.value="",l.textContent="System default voice",n.replaceChildren(l,...t.narrationVoices.map(u=>{let f=document.createElement("option");return f.value=u.voiceURI,f.textContent=`${u.name} (${u.lang})${u.default?" \u2014 default":""}`,f})),n.value=t.narrationVoiceURI,n.disabled=t.narrationVoices.length===0}};c(),window.speechSynthesis.addEventListener("voiceschanged",c)}function fo(){let n=Number(window.localStorage.getItem(y));return b.has(n)?n:1}function ho(){let n=null;return{speak(o,c){if(!m){c.onError("Device narration is not supported by this browser.");return}let l=new window.SpeechSynthesisUtterance(o.speechText),u=t.narrationVoices.find(f=>f.voiceURI===t.narrationVoiceURI);u&&(l.voice=u),l.rate=t.narrationRate,l.onend=()=>{n===l&&(n=null),c.onEnd()},l.onerror=f=>{n===l&&(n=null),c.onError(po(f.error))},n=l,window.speechSynthesis.speak(l)},pause(){m&&window.speechSynthesis.pause()},resume(){m&&window.speechSynthesis.resume()},cancel(){n=null,m&&window.speechSynthesis.cancel()}}}function po(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 mo(){if(!m||t.mode!=="tour")return;let n=Mn("playback-start");if(!n)return;let o=n.segments[0];St(!!(o&&["chapter","scene-title","summary","bullet","takeaway"].includes(o.source.field))),t.renderedNarrationUnit=n,Oo(n),R.start(n,!0)}function Dn(){R.state.kind==="playing"||R.state.kind==="paused"?R.togglePause():mo()}function Mn(n){return!t.tour||t.activeSceneIndex<0?null:Or(t.tour,{sceneIndex:t.activeSceneIndex,stepIndex:t.activeStepIndex},{entry:n})}function go(n,o){let c=t.tour;return!!(c&&kn(c.scenes,n.position,o))}function yo(n,o){let c=t.tour;if(!c)return null;let l=kn(c.scenes,n.position,o);return l?oe(l.sceneIndex,l.stepIndex,{narrationNavigation:"controller",narrationEntry:"continuous",showIntro:!1}):null}function wo(){fetch("/narration/claim",{method:"POST",cache:"no-store"}).catch(()=>{})}function Kt(n){let o=document.getElementById("tour-listen"),c=document.getElementById("tour-stop"),l=document.getElementById("tour-narration-skip-back"),u=document.getElementById("tour-narration-skip-ahead");if(o){o.disabled=!m||t.mode!=="tour";let f=n.kind==="playing";o.querySelector(".tour-play-pause-icon")?.setAttribute("d",f?"M7 5h4v14H7zM13 5h4v14h-4z":"m8 5 11 7-11 7Z");let g=f?"Pause narration":n.kind==="paused"?"Resume narration":"Listen from the current tour item";o.title=g,o.setAttribute("aria-label",g),document.getElementById("tour-listen-label").textContent=f?"Pause":n.kind==="paused"?"Resume":"Listen"}if(c&&(c.disabled=n.kind!=="playing"&&n.kind!=="paused"),l&&(l.disabled=!R.canSkipSegment(-1)),u&&(u.disabled=!R.canSkipSegment(1)),n.kind==="playing"||n.kind==="paused"){let f=n.segmentIndex+1,g=n.unit.segments.length;Qe(`${n.kind==="paused"?"Paused":"Speaking"} \xB7 segment ${f} of ${g}`)}else n.kind==="completed"?Qe("Narration complete"):n.kind==="error"?Qe(n.message):m&&Qe("Device voice ready")}function Qe(n){let o=document.getElementById("tour-narration-status");o&&(o.textContent=n)}function bo(n,o){if(document.querySelectorAll(".tour-narration-segment.is-speaking").forEach(w=>{w.classList.remove("is-speaking","is-paused")}),!n)return;let c=[...document.querySelectorAll("[data-narration-segment-id]")].find(w=>w.dataset.narrationSegmentId===n.id);if(!c||(c.classList.add("is-speaking"),c.classList.toggle("is-paused",o),o))return;let l=c.closest("[data-reading-kind]");if(l?.dataset.readingKind==="scene"){let w=["chapter","scene-title","summary","bullet","takeaway"].includes(n.source.field);St(w)}else l?.dataset.readingKind==="step"&&St(!1);let u=document.getElementById("tour-narrative-content");if(!u)return;let f=c.getBoundingClientRect(),g=u.getBoundingClientRect();(f.top<g.top||f.bottom>g.bottom)&&(c.scrollIntoView({block:"nearest"}),$=u.scrollTop)}let et=[];function Ee(){let n=document.getElementById("tour-search-input"),o=document.getElementById("tour-search-scope"),c=document.getElementById("tour-search-status"),l=document.getElementById("tour-search-results");if(!(!t.tour||!n||!o||!c||!l)){if(et=Br(t.tour,n.value,o.value),!n.value.trim()){c.textContent="Cmd/Ctrl+Shift+F",l.replaceChildren();return}c.textContent=`${et.length} result${et.length===1?"":"s"}`,l.replaceChildren(...et.map((u,f)=>{let g=document.createElement("button");g.type="button",g.className="tour-search-result",g.setAttribute("role","option"),g.dataset.tourSearchResult=String(f),g.title=`Open ${u.kind==="code"?`${u.label}:${u.lineNumber}`:u.label}`;let w=document.createElement("span");w.className="tour-search-location",w.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(),g.append(w,k),g}))}}function vo(n){let o=et[n];if(o){if(o.kind==="narrative"){se(),oe(o.sceneIndex,o.stepIndex??0,{showIntro:o.stepIndex===void 0});return}rn(o.fileIndex)&&(St(!1),window.requestAnimationFrame(()=>W({type:"revealSearchResult",sideIndex:o.sideIndex,lineNumber:o.lineNumber,startColumn:o.startColumn,endColumn:o.endColumn})))}}function xo(){let n=document.getElementById("tour-shell"),o=document.getElementById("tour-sidebar-resizer"),c=document.getElementById("tour-sidebar-hide"),l=document.getElementById("tour-sidebar-show");!n||!o||!c||!l||(Bn(),c.addEventListener("click",()=>Xt(!0)),l.addEventListener("click",()=>Xt(!1)),o.addEventListener("pointerdown",u=>{u.preventDefault(),document.body.classList.add("is-resizing-tour-sidebar"),o.setPointerCapture?.(u.pointerId);let f=w=>Fn(w.clientX),g=()=>{document.body.classList.remove("is-resizing-tour-sidebar"),window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",g),window.removeEventListener("pointercancel",g),window.localStorage.setItem(r,String(t.tourSidebarWidth))};window.addEventListener("pointermove",f),window.addEventListener("pointerup",g),window.addEventListener("pointercancel",g)}),o.addEventListener("keydown",u=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(u.key))return;u.preventDefault();let f=t.tourSidebarWidth;u.key==="Home"?f=240:u.key==="End"?f=Vt():f+=u.key==="ArrowLeft"?-16:16,Fn(f),window.localStorage.setItem(r,String(t.tourSidebarWidth))}))}function ko(){let n=Number.parseInt(window.localStorage.getItem(r)||"",10);return Number.isFinite(n)?Math.min(600,Math.max(240,n)):300}function Vt(){return Math.max(240,Math.min(600,Math.floor(window.innerWidth*.6)))}function Fn(n){t.tourSidebarWidth=Math.min(Vt(),Math.max(240,Math.round(n))),Bn(),window.dispatchEvent(new Event("resize"))}function Bn(){document.documentElement.style.setProperty("--tour-rail-width",`${t.tourSidebarWidth}px`);let n=document.getElementById("tour-sidebar-resizer");n?.setAttribute("aria-valuemax",String(Vt())),n?.setAttribute("aria-valuenow",String(t.tourSidebarWidth))}function Xt(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 Io(){let n=document.getElementById("tour-narrative-resizer");n&&(Yt(),n.addEventListener("pointerdown",o=>{if(o.button!==0)return;o.preventDefault(),document.body.classList.add("is-resizing-tour-narrative"),n.setPointerCapture?.(o.pointerId),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-start"));let c=document.getElementById("tour-narrative").getBoundingClientRect().top,l=f=>_n(f.clientY-c),u=()=>{document.body.classList.remove("is-resizing-tour-narrative"),window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",u),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-end")),window.localStorage.setItem(s,String(t.tourNarrativeHeight))};window.addEventListener("pointermove",l),window.addEventListener("pointerup",u),window.addEventListener("pointercancel",u)}),n.addEventListener("keydown",o=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(o.key))return;o.preventDefault();let c=o.key==="Home"?180:o.key==="End"?Jt():t.tourNarrativeHeight+(o.key==="ArrowUp"?-16:16);_n(c),window.localStorage.setItem(s,String(t.tourNarrativeHeight))}),window.addEventListener("resize",Yt))}function So(){let n=Number.parseInt(window.localStorage.getItem(s)||"",10);return Number.isFinite(n)?n:Math.min(window.innerHeight*.38,360)}function Jt(){return Math.max(180,window.innerHeight-180)}function _n(n){t.tourNarrativeHeight=n,Yt()}function Yt(){t.tourNarrativeHeight=Math.min(Jt(),Math.max(180,Math.round(t.tourNarrativeHeight))),document.getElementById("tour-narrative").style.height=`${t.tourNarrativeHeight}px`;let n=document.getElementById("tour-narrative-resizer");n?.setAttribute("aria-valuemax",String(Jt())),n?.setAttribute("aria-valuenow",String(t.tourNarrativeHeight))}function Co(){let n=document.getElementById("tour-narrative");if(!n)return;let o=()=>{let c=n.hidden?0:Math.ceil(n.getBoundingClientRect().height);document.documentElement.style.setProperty("--tour-narrative-height",`${c}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 Un(n){me("Loading change tour\u2026");let o=Zr(n),c={...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,f=document.getElementById("tour-narrative")?.hidden,g=document.getElementById("tour-mode-controls")?.hidden,w=ne,k=X,L=Ce,F=J;try{R.stop();let G=await fetch(n,{cache:"no-store"});if(!G.ok)throw new Error(`Manifest request failed (${G.status}).`);let j=$r(await G.json()),V=C(j).deconstructed?"deconstructed":"historical",M=B(j)?(await be("list",{commit:j.range.headOid},o,j)).entries:[];t.tour=j,t.authoredTour=j,t.historyPrefix=o,t.zoom=new _t(V),t.historyEntries=M,t.zoom&&(t.tour=Ze(V)),t.mode="tour",document.body.classList.add("tour-mode"),_e(),Fe(),Ee();let _=new URLSearchParams(window.location.search),T=xn(t.tour.scenes,_.get("scene"),_.get("step"));if(oe(T.sceneIndex,T.stepIndex,{showIntro:_.get("view")==="overview"||!_.get("step"),readingKey:!_.get("scene")&&!_.get("step")?"title":void 0}),["tour","chapter"].includes(_.get("view"))&&Ct(_.get("view")),t.zoom){let D={explanation:"deconstructed",revisions:"historical",final:we()?"historical":"compare"}[_.get("mode")]||_.get("mode");if(D==="history"&&A().includes("history"))t.historyPath=_.get("file"),t.tourNavigatorTab="commits",t.zoom.enter("history"),t.tour=Ze("history"),_e(),Fe(),await Be(t.historyPath||t.tour.files.find(Y=>Y.kind==="text-diff")?.path,_.get("commit"));else if(D==="compare"&&A().includes("compare")){let Y=_.get("commits")?.split(",").filter(Boolean);await xe("compare",{commits:Y?.length?Y:[_.get("from")||t.authoredTour.range.mergeBaseOid,_.get("to")||t.authoredTour.range.headOid],..._.get("scope")?{path:_.get("scope")}:{}},_.get("file"))}else if(D&&D!==t.zoom.mode&&A().includes(D)){await xe(D);let Y=xn(t.tour.scenes,_.get("scene"),_.get("step"));oe(Y.sceneIndex,Y.stepIndex,{showIntro:_.get("view")==="overview"||!_.get("step"),readingKey:!_.get("scene")&&!_.get("step")?"title":void 0}),["tour","chapter"].includes(_.get("view"))&&Ct(_.get("view"))}let re=z;z=null,O&&re&&re!==t.zoom.mode&&A().includes(re)&&await xe(re)}return t.directoryEvidence&&_.get("file")&&Qt(_.get("file")),Kt(R.state),t.workspacePromptStatus="",he(),me(""),!0}catch(G){Object.assign(t,c),ne=w,X=k,Ce=L,J=F,document.body.className=l;let j=document.getElementById("tour-shell");j&&u!==void 0&&(j.hidden=u);let U=document.getElementById("tour-narrative");U&&f!==void 0&&(U.hidden=f);let V=document.getElementById("tour-mode-controls");return V&&g!==void 0&&(V.hidden=g),t.mode==="tour"&&t.tour&&(_e(),Fe(),Ee(),he()),me(`Could not load change tour: ${G instanceof Error?G.message:String(G)}`),!1}}function _e(){It();let n=t.tour;if(!n)return;let o=document.getElementById("tour-shell"),c=document.getElementById("tour-title"),l=document.getElementById("tour-source"),u=document.getElementById("tour-range"),f=document.getElementById("tour-stats"),g=document.getElementById("tour-authoring-coverage"),w=document.getElementById("tour-scenes"),k=document.getElementById("tour-scene-count"),L=document.getElementById("tour-files"),F=document.getElementById("tour-file-count");if(!o||!c||!l||!u||!f||!g||!w||!k||!L||!F)throw new Error("Presenter UI is incomplete.");o.hidden=!1,c.textContent=n.title,document.title=Hr(n),n.sourceUrl?(l.href=n.sourceUrl,l.hidden=!1):(l.removeAttribute("href"),l.hidden=!0);let G=Ue(n.range.baseRef),j=Ue(n.range.headRef),U=n.range.headOid.slice(0,7);u.textContent=`${G} \u2192 ${j}${j===U?"":` \xB7 ${U}`}`,f.textContent=`${it(n.summary.changedFiles,"file")} \xB7 +${n.summary.additions} \u2212${n.summary.deletions} \xB7 ${it(n.summary.commitCount,"commit")}`,$o(g,n.authoringCoverage),Eo(),k.textContent=String(n.scenes.length),F.textContent=String(n.files.length),w.replaceChildren(),ee()&&dn();let V=new Map(n.scenes.map(M=>[M.id,M]));for(let M of n.chapters){let _=Kn(`chapter:${M.id}`,M.title,"tour-chapter-link",()=>{let K=x.find(D=>D.kind==="chapter"&&D.chapterId===M.id)||x.find(D=>D.kind==="scene"&&M.sceneIds.includes(n.scenes[D.sceneIndex]?.id));K&&st(K)}),T=n.chapters.length>1?_.children:w;n.chapters.length>1&&w.append(_.group);for(let K of M.sceneIds){let D=V.get(K);if(!D)continue;let re=n.scenes.indexOf(D),Y=Kn(`scene:${D.id}`,D.title,"tour-scene",()=>oe(re,0,{userNavigation:!0,showIntro:!0})),Et=Y.link;Et.replaceChildren(),Et.dataset.sceneId=D.id,D.kind==="text-diff"&&(Et.dataset.filePath=D.path),Y.link.title=`Open scene: ${D.kind==="text-diff"?D.path:D.title}`;let ln=document.createElement("span");ln.className="tour-scene-number",ln.textContent=String(re+1).padStart(2,"0");let un=document.createElement("span");un.className="tour-scene-copy";for(let[at,He]of[["tour-scene-title",D.title],["tour-scene-path",D.kind==="text-diff"?D.path:D.kind==="deconstructed-diff"?`${it(D.panels.length-1,"comparison stage")} \xB7 ${it(D.steps.length,"tour slide")}`:ke(D)?it(D.steps.length,"code step"):"Discussion"],["tour-scene-note",D.takeaway]]){let Ie=document.createElement("span");Ie.className=at,Ie.textContent=He,un.append(Ie)}if(Et.append(ln,un),T.append(Y.group),ke(D)){let at=Y.children;at.classList.add("tour-outline-steps"),at.dataset.sceneId=D.id,D.steps.forEach((He,Ie)=>{let Se=document.createElement("button");Se.type="button",Se.className="tour-outline-step",Se.dataset.sceneId=D.id,Se.dataset.stepIndex=String(Ie);let Wo=D.kind==="deconstructed-diff"?`Stage ${(He.stageIndex??He.pairIndex)+1}: `:"";Se.textContent=`${Ie+1}. ${Wo}${He.title}`,Se.title=`Open step ${Ie+1}: ${He.title}`,Se.addEventListener("click",()=>oe(re,Ie,{userNavigation:!0,showIntro:!1})),at.append(Se)})}else Y.toggle.hidden=!0}}L.replaceChildren(...n.files.map((M,_)=>{let T=document.createElement("button");T.type="button",T.className=`tour-file${M.kind==="omitted"?" is-omitted":""}`,T.dataset.filePath=M.path,T.disabled=M.kind==="omitted",T.title=M.kind==="omitted"?`${M.path}: ${M.reason}`:`Open file: ${M.path}`,M.kind==="text-diff"&&T.addEventListener("click",()=>nt(_));let K=document.createElement("span");K.className="tour-file-marker",K.textContent=M.kind==="omitted"?"\xD7":on(M.changeKind);let D=document.createElement("span");D.className="tour-file-copy";let re=document.createElement("span");re.className="tour-file-path",re.textContent=M.path;let Y=document.createElement("span");return Y.className="tour-file-meta",Y.textContent=M.kind==="omitted"?`Not rendered \xB7 ${M.reason}`:`${sn(M.changeKind)} \xB7 +${M.additions} \u2212${M.deletions}`,D.append(re,Y),T.append(K,D),T})),kt(t.tourNavigatorTab)}function bt(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 Eo(){let n=t.authoredTour,o=n?.review,c=document.getElementById("tour-review-toggle"),l=document.getElementById("tour-review-content");if(c.hidden=!o,l.replaceChildren(),!o){document.getElementById("tour-review").hidden=!0,c.setAttribute("aria-expanded","false");return}c.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 f=document.createElement("p");f.className="tour-review-range",f.textContent=`Reviewed snapshot: ${o.baseOid.slice(0,7)} \u2192 ${o.headOid.slice(0,7)}. Evidence opens this range\u2019s final diff.`,f.title=`${o.baseOid} \u2192 ${o.headOid}`,l.append(u,f);let g=n.zoom?.final.scenes||n.scenes;for(let[w,k]of[["concept","Concepts and invariants"],["boundary","Boundaries and prerequisites"],["tradeoff","Complexity tradeoffs"],["question","Open questions"]]){let L=o.items.filter(G=>G.kind===w);if(!L.length)continue;let F=document.createElement("h3");F.textContent=k,l.append(F);for(let G of L){let j=document.createElement("article");j.className="tour-review-item";let U=document.createElement("h4");U.textContent=G.title;let V=document.createElement("p");V.textContent=G.body,j.append(U,V);for(let M of G.evidence){let T=g.find(D=>D.id===M.sceneId).steps.find(D=>D.id===M.stepId),K=document.createElement("button");K.type="button",K.className="tour-review-evidence",K.textContent=`${T.title} \xB7 ${T.focus.path}:${T.focus.startLine} (${T.focus.revision})`,K.title=`Open evidence in the reviewed snapshot: ${T.title}`,K.addEventListener("click",()=>{To(M)}),j.append(K)}if(G.nextCheck){let M=document.createElement("p");M.className="tour-review-next",M.textContent=`Next check: ${G.nextCheck}`,j.append(M)}l.append(j)}}}async function To(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 xe("final");let c=t.tour.scenes.findIndex(f=>f.id===n.sceneId),l=t.tour.scenes[c],u=l?.kind==="walkthrough"?l.steps.findIndex(f=>f.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}X=null,oe(c,u,{userNavigation:!0}),bt(!1)}function $o(n,o){if(n.replaceChildren(),n.hidden=!o,!o)return;let c=[{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 c){let u=document.createElement("div");u.className="tour-coverage-item",u.dataset.metric=l.metric,u.dataset.tooltip=l.description,u.tabIndex=0,u.setAttribute("aria-description",l.description);let f=document.createElement("div");f.className="tour-coverage-heading";let g=document.createElement("span");g.textContent=l.label;let w=document.createElement("strong");w.textContent=`${l.covered}/${l.total} \xB7 ${l.percent}%`,f.append(g,w);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 L=document.createElement("span");L.style.width=`${l.percent}%`,k.append(L),u.append(f,k),n.append(u)}}function oe(n,o=0,c={}){let l=t.tour;if(!l||n<0||n>=l.scenes.length)return null;if(c.userNavigation&&se(),t.zoom?.mode==="history"&&!t.zoomSwitching){let k=l.scenes[n],L=k.path||k.steps?.[o]?.file||t.activeTourFilePath;return Be(L,t.historyCommit).catch(F=>{document.getElementById("tour-mode-status").textContent=F.message}),null}t.directoryEvidence=null,It(),dn();let u=x.find(k=>k.key===c.readingKey)||Ft(x,n,o,c.showIntro?"overview":null);u&&(n=u.sceneIndex,o=u.stepIndex);let f=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=ke(f)?Math.min(Math.max(o,0),Math.max(f.steps.length-1,0)):0,t.tourFocusFilePath=f.kind==="text-diff"?f.path:f.kind==="walkthrough"?f.steps[t.activeStepIndex]?.diff.path??null:ae(f)?f.steps[t.activeStepIndex]?.file??null:null;let g=jn(l,n);Jn();let w=Mn(c.narrationEntry||"playback-start");return t.renderedNarrationUnit=w,Xn(f,g,w),c.fromReadingScroll||Fo(t.readingKey),w&&!c.zoomLanding&&(!t.zoom||ee())&&(c.narrationNavigation==="linear"?R.followLinearNavigation(w):c.narrationNavigation!=="controller"&&R.followDirectNavigation(w)),ce(),t.sceneIntroVisible&&vt()?w:f.kind==="discussion"?(++ne,t.displayedPanels=[],t.activeTourFilePath=null,W({type:"updateCommitHistory",history:Ln()}),document.body.classList.add("tour-discussion"),Te(),w):(document.body.classList.remove("tour-discussion"),f.kind==="walkthrough"?(tn(f),w):ae(f)?(nn(f),w):(tt(f,xt(f.path)),w))}function Zt(n){let o=document.getElementById("status-banner");o.textContent=n,o.hidden=!n}function vt(){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,c=zr(t.tour,o);return t.directoryEvidence=c,t.activeTourFilePath=null,Te(),document.body.classList.remove("tour-discussion"),W({type:"showDirectoryDiff",leftLabel:c.labels[0],rightLabel:c.labels[1],labels:c.labels,entries:c.entries,canMutate:!1}),Zt(c.entries.length?"":"No changed files in this directory for the selected comparison."),ce(),!0}function Qt(n){let o=t.directoryEvidence;if(!o)return!1;let c=o.files.find(l=>l.path===n);if(!c){let l=o.omitted.find(u=>u.path===n);return Zt(l?`${n}: ${l.reason}`:"This file has no change in the overview comparison."),!1}return se(),Zt(""),tt(c,[],`directory-${t.tour.scenes[t.activeSceneIndex].id}-${n}`),ce(),!0}function xt(n){let o=t.tour;return!o||!n?[]:_r(o,n,t.activeSceneIndex,t.activeStepIndex)}function No(n,o){let c=t.tour;return!c||!n?[]:Ur(c,n,t.activeSceneIndex,t.activeStepIndex,(l,u)=>Sn(o?.[l]?.diffModel,u))}function en(n){return`file::${n}`}function tt(n,o=[],c=en(n.path),l=null){if(!t.tour)return;t.activeTourFilePath=t.zoom?.mode==="history"&&t.historyPath||n.path,Te();let f=ie(n.leftContent,n.rightContent),g=Hn(n,n.leftLabel,t.zoom?.mode==="compare"?"from":"base"),w=Hn(n,n.rightLabel,t.zoom?.mode==="compare"?"to":"head"),k=o.find(F=>F.active),L=n.changeKind==="added"?{left:!1,right:!0}:n.changeKind==="deleted"?{left:!0,right:!1}:{left:!0,right:!0};W({type:"showDiff",file1:`1. ${g}`,file2:`2. ${w}`,comparisonId:`tour-${c}`,leftContent:n.leftContent,rightContent:n.rightContent,canReturnToDirectory:!!t.directoryEvidence,sourceInfo:{leftPath:n.previousPath||n.path,rightPath:n.path},fileExists:L,diffModel:f,history:l,fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(1)},editableSides:{left:!1,right:!1},comparisonSummary:n.takeaway?`${n.path} \xB7 ${n.takeaway}`:n.path,initialChangeIndex:k?Gn(f,k.side,k.startLine):n.focusChangeIndex,tourAnnotations:o})}function Hn(n,o,c){if(t.zoom?.mode==="history")return o;let l=o.startsWith(n.path)?o.slice(n.path.length).trim():o.trim();return l?`${c} ${l}`:c}function tn(n){let o=n.steps[t.activeStepIndex];o&&tt(o.diff,xt(o.diff.path),en(o.diff.path))}function nn(n){let o=n.steps[t.activeStepIndex];o&&zn(n,o.file,o)}function zn(n,o,c){let l=rt(n,o);if(!c||!l)return;t.activeTourFilePath=l.path,Te();let u=l.panels.map((U,V)=>({id:`${n.id}-${l.path}-${U.id}`,commit:n.kind==="stacked-diff"?ot(n)[V].oid:void 0,label:U.label,path:U.path||l.path,content:U.content,savedContent:U.content,dirty:!1,editable:!1,stackId:ot(n)[V].id})),f=u.slice(0,-1).map((U,V)=>({leftIndex:V,rightIndex:V+1,diffModel:ie(U.content,u[V+1].content)})),g=No(l.path,f),w=g.find(U=>U.active),k=w?.pairIndex??c.pairIndex,L=w?.side??c.side,F=w?.startLine??c.startLine,G=f[k]?.diffModel,j=G&&F?Gn(G,L,F):0;W({type:"showMultiDiff",panels:u,pairs:f,activePanelId:u[k+(L==="right"?1:0)]?.id,activePairIndex:k,initialChangeIndex:j,revealFirstChangeInEachPanel:n.kind==="deconstructed-diff",history:null,fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(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:g})}function qn(n){if(!ee())return!1;let o=Mr(x,t.readingKey,n);return o?(st(o),!0):!1}function pe(n){let o=t.tour;if(!o||n!==-1&&n!==1)return null;let c=o.scenes[t.activeSceneIndex];if(t.directoryEvidence){let l=t.directoryEvidence.files,u=l.findIndex(w=>w.path===t.activeTourFilePath),f=l[u+n],g=f?o.files.findIndex(w=>w.path===f.path):-1;return g>=0?{fileIndex:g,path:f.path}:null}if(ae(c)){let l=c.steps[t.activeStepIndex]?.pairIndex;if(!Number.isInteger(l))return null;let u=o.files.flatMap(w=>{if(w.kind!=="text-diff")return[];let k=rt(c,w.path);return k?[k]:[]}),f=Lr(u,l,t.activeTourFilePath,n);if(!f)return null;let g=o.files.findIndex(w=>w.kind==="text-diff"&&w.path===f.path);return g>=0?{fileIndex:g,path:f.path}:null}return Rr(o.files,t.activeTourFilePath,n)}function Wn(n){let o=pe(n);return o?nt(o.fileIndex):!1}function rn(n,o=!0){let c=t.tour?.files[n];return!c||c.kind!=="text-diff"?!1:(o&&R.interruptForExploration(),tt(c,xt(c.path),en(c.path)),!0)}function nt(n){let o=t.tour?.files[n];if(!o||o.kind!=="text-diff")return!1;if(se(),t.zoom?.mode==="history")return Be(o.path,t.historyCommit).catch(l=>{document.getElementById("tour-mode-status").textContent=l.message}),!0;if(t.zoom?.mode==="compare")return Rn(o);if(t.directoryEvidence&&ee())return Qt(o.path);t.zoomSwitching||R.interruptForExploration();let c=t.tour?.scenes[t.activeSceneIndex];if(ae(c)){let l=c.steps[t.activeStepIndex];return l&&rt(c,o.path)?(zn(c,o.path,l),!0):!1}return rn(n,!1)}function rt(n,o){let c=n?.files?.find(f=>f.path===o);if(c||n?.kind!=="deconstructed-diff")return c;let l=t.tour?.files.find(f=>f.kind==="text-diff"&&f.path===o);if(!l||l.kind!=="text-diff")return null;let u=l.changeKind!=="deleted";return{path:l.path,panels:ot(n).map(f=>({id:f.id,label:`${f.label} / ${l.path}${u?"":" (absent)"}`,path:u?l.path:void 0,content:u?l.rightContent:"",exists:u}))}}function Ao(){if(t.directoryEvidence)return vt();let n=t.tour?.scenes[t.activeSceneIndex];if(!n||!t.tourFocusFilePath)return!1;if(n.kind==="walkthrough")tn(n);else if(ae(n))nn(n);else if(n.kind==="text-diff")tt(n,xt(n.path));else return!1;return!0}function kt(n){["tour","files","commits"].includes(n)&&(t.tourNavigatorTab=n,document.querySelectorAll("[data-tour-navigator]").forEach(o=>{let c=o.dataset.tourNavigator===n;o.classList.toggle("is-active",c),o.setAttribute("aria-selected",String(c)),o.tabIndex=c?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 It(){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 c=document.getElementById("tour-directory-root");o?c.removeAttribute("aria-current"):c.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 Te(){It();let n=t.tour?.scenes[t.activeSceneIndex],o=ae(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 f=t.tour?.files.find(k=>k.path===u),g=l.querySelector(".tour-file-marker"),w=l.querySelector(".tour-file-meta");if(t.directoryEvidence&&l.disabled&&f?.kind==="text-diff"){let k="Not in this overview comparison";l.setAttribute("title",`${u} \xB7 ${k}`),l.setAttribute("aria-label",`${u}, ${k}`),w&&(w.textContent=k),g&&(g.textContent="\u25CB");return}if(t.directoryEvidence&&f?.kind==="text-diff"){let k=t.directoryEvidence.files.find(F=>F.path===u),L=`${sn(k.changeKind)} in overview`;l.setAttribute("title",`${u} \xB7 ${L}`),l.setAttribute("aria-label",`${u}, ${L}`),w&&(w.textContent=L),g&&(g.textContent=on(k.changeKind));return}if(o&&f?.kind==="text-diff"){let k=rt(n,u);if(k){let L=vn(k,o.pairIndex),F=Lo(L);l.dataset.comparisonState=L,l.classList.add(F.changed?"is-comparison-changed":"is-comparison-empty"),l.setAttribute("title",`${f.path} \xB7 ${F.label}`),l.setAttribute("aria-label",`${f.path}, ${F.label}`),g&&(g.textContent=F.marker),w&&(w.textContent=F.label);return}}if(f){let k=f.kind==="omitted"?`${f.path}: ${f.reason}`:`Open file: ${f.path}`;l.setAttribute("title",k),l.setAttribute("aria-label",k),g&&(g.textContent=f.kind==="omitted"?"\xD7":on(f.changeKind)),w&&(w.textContent=f.kind==="omitted"?`Not rendered \xB7 ${f.reason}`:`${sn(f.changeKind)} \xB7 +${f.additions} \u2212${f.deletions}`)}}),document.querySelector(".tour-file.is-active")?.scrollIntoView({block:"nearest"});let c=document.getElementById("tour-return-focus");if(c){let l=ee();c.hidden=!l||!!t.directoryEvidence||!t.tourFocusFilePath||t.activeTourFilePath===t.tourFocusFilePath}}function Lo(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 ke(n){return n.kind==="walkthrough"||n.kind==="stacked-diff"||n.kind==="deconstructed-diff"}function ae(n){return n?.kind==="stacked-diff"||n?.kind==="deconstructed-diff"}function ot(n){return n.kind==="deconstructed-diff"?n.panels:n.stack}function on(n){return{added:"+",deleted:"\u2212",renamed:"\u2192",modified:"\u2022"}[n]||"\u2022"}function sn(n){return`${n.charAt(0).toUpperCase()}${n.slice(1)}`}function jn(n,o){let c=n.scenes[o],l=n.chapters.findIndex(w=>w.sceneIds.includes(c.id)),u=l>=0?n.chapters[l]:null,f=u?u.sceneIds.indexOf(c.id)+1:o+1,g=u?u.sceneIds.length:n.scenes.length;return{chapter:u,chapterIndex:l,chapterNumber:l>=0?l+1:o+1,sceneInChapter:f,scenesInChapter:g,sceneNumber:o+1,sceneCount:n.scenes.length}}function Ro(n,o,c){return ke(o)?`Scene ${n.sceneNumber} of ${n.sceneCount} \xB7 Step ${c+1} of ${o.steps.length}`:`Scene ${n.sceneNumber} of ${n.sceneCount}`}function Gn(n,o,c){let u=(o==="left"?n.leftLines:n.rightLines).findIndex(F=>F.lineNumber===c);if(u<0)return 0;let f=o==="left"?"leftStart":"rightStart",g=o==="left"?"leftEnd":"rightEnd",w=n.blocks.findIndex(F=>u>=F[f]&&u<F[g]);if(w>=0)return w;let k=0,L=Number.POSITIVE_INFINITY;return n.blocks.forEach((F,G)=>{let j=Math.min(Math.abs(u-F[f]),Math.abs(u-F[g]));j<L&&(k=G,L=j)}),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 Po(n){return n instanceof Element&&!!n.closest('a, button, input, select, summary, textarea, [contenteditable="true"], [role="textbox"], .monaco-editor')}function Oo(n){let o=t.tour?.scenes[t.activeSceneIndex];!t.tour||!o||Xn(o,jn(t.tour,t.activeSceneIndex),n)}function St(n){let o=t.tour?.scenes[t.activeSceneIndex];if(!o)return;t.narrativeParent=null,t.sceneIntroVisible=n;let c=Ft(x,t.activeSceneIndex,t.activeStepIndex,n?"overview":null);c&&(t.readingKey=c.key),Jn(),cn(),t.sceneIntroVisible&&!t.directoryEvidence?vt():!t.sceneIntroVisible&&t.directoryEvidence&&(t.directoryEvidence=null,o.kind==="walkthrough"?tn(o):ae(o)&&nn(o)),ce()}function Ct(n){let o=Ft(x,t.activeSceneIndex,t.activeStepIndex,n==="scene"?"overview":n==="step"?null:n);o&&st(o)}function an(n,o,c){let l=document.createElement("button");return l.type="button",l.textContent=n,l.title=o,l.addEventListener("click",c),l}function Kn(n,o,c,l){let u=document.createElement("div");u.className="tour-outline-group",u.dataset.readingGroup=n;let f=document.createElement("div");f.className="tour-outline-heading";let g=document.createElement("div");g.className="tour-outline-children",g.id=`outline-${encodeURIComponent(n)}`;let w=`${t.zoom?.mode||"tour"}:${n}`,k=an("\u25BE",`Expand or collapse ${o}`,()=>{E.has(w)?E.delete(w):E.add(w),L()});k.className="tour-outline-toggle",k.setAttribute("aria-controls",g.id);let L=()=>{g.hidden=E.has(w),k.setAttribute("aria-expanded",String(!g.hidden)),k.textContent=g.hidden?"\u25B8":"\u25BE"};L();let F=an(o,`Read ${o}`,l);return F.className=c,F.dataset.readingLink=n,f.append(k,F),u.append(f,g),{group:u,children:g,link:F,toggle:k}}function Do(){let n=document.getElementById("tour-audio-settings");n&&(n.hidden=!n.hidden,cn())}function cn(){It();let n=document.getElementById("tour-narration"),o=document.getElementById("tour-audio-settings");if(n){let c=!!(o&&!o.hidden);n.setAttribute("aria-expanded",String(c)),n.textContent=c?"\u203A":"\u2039 Narration",n.title=c?"Hide narration controls":"Show narration controls",n.setAttribute("aria-label",n.title)}}function ce(){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 c=ke(n)?n.steps[t.activeStepIndex]:null;c?o.set("step",c.id):o.delete("step"),t.directoryEvidence&&t.activeTourFilePath?o.set("file",t.activeTourFilePath):o.delete("file"),t.narrativeParent?o.set("view",t.narrativeParent):c&&t.sceneIntroVisible?o.set("view","overview"):o.delete("view"),window.history.replaceState(null,"",`${window.location.pathname}?${o.toString()}`)}function Vn(n=t.tour?.scenes[t.activeSceneIndex],o=t.activeStepIndex){if(!n||!ke(n))return null;let c=n.steps[o];if(!c)return null;if(n.kind==="walkthrough"){let u=c.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=c.startLine;if(!Number.isInteger(l)){let u=rt(n,c.file),f=u?.panels?.[c.pairIndex],g=u?.panels?.[c.pairIndex+1];if(f&&g){let w=ie(f.content,g.content);l=Sn(w,c.side)?.startLine}}return!c.file||!Number.isInteger(l)?null:{filePath:c.file,sideIndex:c.pairIndex+(c.side==="right"?1:0),lineNumber:l,label:`${c.file}:${l}`}}function Mo(){let n=Vn(),o=t.tour?.scenes[t.activeSceneIndex];if(t.sceneIntroVisible||!n||!o)return!1;if(R.interruptForExploration(),t.activeTourFilePath!==n.filePath){let c=t.tour.files.findIndex(u=>u.kind==="text-diff"&&u.path===n.filePath);if(c<0||!(ae(o)?nt(c):rn(c,!1)))return!1}return window.requestAnimationFrame(()=>W({type:"revealSearchResult",sideIndex:n.sideIndex,lineNumber:n.lineNumber,startColumn:1,endColumn:1})),!0}function Xn(n,o,c){dn(),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`:Ro(o,n,t.activeStepIndex);let l=S.get(`scene:${n.id}`),u=ke(n)?n.steps[t.activeStepIndex]:null,f=u&&S.get(`step:${n.id}:${u.id}`);for(let g of[l,f].filter(Boolean))g.querySelectorAll("[data-reading-field]").forEach(w=>{Ho(w,w.dataset.readingText,{field:w.dataset.readingField,...w.dataset.itemIndex!==void 0?{itemIndex:Number(w.dataset.itemIndex)}:{}},c)});cn()}function dn(){if(N===t.tour)return;N=t.tour,x=Dr(t.tour),S.clear();let n=document.getElementById("tour-narrative-content"),o=(l,u,f,g,w,k)=>{let L=document.createElement(u);return L.className=f,L.textContent=g||"",w&&(L.dataset.readingField=w,L.dataset.readingText=g||"",k!==void 0&&(L.dataset.itemIndex=String(k))),l.append(L),L},c=(l,u,f)=>{if(o(l,"p","tour-narrative-summary",u.summary,f?"summary":null),u.bullets.length){let g=document.createElement("ul");g.className="tour-narrative-bullets",u.bullets.forEach((w,k)=>o(g,"li","",w,f?"bullet":null,k)),l.append(g)}u.takeaway&&o(l,"p","tour-narrative-takeaway",u.takeaway,f?"takeaway":null)};for(let l of x){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 f=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(g=>g.id===l.chapterId)?.title);else if(l.kind==="scene"){o(u,"h2","tour-scene-heading",f.title,"scene-title"),c(u,f,!0);let g=o(u,"div","tour-narrative-tags","");f.tags.forEach(w=>o(g,"span","",w))}else{let g=f.steps[l.stepIndex],w=document.createElement("details");w.className="tour-step-context",o(w,"summary","",`Scene context \xB7 ${f.title}`);let k=o(w,"div","tour-step-context-body","");c(k,f,!1),u.append(w);let L=f.kind==="deconstructed-diff"?`Stage ${(g.stageIndex??g.pairIndex)+1} \xB7 `:"";L&&o(u,"div","tour-narrative-chapter",L),o(u,"h3","tour-step-title",g.title,"step-title"),o(u,"p","tour-step-body",g.body,"step-body");let F=o(u,"div","tour-step-requirement","");Uo(F,g.requirement),g.connection&&(o(u,"p","tour-connection",`${g.connection.from.path} \u2192 ${g.connection.to.path}`),o(u,"p","tour-connection",g.connection.label,"connection"));let G=Vn(f,l.stepIndex);if(G){let j=o(u,"div","tour-step-code","");o(j,"span","tour-step-code-location",G.label);let U=an("Show in code",`Show ${G.label}`,()=>{st(l),Mo()});U.className="tour-show-in-code",j.append(U)}}S.set(l.key,u)}n.replaceChildren(...S.values()),$=n.scrollTop}function Jn(){for(let[c,l]of S)l.classList.toggle("is-active",c===t.readingKey);document.querySelectorAll("[data-reading-link], .tour-outline-step, #tour-title").forEach(c=>{let l=t.tour?.scenes[t.activeSceneIndex],u=l&&ke(l)?l.steps[Number(c.dataset.stepIndex)]:null,g=(c.id==="tour-title"?"title":c.dataset.readingLink||(u&&c.dataset.sceneId===l.id?`step:${l.id}:${u.id}`:null))===t.readingKey;c.classList.toggle("is-active",g),g?c.setAttribute("aria-current","location"):c.removeAttribute("aria-current")}),document.querySelectorAll(".tour-outline-group").forEach(c=>{c.classList.toggle("has-active",!!c.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 c=n.getBoundingClientRect(),l=o.getBoundingClientRect();l.top<c.top?n.scrollTop+=l.top-c.top:l.bottom>c.bottom&&(n.scrollTop+=l.bottom-c.bottom)}}function Fo(n){let o=document.getElementById("tour-narrative-content"),c=S.get(n);!o||!c||(o.scrollTop+=c.getBoundingClientRect().top-o.getBoundingClientRect().top,$=o.scrollTop)}function st(n,o=!1){return oe(n.sceneIndex,n.stepIndex,{readingKey:n.key,showIntro:n.kind!=="step",userNavigation:!0,fromReadingScroll:o})}function Bo(){P===null&&(P=window.requestAnimationFrame(()=>{if(P=null,!ee()||t.zoomSwitching)return;let n=document.getElementById("tour-narrative-content");if($!==null&&Math.abs(n.scrollTop-$)<2)return;$=null;let o=n.getBoundingClientRect().top+24,c=x[0];for(let l of x){if(S.get(l.key).getBoundingClientRect().top>o)break;c=l}c&&c.key!==t.readingKey&&st(c,!0)}))}function _o(n){let o=[];return n.source&&o.push(n.source),n.confidence&&o.push(`${n.confidence} confidence`),o.join(" \xB7 ")}function Uo(n,o){if(!o){n.hidden=!0,n.replaceChildren(),n.removeAttribute("title");return}let c=document.createElement("span");c.className="tour-requirement-chip",c.dataset.status=o.status||"unspecified",c.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=[c,l],f=_o(o);if(f){let g=document.createElement("span");g.className="tour-requirement-meta",g.textContent=f,u.push(g)}n.replaceChildren(...u),n.title=[`${o.id}: ${o.text}`,f].filter(Boolean).join(" \u2014 "),n.hidden=!1}function Ho(n,o,c,l,u={}){let f=l?.segments.filter(k=>k.source.field===c.field&&k.source.itemIndex===c.itemIndex)||[];if(f.length===0){n.textContent=`${u.prefix||""}${o}${u.suffix||""}`;return}let g=[];u.prefix&&g.push(document.createTextNode(u.prefix));let w=0;for(let k of f){k.startOffset>w&&g.push(document.createTextNode(o.slice(w,k.startOffset)));let L=document.createElement("span");L.className="tour-narration-segment",L.dataset.narrationSegmentId=k.id,L.textContent=o.slice(k.startOffset,k.endOffset),g.push(L),w=k.endOffset}w<o.length&&g.push(document.createTextNode(o.slice(w))),u.suffix&&g.push(document.createTextNode(u.suffix)),n.replaceChildren(...g)}function Yn(){R.stop();let n=Ir();t.mode="diff",t.comparisonId+=1,t.left={name:n.leftFileName,content:n.leftContent},t.right={name:n.rightFileName,content:n.rightContent},me("Loaded sample diff."),W({type:"showDiff",file1:t.left.name,file2:t.right.name,comparisonId:`web-${t.comparisonId}`,leftContent:t.left.content,rightContent:t.right.content,diffModel:ie(t.left.content,t.right.content),history:null})}async function zo(n){R.stop();let[o,c]=n,[l,u]=await Promise.all([o.text(),c.text()]);t.mode="diff",t.comparisonId+=1,t.left={name:o.name,content:l},t.right={name:c.name,content:u},me(`Loaded ${o.name} and ${c.name}.`),W({type:"showDiff",file1:o.name,file2:c.name,comparisonId:`web-${t.comparisonId}`,leftContent:l,rightContent:u,diffModel:ie(l,u),history:null})}async function qo(n){R.stop();let o=await Promise.all(n.map(async(c,l)=>{let u=await c.text();return{id:`web-panel-${l}`,label:c.name,content:u,savedContent:u,dirty:!1,editable:!0}}));t.mode="multi-diff",me(`Loaded ${o.length}-panel diff for ${o.map(c=>c.label).join(", ")}.`),W({type:"showMultiDiff",panels:o,pairs:o.slice(0,-1).map((c,l)=>({leftIndex:l,rightIndex:l+1,diffModel:ie(c.content,o[l+1].content)}))})}function me(n){let o=document.getElementById("web-status");o&&(o.textContent=n)}})();})();
|
|
564
|
+
`;var Ut=["history","compare","historical","deconstructed"],Tn={history:"History",compare:"Compare",historical:"Historical tour",deconstructed:"Deconstructed tour"},Vr={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."},os=new Set(["exact","none","multiple","uncommitted","reversed","divergent","unavailable"]),is=0;function Zr({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 s=typeof r=="function"?r:()=>{},a=++is,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 g=new Map,w=new Map;for(let E of Ut){let A=i.createElement("button");A.type="button",A.className="workspace-mode-button",A.setAttribute("data-workspace-mode",E),A.textContent=Tn[E];let B=i.createElement("span");B.className="workspace-mode-description visually-hidden";let Q=`bygone-workspace-${a}-${E}-description`;B.id=Q,p.appendChild(B),A.setAttribute("aria-describedby",Q),g.set(E,A),w.set(E,B),f.appendChild(A)}let m=i.createElement("button");m.type="button",m.className="workspace-back-button",m.textContent="Back to comparison",m.title="Return to the comparison that opened this workspace",m.setAttribute("aria-label","Back to comparison"),m.setAttribute("data-workspace-back","true"),c.appendChild(m);let t=i.createElement("div");t.className="workspace-status",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),c.appendChild(t);let b=ss(i,a);c.appendChild(b.dialog),e.appendChild(c);let I=Xr(),N=!1,x=null,S=null,C=!1,$="",P=new Map,O=new Map;for(let[E,A]of g)A.addEventListener("click",()=>{if(N||A.disabled)return;let B=Jr(E,I);if((E==="historical"||E==="deconstructed")&&!B){ye(E,A);return}s({type:"workspaceMode",mode:E})});return m.addEventListener("click",()=>{!N&&!m.disabled&&s({type:"workspaceBack"})}),b.textarea.addEventListener("input",()=>{if(!x)return;let E=Le(x);E.text=b.textarea.value,E.edited=!0}),b.copyButton.addEventListener("click",()=>{if(!x)return;let E=we(x);Ht(E.text)}),b.resetButton.addEventListener("click",()=>{if(!x)return;let E=Le(x,{reset:!0});b.textarea.value=E.text,se(),b.textarea.focus()}),b.saveSkillButton.addEventListener("click",()=>{if(I.nativeSkillFiles){s({type:"workspaceSkillSave"});return}let E=Re(),A=URL.createObjectURL(new Blob([E.text],{type:"text/markdown;charset=utf-8"})),B=i.createElement("a");B.href=A,B.download=E.name||"bygone-tour-skill.md",B.click(),setTimeout(()=>URL.revokeObjectURL(A),1e3),J("Markdown downloaded. Edit your copy, then choose Use my copy. Attach it alongside the prompt when your agent cannot read local files.")}),b.chooseSkillButton.addEventListener("click",()=>{I.nativeSkillFiles?s({type:"workspaceSkillChoose"}):b.skillFile.click()}),b.skillFile.addEventListener("change",async()=>{let E=b.skillFile.files?.[0],A=I.sessionId;if(b.skillFile.value="",!!E)try{if(!E.name.toLowerCase().endsWith(".md")||E.size>1024*1024)throw new Error("Choose a Markdown file smaller than 1 MiB.");let B=await E.text();if(!B.trim())throw new Error("The instructions file is empty.");if(O.set(A,{name:E.name,text:B}),N||I.sessionId!==A)return;se(),J("Custom instructions selected. Attach this Markdown file with the prompt.")}catch(B){!N&&I.sessionId===A&&J(`Could not load instructions: ${B.message}`)}}),b.openExistingButton.addEventListener("click",()=>{if(!x)return;we(x);let E=x;X(),s({type:"workspaceOpenTour",kind:E})}),b.chooseCompareButton.addEventListener("click",()=>{x&&(we(x),X(),s({type:"workspaceMode",mode:"compare"}))}),b.closeButton.addEventListener("click",()=>X()),b.dialog.addEventListener("cancel",E=>{E.preventDefault(),X()}),b.dialog.addEventListener("close",()=>{x=null,$="",C||ne()}),z(),{update:z,destroy:R};function z(E){if(N)return;let A=Xr(E);A.sessionId!==I.sessionId&&Ee()&&X(),zt(A),x&&A.status!==I.status&&($=A.status),I=A,W(),fe(),x&&se()}function R(){N||(N=!0,X(),typeof c.remove=="function"?c.remove():c.parentNode?.removeChild(c),g.clear(),w.clear(),P.clear(),O.clear())}function W(){for(let E of Ut){let A=g.get(E),B=w.get(E),Q=Jr(E,I),Oe=Q&&I.mode===E,Xe=(E==="historical"||E==="deconstructed")&&!Q,Je=E==="history"&&I.history.enabled===!1,he=E==="compare"&&I.compare.enabled===!1,Me=E==="history"?I.history.label:E==="compare"?I.compare.label:I.modeLabels[E]||Tn[E],Ye=Xe?`${Vr[E]} Opens a prompt dialog without changing the current mode.`:Je?I.history.reason||"History is unavailable for this workspace.":he?I.compare.reason||"Compare is unavailable for this workspace.":Oe?`${Me} is the current workspace mode.`:`Switch to ${Me}.`;A.textContent=Me,A.title=Ye,A.setAttribute("aria-label",Me),A.setAttribute("aria-description",Ye),B.textContent=Ye,A.classList.toggle("is-active",Oe),A.classList.toggle("is-missing",Xe),A.classList.toggle("is-unavailable",Je||he),A.disabled=Je||he,Xe?A.removeAttribute("aria-pressed"):A.setAttribute("aria-pressed",String(Oe))}m.hidden=I.canReturn!==!0,m.disabled=I.canReturn!==!0}function fe(){t.textContent=I.status||"",t.hidden=!I.status}function ye(E,A){if(!(N||E!=="historical"&&E!=="deconstructed")){if(x=E,S=A,$=I.status||"",se(),typeof b.dialog.showModal=="function")try{b.dialog.showModal()}catch{b.dialog.setAttribute("open","")}else b.dialog.setAttribute("open","");b.textarea.focus()}}function X(){if(!Ee()){x=null,ne();return}C=!0;try{typeof b.dialog.close=="function"?b.dialog.close():b.dialog.removeAttribute("open"),x=null,$=""}finally{C=!1,ne()}}function ne(){let E=S;if(S=null,!(!E||typeof E.focus!="function")&&E.isConnected!==!1)try{E.focus()}catch{}}function Ee(){return b.dialog.open===!0||b.dialog.hasAttribute("open")}function se(){if(!x)return;let E=Le(x),A=Re();b.title.textContent=`${Tn[x]} prompt`,b.description.textContent=Vr[x],b.context.textContent=`Current context: ${Yr(I.promptContext)}`,E.skillKey!==Pe()?(b.draftNotice.hidden=!1,b.draftNotice.textContent="The selected instructions changed. Your edited prompt was preserved; use Reset prompt to reference the selected file, or update its reference yourself."):E.contextKey!==$n(I.promptContext)?(b.draftNotice.hidden=!1,b.draftNotice.textContent=`This draft is based on earlier workspace context: ${E.contextSummary}. Review the repository, revision boundaries, and selected paths before copying.`):(b.draftNotice.hidden=!0,b.draftNotice.textContent=""),b.textarea.value=E.text,b.skillText.value=A.text,b.skillReference.textContent=A.path?`Instructions: ${A.path}. Local agents can read this path; for browser chats, save and attach a copy.`:`Instructions: ${A.name||"bygone-tour-skill.md"} (attachment). Download and attach it with the prompt; browsers do not expose its full local path.`,b.status.textContent=$,b.status.hidden=!$}function Ht(E){let A=i.defaultView?.navigator?.clipboard||globalThis.navigator?.clipboard;if(!A||typeof A.writeText!="function"){J("Could not copy the prompt: clipboard access is unavailable.");return}Promise.resolve().then(()=>A.writeText(E)).then(()=>J("Prompt copied to the clipboard.")).catch(B=>{let Q=B instanceof Error&&B.message?` ${B.message}`:"";J(`Could not copy the prompt.${Q}`)})}function J(E){$=E,b.status.textContent=E,b.status.hidden=!E}function we(E){let A=Le(E);return A.text=b.textarea.value,A.edited=!0,A}function Le(E,{reset:A=!1}={}){let B=P.get(I.sessionId)||new Map;P.set(I.sessionId,B);let Q=B.get(E);return(A||!Q||!Q.edited&&Q.skillKey!==Pe())&&B.set(E,{text:Kr(E,I.promptContext,Re()),skillKey:Pe(),contextKey:$n(I.promptContext),contextSummary:Yr(I.promptContext),edited:!1}),B.get(E)}function Re(){return I.tourSkill||O.get(I.sessionId)||{name:"bygone-tour-skill.md",text:Cn}}function Pe(){let E=Re();return JSON.stringify([E.path||"",E.name||"",E.text])}function zt(E){let A=P.get(E.sessionId);if(A)for(let B of A.values())B.contextChanged=B.contextKey!==$n(E.promptContext)}}function ss(e,r){let i=e.createElement("dialog");i.className="workspace-prompt-dialog",i.setAttribute("aria-modal","true");let s=e.createElement("h2");s.id=`bygone-workspace-${r}-prompt-title`,i.setAttribute("aria-labelledby",s.id),i.appendChild(s);let a=e.createElement("p");a.className="workspace-prompt-description",a.id=`bygone-workspace-${r}-prompt-description`,i.setAttribute("aria-describedby",a.id),i.appendChild(a);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 g=e.createElement("textarea");g.id=`bygone-workspace-${r}-prompt-textarea`,g.rows=9,g.spellcheck=!1,g.setAttribute("aria-label","Tour authoring prompt draft"),p.textContent="Prompt draft",p.appendChild(g),i.appendChild(p);let w=e.createElement("p");w.className="workspace-prompt-context",i.appendChild(w);let m=e.createElement("details"),t=e.createElement("summary");t.textContent="Read instructions (Markdown)";let b=e.createElement("textarea");b.readOnly=!0,b.rows=12,b.setAttribute("aria-label","Tour skill Markdown instructions"),m.append(t,b),i.appendChild(m);let I=e.createElement("div");I.className="workspace-prompt-actions";let N=Ae(e,"Save an editable copy","workspace-skill-save"),x=Ae(e,"Use my copy","workspace-skill-choose"),S=e.createElement("input");S.type="file",S.accept=".md,text/markdown",S.hidden=!0,I.append(N,x,S),i.appendChild(I);let C=e.createElement("p");C.className="workspace-prompt-status",C.setAttribute("role","status"),C.setAttribute("aria-live","polite"),C.setAttribute("aria-atomic","true"),C.hidden=!0,i.appendChild(C);let $=e.createElement("div");$.className="workspace-prompt-actions";let P=Ae(e,"Copy prompt","workspace-prompt-copy"),O=Ae(e,"Reset prompt","workspace-prompt-reset"),z=Ae(e,"Open existing tour","workspace-prompt-open"),R=Ae(e,"Choose revisions in Compare","workspace-prompt-compare"),W=Ae(e,"Close","workspace-prompt-close");return $.append(P,O,z,R,W),i.appendChild($),{dialog:i,title:s,description:a,context:c,draftNotice:f,textarea:g,skillText:b,skillReference:w,saveSkillButton:N,chooseSkillButton:x,skillFile:S,status:C,copyButton:P,resetButton:O,openExistingButton:z,chooseCompareButton:R,closeButton:W}}function Ae(e,r,i){let s=e.createElement("button");return s.type="button",s.textContent=r,s.title=r,s.setAttribute("data-workspace-prompt-action",i),s}function Xr(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:""},s=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:""},a=Array.isArray(e?.availableTours)?e.availableTours.filter(c=>c==="historical"||c==="deconstructed"):null;return{sessionId:cs(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:s,availableTours:a,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:Cn}:null,promptContext:as(e?.promptContext),canReturn:e?.canReturn===!0,status:ht(e?.status,"")}}function as(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")}:{},...os.has(r.rangeStatus)?{rangeStatus:r.rangeStatus}:{},...typeof r.reason=="string"?{reason:r.reason}:{}}}function Jr(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 $n(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 Yr(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)",s=Array.isArray(e.revisions)&&e.revisions.length>0?e.revisions.join(", "):"(none reported)";return`repository ${r}; paths ${i}; revisions ${s}; range ${e.rangeStatus||"unavailable"}`}function cs(e){return typeof e=="string"||typeof e=="number"?String(e):"default"}function ht(e,r){return typeof e=="string"?e:r}function An(e,r,i=[]){let s=[],a=/\[([^\]\n]+)\]\((https?:\/\/(?:[^\s()]|\([^\s()]*\))+)\)/gu,c=0;for(let f of r.matchAll(a)){if(f.index>0&&r[f.index-1]==="!")continue;let p;try{p=new URL(f[2])}catch{continue}if(p.protocol!=="https:"&&p.protocol!=="http:")continue;s.push(...Nn(e,r,c,f.index,i));let g=e.createElement("a");g.href=p.href,g.target="_blank",g.rel="noopener noreferrer";let w=f.index+1;g.replaceChildren(...Nn(e,r,w,w+f[1].length,i)),s.push(g),c=f.index+f[0].length}return s.push(...Nn(e,r,c,r.length,i)),s}function Nn(e,r,i,s,a){let c=[],f=i;for(let p of a){let g=Math.max(i,p.startOffset),w=Math.min(s,p.endOffset);if(g>=w)continue;g>f&&c.push(e.createTextNode(r.slice(f,g)));let m=e.createElement("span");m.className="tour-narration-segment",m.dataset.narrationSegmentId=p.id,m.textContent=r.slice(g,w),c.push(m),f=w}return f<s&&c.push(e.createTextNode(r.slice(f,s))),c}(function(){let r="bygone.tourSidebarWidth",a="bygone.tourNarrativeHeight",p="bygone.tourNarrationVoice",g="bygone.tourNarrationRate",w=new Set([.75,1,1.25,1.5]),m="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:So(),tourSidebarHidden:!1,tourNarrativeHeight:Co(),tourNavigatorTab:"tour",narrationVoiceURI:window.localStorage.getItem(p)||"",narrationRate:po(),narrationVoices:[],renderedNarrationUnit:null,workspacePromptStatus:"",historyPrefix:"/history/"},b=null,I=null,N=null,x=[],S=new Map,C=new Set,$=null,P=null,O=new URLSearchParams(window.location.search).get("workspaceEmbedded")==="1",z=null,R=new Bt(mo(),{claimAudio:vo,onStateChange:Kt,onSegmentChange:xo,canNavigateUnit:wo,navigateUnit:bo});window.__BYGONE_HOST__={environment:"web",editorWorkerUrl:"/media/editor.worker.js",diffWorkerUrl:"/media/diff.worker.js",postMessage(n){uo(n)}},window.addEventListener("message",n=>{if(!O||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"||(z=o.mode,!(!t.zoom||t.zoom.mode===o.mode||!A().includes(o.mode))&&xe(o.mode).catch(te))}),window.addEventListener("DOMContentLoaded",()=>{if(fo(),O){let n=document.getElementById("tour-mode-tabs"),o=document.getElementById("tour-mode-description");n&&(n.hidden=!0),o&&(o.hidden=!0)}me("Browser host ready.")});function W(n){(n.type==="showDiff"||n.type==="showMultiDiff"||n.type==="showDirectoryDiff")&&(n={...n,renderRequestId:++ne},t.mode==="tour"&&(t.displayedPanels=n.type==="showMultiDiff"?n.panels:io(),n.history||(n.history=Pn()),he()),X&&(Ee=n.renderRequestId)),window.dispatchEvent(new window.CustomEvent("bygone:host-message",{detail:n}))}let fe=0,ye=new Map,X=null,ne=0,Ee=null;function se(){t.zoomSwitching||(X=null)}function Ht(){return new Promise(n=>{let o=++fe,d=u=>{ye.delete(o);let h=t.tour?.scenes[t.activeSceneIndex],y=u?.activeMultiPairIndex,v=h&&ae(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:v[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);ye.set(o,u=>{window.clearTimeout(l),d(u)}),W({type:"captureNavigationState",requestId:o})})}let J=0;function we(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 Le={history:"History",compare:"Compare",historical:"Historical tour",deconstructed:"Deconstructed tour"},Re={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 Pe(n){return n==="historical"&&we()?"Final tour":Le[n]}function zt(n){return n==="historical"&&we()?"The authored walkthrough of the completed endpoint diff.":Re[n]}function E(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=we(n);return{...d?{historical:d}:{},deconstructed:{scenes:n.scenes,chapters:n.chapters}}}function A(){return[...B()?["history","compare"]:[],...Object.keys(E()).filter(n=>E()[n])]}function B(n=t.authoredTour){return Number(n?.version)>=2}function Q(){return"History is unavailable for legacy v1 tours; open a version 2 tour to browse commit history."}function Oe(){return"Compare is unavailable for legacy v1 tours because this tour has no history backend."}function Xe(){if(b)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),I=document.createElement("div"),I.id="workspace-mode-controls",n.prepend(I),b=Zr({container:I,send:Je})}function Je(n){if(!(!n||typeof n!="object")){if(n.type==="workspaceMode"&&["history","compare","historical","deconstructed"].includes(n.mode)){xe(n.mode).catch(te);return}n.type==="workspaceOpenTour"&&(n.kind==="historical"||n.kind==="deconstructed")&&oo()}}function he(){if(!t.zoom||(Xe(),!b))return;I.hidden=O;let n=document.getElementById("tour-mode-tabs"),o=document.getElementById("tour-mode-description");n&&(n.dataset.workspaceModeLabel=Pe(t.zoom.mode)),o&&(o.textContent=zt(t.zoom.mode));let d=B();b.update({sessionId:Me(),mode:t.zoom.mode,modeLabels:{historical:Pe("historical")},history:{enabled:d,label:"History",...d?{}:{reason:Q()}},compare:{enabled:d,label:"Compare",...d?{}:{reason:Oe()}},availableTours:Object.keys(E()).filter(l=>l==="historical"||l==="deconstructed"),promptContext:Ye(),status:t.workspacePromptStatus})}function Me(){let n=t.authoredTour;return[n?.repository?.root||"",n?.range?.mergeBaseOid||"",n?.range?.headOid||""].join("\0")||"browser-workspace"}function Ye(){let n=t.authoredTour,o=n?.range,d=Array.isArray(t.displayedPanels)?t.displayedPanels:[],l=pt(d.map(k=>k?.commit)),u=d.length>0?l:pt([o?.mergeBaseOid,o?.headOid]),h=pt(d.map(k=>k?.path)),y=h.length>0?h:pt(t.tour?.files?.map(k=>k?.path)),v=Qr(u,n);return{...typeof n?.repository?.root=="string"?{repository:n.repository.root}:{},...y.length>0?{paths:y}:{},...u.length>0?{revisions:u}:{},rangeStatus:v.status,...v.reason?{reason:v.reason}:{}}}function Qr(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 pt(n){return[...new Set(n.filter(o=>typeof o=="string"&&o.trim()).map(o=>o.trim()))]}function De(n){t.workspacePromptStatus=n,he()}function eo(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 to(){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 no(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:"",v=typeof n.range?.headOid=="string"?n.range.headOid:"";return!!(d&&h&&d!==h||l&&y&&l!==y||u&&v&&u!==v)}function ro(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(`
|
|
565
|
+
`)}async function oo(){try{let n=await to();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(no(u)&&!window.confirm(ro(u))){De("Kept the current tour.");return}if(!await zn(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 Ze(n){let o=t.authoredTour;return E()[n]?{...o,...E()[n]}:{...o,scenes:[],chapters:[],files:n==="compare"&&t.compare?t.compare.files:o.files}}function Fe(){let n=document.getElementById("tour-mode-controls");if(n.hidden=!t.zoom||O,!t.zoom)return;he();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=B();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;mt()}function mt(){let n=t.comparisonDraftCommits.length,o=document.getElementById("tour-history-compare");o.textContent=`Compare selected (${n})`,o.disabled=n<2||!B();let d=document.getElementById("tour-compare-apply");d.textContent=`Update comparison (${n})`,d.disabled=n<2||!B(),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=!B()||!t.historyCommit}function qt(){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 Ln(n){return jr(n,qt())}async function be(n,o,d=t.historyPrefix,l=t.authoredTour){if(!B(l))throw new Error(Q());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 te(n){let o=n instanceof Error?n.message:String(n),d=document.getElementById("tour-mode-status");d&&(d.textContent=o),b&&De(o)}function Rn(){return t.displayedPanels.map(n=>n.commit).filter(Boolean)}function io(){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&&ae(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 Pn(){let n=t.displayedPanels.map(o=>o.commit);return{...yt(jt({commits:Rn()},null),n,null),navigatorOnly:!0}}async function so(n){if(!n||!t.zoom||!B())return[];if(!t.fileHistoryCache.has(n)){let o=be("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 ao(n,o){try{let d=await so(n);if(o!==ne)return;W({type:"updateCommitMarkers",changedCommits:d.map(l=>l.commit),path:n})}catch(d){o===ne&&te(d)}}async function Be(n,o,d=!0){let l=++J,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(U=>U.commit===o);if(t.historyPath===n&&t.historyCommit===o&&t.historyPanels.length){wt();return}let y=await be("diff",{path:n,commit:o,head:t.authoredTour.range.headOid});if(l!==J||t.zoom.mode!=="history")return;if(d&&t.historyPanels.length&&t.historyCommit===o){let U=await Promise.all(t.historyPanels.map(async V=>{let D=V.commit?await be("diff",{path:n,commit:V.commit,head:t.authoredTour.range.headOid}):{rightContent:"",path:n};return{...V,content:D.rightContent,path:D.path}}));if(l!==J||t.zoom.mode!=="history")return;t.historyPanels=U,t.historyPath=n,t.historyDiff=y,wt(),ce();return}let v=u.findIndex(U=>U.commit===o),L=(v>=0?u[v+1]:null)?.commit||y.parentCommit,F=L&&L!==y.parentCommit?(await be("diff",{path:n,commit:L,head:t.authoredTour.range.headOid})).rightContent:y.leftContent;if(l!==J||t.zoom.mode!=="history")return;t.historyPath=n,t.historyCommit=o;let G=Math.max(2,t.historyPanels.length);t.historyDiff=y;let j=(U,V,D)=>({id:`history-${U||"empty"}`,commit:U,content:V,label:D,path:y.path,editable:!1});for(t.historyPanels=[j(L,F,L?.slice(0,7)||"Empty tree"),j(o,y.rightContent,h?`${h.shortCommit} ${h.summary}`:o.slice(0,7))],t.historyFocus=`history-${o}`;t.historyPanels.length<G;){let U=gt(t.historyPanels[0],"left");if(!U)break;let V=await be("diff",{path:n,commit:U.commit,head:t.authoredTour.range.headOid});if(l!==J||t.zoom.mode!=="history")return;t.historyPanels.unshift(j(U.commit,V.rightContent,`${U.shortCommit} ${U.summary}`))}wt(),document.getElementById("tour-mode-status").textContent="",mt(),ce()}function co(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,commit:h.commit,summary:h.summary,timestamp:h.timestamp,author:h.author,authorEmail:h.authorEmail,message:h.message,parents:h.parents,active:y===l,selected:t.comparisonDraftCommits.includes(h.commit),kind:"history-entry",index:y}))}}}}function gt(n,o){let d=qt(),l=d.indexOf(n.commit);if(l<0)return null;let u=new Set(t.historyPanels.map(v=>v.commit)),y=(o==="left"?d.slice(0,l).reverse():d.slice(l+1)).find(v=>!u.has(v)&&t.historyEntries.some(k=>k.commit===v));return t.historyEntries.find(v=>v.commit===y)}function yt(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 wt(){let n=t.historyPanels.map(d=>({...d,addLeftEnabled:!!gt(d,"left"),addRightEnabled:!!gt(d,"right"),removeEnabled:t.historyPanels.length>2})),o=n.find(d=>d.id===t.historyFocus)?.commit;t.activeTourFilePath=t.historyPath,Te(),W({type:"showMultiDiff",panels:n,pairs:n.slice(0,-1).map((d,l)=>({leftIndex:l,rightIndex:l+1,diffModel:ie(d.content,n[l+1].content)})),activePanelId:t.historyFocus,mutationEnabled:!0,fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(1)},history:yt(co(t.historyEntries,t.historyCommit,t.historyDiff),n.map(d=>d.commit),o)})}async function lo(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;++J,t.historyPanels=t.historyPanels.filter(d=>d!==o),t.historyFocus===o.id&&(t.historyFocus=t.historyPanels.at(-1).id)}else{let d=gt(o,n.side);if(!d)return;let l=++J,u=await be("diff",{path:t.historyPath,commit:d.commit,head:t.authoredTour.range.headOid});if(l!==J||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=qt();t.historyPanels.sort((v,k)=>y.indexOf(v.commit)-y.indexOf(k.commit)),t.historyFocus=h.id}wt()}}function Wt(n){let o=t.historyEntries.findIndex(l=>l.commit===t.historyCommit),d=t.historyEntries[o+n];if(d)return Be(t.historyPath,d.commit,!1)}function jt(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,commit:d.commit,summary:d.summary,timestamp:d.timestamp,author:d.author,authorEmail:d.authorEmail,message:d.message,parents:d.parents,active:d.commit===o,selected:t.comparisonDraftCommits.includes(d.commit),panelNumber:n.commits.indexOf(d.commit)+1||null,kind:"history-entry",index:l}))}}}}function On(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:ie(u.content,d[h+1].content)}));return t.activeTourFilePath=n.path,Te(),W({type:"showMultiDiff",panels:d,pairs:l,activePanelId:o?`compare-${o}`:null,history:yt(jt(t.compare,o),t.compare.commits,o),fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(1)},mutationEnabled:!1}),ce(),!0}async function Mn(n,o,d=null){n=Ln(n);let l=++J,u=await be("compare-many",n);if(l!==J||t.zoom.mode!=="compare")return;let h=u.files;t.comparisonCommits=n.commits,t.compare={...n,files:h},t.tour=Ze("compare"),t.activeSceneIndex=-1,t.tourFocusFilePath=null,_e(),Fe(),Ce();let y=h.find(v=>v.kind==="text-diff"&&v.path===o)||h.find(v=>v.kind==="text-diff");if(y)On(y,d);else{t.activeTourFilePath=null;let v=n.commits.map(k=>({id:`compare-${k}`,commit:k,path:"No text changes",content:"",label:k.slice(0,7),editable:!1}));W({type:"showMultiDiff",panels:v,pairs:v.slice(0,-1).map((k,L)=>({leftIndex:L,rightIndex:L+1,diffModel:ie("","")})),mutationEnabled:!1,history:yt(jt(n,null),n.commits,null)}),t.activeTourFilePath=null,X=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.",ce()}async function ve(n){if(!B()){De(Oe());return}t.zoomSwitching||(t.zoom.mode!=="compare"?await xe("compare",n):await Mn(n,t.activeTourFilePath),kt("commits"))}function Gt(){return{commits:[t.authoredTour.range.mergeBaseOid,t.authoredTour.range.headOid]}}function Dn(){return t.historyEntries.find(n=>n.commit===t.historyCommit)?.path||t.historyPath}async function xe(n,o,d){if(!t.zoom||t.zoomSwitching||n===t.zoom.mode||!A().includes(n))return;t.zoomSwitching=!0,++J;let l=t.zoom.mode,u;try{u=await Ht(),t.zoom.depart(u),R.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=Ze(n),_e(),Ce(),Fe(),document.getElementById("tour-mode-status").textContent="",X=h.restore&&!o?h.location:null,n==="history")await Be(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 Mn(o||t.compare||Gt(),d||h.location.path||u.path);else if(oe(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(v=>v.path===h.location.path);y>=0&&nt(y)}ce()}catch(h){X=null,t.zoom.enter(l),t.tour=Ze(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),_e(),Fe(),Ce(),u&&ee()&&(X=u,oe(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))),Te(),ce(),te(h)}finally{t.zoomSwitching=!1}}async function uo(n){if(!(!n||typeof n!="object")){if(n.type==="navigationState"){ye.get(n.requestId)?.(n.navigation);return}if(n.type==="renderComplete"&&t.mode==="tour"&&n.renderRequestId===ne&&ao(t.activeTourFilePath,ne),n.type==="renderComplete"&&X&&n.renderRequestId===Ee){let o=X;X=null,W({type:"restoreNavigationState",navigation:o.navigation});let d=document.getElementById("tour-narrative-content");d&&(d.scrollTop=o.narrativeScroll||0,$=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?zn(d):o.get("demo")==="1"&&Qn();return}if(t.mode==="tour"&&t.directoryEvidence&&ee()){if(n.type==="openDirectoryEntry"){Qt(n.relativePath);return}if(n.type==="returnToDirectory"){vt();return}}if(t.mode==="tour"){if(t.zoom?.mode==="history"&&["multiAddPanel","multiRemovePanel"].includes(n.type)){lo(n).catch(te);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=Wt(n.type==="historyBack"?1:-1);o&&o.catch(te);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?Ln({commits:l}).commits:l,mt();return}if(n.type==="compareHistoryEntry"&&Number.isInteger(n.index)){let o=t.historyEntries[n.index];o?.parentCommit&&ve({commits:[o.parentCommit,o.commit],path:t.activeTourFilePath}).catch(te);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,W({type:"focusHistoryPanel",panelId:d.id})):Be(t.historyPath,o.commit,!1).catch(te)}if(o&&t.zoom?.mode!=="history"){let d=t.displayedPanels.find(l=>l.commit===o.commit);d?W({type:"focusHistoryPanel",panelId:d.id}):(t.historyCommit=o.commit,t.historyPath=t.activeTourFilePath||t.historyPath,xe("history").catch(te))}return}}if(n.type==="navigateFile"&&t.mode==="tour"){Gn(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)&&oe(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,W({type:"showDiff",file1:t.left.name,file2:t.right.name,comparisonId:`web-${t.comparisonId}`,leftContent:t.left.content,rightContent:t.right.content,diffModel:ie(t.left.content,t.right.content),history:null}))}}function fo(){document.getElementById("tour-review-toggle")?.addEventListener("click",()=>{bt(document.getElementById("tour-review").hidden)}),document.getElementById("tour-review-close")?.addEventListener("click",()=>bt(!1)),document.getElementById("tour-review")?.addEventListener("keydown",T=>{T.key==="Escape"&&(T.preventDefault(),bt(!1))});let n=(T,K)=>document.getElementById(T)?.addEventListener("click",()=>{Promise.resolve().then(K).catch(te)});n("tour-history-compare",()=>ve({commits:t.comparisonDraftCommits})),n("tour-compare-apply",()=>ve({commits:t.comparisonDraftCommits,path:t.compare?.path})),n("tour-history-parent",()=>{let T=t.historyEntries.find(K=>K.commit===t.historyCommit)?.parentCommit;if(!T){te("This is the first commit; History already shows its comparison with the empty tree.");return}return ve({commits:[T,t.historyCommit],path:Dn()})}),n("tour-history-base",()=>ve({commits:[t.authoredTour.range.mergeBaseOid,t.historyCommit],path:Dn()})),n("tour-history-final",()=>ve(Gt())),n("tour-compare-final",()=>ve(Gt())),n("tour-compare-all",()=>ve({commits:t.compare.commits}));let o=T=>{t.comparisonDraftCommits=T.filter(Boolean),mt(),W({type:"updateHistorySelection",commits:t.comparisonDraftCommits})};for(let T of["history","compare"])n(`tour-${T}-clear`,()=>o([])),n(`tour-${T}-reset`,()=>o(Rn()));for(let T of["wheel","pointerdown","keydown"])document.addEventListener(T,K=>{!K.isTrusted||K.target?.closest?.("#tour-mode-controls")||K.target?.closest?.(".monaco-editor, .diff-toolbar, #tour-narrative")&&se()},{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"),v=document.getElementById("tour-narration"),k=document.getElementById("tour-return-focus"),L=document.getElementById("tour-search-input"),F=document.getElementById("tour-search-scope"),G=document.getElementById("tour-listen"),j=document.getElementById("tour-stop"),U=document.getElementById("tour-narration-skip-back"),V=document.getElementById("tour-narration-skip-ahead"),D=document.getElementById("tour-narration-voice"),_=document.getElementById("tour-narration-rate");Io(),Eo(),To(),ho(),document.getElementById("tour-navigator-tabs")?.addEventListener("click",T=>{let K=T.target instanceof Element?T.target.closest("[data-tour-navigator]"):null;K?.dataset.tourNavigator&&kt(K.dataset.tourNavigator)}),d?.addEventListener("click",()=>{Qn()}),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){me("Select exactly 2 files for a diff.");return}await Wo(T)}),y?.addEventListener("change",async()=>{let T=Array.from(y.files||[]);if(T.length<1){me("Select one or more files.");return}await jo(T)}),document.getElementById("tour-title")?.addEventListener("click",()=>Et("tour")),document.getElementById("tour-narrative-content")?.addEventListener("scroll",Uo,{passive:!0}),v?.addEventListener("click",()=>Fo()),k?.addEventListener("click",Ro),document.getElementById("tour-directory-root")?.addEventListener("click",()=>{Et("scene"),document.getElementById("tour-directory-root").focus({preventScroll:!0})}),L?.addEventListener("input",Ce),F?.addEventListener("change",Ce),G?.addEventListener("click",Fn),j?.addEventListener("click",()=>R.stop()),U?.addEventListener("click",()=>R.skipSegment(-1)),V?.addEventListener("click",()=>R.skipSegment(1)),D?.addEventListener("change",()=>{t.narrationVoiceURI=D.value,window.localStorage.setItem(p,t.narrationVoiceURI)}),_&&(_.value=String(t.narrationRate),_.addEventListener("change",()=>{let T=Number(_.value);t.narrationRate=w.has(T)?T:1,_.value=String(t.narrationRate),window.localStorage.setItem(g,String(t.narrationRate))})),document.getElementById("tour-search-results")?.addEventListener("click",T=>{let K=T.target instanceof Element?T.target.closest("[data-tour-search-result]"):null;K&&ko(Number(K.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&&Xt(!1),kt("tour"),document.querySelector(".tour-search-disclosure")?.setAttribute("open",""),L?.focus(),L?.select();return}t.mode!=="tour"||T.metaKey||T.ctrlKey||T.altKey||Mo(T.target)||T.target.closest?.("#tour-review")||(T.key==="PageUp"||T.key==="ArrowLeft"?(T.preventDefault(),t.zoom?.mode==="history"?Wt(1)?.catch(te):jn(-1)):T.key==="PageDown"||T.key==="ArrowRight"?(T.preventDefault(),t.zoom?.mode==="history"?Wt(-1)?.catch(te):jn(1)):t.zoom?.mode==="history"&&["ArrowUp","ArrowDown"].includes(T.key)&&(T.preventDefault(),Gn(T.key==="ArrowUp"?-1:1)))},!0),window.addEventListener("bygone:tour-command",T=>{T.detail==="toggleNarration"&&Fn(),T.detail==="pauseNarration"&&R.pauseForExternalOwner()}),window.addEventListener("beforeunload",()=>R.dispose(),{once:!0}),Kt(R.state)}function ho(){let n=document.getElementById("tour-narration-voice"),o=document.getElementById("tour-listen");if(!m){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(p)),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 po(){let n=Number(window.localStorage.getItem(g));return w.has(n)?n:1}function mo(){let n=null;return{speak(o,d){if(!m){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(go(h.error))},n=l,window.speechSynthesis.speak(l)},pause(){m&&window.speechSynthesis.pause()},resume(){m&&window.speechSynthesis.resume()},cancel(){n=null,m&&window.speechSynthesis.cancel()}}}function go(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 yo(){if(!m||t.mode!=="tour")return;let n=Bn("playback-start");if(!n)return;let o=n.segments[0];St(!!(o&&["chapter","scene-title","summary","bullet","takeaway"].includes(o.source.field))),t.renderedNarrationUnit=n,Do(n),R.start(n,!0)}function Fn(){R.state.kind==="playing"||R.state.kind==="paused"?R.togglePause():yo()}function Bn(n){return!t.tour||t.activeSceneIndex<0?null:Dr(t.tour,{sceneIndex:t.activeSceneIndex,stepIndex:t.activeStepIndex},{entry:n})}function wo(n,o){let d=t.tour;return!!(d&&kn(d.scenes,n.position,o))}function bo(n,o){let d=t.tour;if(!d)return null;let l=kn(d.scenes,n.position,o);return l?oe(l.sceneIndex,l.stepIndex,{narrationNavigation:"controller",narrationEntry:"continuous",showIntro:!1}):null}function vo(){fetch("/narration/claim",{method:"POST",cache:"no-store"}).catch(()=>{})}function Kt(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=!m||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=!R.canSkipSegment(-1)),u&&(u.disabled=!R.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):m&&Qe("Device voice ready")}function Qe(n){let o=document.getElementById("tour-narration-status");o&&(o.textContent=n)}function xo(n,o){if(document.querySelectorAll(".tour-narration-segment.is-speaking").forEach(k=>{k.classList.remove("is-speaking","is-paused")}),!n)return;let d=[...document.querySelectorAll("[data-narration-segment-id]")].filter(k=>k.dataset.narrationSegmentId===n.id),l=d[0];if(!l||(d.forEach(k=>{k.classList.add("is-speaking"),k.classList.toggle("is-paused",o)}),o))return;let u=l.closest("[data-reading-kind]");if(u?.dataset.readingKind==="scene"){let k=["chapter","scene-title","summary","bullet","takeaway"].includes(n.source.field);St(k)}else u?.dataset.readingKind==="step"&&St(!1);let h=document.getElementById("tour-narrative-content");if(!h)return;let y=l.getBoundingClientRect(),v=h.getBoundingClientRect();(y.top<v.top||y.bottom>v.bottom)&&(l.scrollIntoView({block:"nearest"}),$=h.scrollTop)}let et=[];function Ce(){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=Ur(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 v=document.createElement("span");v.className="tour-search-location",v.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(v,k),y}))}}function ko(n){let o=et[n];if(o){if(o.kind==="narrative"){se(),oe(o.sceneIndex,o.stepIndex??0,{showIntro:o.stepIndex===void 0});return}rn(o.fileIndex)&&(St(!1),window.requestAnimationFrame(()=>W({type:"revealSearchResult",sideIndex:o.sideIndex,lineNumber:o.lineNumber,startColumn:o.startColumn,endColumn:o.endColumn})))}}function Io(){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||(Un(),d.addEventListener("click",()=>Xt(!0)),l.addEventListener("click",()=>Xt(!1)),o.addEventListener("pointerdown",u=>{u.preventDefault(),document.body.classList.add("is-resizing-tour-sidebar"),o.setPointerCapture?.(u.pointerId);let h=v=>_n(v.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=Vt():h+=u.key==="ArrowLeft"?-16:16,_n(h),window.localStorage.setItem(r,String(t.tourSidebarWidth))}))}function So(){let n=Number.parseInt(window.localStorage.getItem(r)||"",10);return Number.isFinite(n)?Math.min(600,Math.max(240,n)):300}function Vt(){return Math.max(240,Math.min(600,Math.floor(window.innerWidth*.6)))}function _n(n){t.tourSidebarWidth=Math.min(Vt(),Math.max(240,Math.round(n))),Un(),window.dispatchEvent(new Event("resize"))}function Un(){document.documentElement.style.setProperty("--tour-rail-width",`${t.tourSidebarWidth}px`);let n=document.getElementById("tour-sidebar-resizer");n?.setAttribute("aria-valuemax",String(Vt())),n?.setAttribute("aria-valuenow",String(t.tourSidebarWidth))}function Xt(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 Eo(){let n=document.getElementById("tour-narrative-resizer");n&&(Yt(),n.addEventListener("pointerdown",o=>{if(o.button!==0)return;o.preventDefault(),document.body.classList.add("is-resizing-tour-narrative"),n.setPointerCapture?.(o.pointerId),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-start"));let d=document.getElementById("tour-narrative").getBoundingClientRect().top,l=h=>Hn(h.clientY-d),u=()=>{document.body.classList.remove("is-resizing-tour-narrative"),window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",u),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-end")),window.localStorage.setItem(a,String(t.tourNarrativeHeight))};window.addEventListener("pointermove",l),window.addEventListener("pointerup",u),window.addEventListener("pointercancel",u)}),n.addEventListener("keydown",o=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(o.key))return;o.preventDefault();let d=o.key==="Home"?180:o.key==="End"?Jt():t.tourNarrativeHeight+(o.key==="ArrowUp"?-16:16);Hn(d),window.localStorage.setItem(a,String(t.tourNarrativeHeight))}),window.addEventListener("resize",Yt))}function Co(){let n=Number.parseInt(window.localStorage.getItem(a)||"",10);return Number.isFinite(n)?n:Math.min(window.innerHeight*.38,360)}function Jt(){return Math.max(180,window.innerHeight-180)}function Hn(n){t.tourNarrativeHeight=n,Yt()}function Yt(){t.tourNarrativeHeight=Math.min(Jt(),Math.max(180,Math.round(t.tourNarrativeHeight))),document.getElementById("tour-narrative").style.height=`${t.tourNarrativeHeight}px`;let n=document.getElementById("tour-narrative-resizer");n?.setAttribute("aria-valuemax",String(Jt())),n?.setAttribute("aria-valuenow",String(t.tourNarrativeHeight))}function To(){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 zn(n){me("Loading change tour\u2026");let o=eo(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,v=ne,k=X,L=Ee,F=J;try{R.stop();let G=await fetch(n,{cache:"no-store"});if(!G.ok)throw new Error(`Manifest request failed (${G.status}).`);let j=Ar(await G.json()),V=E(j).deconstructed?"deconstructed":"historical",D=B(j)?(await be("list",{commit:j.range.headOid},o,j)).entries:[];t.tour=j,t.authoredTour=j,t.historyPrefix=o,t.zoom=new _t(V),t.historyEntries=D,t.zoom&&(t.tour=Ze(V)),t.mode="tour",document.body.classList.add("tour-mode"),_e(),Fe(),Ce();let _=new URLSearchParams(window.location.search),T=xn(t.tour.scenes,_.get("scene"),_.get("step"));if(oe(T.sceneIndex,T.stepIndex,{showIntro:_.get("view")==="overview"||!_.get("step"),readingKey:!_.get("scene")&&!_.get("step")?"title":void 0}),["tour","chapter"].includes(_.get("view"))&&Et(_.get("view")),t.zoom){let M={explanation:"deconstructed",revisions:"historical",final:we()?"historical":"compare"}[_.get("mode")]||_.get("mode");if(M==="history"&&A().includes("history"))t.historyPath=_.get("file"),t.tourNavigatorTab="commits",t.zoom.enter("history"),t.tour=Ze("history"),_e(),Fe(),await Be(t.historyPath||t.tour.files.find(Y=>Y.kind==="text-diff")?.path,_.get("commit"));else if(M==="compare"&&A().includes("compare")){let Y=_.get("commits")?.split(",").filter(Boolean);await xe("compare",{commits:Y?.length?Y:[_.get("from")||t.authoredTour.range.mergeBaseOid,_.get("to")||t.authoredTour.range.headOid],..._.get("scope")?{path:_.get("scope")}:{}},_.get("file"))}else if(M&&M!==t.zoom.mode&&A().includes(M)){await xe(M);let Y=xn(t.tour.scenes,_.get("scene"),_.get("step"));oe(Y.sceneIndex,Y.stepIndex,{showIntro:_.get("view")==="overview"||!_.get("step"),readingKey:!_.get("scene")&&!_.get("step")?"title":void 0}),["tour","chapter"].includes(_.get("view"))&&Et(_.get("view"))}let re=z;z=null,O&&re&&re!==t.zoom.mode&&A().includes(re)&&await xe(re)}return t.directoryEvidence&&_.get("file")&&Qt(_.get("file")),Kt(R.state),t.workspacePromptStatus="",he(),me(""),!0}catch(G){Object.assign(t,d),ne=v,X=k,Ee=L,J=F,document.body.className=l;let j=document.getElementById("tour-shell");j&&u!==void 0&&(j.hidden=u);let U=document.getElementById("tour-narrative");U&&h!==void 0&&(U.hidden=h);let V=document.getElementById("tour-mode-controls");return V&&y!==void 0&&(V.hidden=y),t.mode==="tour"&&t.tour&&(_e(),Fe(),Ce(),he()),me(`Could not load change tour: ${G instanceof Error?G.message:String(G)}`),!1}}function _e(){It();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"),v=document.getElementById("tour-scenes"),k=document.getElementById("tour-scene-count"),L=document.getElementById("tour-files"),F=document.getElementById("tour-file-count");if(!o||!d||!l||!u||!h||!y||!v||!k||!L||!F)throw new Error("Presenter UI is incomplete.");o.hidden=!1,d.textContent=n.title,document.title=qr(n),n.sourceUrl?(l.href=n.sourceUrl,l.hidden=!1):(l.removeAttribute("href"),l.hidden=!0);let G=Ue(n.range.baseRef),j=Ue(n.range.headRef),U=n.range.headOid.slice(0,7);u.textContent=`${G} \u2192 ${j}${j===U?"":` \xB7 ${U}`}`,h.textContent=`${it(n.summary.changedFiles,"file")} \xB7 +${n.summary.additions} \u2212${n.summary.deletions} \xB7 ${it(n.summary.commitCount,"commit")}`,Ao(y,n.authoringCoverage),$o(),k.textContent=String(n.scenes.length),F.textContent=String(n.files.length),v.replaceChildren(),ee()&&dn();let V=new Map(n.scenes.map(D=>[D.id,D]));for(let D of n.chapters){let _=Xn(`chapter:${D.id}`,D.title,"tour-chapter-link",()=>{let K=x.find(M=>M.kind==="chapter"&&M.chapterId===D.id)||x.find(M=>M.kind==="scene"&&D.sceneIds.includes(n.scenes[M.sceneIndex]?.id));K&&st(K)}),T=n.chapters.length>1?_.children:v;n.chapters.length>1&&v.append(_.group);for(let K of D.sceneIds){let M=V.get(K);if(!M)continue;let re=n.scenes.indexOf(M),Y=Xn(`scene:${M.id}`,M.title,"tour-scene",()=>oe(re,0,{userNavigation:!0,showIntro:!0})),Ct=Y.link;Ct.replaceChildren(),Ct.dataset.sceneId=M.id,M.kind==="text-diff"&&(Ct.dataset.filePath=M.path),Y.link.title=`Open scene: ${M.kind==="text-diff"?M.path:M.title}`;let ln=document.createElement("span");ln.className="tour-scene-number",ln.textContent=String(re+1).padStart(2,"0");let un=document.createElement("span");un.className="tour-scene-copy";for(let[at,He]of[["tour-scene-title",M.title],["tour-scene-path",M.kind==="text-diff"?M.path:M.kind==="deconstructed-diff"?`${it(M.panels.length-1,"comparison stage")} \xB7 ${it(M.steps.length,"tour slide")}`:ke(M)?it(M.steps.length,"code step"):"Discussion"],["tour-scene-note",M.takeaway]]){let Ie=document.createElement("span");Ie.className=at,Ie.textContent=He,un.append(Ie)}if(Ct.append(ln,un),T.append(Y.group),ke(M)){let at=Y.children;at.classList.add("tour-outline-steps"),at.dataset.sceneId=M.id,M.steps.forEach((He,Ie)=>{let Se=document.createElement("button");Se.type="button",Se.className="tour-outline-step",Se.dataset.sceneId=M.id,Se.dataset.stepIndex=String(Ie);let Go=M.kind==="deconstructed-diff"?`Stage ${(He.stageIndex??He.pairIndex)+1}: `:"";Se.textContent=`${Ie+1}. ${Go}${He.title}`,Se.title=`Open step ${Ie+1}: ${He.title}`,Se.addEventListener("click",()=>oe(re,Ie,{userNavigation:!0,showIntro:!1})),at.append(Se)})}else Y.toggle.hidden=!0}}L.replaceChildren(...n.files.map((D,_)=>{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(_));let K=document.createElement("span");K.className="tour-file-marker",K.textContent=D.kind==="omitted"?"\xD7":on(D.changeKind);let M=document.createElement("span");M.className="tour-file-copy";let re=document.createElement("span");re.className="tour-file-path",re.textContent=D.path;let Y=document.createElement("span");return Y.className="tour-file-meta",Y.textContent=D.kind==="omitted"?`Not rendered \xB7 ${D.reason}`:`${sn(D.changeKind)} \xB7 +${D.additions} \u2212${D.deletions}`,M.append(re,Y),T.append(K,M),T})),kt(t.tourNavigatorTab)}function bt(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 $o(){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[v,k]of[["concept","Concepts and invariants"],["boundary","Boundaries and prerequisites"],["tradeoff","Complexity tradeoffs"],["question","Open questions"]]){let L=o.items.filter(G=>G.kind===v);if(!L.length)continue;let F=document.createElement("h3");F.textContent=k,l.append(F);for(let G of L){let j=document.createElement("article");j.className="tour-review-item";let U=document.createElement("h4");U.textContent=G.title;let V=document.createElement("p");V.textContent=G.body,j.append(U,V);for(let D of G.evidence){let T=y.find(M=>M.id===D.sceneId).steps.find(M=>M.id===D.stepId),K=document.createElement("button");K.type="button",K.className="tour-review-evidence",K.textContent=`${T.title} \xB7 ${T.focus.path}:${T.focus.startLine} (${T.focus.revision})`,K.title=`Open evidence in the reviewed snapshot: ${T.title}`,K.addEventListener("click",()=>{No(D)}),j.append(K)}if(G.nextCheck){let D=document.createElement("p");D.className="tour-review-next",D.textContent=`Next check: ${G.nextCheck}`,j.append(D)}l.append(j)}}}async function No(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 xe("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}X=null,oe(d,u,{userNavigation:!0}),bt(!1)}function Ao(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.dataset.tooltip=l.description,u.tabIndex=0,u.setAttribute("aria-description",l.description);let h=document.createElement("div");h.className="tour-coverage-heading";let y=document.createElement("span");y.textContent=l.label;let v=document.createElement("strong");v.textContent=`${l.covered}/${l.total} \xB7 ${l.percent}%`,h.append(y,v);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 L=document.createElement("span");L.style.width=`${l.percent}%`,k.append(L),u.append(h,k),n.append(u)}}function oe(n,o=0,d={}){let l=t.tour;if(!l||n<0||n>=l.scenes.length)return null;if(d.userNavigation&&se(),t.zoom?.mode==="history"&&!t.zoomSwitching){let k=l.scenes[n],L=k.path||k.steps?.[o]?.file||t.activeTourFilePath;return Be(L,t.historyCommit).catch(F=>{document.getElementById("tour-mode-status").textContent=F.message}),null}t.directoryEvidence=null,It(),dn();let u=x.find(k=>k.key===d.readingKey)||Ft(x,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=ke(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:ae(h)?h.steps[t.activeStepIndex]?.file??null:null;let y=Kn(l,n);Zn();let v=Bn(d.narrationEntry||"playback-start");return t.renderedNarrationUnit=v,Yn(h,y,v),d.fromReadingScroll||_o(t.readingKey),v&&!d.zoomLanding&&(!t.zoom||ee())&&(d.narrationNavigation==="linear"?R.followLinearNavigation(v):d.narrationNavigation!=="controller"&&R.followDirectNavigation(v)),ce(),t.sceneIntroVisible&&vt()?v:h.kind==="discussion"?(++ne,t.displayedPanels=[],t.activeTourFilePath=null,W({type:"updateCommitHistory",history:Pn()}),document.body.classList.add("tour-discussion"),Te(),v):(document.body.classList.remove("tour-discussion"),h.kind==="walkthrough"?(tn(h),v):ae(h)?(nn(h),v):(tt(h,xt(h.path)),v))}function Zt(n){let o=document.getElementById("status-banner");o.textContent=n,o.hidden=!n}function vt(){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=Wr(t.tour,o);return t.directoryEvidence=d,t.activeTourFilePath=null,Te(),document.body.classList.remove("tour-discussion"),W({type:"showDirectoryDiff",leftLabel:d.labels[0],rightLabel:d.labels[1],labels:d.labels,entries:d.entries,canMutate:!1}),Zt(d.entries.length?"":"No changed files in this directory for the selected comparison."),ce(),!0}function Qt(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 Zt(l?`${n}: ${l.reason}`:"This file has no change in the overview comparison."),!1}return se(),Zt(""),tt(d,[],`directory-${t.tour.scenes[t.activeSceneIndex].id}-${n}`),ce(),!0}function xt(n){let o=t.tour;return!o||!n?[]:Hr(o,n,t.activeSceneIndex,t.activeStepIndex)}function Lo(n,o){let d=t.tour;return!d||!n?[]:zr(d,n,t.activeSceneIndex,t.activeStepIndex,(l,u)=>Sn(o?.[l]?.diffModel,u))}function en(n){return`file::${n}`}function tt(n,o=[],d=en(n.path),l=null){if(!t.tour)return;t.activeTourFilePath=t.zoom?.mode==="history"&&t.historyPath||n.path,Te();let h=ie(n.leftContent,n.rightContent),y=qn(n,n.leftLabel,t.zoom?.mode==="compare"?"from":"base"),v=qn(n,n.rightLabel,t.zoom?.mode==="compare"?"to":"head"),k=o.find(F=>F.active),L=n.changeKind==="added"?{left:!1,right:!0}:n.changeKind==="deleted"?{left:!0,right:!1}:{left:!0,right:!0};W({type:"showDiff",file1:`1. ${y}`,file2:`2. ${v}`,comparisonId:`tour-${d}`,leftContent:n.leftContent,rightContent:n.rightContent,canReturnToDirectory:!!t.directoryEvidence,sourceInfo:{leftPath:n.previousPath||n.path,rightPath:n.path},fileExists:L,diffModel:h,history:l,fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(1)},editableSides:{left:!1,right:!1},comparisonSummary:n.takeaway?`${n.path} \xB7 ${n.takeaway}`:n.path,initialChangeIndex:k?Vn(h,k.side,k.startLine):n.focusChangeIndex,tourAnnotations:o})}function qn(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 tn(n){let o=n.steps[t.activeStepIndex];o&&tt(o.diff,xt(o.diff.path),en(o.diff.path))}function nn(n){let o=n.steps[t.activeStepIndex];o&&Wn(n,o.file,o)}function Wn(n,o,d){let l=rt(n,o);if(!d||!l)return;t.activeTourFilePath=l.path,Te();let u=l.panels.map((U,V)=>({id:`${n.id}-${l.path}-${U.id}`,commit:n.kind==="stacked-diff"?ot(n)[V].oid:void 0,label:U.label,path:U.path||l.path,content:U.content,savedContent:U.content,dirty:!1,editable:!1,stackId:ot(n)[V].id})),h=u.slice(0,-1).map((U,V)=>({leftIndex:V,rightIndex:V+1,diffModel:ie(U.content,u[V+1].content)})),y=Lo(l.path,h),v=y.find(U=>U.active),k=v?.pairIndex??d.pairIndex,L=v?.side??d.side,F=v?.startLine??d.startLine,G=h[k]?.diffModel,j=G&&F?Vn(G,L,F):0;W({type:"showMultiDiff",panels:u,pairs:h,activePanelId:u[k+(L==="right"?1:0)]?.id,activePairIndex:k,initialChangeIndex:j,revealFirstChangeInEachPanel:n.kind==="deconstructed-diff",history:null,fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(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 jn(n){if(!ee())return!1;let o=Br(x,t.readingKey,n);return o?(st(o),!0):!1}function pe(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(v=>v.path===t.activeTourFilePath),h=l[u+n],y=h?o.files.findIndex(v=>v.path===h.path):-1;return y>=0?{fileIndex:y,path:h.path}:null}if(ae(d)){let l=d.steps[t.activeStepIndex]?.pairIndex;if(!Number.isInteger(l))return null;let u=o.files.flatMap(v=>{if(v.kind!=="text-diff")return[];let k=rt(d,v.path);return k?[k]:[]}),h=Pr(u,l,t.activeTourFilePath,n);if(!h)return null;let y=o.files.findIndex(v=>v.kind==="text-diff"&&v.path===h.path);return y>=0?{fileIndex:y,path:h.path}:null}return Or(o.files,t.activeTourFilePath,n)}function Gn(n){let o=pe(n);return o?nt(o.fileIndex):!1}function rn(n,o=!0){let d=t.tour?.files[n];return!d||d.kind!=="text-diff"?!1:(o&&R.interruptForExploration(),tt(d,xt(d.path),en(d.path)),!0)}function nt(n){let o=t.tour?.files[n];if(!o||o.kind!=="text-diff")return!1;if(se(),t.zoom?.mode==="history")return Be(o.path,t.historyCommit).catch(l=>{document.getElementById("tour-mode-status").textContent=l.message}),!0;if(t.zoom?.mode==="compare")return On(o);if(t.directoryEvidence&&ee())return Qt(o.path);t.zoomSwitching||R.interruptForExploration();let d=t.tour?.scenes[t.activeSceneIndex];if(ae(d)){let l=d.steps[t.activeStepIndex];return l&&rt(d,o.path)?(Wn(d,o.path,l),!0):!1}return rn(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 Ro(){if(t.directoryEvidence)return vt();let n=t.tour?.scenes[t.activeSceneIndex];if(!n||!t.tourFocusFilePath)return!1;if(n.kind==="walkthrough")tn(n);else if(ae(n))nn(n);else if(n.kind==="text-diff")tt(n,xt(n.path));else return!1;return!0}function kt(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 It(){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 Te(){It();let n=t.tour?.scenes[t.activeSceneIndex],o=ae(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"),v=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}`),v&&(v.textContent=k),y&&(y.textContent="\u25CB");return}if(t.directoryEvidence&&h?.kind==="text-diff"){let k=t.directoryEvidence.files.find(F=>F.path===u),L=`${sn(k.changeKind)} in overview`;l.setAttribute("title",`${u} \xB7 ${L}`),l.setAttribute("aria-label",`${u}, ${L}`),v&&(v.textContent=L),y&&(y.textContent=on(k.changeKind));return}if(o&&h?.kind==="text-diff"){let k=rt(n,u);if(k){let L=vn(k,o.pairIndex),F=Po(L);l.dataset.comparisonState=L,l.classList.add(F.changed?"is-comparison-changed":"is-comparison-empty"),l.setAttribute("title",`${h.path} \xB7 ${F.label}`),l.setAttribute("aria-label",`${h.path}, ${F.label}`),y&&(y.textContent=F.marker),v&&(v.textContent=F.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":on(h.changeKind)),v&&(v.textContent=h.kind==="omitted"?`Not rendered \xB7 ${h.reason}`:`${sn(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 Po(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 ke(n){return n.kind==="walkthrough"||n.kind==="stacked-diff"||n.kind==="deconstructed-diff"}function ae(n){return n?.kind==="stacked-diff"||n?.kind==="deconstructed-diff"}function ot(n){return n.kind==="deconstructed-diff"?n.panels:n.stack}function on(n){return{added:"+",deleted:"\u2212",renamed:"\u2192",modified:"\u2022"}[n]||"\u2022"}function sn(n){return`${n.charAt(0).toUpperCase()}${n.slice(1)}`}function Kn(n,o){let d=n.scenes[o],l=n.chapters.findIndex(v=>v.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 Oo(n,o,d){return ke(o)?`Scene ${n.sceneNumber} of ${n.sceneCount} \xB7 Step ${d+1} of ${o.steps.length}`:`Scene ${n.sceneNumber} of ${n.sceneCount}`}function Vn(n,o,d){let u=(o==="left"?n.leftLines:n.rightLines).findIndex(F=>F.lineNumber===d);if(u<0)return 0;let h=o==="left"?"leftStart":"rightStart",y=o==="left"?"leftEnd":"rightEnd",v=n.blocks.findIndex(F=>u>=F[h]&&u<F[y]);if(v>=0)return v;let k=0,L=Number.POSITIVE_INFINITY;return n.blocks.forEach((F,G)=>{let j=Math.min(Math.abs(u-F[h]),Math.abs(u-F[y]));j<L&&(k=G,L=j)}),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 Mo(n){return n instanceof Element&&!!n.closest('a, button, input, select, summary, textarea, [contenteditable="true"], [role="textbox"], .monaco-editor')}function Do(n){let o=t.tour?.scenes[t.activeSceneIndex];!t.tour||!o||Yn(o,Kn(t.tour,t.activeSceneIndex),n)}function St(n){let o=t.tour?.scenes[t.activeSceneIndex];if(!o)return;t.narrativeParent=null,t.sceneIntroVisible=n;let d=Ft(x,t.activeSceneIndex,t.activeStepIndex,n?"overview":null);d&&(t.readingKey=d.key),Zn(),cn(),t.sceneIntroVisible&&!t.directoryEvidence?vt():!t.sceneIntroVisible&&t.directoryEvidence&&(t.directoryEvidence=null,o.kind==="walkthrough"?tn(o):ae(o)&&nn(o)),ce()}function Et(n){let o=Ft(x,t.activeSceneIndex,t.activeStepIndex,n==="scene"?"overview":n==="step"?null:n);o&&st(o)}function an(n,o,d){let l=document.createElement("button");return l.type="button",l.textContent=n,l.title=o,l.addEventListener("click",d),l}function Xn(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 v=`${t.zoom?.mode||"tour"}:${n}`,k=an("\u25BE",`Expand or collapse ${o}`,()=>{C.has(v)?C.delete(v):C.add(v),L()});k.className="tour-outline-toggle",k.setAttribute("aria-controls",y.id);let L=()=>{y.hidden=C.has(v),k.setAttribute("aria-expanded",String(!y.hidden)),k.textContent=y.hidden?"\u25B8":"\u25BE"};L();let F=an(o,`Read ${o}`,l);return F.className=d,F.dataset.readingLink=n,h.append(k,F),u.append(h,y),{group:u,children:y,link:F,toggle:k}}function Fo(){let n=document.getElementById("tour-audio-settings");n&&(n.hidden=!n.hidden,cn())}function cn(){It();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 ce(){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=ke(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 Jn(n=t.tour?.scenes[t.activeSceneIndex],o=t.activeStepIndex){if(!n||!ke(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 v=ie(h.content,y.content);l=Sn(v,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 Bo(){let n=Jn(),o=t.tour?.scenes[t.activeSceneIndex];if(t.sceneIntroVisible||!n||!o)return!1;if(R.interruptForExploration(),t.activeTourFilePath!==n.filePath){let d=t.tour.files.findIndex(u=>u.kind==="text-diff"&&u.path===n.filePath);if(d<0||!(ae(o)?nt(d):rn(d,!1)))return!1}return window.requestAnimationFrame(()=>W({type:"revealSearchResult",sideIndex:n.sideIndex,lineNumber:n.lineNumber,startColumn:1,endColumn:1})),!0}function Yn(n,o,d){dn(),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`:Oo(o,n,t.activeStepIndex);let l=S.get(`scene:${n.id}`),u=ke(n)?n.steps[t.activeStepIndex]:null,h=u&&S.get(`step:${n.id}:${u.id}`);for(let y of[l,h].filter(Boolean))y.querySelectorAll("[data-reading-field]").forEach(v=>{qo(v,v.dataset.readingText,{field:v.dataset.readingField,...v.dataset.itemIndex!==void 0?{itemIndex:Number(v.dataset.itemIndex)}:{}},d)});cn()}function dn(){if(N===t.tour)return;N=t.tour,x=Fr(t.tour),S.clear();let n=document.getElementById("tour-narrative-content"),o=(l,u,h,y,v,k)=>{let L=document.createElement(u);return L.className=h,L.replaceChildren(...An(document,y||"")),v&&(L.dataset.readingField=v,L.dataset.readingText=y||"",k!==void 0&&(L.dataset.itemIndex=String(k))),l.append(L),L},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((v,k)=>o(y,"li","",v,h?"bullet":null,k)),l.append(y)}u.takeaway&&o(l,"p","tour-narrative-takeaway",u.takeaway,h?"takeaway":null)};for(let l of x){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(v=>o(y,"span","",v))}else{let y=h.steps[l.stepIndex],v=document.createElement("details");v.className="tour-step-context",o(v,"summary","",`Scene context \xB7 ${h.title}`);let k=o(v,"div","tour-step-context-body","");d(k,h,!1),u.append(v);let L=h.kind==="deconstructed-diff"?`Stage ${(y.stageIndex??y.pairIndex)+1} \xB7 `:"";L&&o(u,"div","tour-narrative-chapter",L),o(u,"h3","tour-step-title",y.title,"step-title"),o(u,"p","tour-step-body",y.body,"step-body");let F=o(u,"div","tour-step-requirement","");zo(F,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 G=Jn(h,l.stepIndex);if(G){let j=o(u,"div","tour-step-code","");o(j,"span","tour-step-code-location",G.label);let U=an("Show in code",`Show ${G.label}`,()=>{st(l),Bo()});U.className="tour-show-in-code",j.append(U)}}S.set(l.key,u)}n.replaceChildren(...S.values()),$=n.scrollTop}function Zn(){for(let[d,l]of S)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&&ke(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 _o(n){let o=document.getElementById("tour-narrative-content"),d=S.get(n);!o||!d||(o.scrollTop+=d.getBoundingClientRect().top-o.getBoundingClientRect().top,$=o.scrollTop)}function st(n,o=!1){return oe(n.sceneIndex,n.stepIndex,{readingKey:n.key,showIntro:n.kind!=="step",userNavigation:!0,fromReadingScroll:o})}function Uo(){P===null&&(P=window.requestAnimationFrame(()=>{if(P=null,!ee()||t.zoomSwitching)return;let n=document.getElementById("tour-narrative-content");if($!==null&&Math.abs(n.scrollTop-$)<2)return;$=null;let o=n.getBoundingClientRect().top+24,d=x[0];for(let l of x){if(S.get(l.key).getBoundingClientRect().top>o)break;d=l}d&&d.key!==t.readingKey&&st(d,!0)}))}function Ho(n){let o=[];return n.source&&o.push(n.source),n.confidence&&o.push(`${n.confidence} confidence`),o.join(" \xB7 ")}function zo(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=Ho(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 qo(n,o,d,l,u={}){let h=l?.segments.filter(v=>v.source.field===d.field&&v.source.itemIndex===d.itemIndex)||[],y=[];u.prefix&&y.push(document.createTextNode(u.prefix)),y.push(...An(document,o,h)),u.suffix&&y.push(document.createTextNode(u.suffix)),n.replaceChildren(...y)}function Qn(){R.stop();let n=Er();t.mode="diff",t.comparisonId+=1,t.left={name:n.leftFileName,content:n.leftContent},t.right={name:n.rightFileName,content:n.rightContent},me("Loaded sample diff."),W({type:"showDiff",file1:t.left.name,file2:t.right.name,comparisonId:`web-${t.comparisonId}`,leftContent:t.left.content,rightContent:t.right.content,diffModel:ie(t.left.content,t.right.content),history:null})}async function Wo(n){R.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},me(`Loaded ${o.name} and ${d.name}.`),W({type:"showDiff",file1:o.name,file2:d.name,comparisonId:`web-${t.comparisonId}`,leftContent:l,rightContent:u,diffModel:ie(l,u),history:null})}async function jo(n){R.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",me(`Loaded ${o.length}-panel diff for ${o.map(d=>d.label).join(", ")}.`),W({type:"showMultiDiff",panels:o,pairs:o.slice(0,-1).map((d,l)=>({leftIndex:l,rightIndex:l+1,diffModel:ie(d.content,o[l+1].content)}))})}function me(n){let o=document.getElementById("web-status");o&&(o.textContent=n)}})();})();
|
|
566
566
|
//# sourceMappingURL=web-host.js.map
|