@davmash/bygone 0.9.7 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -1
- package/README.md +74 -1
- package/cli/commandSpec.js +2 -0
- package/cli/completions.js +3 -3
- package/cli/present.js +28 -10
- package/cli/tour.js +22 -1
- package/cli/tourExport.js +147 -0
- package/cli/tourFile.js +109 -4
- package/cli/tourHistory.js +31 -1
- package/completions/_bygone +1 -1
- package/completions/bygone +1 -1
- package/completions/bygone.fish +1 -1
- package/docs/change-tour-format.md +86 -67
- package/docs/explore.md +14 -3
- package/docs/generating-change-tours.md +84 -46
- package/docs/present.md +103 -14
- package/docs/product-surface.md +19 -8
- package/docs/sharing-tours.md +95 -0
- package/docs/visual-walkthrough/README.md +89 -0
- package/docs/visual-walkthrough/build-tour.mjs +54 -0
- package/docs/visual-walkthrough/capture-desktop.cjs +42 -0
- package/docs/visual-walkthrough/capture-desktop.mjs +21 -0
- package/docs/visual-walkthrough/captures.md +49 -0
- package/docs/visual-walkthrough/create-demo.mjs +57 -0
- package/docs/visual-walkthrough/deconstructed-demo.bygone +100 -0
- package/docs/visual-walkthrough/images/01-two-files.png +0 -0
- package/docs/visual-walkthrough/images/02-many-panels.png +0 -0
- package/docs/visual-walkthrough/images/03-directories.png +0 -0
- package/docs/visual-walkthrough/images/04-search.png +0 -0
- package/docs/visual-walkthrough/images/05-repository-history.png +0 -0
- package/docs/visual-walkthrough/images/06-file-history.png +0 -0
- package/docs/visual-walkthrough/images/07-branch-review.png +0 -0
- package/docs/visual-walkthrough/images/08-tour-reader.png +0 -0
- package/docs/visual-walkthrough/images/09-focused-step.png +0 -0
- package/docs/visual-walkthrough/images/10-deconstructed.png +0 -0
- package/docs/visual-walkthrough/images/11-exploration.png +0 -0
- package/docs/visual-walkthrough/images/12-authoring.png +0 -0
- package/docs/visual-walkthrough/images/13-export.png +0 -0
- package/docs/visual-walkthrough/images/14-vscode.png +0 -0
- package/docs/visual-walkthrough/images/15-cli.png +0 -0
- package/docs/visual-walkthrough/narrative.md +134 -0
- package/docs/visual-walkthrough/outline.md +52 -0
- package/docs/visual-walkthrough/walkthrough.bygone +340 -0
- package/docs/walkthrough.md +6 -101
- package/examples/bygone-history.bygone +11 -44
- package/examples/marker-focus.bygone +116 -0
- package/examples/navigation-lab.bygone.yaml +401 -336
- package/examples/tour-orientation.bygone +349 -0
- package/media/diff.worker.js +13 -3
- package/media/webview.css +1 -1
- package/media/webview.js +394 -319
- package/out/changeTour.js +865 -397
- package/out/deepLink.js +167 -0
- package/out/historyDirectory.js +66 -0
- package/out/standalone-main.js +20515 -16822
- package/out/tourCoverage.js +850 -386
- package/out/tourDocument.js +97 -0
- package/package.json +1 -1
- package/schemas/change-tour-source.schema.json +91 -64
- package/skills/pr-tour-guide/SKILL.md +144 -128
- package/skills/pr-tour-guide/references/expectations-and-feedback.md +57 -0
- package/standalone/index.html +10 -25
- package/web/export-bootstrap.js +62 -0
- package/web/export-licenses.txt +78 -0
- package/web/export-runtime.json +12 -0
- package/web/index.html +54 -47
- package/web/presenter.css +337 -176
- package/web/web-host.js +239 -137
package/web/web-host.js
CHANGED
|
@@ -1,7 +1,17 @@
|
|
|
1
|
-
"use strict";(()=>{function ge(){}ge.prototype={diff:function(r,i){var a,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},d=s.callback;typeof s=="function"&&(d=s,s={}),this.options=s;var h=this;function p(O){return d?(setTimeout(function(){d(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 y=i.length,b=r.length,m=1,t=y+b;s.maxEditLength&&(t=Math.min(t,s.maxEditLength));var v=(a=s.timeout)!==null&&a!==void 0?a:1/0,I=Date.now()+v,N=[{oldPos:-1,lastComponent:void 0}],x=this.extractCommon(N[0],i,r,0);if(N[0].oldPos+1>=b&&x+1>=y)return p([{value:this.join(i),count:i.length}]);var S=-1/0,E=1/0;function $(){for(var O=Math.max(S,-m);O<=Math.min(E,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<y}var X=R&&R.oldPos+1<b;if(!fe&&!X){N[O]=void 0;continue}if(!X||fe&&R.oldPos+1<W.oldPos?z=h.addToPath(W,!0,void 0,0):z=h.addToPath(R,void 0,!0,1),x=h.extractCommon(z,i,r,O),z.oldPos+1>=b&&x+1>=y)return p(jo(h,z.lastComponent,i,r,h.useLongestToken));N[O]=z,z.oldPos+1>=b&&(E=Math.min(E,O-1)),x+1>=y&&(S=Math.max(S,O+1))}m++}if(d)(function O(){setTimeout(function(){if(m>t||Date.now()>I)return d();$()||O()},0)})();else for(;m<=t&&Date.now()<=I;){var P=$();if(P)return P}},addToPath:function(r,i,a,s){var d=r.lastComponent;return d&&d.added===i&&d.removed===a?{oldPos:r.oldPos+s,lastComponent:{count:d.count+1,added:i,removed:a,previousComponent:d.previousComponent}}:{oldPos:r.oldPos+s,lastComponent:{count:1,added:i,removed:a,previousComponent:d}}},extractCommon:function(r,i,a,s){for(var d=i.length,h=a.length,p=r.oldPos,y=p-s,b=0;y+1<d&&p+1<h&&this.equals(i[y+1],a[p+1]);)y++,p++,b++;return b&&(r.lastComponent={count:b,previousComponent:r.lastComponent}),r.oldPos=p,y},equals:function(r,i){return this.options.comparator?this.options.comparator(r,i):r===i||this.options.ignoreCase&&r.toLowerCase()===i.toLowerCase()},removeEmpty:function(r){for(var i=[],a=0;a<r.length;a++)r[a]&&i.push(r[a]);return i},castInput:function(r){return r},tokenize:function(r){return r.split("")},join:function(r){return r.join("")}};function jo(e,r,i,a,s){for(var d=[],h;r;)d.push(r),h=r.previousComponent,delete r.previousComponent,r=h;d.reverse();for(var p=0,y=d.length,b=0,m=0;p<y;p++){var t=d[p];if(t.removed){if(t.value=e.join(a.slice(m,m+t.count)),m+=t.count,p&&d[p-1].added){var I=d[p-1];d[p-1]=d[p],d[p]=I}}else{if(!t.added&&s){var v=i.slice(b,b+t.count);v=v.map(function(x,S){var E=a[m+S];return E.length>x.length?E:x}),t.value=e.join(v)}else t.value=e.join(i.slice(b,b+t.count));b+=t.count,t.added||(m+=t.count)}}var N=d[y-1];return y>1&&typeof N.value=="string"&&(N.added||N.removed)&&e.equals("",N.value)&&(d[y-2].value+=N.value,d.pop()),d}var Go=new ge;function er(e,r,i){return Go.diff(e,r,i)}var Zn=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Qn=/\S/,hn=new ge;hn.equals=function(e,r){return this.options.ignoreCase&&(e=e.toLowerCase(),r=r.toLowerCase()),e===r||this.options.ignoreWhitespace&&!Qn.test(e)&&!Qn.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]&&Zn.test(r[i])&&Zn.test(r[i+2])&&(r[i]+=r[i+2],r.splice(i+1,2),i--);return r};function tr(e,r,i){return hn.diff(e,r,i)}var nr=new ge;nr.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
2
|
-
`));var
|
|
1
|
+
"use strict";(()=>{function dt(e,t){let o=new Map,a=t.map(i=>{let s=new Set(i);for(let l of i){let f=l.split("/");for(let p=1;p<f.length;p++)s.add(f.slice(0,p).join("/"))}return s});for(let i of e){let s=i.split("/");for(let l=0;l<s.length;l++){let f=s.slice(0,l+1).join("/");if(o.has(f))continue;let p=a.map(m=>m.has(f));o.set(f,{relativePath:f,displayName:s[l],depth:l,isDirectory:l<s.length-1,sides:p,status:p.every(Boolean)?"modified":p.length!==2?"partial":p[0]?"left-only":"right-only"})}}return[...o.values()].sort((i,s)=>{let l=i.relativePath.split("/"),f=s.relativePath.split("/");for(let p=0;p<Math.min(l.length,f.length);p++)if(l[p]!==f[p])return Number(p<f.length-1||s.isDirectory)-Number(p<l.length-1||i.isDirectory)||l[p].localeCompare(f[p]);return l.length-f.length})}function Qt(e,t){let o="overview"in t?t.overview:void 0,a=(o?.path||"").split("/").filter(I=>I&&I!==".").join("/"),i=I=>!a||I.startsWith(`${a}/`),s=[e.range.baseRef,e.range.headRef],l,f=[];if(t.kind==="stacked-diff"||t.kind==="deconstructed-diff"){let I=t.kind==="stacked-diff"?t.stack:t.panels,T=o?.comparison?I.findIndex(x=>x.id===o.comparison?.from):0,v=o?.comparison?I.findIndex(x=>x.id===o.comparison?.to):I.length-1;if(!I[T]||!I[v]||T===v)throw new Error(`Scene ${t.id} has invalid overview comparison endpoints.`);s=[I[T].label,I[v].label],l=t.files.flatMap(x=>{if(!i(x.path))return[];let N=x.panels[T],B=x.panels[v];if(!N||!B)return[];if(N.exists===B.exists&&N.content===B.content)return[];let M=N.exists?B.exists?"modified":"deleted":"added";return[{id:`${t.id}-overview-${x.path}`,kind:"text-diff",title:x.path,path:x.path,changeKind:M,leftContent:N.content,rightContent:B.content,leftLabel:s[0],rightLabel:s[1],summary:"",bullets:[],tags:[],takeaway:"",additions:0,deletions:0}]})}else l=e.files.filter(I=>I.kind==="text-diff"&&i(I.path)),f=e.files.filter(I=>I.kind==="omitted"&&i(I.path));let p=[...l,...f],m=new Map(p.map(I=>[I.path,I])),y=[new Set(p.filter(I=>I.changeKind!=="added").map(I=>I.path)),new Set(p.filter(I=>I.changeKind!=="deleted").map(I=>I.path))],b=dt(p.map(I=>I.path),y).map(I=>{let T=m.get(I.relativePath);return!T||I.isDirectory?I:{...I,gitChangeKind:T.changeKind,...T.previousPath?{previousPath:T.previousPath}:{},...T.kind==="omitted"?{relationSummary:`Unavailable: ${T.reason}`}:{}}}),E=a?` / ${a}/`:"";return{entries:b,files:l,labels:[s[0]+E,s[1]+E],omitted:f}}function en(e,t){if(t.kind==="title"||t.kind==="chapter"||t.kind==="conclusion")return"narrative";let o=e.scenes[t.sceneIndex];return!o||o.kind==="discussion"?"narrative":t.kind==="step"||o.kind==="text-diff"?"evidence":o.overview?"overview":"preview"}function fe(e,t,o="",a){let i=en(e,t);if(i==="narrative")return null;let s=e.scenes[t.sceneIndex],l=i==="overview",f="steps"in s?s.steps[t.kind==="step"?t.stepIndex:0]:void 0,p=[e.range.mergeBaseOid,e.range.headOid],m=[lt(e.range.baseRef,p[0]),lt(e.range.headRef,p[1])],y=s.kind==="deconstructed-diff"?"synthetic":"real";if(s.kind==="stacked-diff"||s.kind==="deconstructed-diff"){let I=s.kind==="stacked-diff"?s.stack:s.panels,T=a??(f&&"pairIndex"in f?f.pairIndex:0),v=l?s.overview?.comparison?I.findIndex(N=>N.id===s.overview?.comparison?.from):0:T,x=l?s.overview?.comparison?I.findIndex(N=>N.id===s.overview?.comparison?.to):I.length-1:T+1;if(!I[v]||!I[x])throw new Error(`Scene ${s.id} has unavailable comparison endpoints.`);s.kind==="stacked-diff"?(p=[s.stack[v].oid,s.stack[x].oid],m=[lt(I[v].label,p[0]),lt(I[x].label,p[1])]):(p=[I[v].id,I[x].id],m=[I[v].label,I[x].label])}let b=l?`Directory: ${"overview"in s&&s.overview?.path||"/"} (authored inventory)`:s.kind==="text-diff"?s.path:f&&"diff"in f?f.diff.path:f&&"file"in f?f.file:"",E=l?Qt(e,s):null;return{kind:y,labels:m,scope:b,overview:l,comparisonKey:JSON.stringify(y==="real"?[y,...p]:[y,o,e.generatedAt,e.range.mergeBaseOid,e.range.headOid,s.id,...p]),scopeKey:JSON.stringify([b,...E?[...E.files,...E.omitted].map(I=>I.path).sort():[]])}}function eo(e,t){let o=[e.range.mergeBaseOid,e.range.headOid];return{kind:"real",comparisonKey:JSON.stringify(["real",...o]),labels:[lt(e.range.baseRef,o[0]),lt(e.range.headRef,o[1])],scope:t,scopeKey:JSON.stringify([t]),overview:!1}}function ut(e){return`${e.kind==="synthetic"?"Explanation stages":"Comparison"}: ${e.labels.join(" \u2192 ")} \xB7 ${e.scope}`}function qn(e,t){if(!e)return ut(t);if(e.kind!==t.kind)return`${t.kind==="synthetic"?"Switching to explanation stages":"Switching to real revisions"}. ${ut(t)}`;if(e.comparisonKey!==t.comparisonKey)return`${t.kind==="synthetic"?"Explanation stages changed":"Revision comparison changed"}: ${e.labels.join(" \u2192 ")} to ${t.labels.join(" \u2192 ")} \xB7 ${t.scope}`;let o=e.scopeKey!==t.scopeKey?`${e.overview||t.overview?"view":"file"} changed from ${e.scope} to ${t.scope}`:`same ${t.overview?"directory view":"file"}: ${t.scope}`;return`Same ${t.kind==="synthetic"?"explanation stages":"revision comparison"}; ${o} \xB7 ${t.labels.join(" \u2192 ")}`}function lt(e,t){return e===t||e===t.slice(0,7)?t.slice(0,7):`${e} (${t.slice(0,7)})`}function Fe(e,t){if(t.kind==="chapter"){let a=e.chapters.findIndex(i=>i.id===t.chapterId);return e.chapters[a].title}let o=e.scenes[t.sceneIndex];return t.kind==="step"&&"steps"in o?o.steps[t.stepIndex].title:o.title}function to(e,t){let o=e.scenes[t];return o.kind==="discussion"?[]:("steps"in o?o.steps.flatMap((i,s)=>"image"in i&&i.image?[]:[{kind:"step",key:`step:${o.id}:${i.id}`,sceneIndex:t,stepIndex:s}]):[{kind:"scene",key:`scene:${o.id}`,sceneIndex:t,stepIndex:0}]).map(i=>fe(e,i)).filter(Boolean)}function Rt(e){let t=e.scenes.map((i,s)=>({sceneIndex:s,title:Fe(e,{kind:"scene",key:`scene:${i.id}`,sceneIndex:s,stepIndex:0}),purpose:i.summary,evidence:ps(e,s)})),o=(e.chapters||[]).map((i,s)=>{let l=t.filter(T=>i.sceneIds.includes(e.scenes[T.sceneIndex].id)),f=l.flatMap(T=>to(e,T.sceneIndex)),p=[...f];for(let T of l){let v=e.scenes[T.sceneIndex];if("overview"in v&&v.overview&&!(v.kind==="walkthrough"&&v.steps.every(x=>x.image))){let x=fe(e,{kind:"scene",key:`scene:${v.id}`,sceneIndex:T.sceneIndex,stepIndex:0});x&&p.push(x)}}let m=p.filter((T,v)=>p.findIndex(x=>x.comparisonKey===T.comparisonKey)===v),y=[...new Set(f.map(T=>T.scope))],b=l.reduce((T,v)=>{let x=e.scenes[v.sceneIndex];return T+("steps"in x?x.steps.length:0)},0),E=y.length?`Focus files: ${y.join(", ")}.`:"No code steps; this chapter uses discussion or images.",I=m.map(T=>`${T.kind==="synthetic"?"Constructed stages":"Revisions"}: ${T.labels.join(" \u2192 ")}.`).join(" ");return{chapterIndex:s,chapterId:i.id,title:i.title,...i.summary?{summary:i.summary}:{},evidence:`${l.length} ${l.length===1?"scene":"scenes"} \xB7 ${b} ${b===1?"step":"steps"}. ${E}${I?` ${I}`:""}`,scenes:l}}),a=e.scenes.reduce((i,s)=>i+("steps"in s?s.steps.length:0),0);return{summary:`${o.length} ${o.length===1?"chapter":"chapters"} \u2192 ${t.length} ${t.length===1?"scene":"scenes"} \u2192 ${a} ${a===1?"step":"steps"}. Chapters group topics; scenes explain one idea; steps show the evidence.`,chapters:o,scenes:t}}function ps(e,t){let o=e.scenes[t];if(o.kind==="discussion")return"Discussion: pause to connect the findings. No code comparison is displayed.";if(o.kind==="walkthrough"&&o.steps.every(b=>b.image))return`${o.steps.length} images in reading order. Each step explains what to notice in its image.`;let a=o.kind==="walkthrough"?o.steps.filter(b=>b.image).length:0,i=to(e,t),s=i.map(b=>b.scope).filter((b,E,I)=>E===0||b!==I[E-1]),l=i.filter((b,E)=>E===0||b.comparisonKey!==i[E-1].comparisonKey),f=`${"steps"in o?`${o.steps.length} ${o.steps.length===1?"step":"steps"}. `:""}${s.length===1?"File":"Files in order"}: ${s.join(" \u2192 ")}.`,p=`${o.kind==="deconstructed-diff"?"Explanation stages (constructed, not commits)":"Revisions"}: ${l.map(b=>b.labels.join(" \u2192 ")).join("; then ")}.`,m="overview"in o&&o.overview?fe(e,{kind:"scene",key:`scene:${o.id}`,sceneIndex:t,stepIndex:0}):null;return`${m?`Starts with a directory overview${m.comparisonKey!==i[0]?.comparisonKey?` (${m.labels.join(" \u2192 ")})`:""}, then follows the evidence. `:""}${f} ${p}${a?` Also includes ${a} image ${a===1?"step":"steps"}.`:""}`}function tn(e,t,o){let a=e.scenes[t];if(!("steps"in a))return"";let i=a.steps[o],s=`Step ${o+1} of ${a.steps.length}.`;if("image"in i&&i.image)return`${s} Image: ${i.title}.`;let l={kind:"step",key:`step:${a.id}:${i.id}`,sceneIndex:t,stepIndex:o},f=fe(e,l),p=o>0&&!(a.kind==="walkthrough"&&a.steps[o-1].image)?fe(e,{...l,stepIndex:o-1}):null;if(!p)return`${s} Evidence in ${f.scope}.`;let m=p.comparisonKey!==f.comparisonKey,y=p.scope!==f.scope,b=f.kind==="synthetic"?"explanation stages":"revisions",E=m?`Switch ${b} to ${f.labels.join(" \u2192 ")}.`:`Keep the same ${b}.`;return`${s} ${E} ${y?`Move from ${p.scope} to ${f.scope}.`:`Continue in ${f.scope}.`}`}function We(e,t){if(!e.currentPath||t!==-1&&t!==1)return null;let o=e.paths.indexOf(e.currentPath);if(o<0)return null;for(let a=o+t;a>=0&&a<e.paths.length;a+=t)if(!e.changedPaths||e.changedPaths.has(e.paths[a]))return e.paths[a];return null}function ms(e){return{canGoPrevious:We(e,-1)!==null,canGoNext:We(e,1)!==null}}function no(e,t,o){if(e.type==="returnToDirectory")return o?{path:null}:null;if(e.type==="openDirectoryEntry")return typeof e.relativePath=="string"&&t.paths.includes(e.relativePath)?{path:e.relativePath}:null;if(e.type==="navigateFile"&&(e.direction==="previous"||e.direction==="next")){let a=We(t,e.direction==="previous"?-1:1);return a===null?null:{path:a}}return null}function nn(e,t){return{type:"showDirectoryDiff",labels:e,leftLabel:e[0],rightLabel:e[e.length-1],entries:t,canMutate:!1}}function jn(e,t){return e.slice(0,-1).map((o,a)=>({leftIndex:a,rightIndex:a+1,...t?{diffModel:t(o,e[a+1])}:{}}))}function rn(e,t){let{files:o,...a}=e;return{type:"showMultiDiff",...a,pairs:jn(a.panels,t),fileNavigation:ms(o)}}function ro(e,t){let o=t.displayed||[],a=s=>({active:s===t.active,selected:s!==null&&t.selected.includes(s),panelNumber:o.indexOf(s)+1||void 0}),i=e.map((s,l)=>({kind:"history-entry",index:l,commit:s.commit,label:`${s.shortCommit} ${s.summary}`.trim(),meta:s.timestamp||"",summary:s.summary,timestamp:s.timestamp,author:s.author,authorEmail:s.authorEmail,message:s.message,parents:s.parents||(s.parentCommit?[s.parentCommit]:[]),selectionEnabled:t.selectionEnabled,...a(s.commit),...t.changed?{changesFile:t.changed.has(s.commit)}:{},...t.tourCommits?{inTour:t.tourCommits.has(s.commit)}:{}}));return o.forEach((s,l)=>{s===void 0||i.some(f=>f.commit===s)||i.push({kind:"panel-revision",index:-l-1,commit:s,label:t.missingRevisionLabel(s),meta:"",summary:"",timestamp:void 0,author:void 0,authorEmail:void 0,message:void 0,parents:[],selectionEnabled:!!t.missingRevisionSelectionEnabled,...a(s)})}),i}function oo(){let e,t;function o(){t?.close(),t?.remove(),e?.remove(),t=e=void 0,document.body.classList.remove("tour-image-active")}function a(i,s){o(),e=document.createElement("figure"),e.className="tour-image-evidence";let l=document.createElement("figcaption"),f=document.createElement("span");f.textContent=s;let p=document.createElement("button");p.type="button",p.textContent="Expand image";let m=document.createElement("img");m.src=i.dataUrl,m.alt=i.alt,m.addEventListener("error",()=>{f.textContent=`${s} \u2014 image could not be decoded`}),l.append(f,p),e.append(l,m),document.getElementById("container").append(e),document.body.classList.add("tour-image-active"),p.addEventListener("click",()=>{t?.remove(),t=document.createElement("dialog"),t.className="tour-image-dialog",t.setAttribute("aria-label",s);let y=document.createElement("button");y.type="button",y.textContent="Close image",y.addEventListener("click",()=>t.close()),t.append(y,m.cloneNode()),document.body.append(t),t.showModal()})}return{show:a,clear:o,isVisible:()=>!!e}}var gs=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Wn=["part","chapter","scene","step"];function De(e,t){let o=e.get(t);if(!o||o.length>4096||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`Invalid or missing ${t}.`);return o}function io(e){if(!e||e.startsWith("/")||e.includes("\\")||e.includes("\0")||e.split("/").some(t=>!t||t==="."||t===".."))throw new Error("Expected a repository-relative path without traversal.");return e}function Kn(e,t,o=[]){for(let a of e.keys()){if(!t.includes(a))throw new Error(`Unsupported link field: ${a}.`);if(!o.includes(a)&&e.getAll(a).length!==1)throw new Error(`Duplicate link field: ${a}.`)}}function so(e){let t=new URL(e);if(t.protocol!=="file:"||t.hostname||t.search||t.hash||t.username||t.password||!t.pathname.startsWith("/"))throw new Error("Links require a local file URL.");return e}function ao(e){let t=De(e,"part"),o=t==="title"||t==="conclusion"?[]:t==="chapter"?["chapter"]:t==="scene"?["scene"]:t==="step"?["scene","step"]:null;if(!o)throw new Error(`Unsupported document part: ${t}.`);for(let a of Wn.filter(i=>i!=="part"))if(e.has(a)&&!o.includes(a))throw new Error(`${a} is incompatible with ${t}.`);return Object.fromEntries([["part",t],...o.map(a=>[a,De(e,a)])])}function Gn(e){if(e.length>16384||/%(?![\da-f]{2})/i.test(e))throw new Error("Invalid or oversized Bygone link.");let t=new URL(e);if(t.protocol!=="bygone:"||t.hostname!=="open"||t.pathname!=="/v1"||t.username||t.password||t.port||t.hash)throw new Error("Unsupported Bygone link address or version.");let o=t.searchParams,a=De(o,"kind"),i=so(De(o,"repo"));if(a==="tour"){Kn(o,["kind","repo","tour","mode",...Wn]);let m=De(o,"mode");if(m!=="historical"&&m!=="deconstructed")throw new Error("Unsupported authored tour mode.");let y=De(o,"tour");return/^[a-z][a-z\d+.-]*:/i.test(y)?so(y):io(y),{kind:a,repo:i,tour:y,mode:m,focus:ao(o)}}if(a!=="compare")throw new Error("Unsupported Bygone link kind.");Kn(o,["kind","repo","rev","file","revision","line"],["rev"]);let s=o.getAll("rev");if(s.length!==2||s.some(m=>!gs.test(m))||s[0]===s[1])throw new Error("Comparison links require two distinct full commit IDs in order.");let l=o.has("file")?io(De(o,"file")):void 0,f=o.has("revision")?De(o,"revision"):void 0;if(f&&(!l||!s.includes(f)))throw new Error("Code focus requires a file and one of the comparison revisions.");let p=o.has("line")?Number(De(o,"line")):void 0;if(p!==void 0&&(!f||!Number.isSafeInteger(p)||p<1))throw new Error("Line focus requires a revision and positive line number.");return{kind:a,repo:i,revisions:s,...l?{file:l}:{},...f?{revision:f}:{},...p!==void 0?{line:p}:{}}}function co(e){let t=new URL("bygone://open/v1");if(t.searchParams.set("kind",e.kind),t.searchParams.set("repo",e.repo),e.kind==="tour"){t.searchParams.set("tour",e.tour),t.searchParams.set("mode",e.mode);for(let[o,a]of Object.entries(e.focus))t.searchParams.set(o,a)}else{for(let o of e.revisions)t.searchParams.append("rev",o);for(let o of["file","revision","line"])e[o]!==void 0&&t.searchParams.set(o,String(e[o]))}return Gn(t.href),t.href}function ys(e,t){if(e.tours){let a=e.tours[t];if(!a)throw new Error(`This tour has no ${t} mode.`);return a}let o=e.scenes.some(a=>a.kind==="deconstructed-diff");if(t==="deconstructed"&&o||t==="historical"&&!o)return e;if(t==="historical"&&e.zoom?.final.scenes.some(a=>a.kind==="walkthrough"))return e.zoom.final;throw new Error(`This tour has no ${t} mode.`)}function Vn(e,t,o){let a=ys(e,t);if(o.part==="title")return{key:"title",sceneIndex:0,stepIndex:0};if(o.part==="conclusion"){if(!a.conclusion)throw new Error("Conclusion is unavailable in this tour mode.");return{key:"conclusion",sceneIndex:-1,stepIndex:0}}if(o.part==="chapter"){let f=a.chapters.find(m=>m.id===o.chapter),p=a.scenes.findIndex(m=>m.id===f?.sceneIds[0]);if(!f||p<0)throw new Error(`Chapter is unavailable: ${o.chapter}.`);return{key:f.summary?.trim()?`chapter:${f.id}`:`scene:${a.scenes[p].id}`,sceneIndex:p,stepIndex:0}}let i=a.scenes.findIndex(f=>f.id===o.scene);if(i<0)throw new Error(`Scene is unavailable: ${o.scene}.`);let s=a.scenes[i];if(o.part==="scene")return{key:`scene:${s.id}`,sceneIndex:i,stepIndex:0};let l="steps"in s?s.steps.findIndex(f=>f.id===o.step):-1;if(l<0)throw new Error(`Step is unavailable: ${o.step}.`);return{key:`step:${s.id}:${o.step}`,sceneIndex:i,stepIndex:l}}function Ze(e,t){return`#${new URLSearchParams({location:"1",mode:e,...t})}`}function Jn(e){if(!e)return null;if(e.length>16384||/%(?![\da-f]{2})/i.test(e))throw new Error("Oversized tour location.");let t=new URLSearchParams(e.replace(/^#/,""));if(Kn(t,["location","mode",...Wn]),t.get("location")!=="1")throw new Error("Unsupported tour location version.");let o=t.get("mode");if(o!=="historical"&&o!=="deconstructed")throw new Error("Unsupported tour location mode.");return{mode:o,focus:ao(t)}}function Me(){}Me.prototype={diff:function(t,o){var a,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=i.callback;typeof i=="function"&&(s=i,i={}),this.options=i;var l=this;function f(n){return s?(setTimeout(function(){s(void 0,n)},0),!0):n}t=this.castInput(t),o=this.castInput(o),t=this.removeEmpty(this.tokenize(t)),o=this.removeEmpty(this.tokenize(o));var p=o.length,m=t.length,y=1,b=p+m;i.maxEditLength&&(b=Math.min(b,i.maxEditLength));var E=(a=i.timeout)!==null&&a!==void 0?a:1/0,I=Date.now()+E,T=[{oldPos:-1,lastComponent:void 0}],v=this.extractCommon(T[0],o,t,0);if(T[0].oldPos+1>=m&&v+1>=p)return f([{value:this.join(o),count:o.length}]);var x=-1/0,N=1/0;function B(){for(var n=Math.max(x,-y);n<=Math.min(N,y);n+=2){var F=void 0,V=T[n-1],O=T[n+1];V&&(T[n-1]=void 0);var j=!1;if(O){var J=O.oldPos-n;j=O&&0<=J&&J<p}var oe=V&&V.oldPos+1<m;if(!j&&!oe){T[n]=void 0;continue}if(!oe||j&&V.oldPos+1<O.oldPos?F=l.addToPath(O,!0,void 0,0):F=l.addToPath(V,void 0,!0,1),v=l.extractCommon(F,o,t,n),F.oldPos+1>=m&&v+1>=p)return f(ws(l,F.lastComponent,o,t,l.useLongestToken));T[n]=F,F.oldPos+1>=m&&(N=Math.min(N,n-1)),v+1>=p&&(x=Math.max(x,n+1))}y++}if(s)(function n(){setTimeout(function(){if(y>b||Date.now()>I)return s();B()||n()},0)})();else for(;y<=b&&Date.now()<=I;){var M=B();if(M)return M}},addToPath:function(t,o,a,i){var s=t.lastComponent;return s&&s.added===o&&s.removed===a?{oldPos:t.oldPos+i,lastComponent:{count:s.count+1,added:o,removed:a,previousComponent:s.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:o,removed:a,previousComponent:s}}},extractCommon:function(t,o,a,i){for(var s=o.length,l=a.length,f=t.oldPos,p=f-i,m=0;p+1<s&&f+1<l&&this.equals(o[p+1],a[f+1]);)p++,f++,m++;return m&&(t.lastComponent={count:m,previousComponent:t.lastComponent}),t.oldPos=f,p},equals:function(t,o){return this.options.comparator?this.options.comparator(t,o):t===o||this.options.ignoreCase&&t.toLowerCase()===o.toLowerCase()},removeEmpty:function(t){for(var o=[],a=0;a<t.length;a++)t[a]&&o.push(t[a]);return o},castInput:function(t){return t},tokenize:function(t){return t.split("")},join:function(t){return t.join("")}};function ws(e,t,o,a,i){for(var s=[],l;t;)s.push(t),l=t.previousComponent,delete t.previousComponent,t=l;s.reverse();for(var f=0,p=s.length,m=0,y=0;f<p;f++){var b=s[f];if(b.removed){if(b.value=e.join(a.slice(y,y+b.count)),y+=b.count,f&&s[f-1].added){var I=s[f-1];s[f-1]=s[f],s[f]=I}}else{if(!b.added&&i){var E=o.slice(m,m+b.count);E=E.map(function(v,x){var N=a[y+x];return N.length>v.length?N:v}),b.value=e.join(E)}else b.value=e.join(o.slice(m,m+b.count));m+=b.count,b.added||(y+=b.count)}}var T=s[p-1];return p>1&&typeof T.value=="string"&&(T.added||T.removed)&&e.equals("",T.value)&&(s[p-2].value+=T.value,s.pop()),s}var bs=new Me;function fo(e,t,o){return bs.diff(e,t,o)}var lo=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,uo=/\S/,Xn=new Me;Xn.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!uo.test(e)&&!uo.test(t)};Xn.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),o=0;o<t.length-1;o++)!t[o+1]&&t[o+2]&&lo.test(t[o])&&lo.test(t[o+2])&&(t[o]+=t[o+2],t.splice(o+1,2),o--);return t};function ho(e,t,o){return Xn.diff(e,t,o)}var Zn=new Me;Zn.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
2
|
+
`));var t=[],o=e.split(/(\n|\r\n)/);o[o.length-1]||o.pop();for(var a=0;a<o.length;a++){var i=o[a];a%2&&!this.options.newlineIsToken?t[t.length-1]+=i:(this.options.ignoreWhitespace&&(i=i.trim()),t.push(i))}return t};function po(e,t,o){return Zn.diff(e,t,o)}var vs=new Me;vs.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var xs=new Me;xs.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function on(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?on=function(t){return typeof t}:on=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},on(e)}var ks=Object.prototype.toString,Pt=new Me;Pt.useLongestToken=!0;Pt.tokenize=Zn.tokenize;Pt.castInput=function(e){var t=this.options,o=t.undefinedReplacement,a=t.stringifyReplacer,i=a===void 0?function(s,l){return typeof l>"u"?o:l}:a;return typeof e=="string"?e:JSON.stringify(Yn(e,null,null,i),i," ")};Pt.equals=function(e,t){return Me.prototype.equals.call(Pt,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"))};function Yn(e,t,o,a,i){t=t||[],o=o||[],a&&(e=a(i,e));var s;for(s=0;s<t.length;s+=1)if(t[s]===e)return o[s];var l;if(ks.call(e)==="[object Array]"){for(t.push(e),l=new Array(e.length),o.push(l),s=0;s<e.length;s+=1)l[s]=Yn(e[s],t,o,a,i);return t.pop(),o.pop(),l}if(e&&e.toJSON&&(e=e.toJSON()),on(e)==="object"&&e!==null){t.push(e),l={},o.push(l);var f=[],p;for(p in e)e.hasOwnProperty(p)&&f.push(p);for(f.sort(),s=0;s<f.length;s+=1)p=f[s],l[p]=Yn(e[p],t,o,a,p);t.pop(),o.pop()}else l=e;return l}var sn=new Me;sn.tokenize=function(e){return e.slice()};sn.join=sn.removeEmpty=function(e){return e};function mo(e,t,o){return sn.diff(e,t,o)}function go(e){let t=e.manifest,o=e.history,a=[t.range.mergeBaseOid,t.range.headOid],i=p=>{let m=o?.commits.find(y=>y.oid===p);if(!m)throw new Error(`Revision ${p} is outside this export.`);return m},s=(p,m)=>{if(i(p),!o.paths.includes(m))throw new Error(`File ${m} is outside this export.`);let y=o.snapshots[p][m];if(y?.omitted)throw new Error(`${m}: ${y.omitted}`);return y?e.texts[y.blob]:null},l=p=>{let m=new Set,y=b=>{m.has(b)||!o.commits.some(E=>E.oid===b)||(m.add(b),i(b).parents.forEach(y))};return y(p),m},f=(p,m)=>po(p||"",m||"").reduce((y,b)=>(b.added&&(y.additions+=b.count),b.removed&&(y.deletions+=b.count),y),{additions:0,deletions:0});return async(p,m)=>{if(p==="changed-files"){if(!o)throw new Error("Git history is not included in this Minimal export.");let E=m.commits;if(!Array.isArray(E))throw new Error("Expected displayed revisions.");E.filter(T=>T!==null).forEach(i);let I=o.paths.filter(T=>{let v=E.map(x=>x===null?void 0:o.snapshots[x][T]);return v.some(x=>JSON.stringify(x)!==JSON.stringify(v[0]))});return{paths:I,...m.includeFiles?{files:o.paths.filter(T=>E.some(v=>v!==null&&o.snapshots[v][T])).map(T=>{let v=E.map(x=>x===null?null:o.snapshots[x][T]).find(x=>x?.omitted);return{kind:v?"omitted":"text-diff",path:T,changeKind:I.includes(T)?"modified":"unchanged",...v?{reason:v.omitted}:{}}})}:{},...m.includeEntries?{entries:dt(I,E.map(T=>new Set(T===null?[]:o.paths.filter(v=>o.snapshots[T][v]))))}:{}}}if(p==="compare-many"){let E=m.commits;if(!Array.isArray(E)||E.length<2||new Set(E).size!==E.length)throw new Error("Select at least two different included revisions.");if(!o){if(E.length!==2||E.some((x,N)=>x!==a[N]))throw new Error("Minimal exports support only the fixed base \u2192 head comparison.");if(m.path&&!t.files.some(x=>x.path===m.path||x.previousPath===m.path))throw new Error("File is outside the exported scope.");let v=t.files.filter(x=>!m.path||x.path===m.path||x.previousPath===m.path).map(x=>({...x,comparisonPanels:E.map((N,B)=>({id:`compare-${N}`,commit:N,editable:!1,path:B===0&&x.previousPath||x.path,label:B===0?x.leftLabel:x.rightLabel,content:(B===0?x.leftContent:x.rightContent)||""}))}));return{commits:E,files:v,entries:dt(v.map(x=>x.path),E.map((x,N)=>new Set(v.filter(B=>N===0?B.changeKind!=="added":B.changeKind!=="deleted").map(B=>B.path))))}}if(E.forEach(i),m.path&&!o.paths.includes(m.path))throw new Error("File is outside the exported scope.");let T=(m.path?[m.path]:o.paths).flatMap(v=>{let x=E.map(n=>o.snapshots[n][v]);if(!m.path&&x.every(n=>JSON.stringify(n)===JSON.stringify(x[0])))return[];let N=x.find(n=>n?.omitted),B=x.map(n=>n?.blob?e.texts[n.blob]:""),M=B.slice(1).reduce((n,F,V)=>{let O=f(B[V],F);return{additions:n.additions+O.additions,deletions:n.deletions+O.deletions}},{additions:0,deletions:0});return[{kind:N?"omitted":"text-diff",path:v,...M,...N?{reason:N.omitted}:{},changeKind:x[0]?x.at(-1)?"modified":"deleted":"added",comparisonPanels:E.map((n,F)=>({id:`compare-${n}`,commit:n,path:v,label:`${v} @ ${n.slice(0,7)}${x[F]?"":" (absent)"}`,content:B[F],editable:!1}))}]});return{commits:E,files:T,entries:dt(T.map(v=>v.path),E.map(v=>new Set(T.filter(x=>o.snapshots[v][x.path]).map(x=>x.path))))}}if(!o)throw new Error("Git history is not included in this Minimal export.");let y=m.commit||t.range.headOid,b=i(y);if(p==="list"){let E=l(y),I=o.commits.filter(T=>E.has(T.oid));if(m.path){if(!o.paths.includes(m.path))throw new Error("File is outside the exported scope.");I=I.filter(T=>{let v=o.snapshots[T.parents[0]];return!v||JSON.stringify(o.snapshots[T.oid][m.path])!==JSON.stringify(v[m.path])})}return{entries:I,selectedIndex:I.length?0:-1,selectedCommit:I[0]?.oid||null}}if(p==="diff"){let E=b.parents[0]||null;if(E&&!o.snapshots[E])throw new Error("The parent revision is outside this export. Compare two included revisions instead.");let I=E?s(E,m.path):null,T=s(y,m.path);return{commit:y,parentCommit:E,path:m.path,leftContent:I||"",rightContent:T||"",leftLabel:`${m.path} @ ${E?.slice(0,7)||"empty"}`,rightLabel:`${m.path} @ ${y.slice(0,7)}`}}throw new Error(`Unsupported export operation: ${p}.`)}}var Is=2e4,Ss=100,ln=Bo("BYGONE_MAX_INLINE_HIGHLIGHT_LINE_LENGTH",Is),Ro=Bo("BYGONE_DIFF_TIMEOUT_MS",Ss);function we(e,t,o={}){let a=bo(e),i=bo(t);if(e===t)return wo(a);if(a.length===i.length&&a.every((v,x)=>v===i[x])){let v=wo(a),x=e.match(/[^\n]*\n|[^\n]+$/g)||[],N=t.match(/[^\n]*\n|[^\n]+$/g)||[];return a.forEach((B,M)=>{x[M]!==N[M]&&(v.leftLines[M].kind=v.rows[M].left.kind="removed",v.rightLines[M].kind=v.rows[M].right.kind="added",v.leftLines[M].inlineDetail=v.rightLines[M].inlineDetail="line-ending",v.blocks.push(Ft("replace",M,M+1,M,M+1)))}),v.blocks=yo(v.blocks),v.hasChanges=!0,v.formattingOnly=!0,v}let s=Cs(a,i),l=mo(s.left,s.right,{timeout:o.timeoutMs??Ro});if(!l)return Ts(a,i);let f=l.map(v=>({...v,value:v.value.map(x=>s.lines[x])})),p=[],m=[],y=[],b=[],E=1,I=1;for(let v=0;v<f.length;v++){let x=f[v],N=x.removed?x.value:[],B=x.added?x.value:[];if(!x.added&&!x.removed){for(let M of x.value)m.push(Te("context",M,E)),y.push(Te("context",M,I)),p.push(Qe(Ce("context",M,E++),Ce("context",M,I++)));continue}if(x.removed&&v+1<f.length&&f[v+1].added){let M=f[v+1],n=$s(N,M.value,E,I,p,m,y,b);E=n.left,I=n.right,v++;continue}if(x.removed){let M=m.length,n=y.length;for(let F of N)m.push(Te("removed",F,E)),p.push(Qe(Ce("removed",F,E++),ht()));b.push(Ft("delete",M,m.length,n,y.length));continue}if(x.added){let M=m.length,n=y.length;for(let F of B)y.push(Te("added",F,I)),p.push(Qe(ht(),Ce("added",F,I++)));b.push(Ft("insert",M,m.length,n,y.length))}}let T=p.some(v=>v.left.kind!=="context"||v.right.kind!=="context");return Po({rows:p,leftLines:m,rightLines:y,blocks:yo(b),reflows:b.filter(v=>v.reflow),hasChanges:T,quality:"exact"})}function Po(e){for(let t of e.blocks)if(t.kind==="replace")for(let o of["left","right"])for(let a=t[`${o}Start`];a<t[`${o}End`];a++){let i=e[`${o}Lines`][a];i.kind!=="context"&&!i.segments&&(i.inlineDetail="omitted")}return e}function yo(e){let t=[],o=!1;for(let i of e){let s=i.kind!=="replace",l=t[t.length-1];s&&o&&l.leftEnd===i.leftStart&&l.rightEnd===i.rightStart?(l.leftEnd=i.leftEnd,l.rightEnd=i.rightEnd,l.leftEnd>l.leftStart&&l.rightEnd>l.rightStart&&(l.kind="replace")):t.push({...i}),o=s}let a=[];for(let i of t){let s={...i};delete s.reflow;let l=a[a.length-1];l?.kind===s.kind&&l.leftEnd===s.leftStart&&l.rightEnd===s.rightStart?(l.leftEnd=s.leftEnd,l.rightEnd=s.rightEnd):a.push(s)}return a}function Cs(e,t){let o=new Map,a=[],i=s=>{let l=o.get(s);if(l!==void 0)return l;let f=a.length;return o.set(s,f),a.push(s),f};return{left:e.map(i),right:t.map(i),lines:a}}function wo(e){return{rows:e.map((t,o)=>Qe(Ce("context",t,o+1),Ce("context",t,o+1))),leftLines:e.map((t,o)=>Te("context",t,o+1)),rightLines:e.map((t,o)=>Te("context",t,o+1)),blocks:[],hasChanges:!1,quality:"exact"}}function Ts(e,t){let o=e.map((l,f)=>Te("removed",l,f+1)),a=t.map((l,f)=>Te("added",l,f+1)),i=[...e.map((l,f)=>Qe(Ce("removed",l,f+1),ht())),...t.map((l,f)=>Qe(ht(),Ce("added",l,f+1)))],s="replace";return e.length===0?s="insert":t.length===0&&(s="delete"),Po({rows:i,leftLines:o,rightLines:a,blocks:i.length===0?[]:[Ft(s,0,e.length,0,t.length)],hasChanges:i.length>0,quality:"fallback"})}function bo(e){if(e.length===0)return[];let t=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 t[t.length-1]===""&&t.pop(),t}function $s(e,t,o,a,i,s,l,f){let p=fn(e,t),m=p.filter(O=>O.left!==void 0&&O.right!==void 0&&tr(O.left,O.right)).length,y=!p.some(O=>O.reflow)&&Ns(e,t,m),b=p.flatMap(O=>O.reflow||O.left===void 0||O.right===void 0||tr(O.left,O.right)?[O]:[{left:O.left},{right:O.right}]),E=[];for(let O=0;O<b.length;){let j=b[O];if(j.reflow||j.left!==void 0&&j.right!==void 0){E.push(j),O++;continue}let J=O;for(;O<b.length&&!b[O].reflow&&(b[O].left===void 0||b[O].right===void 0);)O++;let oe=b.slice(J,O),Q=oe.filter(de=>de.left!==void 0),ie=oe.filter(de=>de.right!==void 0);if(Q.length===1&&ie.length===1)E.push({left:Q[0].left,right:ie[0].right});else for(let de of oe)E.push(de)}let I=o,T=a,v=[],x=[],N=()=>{Xs(v,x),v=[],x=[]},B,M=!1,n=s.length,F=l.length,V=()=>{if(!B)return;let O=Ft(B,n,s.length,F,l.length);M&&(O.reflow=!0),f.push(O)};for(let{left:O,right:j,reflow:J}of E){(J||O!==void 0&&j!==void 0)&&N();let oe=y||J||O!==void 0&&j!==void 0?"replace":O!==void 0?"delete":"insert";(B!==oe||M!==!!J||J?.start)&&(V(),B=oe,M=!!J,n=s.length,F=l.length);let Q,ie;O!==void 0&&(Q=Te("removed",O,I),s.push(Q)),j!==void 0&&(ie=Te("added",j,T),l.push(ie)),J?(Q&&(Q.segments=J.leftSegments),ie&&(ie.segments=J.rightSegments)):Q&&ie?Ys(Q,ie):y&&(Q&&Lo(Q),ie&&Lo(ie)),!J&&(O===void 0||j===void 0)&&(Q&&v.push(Q),ie&&x.push(ie)),i.push(Qe(O===void 0?ht():Ce("removed",O,I++),j===void 0?ht():Ce("added",j,T++)))}return V(),N(),{left:I,right:T}}function tr(e,t){if(!e.trim()&&!t.trim()||hn(e,t).eligible)return!0;let a=Dt(e);if(a&&a===Dt(t))return!0;let i=new Set(Ot($e(e)).filter(vo));return Ot($e(t)).some(s=>i.has(s)&&vo(s))}var As=new Set(["and","are","for","from","into","that","the","this","to","with"]);function vo(e){return e.length>=3&&/^[\p{L}\p{N}_$]+$/u.test(e)&&!As.has(e)}function Ns(e,t,o){if(o===0)return!1;let a=Math.max(e.length,t.length);if(a<=2||o*2>=a)return!0;let i=[...e,...t].map(Ls);return i[0]!==null&&i.every(s=>s===i[0])}function Ls(e){let t=e.trimStart();return/^[-*+]\s+/.test(t)?"bullet":/^\d+[.)]\s+/.test(t)?"ordered":/^>\s+/.test(t)?"quote":null}var Fo=1e4,nr=2e3,Rs=.52,Ps=.35,Do=.38,Fs=.33,Mo=.86,un=.08,an=.05,cn=-.12,xo=5e3,Ds=2e3,Ms=5e7,ko=4,Os=8,Qn=4;function Eo(e){let t=[];for(let o=0;o<e.length;o++){let a=e[o],i=[a],s=a.match(/^(\s*)(?:[\w-]+:\s+|[-*+]\s+)(\S.*)$/);if(s&&!/^[|>\[{]/.test(s[2]))for(;o+1<e.length;){let l=e[o+1];if(!l.trim()||l.length-l.trimStart().length<=s[1].length||/^\s*(?:[\w-]+:|[-*+]\s|\d+[.)]\s|#)/.test(l))break;i.push(l),o++}t.push(i.join(`
|
|
5
|
+
`))}return t}function fn(e,t){if([...e,...t].some(i=>i.includes(`
|
|
6
|
+
`)))return er(e,t);let o=Eo(e),a=Eo(t);return o.length===e.length&&a.length===t.length?er(e,t):er(o,a).flatMap(i=>{let s=i.left?.split(`
|
|
7
|
+
`)||[],l=i.right?.split(`
|
|
8
|
+
`)||[];if(!s.length||!l.length)return[...s.map(b=>({left:b})),...l.map(b=>({right:b}))];if(s.length===1&&l.length===1)return[i];let p=ar(i.left,i.right)||sr(i.left,i.right),m=p&&ft(p.leftSegments),y=p&&ft(p.rightSegments);return Array.from({length:Math.max(s.length,l.length)},(b,E)=>({left:s[E],right:l[E],reflow:{start:E===0,leftSegments:m?.[E],rightSegments:y?.[E]}}))})}function er(e,t){if(e.length===0)return t.map(v=>({right:v}));if(t.length===0)return e.map(v=>({left:v}));let o=0;for(;o<Math.min(e.length,t.length)&&e[o].trim()===t[o].trim();)o++;if(o)return[...e.slice(0,o).map((v,x)=>({left:v,right:t[x]})),...fn(e.slice(o),t.slice(o))];let a=1,i=1,s=e[0].trim().replace(/\s+/g," "),l=t[0].trim().replace(/\s+/g," ");for(;s&&l&&s!==l;)if(l.startsWith(s+" ")&&a<e.length)s+=" "+e[a++].trim().replace(/\s+/g," ");else if(s.startsWith(l+" ")&&i<t.length)l+=" "+t[i++].trim().replace(/\s+/g," ");else break;if(s===l&&(a>1||i>1)&&![...e,...t].some(v=>v.includes(`
|
|
9
|
+
`))){let v=ar(e.slice(0,a).join(`
|
|
10
|
+
`),t.slice(0,i).join(`
|
|
11
|
+
`));if(v){let x=ft(v.leftSegments),N=ft(v.rightSegments);return[...Array.from({length:Math.max(a,i)},(B,M)=>({left:M<a?e[M]:void 0,right:M<i?t[M]:void 0,reflow:{start:M===0,leftSegments:x[M],rightSegments:N[M]}})),...fn(e.slice(a),t.slice(i))]}}let f=e.reduce((v,x)=>v+Math.min(x.length,nr),0),p=t.reduce((v,x)=>v+Math.min(x.length,nr),0);if(f*p>Ms)return Io(e,t,!0);if(e.length===1&&t.length===1){let v=hn(e[0],t[0]);return!e[0].trim()&&!t[0].trim()||(v.eligible||v.score>=Ps)&&tr(e[0],t[0])&&or(e[0],t[0])&&Mt($e(e[0]))&&Mt($e(t[0]))?[{left:e[0],right:t[0]}]:[{left:e[0]},{right:t[0]}]}if(e.length*t.length>Fo)return Io(e,t);let m=Bs(e,t),y=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(Number.NEGATIVE_INFINITY)),b=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(null));y[0][0]=0;for(let v=1;v<=e.length;v++)y[v][0]=y[v-1][0]+cn,b[v][0]="left";for(let v=1;v<=t.length;v++)y[0][v]=y[0][v-1]+cn,b[0][v]="right";for(let v=1;v<=e.length;v++)for(let x=1;x<=t.length;x++){let N=m[v-1][x-1],M=[{move:"left",score:y[v-1][x]+cn},{move:"right",score:y[v][x-1]+cn},{move:"match",score:N===null?Number.NEGATIVE_INFINITY:y[v-1][x-1]+N}].reduce((n,F)=>F.score>n.score?F:n);y[v][x]=M.score,b[v][x]=M.move}let E=[],I=e.length,T=t.length;for(;I>0||T>0;){let v=b[I][T];v==="match"?E.push({left:e[--I],right:t[--T]}):v==="left"?E.push({left:e[--I]}):E.push({right:t[--T]})}return E.reverse()}function hn(e,t){let o=$e(e),a=$e(t),i=Mt(o),s=Mt(a);if(i&&s&&o===a)return{score:1,eligible:!0,characterSimilarity:1,tokenSimilarity:1,lengthSimilarity:1};if(!i||!s)return{score:0,eligible:!1,characterSimilarity:0,tokenSimilarity:0,lengthSimilarity:0};let l=Ot(o),f=Ot(a),p=B=>B.length<=nr?B:[0,Math.floor(B.length/2)-300,B.length-600].map(M=>B.slice(M,M+600)).join(" "),m=Js(p(o),p(a)),y=Gs(l,f),b=Math.min(o.length,a.length)/Math.max(o.length,a.length),E=Vs(l,f),I=B=>B.match(/^(?:(?:const|let|var)\s+)?([\p{L}_$][\p{L}\p{N}_$.-]*\s*(?::|=(?!=)))\s*/u)?.[1].replace(/\s+/g,""),T=I(o),v=T&&T===I(a)?.12:0,x=Math.min(1,m*.52+y*.32+b*.1+E*.06+v),N=v>0||m>=.52||y>=.45||m>=.48&&y>=.28;return{score:x,eligible:N&&x>=Rs,characterSimilarity:m,tokenSimilarity:y,lengthSimilarity:b}}function Bs(e,t){let o=e.map(v=>t.map(x=>hn(v,x))),a=Oo(e,t),i=o.map(v=>rr(v)),s=t.map((v,x)=>rr(o.map(N=>N[x]))),l=o.map((v,x)=>v.map((N,B)=>{if(a.has(`${x}:${B}`))return Math.max(N.score,1);if(!N.eligible)return null;let M=i[x],n=s[B],F=N.score===M.best&&N.score===n.best,V=N.score>=Mo?un/2:un,O=M.best-M.second>=V,j=n.best-n.second>=V;return F&&O&&j?N.score:null}));if(Math.max(e.length,t.length)>Os||Math.abs(e.length-t.length)>Qn)return l;let f=(v,x,N)=>v.score>=Do&&or(e[x],t[N])&&Math.abs(x-N)<=Qn,p=o.map((v,x)=>dn(v,(N,B)=>f(N,x,B))),m=t.map((v,x)=>dn(o.map(N=>N[x]),(N,B)=>f(N,B,x))),y=(v,x,N)=>v.score>=Fs&&or(e[x],t[N])&&Math.abs(x-N)<=Qn,b=o.map((v,x)=>dn(v,(N,B)=>y(N,x,B))),E=t.map((v,x)=>dn(o.map(N=>N[x]),(N,B)=>y(N,B,x))),I=(v,x)=>{let N=o[v][x];if(!f(N,v,x))return!1;let B=p[v],M=m[x];return N.score===B.best&&N.score===M.best&&B.best-B.second>=an&&M.best-M.second>=an},T=(v,x)=>{let N=o[v][x];if(!y(N,v,x))return!1;let B=b[v],M=E[x];return N.score===B.best&&N.score===M.best&&B.best-B.second>=an&&M.best-M.second>=an};return l.map((v,x)=>v.map((N,B)=>{if(N!==null)return N;let M=I(x,B)&&(Us(l,x,B)||zs(o,x,B,I)),n=Hs(o,x,B,(F,V)=>y(o[F][V],F,V),T);return!M&&!n?null:o[x][B].score}))}function Us(e,t,o){return t>0&&o>0&&e[t-1][o-1]!==null||t+1<e.length&&o+1<e[t+1].length&&e[t+1][o+1]!==null}function zs(e,t,o,a){return t>0&&o>0&&a(t-1,o-1)||t+1<e.length&&o+1<e[t+1].length&&a(t+1,o+1)}function Hs(e,t,o,a,i){let s=t,l=o;for(;s>0&&l>0&&a(s-1,l-1);)s--,l--;let f=t,p=o,m=e[t][o].score,y=1;for(;f+1<e.length&&p+1<e[f+1].length&&a(f+1,p+1);)f++,p++,m+=e[f][p].score,y++;for(let b=t-1,E=o-1;b>=s&&E>=l;b--,E--)m+=e[b][E].score,y++;return y>=3&&m/y>=Do&&i(s,l)&&i(f,p)}function dn(e,t){let o=Number.NEGATIVE_INFINITY,a=Number.NEGATIVE_INFINITY;return e.forEach((i,s)=>{t(i,s)&&(i.score>o?(a=o,o=i.score):i.score>a&&(a=i.score))}),{best:o,second:a}}function rr(e){let t=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let a of e)a.eligible&&(a.score>t?(o=t,t=a.score):a.score>o&&(o=a.score));return{best:t,second:o}}function Io(e,t,o=!1){let a=_s(e,t,o);if(a.length===0)return[...e.map(f=>({left:f})),...t.map(f=>({right:f}))];let i=[],s=0,l=0;for(let f of a)Ao(i,e.slice(s,f.leftIndex),t.slice(l,f.rightIndex)),i.push({left:e[f.leftIndex],right:t[f.rightIndex]}),s=f.leftIndex+1,l=f.rightIndex+1;return Ao(i,e.slice(s),t.slice(l)),i}function _s(e,t,o){let a=qs(e,t,o);if(a===null)return[];let i=Oo(e,t),s=a.map(({leftIndex:y,rightIndex:b,exact:E})=>({leftIndex:y,rightIndex:b,exact:E,structural:i.has(`${y}:${b}`),match:hn(e[y],t[b])})).filter(y=>y.exact||y.structural||y.match.eligible),l=To(s,"leftIndex"),f=To(s,"rightIndex"),p=s.filter(y=>{if(y.exact||y.structural)return!0;let b=l.get(y.leftIndex),E=f.get(y.rightIndex);if(!b||!E||y.match.score!==b.best||y.match.score!==E.best)return!1;let I=y.match.score>=Mo?un/2:un;return b.best-b.second>=I&&E.best-E.second>=I}),m=Ks(p,t.length);return m.length<=Ds?m:[]}function qs(e,t,o){let a=So(e,$e),i=So(t,$e),s=new Map;for(let[p,m]of a){let y=i.get(p);if(!Mt(p)||m.length!==1||y?.length!==1)continue;let b=m[0],E=y[0];if(s.set(`${b}:${E}`,{leftIndex:b,rightIndex:E,exact:!0}),s.size>xo)return null}if(o)return[...s.values()];let l=Co(e),f=Co(t);for(let[p,m]of l){let y=f.get(p);if(!(!y||m.length>ko||y.length>ko))for(let b of m)for(let E of y){let I=`${b}:${E}`;if(!s.has(I)&&(s.set(I,{leftIndex:b,rightIndex:E,exact:!1}),s.size>xo))return null}}return[...s.values()]}function So(e,t){let o=new Map;return e.forEach((a,i)=>{let s=t(a),l=o.get(s)??[];l.push(i),o.set(s,l)}),o}function Co(e){let t=new Map;return e.forEach((o,a)=>{let i=new Set(Ot($e(o)).filter(js));for(let s of i){let l=t.get(s)??[];l.push(a),t.set(s,l)}}),t}function js(e){return e.length>=2&&/[\p{L}\p{N}_$]/u.test(e)}function To(e,t){let o=new Map;for(let a of e){let i=o.get(a[t])??[];i.push(a.match),o.set(a[t],i)}return new Map([...o].map(([a,i])=>[a,rr(i)]))}function Ks(e,t){let o=[...e].sort((m,y)=>m.leftIndex-y.leftIndex||m.rightIndex-y.rightIndex),a=new Array(t+2).fill(0),i=new Array(t+2).fill(-1),s=new Array(o.length).fill(0),l=new Array(o.length).fill(-1);for(let m=0;m<o.length;){let y=m+1;for(;y<o.length&&o[y].leftIndex===o[m].leftIndex;)y++;for(let b=m;b<y;b++){let E=$o(a,i,o[b].rightIndex),I=o[b].exact||o[b].structural?.5:0;s[b]=E.score+o[b].match.score+I,l[b]=E.candidateIndex}for(let b=m;b<y;b++)Ws(a,i,o[b].rightIndex+1,s[b],b);m=y}let f=$o(a,i,t+1),p=[];for(let m=f.candidateIndex;m>=0;m=l[m])p.push({leftIndex:o[m].leftIndex,rightIndex:o[m].rightIndex});return p.reverse()}function $o(e,t,o){let a=0,i=-1;for(let s=o;s>0;s-=s&-s)e[s]>a&&(a=e[s],i=t[s]);return{score:a,candidateIndex:i}}function Ws(e,t,o,a,i){for(let s=o;s<e.length;s+=s&-s)a>e[s]&&(e[s]=a,t[s]=i)}function Ao(e,t,o){if(t.length*o.length<=Fo){e.push(...fn(t,o));return}e.push(...t.map(a=>({left:a}))),e.push(...o.map(a=>({right:a})))}function $e(e){return e.trim().replace(/\s+/g," ")}function Oo(e,t){let o=No(e),a=No(t),i=new Set;for(let[s,l]of o){let f=a.get(s);l.length===1&&f?.length===1&&i.add(`${l[0]}:${f[0]}`)}return i}function No(e){let t=new Map;return e.forEach((o,a)=>{let i=Dt(o);if(!i)return;let s=t.get(i)??[];s.push(a),t.set(i,s)}),t}function or(e,t){let o=Dt(e),a=Dt(t);return!o||!a?o===a:o.split(":",1)[0]===a.split(":",1)[0]}function Dt(e){let t=$e(e),o=[["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,i]of o){let s=t.match(i);if(s)return`${a}:${s[1]}`}return null}function Mt(e){return e.length<3?!1:/[\p{L}\p{N}_$]/u.test(e)&&!/^[\s()[\]{};,.:+\-*/=>|&!?'"`]+$/.test(e)}function Ot(e){return e.toLowerCase().match(/[\p{L}_$][\p{L}\p{N}_$]*|\p{N}+(?:\.\p{N}+)?|[^\s\p{L}\p{N}_$]/gu)??[]}function Gs(e,t){if(e.length+t.length===0)return 1;let o=new Map;e.forEach(i=>o.set(i,(o.get(i)??0)+1));let a=0;for(let i of t){let s=o.get(i)??0;s>0&&(a++,o.set(i,s-1))}return 2*a/(e.length+t.length)}function Vs(e,t){if(e.length===0||t.length===0)return 0;let o=e[0]===t[0]?.5:0,a=e[e.length-1]===t[t.length-1]?.5:0;return o+a}function Js(e,t){let o=e.length+t.length;return o===0?1:2*fo(e,t).filter(i=>!i.added&&!i.removed).reduce((i,s)=>i+s.value.length,0)/o}function Ys(e,t){let o=ar(e.content,t.content);if(o){e.segments=o.leftSegments,t.segments=o.rightSegments;return}let a=sr(e.content,t.content);a&&(e.segments=a.leftSegments,t.segments=a.rightSegments)}function Xs(e,t){if(!e.length||!t.length||e.length===1&&t.length===1)return;let o=y=>y.reduce((b,E)=>b+E.content.length+1,-1);if(o(e)>ln||o(t)>ln)return;let a=e.map(y=>y.content).join(`
|
|
12
|
+
`),i=t.map(y=>y.content).join(`
|
|
13
|
+
`),s=sr(a,i);if(!s)return;let{leftSegments:l,rightSegments:f}=s,p=ft(l),m=ft(f);e.forEach((y,b)=>{y.segments=p[b]}),t.forEach((y,b)=>{y.segments=m[b]})}function Lo(e){/[^\s]/.test(e.content)&&(e.segments=[{kind:e.kind,text:e.content,emphasis:!0}])}var ir=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Zs(e,t){if(e===t)return e?[{value:e}]:[];let o=Array.from(ir.segment(e),f=>f.segment),a=Array.from(ir.segment(t),f=>f.segment),i=Math.min(o.length,a.length),s=0,l=0;for(;s<i&&o[s]===a[s];)s++;for(;l<i&&o[o.length-l-1]===a[a.length-l-1];)l++;return l===i&&s<i&&(s=0),l=Math.min(l,i-s),[{value:o.slice(0,s).join("")},{value:o.slice(s,o.length-l).join(""),removed:!0},{value:a.slice(s,a.length-l).join(""),added:!0},{value:l?o.slice(-l).join(""):""}].filter(f=>f.value.length>0)}function Qs(e,t){let o=ho(e,t,{timeout:Ro,maxEditLength:2e3});if(!o)return;let a=b=>new Set([...Array.from(ir.segment(b),E=>E.index),b.length]),i=a(e),s=a(t),l=[],f=0,p=0,m="",y="";for(let b=0;b<o.length;){let E=o[b];if(!E.added&&!E.removed)m+=E.value,y+=E.value,f+=E.value.length,p+=E.value.length,b++;else for(;b<o.length&&(o[b].added||o[b].removed);){let I=o[b++];I.removed?(m+=I.value,f+=I.value.length):(y+=I.value,p+=I.value.length)}if(i.has(f)&&s.has(p)){for(let I of Zs(m,y)){let T=l[l.length-1];T&&T.added===I.added&&T.removed===I.removed?T.value+=I.value:l.push(I)}m="",y=""}}return l}function sr(e,t){if(e.length>ln||t.length>ln)return;let o=Qs(e,t);if(!o)return;let a=[],i=[],s=!1;for(let l of o){let f=l.value;if(!l.added&&!l.removed){let m={kind:"context",text:f,emphasis:!1};a.push(m),i.push(m);continue}let p=f.length>0;s=s||p,l.removed&&a.push({kind:"removed",text:f,emphasis:p}),l.added&&i.push({kind:"added",text:f,emphasis:p})}return{leftSegments:a,rightSegments:i,hasInlineChanges:s}}function ar(e,t){let o=e.split(/(\S+)/),a=t.split(/(\S+)/);if(o.length!==a.length||o.some((f,p)=>p%2===1&&f!==a[p]))return;let i=[],s=[],l=(f,p,m)=>{if(!m)return;let y=f[f.length-1];y?.kind===p?y.text+=m:f.push({kind:p,text:m,emphasis:p!=="context"})};return o.forEach((f,p)=>{let m=a[p],y=0;if(p>0)for(;y<Math.min(f.length,m.length)&&f[y]===m[y];)y++;let b=0;for(;b<Math.min(f.length,m.length)-y&&f[f.length-b-1]===m[m.length-b-1];)b++;if(p===0)for(;y<Math.min(f.length,m.length)-b&&f[y]===m[y];)y++;l(i,"context",f.slice(0,y)),l(s,"context",m.slice(0,y)),l(i,"removed",f.slice(y,f.length-b)),l(s,"added",m.slice(y,m.length-b)),l(i,"context",f.slice(f.length-b)),l(s,"context",m.slice(m.length-b))}),{leftSegments:i,rightSegments:s}}function ft(e){let t=[[]];for(let o of e)o.text.split(`
|
|
14
|
+
`).forEach((a,i)=>{i>0&&t.push([]),a&&t[t.length-1].push({...o,text:a})});return t}function ht(){return{kind:"placeholder",content:"",lineNumber:null}}function Ce(e,t,o){return{kind:e,content:t,lineNumber:o}}function Te(e,t,o){return{kind:e,content:t,lineNumber:o}}function Qe(e,t){return{left:e,right:t}}function Ft(e,t,o,a,i){return{kind:e,leftStart:t,leftEnd:o,rightStart:a,rightEnd:i}}function Bo(e,t){let o=typeof process<"u"?process.env?.[e]:void 0,a=Number.parseInt(o??"",10);return Number.isFinite(a)&&a>0?a:t}function Uo(){return{leftFileName:"test-file-1.js",rightFileName:"test-file-2.js",leftContent:`// Test File 1 - Example JavaScript Code
|
|
5
15
|
const fs = require('fs');
|
|
6
16
|
const path = require('path');
|
|
7
17
|
|
|
@@ -145,17 +155,30 @@ if (require.main === module) {
|
|
|
145
155
|
}
|
|
146
156
|
|
|
147
157
|
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,`
|
|
158
|
+
`}}function pn(e,t,o){for(let a of["opening","conclusion"]){let i=e[a];if(i===void 0)continue;if(Number(t)<5)throw new Error(`${o}.${a} requires version 5.`);if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`${o}.${a} must be an object.`);let s=i;for(let l of Object.keys(s))if(!["title","summary","bullets"].includes(l))throw new Error(`${o}.${a}.${l} is unsupported.`);for(let l of["title","summary"])cr(s[l],`${o}.${a}.${l}`);if(s.bullets!==void 0){if(!Array.isArray(s.bullets))throw new Error(`${o}.${a}.bullets must be an array.`);s.bullets.forEach((l,f)=>cr(l,`${o}.${a}.bullets[${f}]`))}}}function dr(e,t,o){if(e!==void 0){if(t<5){if(e&&typeof e=="object"&&"purpose"in e)throw new Error(`${o}.purpose requires version 5.`);return}cr(e?.purpose,`${o}.purpose`)}}function cr(e,t){if(typeof e!="string"||!e.trim())throw new Error(`${t} must be a non-empty string.`)}function ea(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ta(e){return typeof e=="string"&&e.length>0&&!/[\\\x00-\x1f:]/.test(e)&&e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function zo(e,t){if(e===void 0)return;if(!ea(e)||!ta(e.path)||typeof e.alt!="string"||!e.alt.trim()||typeof e.revision!="string"||!/^[a-f0-9]{40,64}$/.test(e.revision)||typeof e.dataUrl!="string"||!e.dataUrl.startsWith("data:image/png;base64,"))throw new Error(`${t} must contain pinned, embedded PNG evidence and alt text.`);let o=e.dataUrl.slice(22);if(o.length/4*3-(o.endsWith("==")?2:o.endsWith("=")?1:0)>8388608||o.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(o))throw new Error(`${t} must be a PNG of at most 8 MiB.`);let i=Uint8Array.from(atob(o.slice(0,44)),s=>s.charCodeAt(0));na(i,t)}function na(e,t){let o=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82];if(e.length<33||o.some((l,f)=>e[f]!==l))throw new Error(`${t} must be a PNG with an IHDR header.`);let a=new DataView(e.buffer,e.byteOffset,e.byteLength),i=a.getUint32(16),s=a.getUint32(20);if(!i||!s||i>16384||s>16384||i*s>64*1024*1024)throw new Error(`${t} exceeds the PNG dimension limit.`)}function mn(e,t){if(e!==void 0){if(!Ho(e))throw new Error(`${t} must be an object.`);_o(e,["audience"],t),ra(e.audience,`${t}.audience`)}}function ra(e,t){if(e!==void 0){if(!Ho(e))throw new Error(`${t} must be an object.`);if(_o(e,["codebase","language","domain","readingDemand","purpose","scope","estimatedMinutes"],t),typeof e.codebase!="string"||!["none","some","maintainer"].includes(e.codebase))throw new Error(`${t}.codebase must be none, some, or maintainer.`);if(typeof e.language!="string"||!["none","basic","fluent","advanced"].includes(e.language))throw new Error(`${t}.language must be none, basic, fluent, or advanced.`);if(e.domain!==void 0&&ia(e.domain,`${t}.domain`),typeof e.readingDemand!="string"||!["general","technical","specialist"].includes(e.readingDemand))throw new Error(`${t}.readingDemand must be general, technical, or specialist.`);if(typeof e.purpose!="string"||!["overview","explanation","review"].includes(e.purpose))throw new Error(`${t}.purpose must be overview, explanation, or review.`);if(oa(e.scope,`${t}.scope`),e.estimatedMinutes!==void 0&&(typeof e.estimatedMinutes!="number"||!Number.isFinite(e.estimatedMinutes)||e.estimatedMinutes<=0))throw new Error(`${t}.estimatedMinutes must be a finite positive number.`)}}function Ho(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function oa(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string.`)}function ia(e,t){if(!Array.isArray(e)||e.some(o=>typeof o!="string"||o.trim().length===0))throw new Error(`${t} must be an array of strings.`)}function _o(e,t,o){let a=Object.keys(e).filter(i=>!t.includes(i));if(a.length>0)throw new Error(`${o} contains unknown field${a.length===1?"":"s"}: ${a.join(", ")}`)}function qo(e,t){if(e!==void 0){if(!lr(e))throw new Error(`${t} must be an object.`);if(ur(e,["id","text","status","source","confidence"],t),et(e.id,`${t}.id`),et(e.text,`${t}.text`),e.status!==void 0&&!["fulfilled","gap"].includes(String(e.status)))throw new Error(`${t}.status must be fulfilled or gap.`);if(aa(e.source,`${t}.source`),e.confidence!==void 0&&!["high","medium","low"].includes(String(e.confidence)))throw new Error(`${t}.confidence must be high, medium, or low.`)}}function pt(e,t,o={}){if(e!==void 0){if(!lr(e))throw new Error(`${t} must be an object.`);if(ur(e,["kind","path","comparison","purpose"],t),e.kind!=="directory-diff")throw new Error(`${t}.kind must be directory-diff.`);if(e.purpose!==void 0&&et(e.purpose,`${t}.purpose`),e.path!==void 0&&sa(e.path,`${t}.path`),e.comparison!==void 0){if(o.allowComparison===!1)throw new Error(`${t}.comparison is not supported for walkthrough scenes; use the fixed base-to-head comparison.`);if(!lr(e.comparison))throw new Error(`${t}.comparison must be an object.`);if(ur(e.comparison,["from","to"],`${t}.comparison`),et(e.comparison.from,`${t}.comparison.from`),et(e.comparison.to,`${t}.comparison.to`),e.comparison.from===e.comparison.to)throw new Error(`${t}.comparison.from and to must identify distinct endpoints.`);if(o.endpointIds!==void 0){for(let a of[e.comparison.from,e.comparison.to])if(!o.endpointIds.includes(a))throw new Error(`${t}.comparison endpoint ${a} is not defined by this scene.`)}}}}function sa(e,t){if(et(e,t),e.includes("\\"))throw new Error(`${t} must use a relative POSIX directory path without backslashes.`);if(e.startsWith("/")||/^[A-Za-z]:/.test(e))throw new Error(`${t} must be relative to the repository root.`);if(e.split("/").some(o=>o===".."))throw new Error(`${t} must not contain parent-directory traversal.`)}function lr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function et(e,t){if(typeof e!="string"||e.length===0)throw new Error(`${t} must be a non-empty string.`)}function aa(e,t){e!==void 0&&et(e,t)}function ur(e,t,o){let a=Object.keys(e).filter(i=>!t.includes(i));if(a.length>0)throw new Error(`${o} contains unknown field${a.length===1?"":"s"}: ${a.join(", ")}`)}var fr=5;function Ko(e,t={}){if(W(e)&&Number.isInteger(e.version)&&Number(e.version)>fr)throw new Error(`This tour uses manifest format version ${e.version}, but this version of Bygone supports up to version ${fr}. Upgrade Bygone to open it.`);if(W(e)&&e.version===3)throw new Error("Tour manifest format version 3 is retired. Remove the review block, set source version to 4, and recompile the tour.");if(!W(e)||e.version!==1&&e.version!==2&&e.version!==4&&e.version!==fr)throw new Error("Unsupported or missing change-tour manifest version.");if("review"in e)throw new Error("Change-tour manifests do not support the review field. Put observations in scene and step narrative.");if(pn(e,e.version,"manifest"),G(e.title,"title"),G(e.generatedAt,"generatedAt"),e.windowTitle!==void 0&&G(e.windowTitle,"windowTitle"),e.sourceUrl!==void 0&&G(e.sourceUrl,"sourceUrl"),!W(e.range))throw new Error("Change-tour manifest range must be an object.");for(let i of["baseRef","headRef","mergeBaseOid","headOid"])G(e.range[i],`range.${i}`);if(!W(e.summary))throw new Error("Change-tour manifest summary must be an object.");for(let i of["changedFiles","includedScenes","additions","deletions","commitCount"])ce(e.summary[i],`summary.${i}`);if(gt(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 o=new Set;for(let[i,s]of e.scenes.entries()){if(mt(s,i,e.version),o.has(s.id))throw new Error(`Duplicate change-tour scene id: ${s.id}`);o.add(s.id)}for(let[i,s]of e.chapters.entries()){if(!W(s))throw new Error(`chapters[${i}] must be an object.`);G(s.id,`chapters[${i}].id`),G(s.title,`chapters[${i}].title`),pr(s.summary,e.version,`chapters[${i}].summary`),gt(s.sceneIds,`chapters[${i}].sceneIds`);for(let l of s.sceneIds)if(!o.has(l))throw new Error(`Chapter references unknown scene id: ${l}`)}if(e.summary.includedScenes!==e.scenes.length)throw new Error("summary.includedScenes must match the number of scenes.");if(e.details!==void 0){if(e.version!==5)throw new Error("details requires manifest version 5.");mn(e.details,"details")}let a=e.files===void 0?pa(e.scenes):e.files.map((i,s)=>(ha(i,s),i));if(e.files!==void 0&&e.summary.changedFiles!==a.length)throw new Error("summary.changedFiles must match the number of files.");if(e.authoringCoverage!==void 0&&ca(e.authoringCoverage,e.version),e.tours!==void 0){if(e.version!==4&&e.version!==5)throw new Error("Independent tours require manifest version 4.");da(e.tours,e.version)}return e.version!==1&&la(e,e.version,!!t.exported),{...e,files:a}}function ca(e,t){if(!W(e)||!W(e.walkthrough)||!Array.isArray(e.explanationAssignments))throw new Error("authoringCoverage must contain walkthrough and explanationAssignments.");let o=t>=2?"final":"tour";if(e.walkthrough.scope!==o)throw new Error(`authoringCoverage.walkthrough.scope must be ${o}.`);if(ce(e.walkthrough.coveredUnits,"authoringCoverage.walkthrough.coveredUnits"),ce(e.walkthrough.includedUnits,"authoringCoverage.walkthrough.includedUnits"),jo(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,i]of e.explanationAssignments.entries()){let s=`authoringCoverage.explanationAssignments[${a}]`;if(!W(i))throw new Error(`${s} must be an object.`);if(G(i.sceneId,`${s}.sceneId`),ce(i.assignedUnits,`${s}.assignedUnits`),ce(i.excludedUnits,`${s}.excludedUnits`),ce(i.completeUnits,`${s}.completeUnits`),ce(i.totalUnits,`${s}.totalUnits`),jo(i.assignmentPercent,`${s}.assignmentPercent`),i.assignedUnits+i.excludedUnits!==i.completeUnits||i.completeUnits>i.totalUnits)throw new Error(`${s} contains inconsistent unit counts.`)}}function da(e,t){if(!W(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 o of["historical","deconstructed"]){let a=e[o];if(a===void 0)continue;if(!W(a)||!Array.isArray(a.chapters)||!Array.isArray(a.scenes)||a.chapters.length===0||a.scenes.length===0)throw new Error(`Change-tour manifest tours.${o} must contain non-empty chapters and scenes arrays.`);pn(a,t,`tours.${o}`);let i=new Set,s=!1;for(let[l,f]of a.scenes.entries()){if(mt(f,l,t),i.has(f.id))throw new Error(`Duplicate ${o} tour scene id: ${f.id}`);if(i.add(f.id),f.kind==="deconstructed-diff"&&(s=!0),o==="historical"&&f.kind==="deconstructed-diff")throw new Error("Historical tours cannot contain synthetic deconstructed scenes.")}if(a.details!==void 0){if(t!==5)throw new Error(`tours.${o}.details requires manifest version 5.`);mn(a.details,`tours.${o}.details`)}if(o==="deconstructed"&&!s)throw new Error("Deconstructed tours must contain a constructed deconstructed-diff scene.");for(let[l,f]of a.chapters.entries()){if(!W(f))throw new Error(`tours.${o}.chapters[${l}] must be an object.`);G(f.id,`tours.${o}.chapters[${l}].id`),G(f.title,`tours.${o}.chapters[${l}].title`),pr(f.summary,t,`tours.${o}.chapters[${l}].summary`),gt(f.sceneIds,`tours.${o}.chapters[${l}].sceneIds`);for(let p of f.sceneIds)if(!i.has(p))throw new Error(`tours.${o} chapter references unknown scene id: ${p}`)}}}function la(e,t,o){if(!o&&(!W(e.repository)||typeof e.repository.root!="string"||!e.repository.root))throw new Error("A v2 tour requires its originating repository.root.");if(!W(e.zoom)||!Array.isArray(e.zoom.revisions)||!W(e.zoom.final))throw new Error("A v2 tour requires zoom metadata and real revision evidence.");let a=e.scenes,i=e.zoom.revisions,s=new Set;for(let[b,E]of i.entries()){if(mt(E,b,t),E.kind!=="stacked-diff")throw new Error("zoom.revisions must contain real stacked-diff scenes.");if(s.has(E.id))throw new Error(`Duplicate zoom revision scene: ${E.id}`);s.add(E.id);let I=e.range;if(E.stack[0].oid!==I.mergeBaseOid||E.stack[E.stack.length-1].oid!==I.headOid)throw new Error(`Revision scene ${E.id} endpoints must match the final diff range.`)}for(let b of a){if(b.kind!=="deconstructed-diff"&&b.kind!=="stacked-diff")continue;let E=i.find(I=>I.id===b.id);if(!E)throw new Error(`Scene ${b.id} is missing its real revision evidence.`);if(b.kind==="deconstructed-diff"&&(E.stack[0].oid!==b.realRange.baseOid||E.stack[E.stack.length-1].oid!==b.realRange.targetOid))throw new Error(`Deconstructed scene ${b.id} real stack endpoints must match its explanation range.`)}let l=a.some(b=>b.kind==="deconstructed-diff"),f=i.some(b=>b.stack.length>2),p=l?"explanation":f?"revisions":"final",m=[...l?["explanation"]:[],...f?["revisions"]:[],"final","history"];if(e.zoom.authoredDepth!==p||JSON.stringify(e.zoom.modes)!==JSON.stringify(m))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 y=new Set;for(let[b,E]of e.zoom.final.scenes.entries()){if(mt(E,b,t),E.kind==="stacked-diff"||E.kind==="deconstructed-diff")throw new Error("zoom.final must contain only non-stacked scenes.");if(y.has(E.id))throw new Error(`Duplicate final tour scene: ${E.id}`);y.add(E.id)}for(let[b,E]of e.zoom.final.chapters.entries()){if(!W(E)||!Array.isArray(E.sceneIds))throw new Error(`zoom.final.chapters[${b}] must contain sceneIds.`);G(E.id,`zoom.final.chapters[${b}].id`),G(E.title,`zoom.final.chapters[${b}].title`),pr(E.summary,t,`zoom.final.chapters[${b}].summary`);for(let I of E.sceneIds)if(G(I,`zoom.final.chapters[${b}].sceneIds`),!y.has(I))throw new Error(`Final tour chapter references unknown scene: ${I}`)}}function mt(e,t,o){if(!W(e)||!["text-diff","discussion","walkthrough","stacked-diff","deconstructed-diff"].includes(String(e.kind)))throw new Error(`scenes[${t}] must be a text-diff, discussion, walkthrough, stacked-diff, or deconstructed-diff scene.`);for(let a of["id","title"])G(e[a],`scenes[${t}].${a}`);if(e.overview!==void 0&&o<4)throw new Error(`scenes[${t}].overview requires manifest version 4.`);if(dr(e.overview,o,`scenes[${t}].overview`),ma(e,`scenes[${t}]`),e.kind==="discussion"){pt(e.overview,`scenes[${t}].overview`,{allowComparison:!1});return}if(e.kind==="walkthrough"){if(pt(e.overview,`scenes[${t}].overview`,{allowComparison:!1}),!Array.isArray(e.steps)||e.steps.length===0)throw new Error(`scenes[${t}].steps must be a non-empty array.`);for(let[a,i]of e.steps.entries()){let s=`scenes[${t}].steps[${a}]`;if(!W(i)||!W(i.focus)||!W(i.diff))throw new Error(`${s} must contain focus and diff objects.`);for(let l of["id","title","body"])G(i[l],`${s}.${l}`);if(i.depth!==void 0&&!["mentioned","explained","contextualized"].includes(String(i.depth)))throw new Error(`${s}.depth must be mentioned, explained, or contextualized.`);if(qo(i.requirement,`${s}.requirement`),zo(i.image,`${s}.image`),hr(i.focus,`${s}.focus`),mt(i.diff,t,o),i.diff.kind!=="text-diff")throw new Error(`${s}.diff must be a text-diff scene.`);if(i.connection!==void 0){if(!W(i.connection))throw new Error(`${s}.connection must be an object.`);G(i.connection.id,`${s}.connection.id`),G(i.connection.label,`${s}.connection.label`),hr(i.connection.from,`${s}.connection.from`),hr(i.connection.to,`${s}.connection.to`)}}return}if(e.kind==="stacked-diff"){ua(e,t),pt(e.overview,`scenes[${t}].overview`,{endpointIds:e.stack.map(a=>a.id)});return}if(e.kind==="deconstructed-diff"){fa(e,t),pt(e.overview,`scenes[${t}].overview`,{endpointIds:e.panels.map(a=>a.id)});return}pt(e.overview,`scenes[${t}].overview`,{allowComparison:!1});for(let a of["path","leftLabel","rightLabel","leftContent","rightContent"])G(e[a],`scenes[${t}].${a}`);e.previousPath!==void 0&&G(e.previousPath,`scenes[${t}].previousPath`),G(e.changeKind,`scenes[${t}].changeKind`),ce(e.additions,`scenes[${t}].additions`),ce(e.deletions,`scenes[${t}].deletions`),e.focusChangeIndex!==void 0&&ce(e.focusChangeIndex,`scenes[${t}].focusChangeIndex`)}function ua(e,t){if(!Array.isArray(e.stack)||e.stack.length<2||e.stack.length>6)throw new Error(`scenes[${t}].stack must contain between 2 and 6 revisions.`);for(let[o,a]of e.stack.entries()){if(!W(a))throw new Error(`scenes[${t}].stack[${o}] must be an object.`);for(let i of["id","ref","oid","label"])G(a[i],`scenes[${t}].stack[${o}].${i}`)}Wo(e.files,e.stack.length,t),Go(e.steps,e.stack.length,t,!1)}function fa(e,t){if(e.stageLabel!=="Explanation stages")throw new Error(`scenes[${t}].stageLabel must be Explanation stages.`);if(!W(e.realRange))throw new Error(`scenes[${t}].realRange must be an object.`);for(let a of["baseRef","targetRef","baseOid","targetOid"])G(e.realRange[a],`scenes[${t}].realRange.${a}`);if(!Array.isArray(e.panels)||e.panels.length<2||e.panels.length>13)throw new Error(`scenes[${t}].panels must contain a baseline and between 1 and 12 stages.`);let o=e.panels;for(let[a,i]of o.entries()){if(!W(i))throw new Error(`scenes[${t}].panels[${a}] must be an object.`);for(let l of["id","label","role"])G(i[l],`scenes[${t}].panels[${a}].${l}`);let s=a===0?"baseline":"stage";if(i.role!==s)throw new Error(`scenes[${t}].panels[${a}].role must be ${s}.`);a>0&&G(i.stageId,`scenes[${t}].panels[${a}].stageId`)}if(Wo(e.files,o.length,t),Go(e.steps,o.length,t,!0),Array.isArray(e.steps)){let a=-1;e.steps.forEach((i,s)=>{if(!W(i))return;let l=Number(i.pairIndex);if(l<a)throw new Error(`scenes[${t}].steps must remain grouped in explanation stage order.`);if(a=l,i.stageId!==void 0&&G(i.stageId,`scenes[${t}].steps[${s}].stageId`),i.stageIndex!==void 0&&ce(i.stageIndex,`scenes[${t}].steps[${s}].stageIndex`),i.focusIndex!==void 0&&ce(i.focusIndex,`scenes[${t}].steps[${s}].focusIndex`),i.focusCount!==void 0&&Bt(i.focusCount,`scenes[${t}].steps[${s}].focusCount`),i.stageIndex!==void 0&&Number(i.stageIndex)!==l)throw new Error(`scenes[${t}].steps[${s}].stageIndex must match pairIndex.`);if(i.focusIndex!==void 0&&i.focusCount!==void 0&&Number(i.focusIndex)>=Number(i.focusCount))throw new Error(`scenes[${t}].steps[${s}].focusIndex must be less than focusCount.`)});for(let i=0;i<o.length-1;i+=1){let s=o[i+1],l=e.steps.filter(m=>W(m)&&Number(m.pairIndex)===i);if(!W(s)||l.length===0)throw new Error(`scenes[${t}].steps must cover every explanation stage.`);let f=l[0],p=W(f)?f.id:void 0;if(l.some(m=>W(m)?(m.stageId??p)!==s.stageId:!0))throw new Error(`scenes[${t}].panels must align with explanation stage ids.`)}}}function Wo(e,t,o){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${o}].files must be non-empty.`);for(let[a,i]of e.entries()){if(!W(i))throw new Error(`scenes[${o}].files[${a}] must be an object.`);if(G(i.path,`scenes[${o}].files[${a}].path`),!Array.isArray(i.panels)||i.panels.length!==t)throw new Error(`scenes[${o}].files[${a}].panels must match panel count.`);for(let[s,l]of i.panels.entries()){if(!W(l))throw new Error(`scenes[${o}].files[${a}].panels[${s}] must be an object.`);for(let f of["id","label","content"])G(l[f],`scenes[${o}].files[${a}].panels[${s}].${f}`);if(l.path!==void 0&&G(l.path,`scenes[${o}].files[${a}].panels[${s}].path`),typeof l.exists!="boolean")throw new Error(`scenes[${o}].files[${a}].panels[${s}].exists must be boolean.`)}}}function Go(e,t,o,a){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${o}].steps must be non-empty.`);for(let[i,s]of e.entries()){if(!W(s))throw new Error(`scenes[${o}].steps[${i}] must be an object.`);for(let l of["id","title","body","file","side"])G(s[l],`scenes[${o}].steps[${i}].${l}`);if(ce(s.pairIndex,`scenes[${o}].steps[${i}].pairIndex`),Number(s.pairIndex)>=t-1)throw new Error(`scenes[${o}].steps[${i}].pairIndex is outside the panels.`);if(a&&(gt(s.introducedHunks,`scenes[${o}].steps[${i}].introducedHunks`),s.introducedHunks.length===0))throw new Error(`scenes[${o}].steps[${i}].introducedHunks must be non-empty.`);if(s.side!=="left"&&s.side!=="right")throw new Error(`scenes[${o}].steps[${i}].side must be left or right.`);s.startLine!==void 0&&Bt(s.startLine,`scenes[${o}].steps[${i}].startLine`),s.endLine!==void 0&&Bt(s.endLine,`scenes[${o}].steps[${i}].endLine`)}}function ha(e,t){if(!W(e))throw new Error(`files[${t}] must be an object.`);if(e.kind==="text-diff"){mt(e,t,1);return}if(e.kind!=="omitted")throw new Error(`files[${t}].kind must be text-diff or omitted.`);for(let o of["id","title","path","changeKind","reason"])G(e[o],`files[${t}].${o}`);e.previousPath!==void 0&&G(e.previousPath,`files[${t}].previousPath`),ce(e.additions,`files[${t}].additions`),ce(e.deletions,`files[${t}].deletions`)}function pa(e){let t=new Map;for(let o of e){if(o.kind==="text-diff"){t.has(o.path)||t.set(o.path,o);continue}if(o.kind==="walkthrough")for(let a of o.steps)t.has(a.diff.path)||t.set(a.diff.path,a.diff)}return[...t.values()].sort((o,a)=>o.path.localeCompare(a.path))}function hr(e,t){if(!W(e))throw new Error(`${t} must be an object.`);for(let o of["id","path","revision","excerpt"])G(e[o],`${t}.${o}`);if(e.revision!=="base"&&e.revision!=="head")throw new Error(`${t}.revision must be base or head.`);if(Bt(e.startLine,`${t}.startLine`),Bt(e.endLine,`${t}.endLine`),Number(e.endLine)<Number(e.startLine))throw new Error(`${t}.endLine must not precede startLine.`)}function ma(e,t){G(e.summary,`${t}.summary`),gt(e.bullets,`${t}.bullets`),gt(e.tags,`${t}.tags`),G(e.takeaway,`${t}.takeaway`)}function pr(e,t,o){if(e!==void 0){if(t<5)throw new Error(`${o} requires manifest version 5.`);if(typeof e!="string"||!e.trim())throw new Error(`${o} must be a non-empty string.`)}}function W(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function G(e,t){if(typeof e!="string")throw new Error(`${t} must be a string.`)}function gt(e,t){if(!Array.isArray(e)||e.some(o=>typeof o!="string"))throw new Error(`${t} must be an array of strings.`)}function ce(e,t){if(!Number.isInteger(e)||Number(e)<0)throw new Error(`${t} must be a non-negative integer.`)}function jo(e,t){if(typeof e!="number"||!Number.isFinite(e)||e<0||e>100)throw new Error(`${t} must be a number from 0 to 100.`)}function Bt(e,t){if(!Number.isInteger(e)||Number(e)<1)throw new Error(`${t} must be a positive integer.`)}var ga=new Set(["modified-here","created-here","deleted-here"]);function mr(e,t){let o=e.panels[t],a=e.panels[t+1];return!o||!a?"unchanged-here":o.exists&&a.exists?o.content===a.content?"unchanged-here":"modified-here":!o.exists&&a.exists?"created-here":o.exists&&!a.exists?"deleted-here":e.panels.slice(0,t).some(l=>l.exists)?"already-deleted":(e.panels.slice(t+2).some(l=>l.exists),"not-created-yet")}function Vo(e,t,o,a){let i=new Set(e.filter(l=>ga.has(mr(l,t))).map(l=>l.path)),s=We({paths:e.map(l=>l.path),currentPath:o,changedPaths:i},a);return s?{pairIndex:t,fileIndex:e.findIndex(l=>l.path===s),path:s}:null}function gr(e,t,o){let a=e.findIndex(f=>f.id===t),i=a>=0?a:0,s=e[i];if(!s||s.kind!=="walkthrough"&&s.kind!=="stacked-diff"&&s.kind!=="deconstructed-diff"||!o)return{sceneIndex:i,stepIndex:0};let l=s.steps.findIndex(f=>f.id===o);return{sceneIndex:i,stepIndex:l>=0?l:0}}function Jo(e,t,o){let a=We({paths:e.filter(i=>i.kind==="text-diff").map(i=>i.path),currentPath:t},o);return a?{fileIndex:e.findIndex(i=>i.path===a),path:a}:null}var Zo=240;function Qo(e,t,o){let a=[],i=(l,f,p)=>{f&&a.push({source:{field:l,...p===void 0?{}:{itemIndex:p}},text:f})},s=l=>{l.forEach(f=>{i("route-title",f.title,f.sceneIndex)})};if(t.kind==="title"||t.kind==="conclusion"){let l=t.kind==="title"?e.opening:e.conclusion;if(t.kind==="title"&&i("document-title",e.title),i("passage-title",l?.title),i("summary",l?.summary),l?.bullets?.forEach((f,p)=>i("bullet",f,p)),t.kind==="title"){let f=Rt(e);f.chapters.forEach(p=>{i("route-chapter",p.title,p.chapterIndex)}),f.chapters.length||s(f.scenes)}}else if(t.kind==="chapter"){let l=Rt(e).chapters.find(f=>f.chapterId===t.chapterId);i("chapter",l.title),i("summary",l.summary)}else{let l=e.scenes[t.sceneIndex];if(t.kind==="scene")i("scene-title",Fe(e,{kind:"scene",key:`scene:${l.id}`,sceneIndex:t.sceneIndex,stepIndex:0})),i("summary",l.summary),l.bullets.forEach((f,p)=>i("bullet",f,p)),Xo(l)||i("takeaway",l.takeaway),"overview"in l&&i("overview-purpose",l.overview?.purpose);else if(Xo(l)){let f=l.steps[t.stepIndex];o.entry==="playback-start"&&i("scene-title",Fe(e,{kind:"scene",key:`scene:${l.id}`,sceneIndex:t.sceneIndex,stepIndex:0})),o.entry==="playback-start"&&l.kind==="deconstructed-diff"&&!f.body&&i("stage-title",l.panels[l.steps[t.stepIndex].pairIndex+1].label),i("step-title",Fe(e,t)),i("step-orientation",tn(e,t.sceneIndex,t.stepIndex)),i("step-body",f.body),"connection"in f&&i("connection",f.connection?.label),t.stepIndex===l.steps.length-1&&i("takeaway",l.takeaway)}}return{id:t.key,readingKey:t.key,segments:a.flatMap(l=>ba(t.key,l,o.segmentLimit??Zo))}}function ya(e,t=Zo){if(!Number.isInteger(t)||t<40)throw new Error("Narration segment limit must be an integer of at least 40 characters.");return va(e).flatMap(a=>xa(e,a.startOffset,a.endOffset,t))}function wa(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 ba(e,t,o){let a=t.source.itemIndex===void 0?t.source.field:`${t.source.field}-${t.source.itemIndex}`;return ya(t.text,o).map((i,s)=>({id:`${e}:${a}:${s}`,text:i.text,speechText:wa(i.text),source:t.source,startOffset:i.startOffset,endOffset:i.endOffset})).filter(i=>i.speechText.length>0)}function va(e){let t=[],o=0;for(let a=0;a<e.length;a+=1){if(!".!?".includes(e[a]))continue;let i=a+1;for(;i<e.length&&`"'\u201D\u2019)]}`.includes(e[i]);)i+=1;i<e.length&&!/\s/u.test(e[i])||(gn(e,t,o,i),o=i)}return gn(e,t,o,e.length),t}function xa(e,t,o,a){let i=[],s=t;for(;o-s>a;){let l=s+a,f=s+Math.floor(a*.55),p=Yo(e,f,l,/[;,:—–-]/u);p<=s&&(p=Yo(e,f,l,/\s/u)),p<=s&&(p=l),gn(e,i,s,p),s=p}return gn(e,i,s,o),i}function Yo(e,t,o,a){for(let i=o;i>=t;i-=1)if(a.test(e[i]))return i+1;return-1}function gn(e,t,o,a){let i=o,s=a;for(;i<s&&/\s/u.test(e[i]);)i+=1;for(;s>i&&/\s/u.test(e[s-1]);)s-=1;i<s&&t.push({text:e.slice(i,s),startOffset:i,endOffset:s})}function Xo(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function ei(e){let t=[{kind:"title",key:"title",sceneIndex:0,stepIndex:0,...e.opening?{authored:!0}:{}}],o=new Map;for(let i of e.chapters)for(let s of i.sceneIds)o.has(s)||o.set(s,i.id);let a=new Set;return e.scenes.forEach((i,s)=>{let l=o.get(i.id);e.chapters.find(p=>p.id===l)?.summary?.trim()&&l&&!a.has(l)&&(t.push({kind:"chapter",key:`chapter:${l}`,chapterId:l,sceneIndex:s,stepIndex:0}),a.add(l)),t.push({kind:"scene",key:`scene:${i.id}`,...l?{chapterId:l}:{},sceneIndex:s,stepIndex:0}),ka(i)&&i.steps.forEach((p,m)=>{t.push({kind:"step",key:`step:${i.id}:${p.id}`,sceneIndex:s,stepIndex:m})})}),e.conclusion&&t.push({kind:"conclusion",key:"conclusion",sceneIndex:-1,stepIndex:0}),t}function Ut(e,t,o,a=!1){if(o!==-1&&o!==1)return null;let i=e.findIndex(s=>s.key===t);if(i<0)return null;for(let s=i+o;s>=0&&s<e.length;s+=o){let l=e[s];if(!a||l.kind==="step"||l.kind==="conclusion"||l.kind==="title")return l}return null}function tt(e){return e.scenes.length>0&&e.scenes.every(t=>t.kind==="walkthrough"&&t.steps.length>0&&t.steps.every(o=>!!o.image))}function yn(e,t,o,a=null){if(a==="conclusion")return e.find(s=>s.kind==="conclusion")??null;if(a==="tour")return e.find(s=>s.kind==="title")??null;let i=e.findIndex(s=>s.kind==="scene"&&s.sceneIndex===t);if(i<0)return null;if(a==="overview")return e[i]??null;if(a==="chapter"){let s=e[i];return s.kind!=="scene"?null:e.find(l=>l.kind==="chapter"&&l.chapterId===s.chapterId)??s}return e.find(s=>s.kind==="step"&&s.sceneIndex===t&&s.stepIndex===o)??e[i]??null}function ka(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}var wn=class{constructor(t,o){this.engine=t;this.callbacks=o;this.generation=0;this.continuous=!0;this.currentState={kind:"idle"}}get state(){return this.currentState}get engaged(){return this.currentState.kind==="playing"||this.currentState.kind==="paused"}start(t,o=!0){if(this.resetEngine(),this.continuous=o,t.segments.length===0){this.finishUnit(t);return}this.callbacks.claimAudio(),this.setState({kind:"playing",unit:t,segmentIndex:0}),this.speakCurrent()}togglePause(){if(this.currentState.kind==="playing"){this.engine.pause();let o={kind:"paused",unit:this.currentState.unit,segmentIndex:this.currentState.segmentIndex,pendingStart:!1};this.setState(o),this.callbacks.onSegmentChange(o.unit.segments[o.segmentIndex]||null,!0);return}if(this.currentState.kind!=="paused")return;this.callbacks.claimAudio();let t=this.currentState;this.setState({kind:"playing",unit:t.unit,segmentIndex:t.segmentIndex}),t.pendingStart?this.speakCurrent():(this.engine.resume(),this.callbacks.onSegmentChange(t.unit.segments[t.segmentIndex]||null,!1))}stop(){this.resetEngine(),this.setState({kind:"idle"}),this.callbacks.onSegmentChange(null,!1)}pauseForExternalOwner(){this.currentState.kind==="playing"&&this.togglePause()}canSkipSegment(t){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return!1;let o=this.currentState.segmentIndex+t;return o>=0&&o<this.currentState.unit.segments.length?!0:this.callbacks.canNavigateUnit(this.currentState.unit,t)}skipSegment(t){if(!this.canSkipSegment(t))return!1;let o=this.currentState,a=o.kind==="paused",i=o.unit,s=o.segmentIndex+t;if(s<0||s>=i.segments.length){let l=this.callbacks.navigateUnit(i,t);if(!l||l.segments.length===0)return!1;i=l,s=t<0?i.segments.length-1:0}return this.resetEngine(),a?(this.setState({kind:"paused",unit:i,segmentIndex:s,pendingStart:!0}),this.callbacks.onSegmentChange(i.segments[s]||null,!0)):(this.setState({kind:"playing",unit:i,segmentIndex:s}),this.speakCurrent()),!0}followLinearNavigation(t){this.currentState.kind==="playing"?this.start(t,this.continuous):this.currentState.kind==="paused"&&this.preparePaused(t)}followDirectNavigation(t){this.engaged&&this.preparePaused(t)}interruptForExploration(){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return;let t=this.currentState;this.resetEngine(),this.setState({kind:"paused",unit:t.unit,segmentIndex:t.segmentIndex,pendingStart:!0}),this.callbacks.onSegmentChange(t.unit.segments[t.segmentIndex]||null,!0)}dispose(){this.stop()}preparePaused(t){this.resetEngine(),this.setState({kind:"paused",unit:t,segmentIndex:0,pendingStart:!0}),this.callbacks.onSegmentChange(t.segments[0]||null,!0)}speakCurrent(){if(this.currentState.kind!=="playing")return;let t=this.generation,o=this.currentState.unit.segments[this.currentState.segmentIndex];if(!o){this.finishUnit(this.currentState.unit);return}this.callbacks.onSegmentChange(o,!1),this.engine.speak(o,{onEnd:()=>{if(t!==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=>{t===this.generation&&(this.setState({kind:"error",message:a}),this.callbacks.onSegmentChange(null,!1))}})}finishUnit(t){if(this.continuous){let o=this.callbacks.navigateUnit(t,1);if(o){if(this.generation+=1,o.segments.length===0){this.finishUnit(o);return}this.setState({kind:"playing",unit:o,segmentIndex:0}),this.speakCurrent();return}}this.setState({kind:"completed"}),this.callbacks.onSegmentChange(null,!1)}resetEngine(){this.generation+=1,this.engine.cancel()}setState(t){this.currentState=t,this.callbacks.onStateChange(t)}};function ti(e,t,o="all",a=300){let i=t.trim().toLocaleLowerCase();if(!i||a<=0)return[];let s=[];if(o!=="code"){for(let[f,p]of[["title",e.opening],["conclusion",e.conclusion]]){let m=p&&yr([p.title,p.summary,...p.bullets||[]],i);m&&p&&s.push({kind:"narrative",sceneIndex:f==="title"?0:-1,readingKey:f,label:p.title,preview:m})}let l=new Map;for(let f of e.chapters){let p=e.scenes.findIndex(m=>f.sceneIds.includes(m.id));p>=0&&f.summary?.toLocaleLowerCase().includes(i)&&s.push({kind:"narrative",sceneIndex:p,readingKey:`chapter:${f.id}`,label:f.title,preview:f.summary})}e.chapters.forEach(f=>f.sceneIds.forEach(p=>l.set(p,f.title))),e.scenes.forEach((f,p)=>{let m=[l.get(f.id),f.title,f.summary,"overview"in f?f.overview?.purpose:void 0,...f.bullets,...f.tags,f.takeaway],y=yr(m,i);y&&s.push({kind:"narrative",sceneIndex:p,label:f.title,preview:y}),Ia(f)&&f.steps.forEach((b,E)=>{let I=yr([b.title,b.body,"connection"in b?b.connection?.label:void 0],i);I&&s.push({kind:"narrative",sceneIndex:p,stepIndex:E,label:`${f.title} \xB7 ${b.title}`,preview:I})})})}if(o!=="narrative"&&s.length<a)for(let l=0;l<e.files.length;l+=1){let f=e.files[l];if(f.kind==="text-diff"){for(let[p,m]of[[0,f.leftContent],[1,f.rightContent]])for(let y of Ea(m,i))if(s.push({kind:"code",fileIndex:l,sideIndex:p,label:`${f.path} \xB7 ${p===0?"base":"head"}`,...y}),s.length>=a)return s}}return s.slice(0,a)}function yr(e,t){return e.find(o=>o?.toLocaleLowerCase().includes(t))}function Ea(e,t){let o=[];return e.replace(/\r\n/g,`
|
|
149
159
|
`).split(`
|
|
150
|
-
`).forEach((a,
|
|
151
|
-
`)}function
|
|
160
|
+
`).forEach((a,i)=>{let s=a.toLocaleLowerCase(),l=0;for(;l<=s.length-t.length;){let f=s.indexOf(t,l);if(f<0)break;o.push({lineNumber:i+1,startColumn:f+1,endColumn:f+t.length+1,preview:a}),l=f+Math.max(t.length,1)}}),o}function Ia(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function wr(e,t){return Sa(e,0,t)}function Sa(e,t,o){let a=e?.blocks[t],i=o==="left"?e?.leftLines:e?.rightLines;if(!a||!i?.length)return;let s=o==="left"?a.leftStart:a.rightStart,l=o==="left"?a.leftEnd:a.rightEnd,f=i.slice(s,l),p=f[0]?.lineNumber??i[Math.min(s,i.length-1)]?.lineNumber;if(Number.isInteger(p))return{startLine:p,endLine:f.at(-1)?.lineNumber??p}}function ni(e,t,o,a){let i=[];return e.scenes.forEach((s,l)=>{s.kind==="walkthrough"&&s.steps.forEach((f,p)=>{f.diff.path===t&&i.push({side:f.focus.revision==="base"?"left":"right",startLine:f.focus.startLine,endLine:f.focus.endLine,label:`${s.title} \xB7 ${f.title}: ${f.body}`,active:l===o&&p===a,jumpTarget:{sceneIndex:l,stepIndex:p}})})}),i}function ri(e,t,o,a,i){let s=[];return e.scenes.forEach((l,f)=>{f!==o||l.kind!=="stacked-diff"&&l.kind!=="deconstructed-diff"||l.steps.forEach((p,m)=>{if(p.file!==t)return;let y=p.startLine===void 0?i?.(p.pairIndex,p.side):{startLine:p.startLine,endLine:p.endLine??p.startLine};if(!y)return;let b=p.pairIndex+(p.side==="right"?1:0);s.push({pairIndex:p.pairIndex,panelIndex:b,side:p.side,startLine:y.startLine,endLine:y.endLine,label:`${l.title} \xB7 ${p.title}: ${p.body}`,active:f===o&&m===a,jumpTarget:{sceneIndex:f,stepIndex:m}})})}),s}function Ca(e,t=120){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function oi(e,t="Bygone"){let o=e?.windowTitle?.trim()||e?.title?.trim();return o?Ca(o):`${t} Tour`}function Ta(){return{sceneIndex:0,stepIndex:0,path:null}}var bn=class{constructor(t){this.mode=t;this.cursors=new Map}depart(t){return this.cursors.set(this.mode,t),t}enter(t,o){this.mode=t;let a=this.cursors.get(t);return a?{location:a,restore:!0}:{location:o??Ta(),restore:!1}}};function ii(e,t){let o=new Map;for(let l of t)o.has(l)||o.set(l,o.size);let a=e?.commits,i=Array.isArray(a)?a:[e?.from,e?.to],s=[...new Set(i.filter(l=>typeof l=="string"&&o.has(l)))];if(s.length<2)throw new Error("Select at least two revisions to compare.");return s.sort((l,f)=>o.get(l)-o.get(f)),{commits:s,...typeof e?.path=="string"&&e.path?{path:e.path}:{}}}var $a=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i,Aa="bygone-tour-skill.md";function ai(e,t={},o={}){let a=e==="deconstructed"?"deconstructed":"historical",i=br(t.repository),s=si(t.paths),f=i!==void 0&&Array.isArray(t.paths)&&t.paths.length===0?["."]:s.length>0?s:null,p=si(t.revisions),m=Na(i,p,t.rangeStatus),y=t.rangeStatus||"unavailable",b=[La(o),`Create a v5 ${a} tour.`,`Repository: ${JSON.stringify(i??null)}`,`Selected paths: ${JSON.stringify(f)}`,`Base: ${JSON.stringify(m?p[0]:null)}`,`Head: ${JSON.stringify(m?p[1]:null)}`,"Additional context: (optional)"];return m||b.push(`Warning: range status ${JSON.stringify(y)} 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(p)}`),b.join(`
|
|
161
|
+
`)}function Na(e,t,o){return o==="exact"&&!!e&&t.length===2&&t.every(a=>$a.test(a))}function La(e){let t=br(e.path);if(t)return`Read and follow the Bygone tour skill at ${JSON.stringify(t)}.`;let o=br(e.name)||Aa;return`Read and follow the Bygone tour skill in attached ${JSON.stringify(o)}.`}function si(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").filter(t=>t.length>0):[]}function br(e){return typeof e=="string"&&e.trim().length>0?e:void 0}var ci=`---
|
|
152
162
|
name: pr-tour-guide
|
|
153
|
-
description:
|
|
163
|
+
description: Create, repair, validate, and present Bygone code-change tours grounded in Git evidence. Use for requested guided walkthroughs of commits, branches, or pull requests, .bygone tour documents, and Bygone tour context extraction. General review preparation or documentation work does not require a tour.
|
|
154
164
|
---
|
|
155
165
|
|
|
156
166
|
# PR Tour Guide
|
|
157
167
|
|
|
158
|
-
|
|
168
|
+
Create a guided reading path that connects an explanation of a change to exact
|
|
169
|
+
code evidence. Bygone resolves and displays that evidence; the authoring agent
|
|
170
|
+
is responsible for the explanation and its claims.
|
|
171
|
+
|
|
172
|
+
This skill covers tour authoring, validation, presentation, and synthetic review
|
|
173
|
+
branches for clean comparisons with or without a tour. It works standalone;
|
|
174
|
+
no writing, review, or orchestration skill is required. Existing code, maintained
|
|
175
|
+
docs, requirements, and PR discussion keep their roles. A tour can summarize and
|
|
176
|
+
link to them, but does not replace them or certify a review.
|
|
177
|
+
|
|
178
|
+
Honor an explicit request for a tour. When a broader task leaves the medium open,
|
|
179
|
+
a concise explanation, ordinary code links, or a synthetic branch comparison
|
|
180
|
+
may suffice; no tour is a valid outcome. Do not create a tour to compensate
|
|
181
|
+
for a defect in another artifact.
|
|
159
182
|
|
|
160
183
|
## Install this skill
|
|
161
184
|
|
|
@@ -197,7 +220,7 @@ npx skills add ./skills/pr-tour-guide -y
|
|
|
197
220
|
|
|
198
221
|
## Install Bygone
|
|
199
222
|
|
|
200
|
-
This skill
|
|
223
|
+
This skill uses the \`bygone\` CLI. Tour authoring requires \`tour context\`, \`tour schema\`, \`tour validate\`, and \`tour compile\`; a standalone synthetic branch comparison needs only \`--git-diff\`. Install only when the user asks or when the task cannot proceed without it.
|
|
201
224
|
|
|
202
225
|
**macOS (desktop app + CLI, recommended):**
|
|
203
226
|
|
|
@@ -240,7 +263,7 @@ Verify tour support before authoring:
|
|
|
240
263
|
bygone tour schema >/dev/null
|
|
241
264
|
\`\`\`
|
|
242
265
|
|
|
243
|
-
If neither \`bygone\` nor \`node ./bin/bygone.js\` exposes the \`tour\` subcommands,
|
|
266
|
+
If neither \`bygone\` nor \`node ./bin/bygone.js\` exposes the \`tour\` subcommands, report that tour authoring is unavailable rather than guessing. A requested standalone comparison can still proceed when \`--git-diff\` is supported.
|
|
244
267
|
|
|
245
268
|
Do not rebuild, commit, push, publish, or open a browser unless the user requests it or the surrounding task clearly requires it.
|
|
246
269
|
|
|
@@ -284,80 +307,101 @@ Then read patches only for likely narrative-bearing files. Account explicitly fo
|
|
|
284
307
|
|
|
285
308
|
Compiled tours and context dossiers are large because they embed source snapshots. Inspect them progressively and do not load every patch unless the narrative really needs it.
|
|
286
309
|
|
|
287
|
-
##
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
for
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
Identify the smallest set of reviewer questions that makes the change understandable. Organize by conceptual dependency rather than filename order. Usually move through:
|
|
332
|
-
|
|
333
|
-
1. motivation, contract, or invariant;
|
|
334
|
-
2. core implementation;
|
|
335
|
-
3. integration or side effects;
|
|
336
|
-
4. failure behavior and proof.
|
|
337
|
-
|
|
338
|
-
Keep secondary, generated, dependency, and mechanical files in Bygone's complete Files rail unless they alter a reviewer conclusion.
|
|
339
|
-
|
|
340
|
-
Let the change determine the hierarchy. A chapter is a named conceptual arc containing one or more related scenes; a scene answers one reviewer question or advances one thesis. Do not target a fixed chapter count, and do not create a chapter merely to wrap each scene. Repeated one-scene chapters usually indicate that headings are being generated from a template instead of the change's actual structure.
|
|
310
|
+
## Use existing context
|
|
311
|
+
|
|
312
|
+
Read relevant code and the supplied or directly linked docs, requirements, and
|
|
313
|
+
PR explanation. Keep discovery bounded to the change. Bring in only the context
|
|
314
|
+
needed to explain its behavior and evidence; link to the existing account for
|
|
315
|
+
more detail. People, dates, and review history are useful only when they affect
|
|
316
|
+
the explanation, not as a required inventory.
|
|
317
|
+
|
|
318
|
+
Distinguish requested behavior, an author's stated intent, and behavior supported
|
|
319
|
+
by implementation and tests. Label intent inferred from the diff. Do not invent
|
|
320
|
+
requirements, rationale, authorship, or approval; disclose material uncertainty.
|
|
321
|
+
If another artifact is deficient, identify that destination instead of hiding
|
|
322
|
+
the gap in tour prose. Tour authoring alone does not authorize editing it.
|
|
323
|
+
|
|
324
|
+
## Choose a clean comparison, with or without a tour
|
|
325
|
+
|
|
326
|
+
A synthetic review branch is a first-class option when base-branch merges,
|
|
327
|
+
unrelated commits, or interleaved concerns obscure the change. Use it to keep
|
|
328
|
+
a shared baseline constant across before, author revision, and proposed revision,
|
|
329
|
+
or to decompose a change into cumulative conceptual commits. A standalone
|
|
330
|
+
comparison can complete the task; add a tour when narration would clarify
|
|
331
|
+
relationships the clean diff still leaves difficult to reconstruct.
|
|
332
|
+
|
|
333
|
+
Keep the real source endpoints and history as provenance. Create clearly named
|
|
334
|
+
local refs in an isolated worktree within the task's authorization, preserving
|
|
335
|
+
the development branch and dirty work. These are synthetic review artifacts,
|
|
336
|
+
not a silent substitution for a hosted review's endpoints or permission to push
|
|
337
|
+
or rewrite its branch. Do not invent implementation changes to fill a panel.
|
|
338
|
+
|
|
339
|
+
For a normalized comparison, retain unrelated baseline changes in every panel.
|
|
340
|
+
For decomposition, order cumulative commits by dependency and reviewer question.
|
|
341
|
+
Retain required dependencies and integration changes; label reconstructed states
|
|
342
|
+
and do not present the synthetic sequence as the author's actual history.
|
|
343
|
+
|
|
344
|
+
Verify intended endpoint equivalence with Git tree comparisons, or included-path
|
|
345
|
+
comparisons with explicit exclusions for a scoped view. Record a reconstructed
|
|
346
|
+
baseline's source range and transformation, replay the isolated change, and
|
|
347
|
+
verify that it reproduces the intended endpoint. Inspect conflict resolutions.
|
|
348
|
+
Verify that the final snapshot matches the real head or proposal, and disclose
|
|
349
|
+
intentional differences. Tree equality proves snapshot fidelity, not runtime
|
|
350
|
+
correctness; report untested intermediate states and reuse test results only
|
|
351
|
+
for equivalent code and dependencies.
|
|
352
|
+
|
|
353
|
+
Open the resulting refs with the needed number of panels:
|
|
341
354
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
- A normal pull request often needs one to three chapters with one or more scenes in each.
|
|
346
|
-
- A broad release or long-lived branch may need several chapters, but each boundary must mark a real conceptual transition.
|
|
347
|
-
- Prefer merging adjacent chapters when their scenes form one argument; split a chapter only when its scenes answer materially different reviewer questions.
|
|
355
|
+
\`\`\`sh
|
|
356
|
+
bygone -C <worktree> --read-only --git-diff <before-ref> <author-ref> <proposed-ref>
|
|
357
|
+
\`\`\`
|
|
348
358
|
|
|
349
|
-
|
|
359
|
+
Print the exact one-line command with real paths and refs. Report provenance
|
|
360
|
+
and whether the artifact is local or pushed. If adding a tour, pin its evidence
|
|
361
|
+
to the synthetic commits and link the real source revisions. These materialized
|
|
362
|
+
Git commits are distinct from the compiler's hunk-based Deconstructed stages;
|
|
363
|
+
do not imply they reproduce historical authorship merely because they have OIDs.
|
|
350
364
|
|
|
351
|
-
|
|
365
|
+
## Plan the explanation
|
|
352
366
|
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
367
|
+
Lead with what changes for the user or system and why it matters. Use version 5
|
|
368
|
+
\`opening: { title, summary, bullets? }\` for a short orientation and
|
|
369
|
+
\`conclusion: { title, summary, bullets? }\` for what the evidence established and
|
|
370
|
+
what remains unresolved. Give each independently authored mode enough context
|
|
371
|
+
to stand alone: place its \`opening\` and \`conclusion\` inside \`tours.historical\`
|
|
372
|
+
or \`tours.deconstructed\`; independently authored modes do not inherit root bookends.
|
|
373
|
+
Restate an important expected behavior or boundary from its
|
|
374
|
+
existing source when useful; the opening is an explanation, not a new specification.
|
|
375
|
+
Never silently weaken an expectation to match the implementation.
|
|
376
|
+
|
|
377
|
+
Choose the smallest set of questions that makes the change understandable:
|
|
378
|
+
|
|
379
|
+
- A chapter groups related questions. A scene answers one question; several
|
|
380
|
+
steps can supply its evidence. Split for a new reasoning task, not simply
|
|
381
|
+
a new file or viewport. Use no fixed chapter or step count.
|
|
382
|
+
- Use optional v5 \`chapter.summary\` for one or two brief sentences that explain
|
|
383
|
+
what comes next and why. Omit it when no useful preview is needed: chapters
|
|
384
|
+
without summaries stay in the contents but are skipped as presentation and
|
|
385
|
+
narration stops. A list of scene titles or links is not a preview.
|
|
386
|
+
- Give each scene a distinct purpose. Its summary should prepare the reader for
|
|
387
|
+
the evidence and say what to notice. Meaningful chapter or scene titles form
|
|
388
|
+
the opening's generated route; do not duplicate that itinerary in prose.
|
|
389
|
+
- A scene boundary need not change revisions. When the comparison changes,
|
|
390
|
+
explain why the new revisions matter; otherwise explain the new question.
|
|
391
|
+
Keep reference numbers in navigation and use descriptive titles in narration.
|
|
392
|
+
- Connect the observable outcome to its mechanism and evidence. Explain why
|
|
393
|
+
focused code matters rather than paraphrasing syntax. Preserve causal links
|
|
394
|
+
when shortening prose and include boundaries that change the conclusion.
|
|
395
|
+
- Keep tests beside the behavior they support. Distinguish a test's existence
|
|
396
|
+
from a passing execution, and synthetic stages from real revision history.
|
|
397
|
+
- Add context, connections, and steps only when they add understanding. Keep
|
|
398
|
+
mechanical files in the complete Files rail unless they affect the argument.
|
|
399
|
+
Do not repeat the same point across summaries, bullets, and takeaways.
|
|
400
|
+
|
|
401
|
+
Support claims about intent, safety, performance, or runtime behavior with
|
|
402
|
+
appropriate evidence. A selected reading path is not an exhaustive code review.
|
|
403
|
+
Do not invent slide kinds or metadata keys; keep code anchors and links to
|
|
404
|
+
external explanations distinct.
|
|
361
405
|
|
|
362
406
|
## Author the source
|
|
363
407
|
|
|
@@ -367,14 +411,14 @@ Retrieve the current contract:
|
|
|
367
411
|
bygone tour schema > /tmp/change-tour-source.schema.json
|
|
368
412
|
\`\`\`
|
|
369
413
|
|
|
370
|
-
Write a version
|
|
414
|
+
Write a version 5 \`.bygone\` file for new tours. The legacy \`.bygone.yaml\`
|
|
371
415
|
spelling remains valid when generic YAML tooling requires it. Treat the
|
|
372
416
|
authored source and its compiled \`.tour.json\` as Git-backed, non-portable
|
|
373
417
|
artifacts: pin \`range.base\` and \`range.head\` to the exact OIDs from the
|
|
374
418
|
context, and keep them with the corresponding repository so Bygone can resolve
|
|
375
|
-
those objects and live history. Versions 1 and
|
|
376
|
-
inputs;
|
|
377
|
-
|
|
419
|
+
those objects and live history. Versions 1, 2, and 4 remain readable for legacy
|
|
420
|
+
inputs; v5 adds bookends, optional chapter previews, and requires a purpose for explicit directory overviews.
|
|
421
|
+
Version 3 is retired. The source has no \`review\` or ad hoc \`notes\` field.
|
|
378
422
|
|
|
379
423
|
Set optional \`windowTitle\` when the tour should appear in the native window
|
|
380
424
|
title \u2014 for example a pull request number (\`PR-1234\`) so multiple open tours
|
|
@@ -399,14 +443,14 @@ across modes.
|
|
|
399
443
|
walkthrough scenes for context or proof. A mode-specific deconstructed scene
|
|
400
444
|
may omit \`stack\` and endpoint \`steps\`: its stages, not Git history, define the
|
|
401
445
|
explanation panels.
|
|
402
|
-
- If a mode is omitted,
|
|
446
|
+
- If a mode is omitted, v4 and v5 derive it from the root chapters by scene identity
|
|
403
447
|
and order. Root walkthroughs and real stacks supply Historical; root
|
|
404
448
|
deconstructed scenes supply Deconstructed. A root deconstructed scene enters
|
|
405
449
|
Historical only when it also has explicit endpoint walkthrough \`steps\`; a
|
|
406
450
|
real revision \`stack\` by itself is not that walkthrough. No cross-mode
|
|
407
451
|
correspondence is inferred from filenames or narrative text.
|
|
408
452
|
|
|
409
|
-
For a root
|
|
453
|
+
For a root v4 or v5 \`deconstructed-diff\` scene, provide both an explicit real
|
|
410
454
|
revision \`stack\` and regular endpoint \`steps\`. The stack is used for the real
|
|
411
455
|
Historical/Final fallback and must have the same base and final endpoints as
|
|
412
456
|
the source range; the synthetic stages remain separate. A
|
|
@@ -441,11 +485,14 @@ Keep deconstructed-tour coordinates distinct:
|
|
|
441
485
|
- When an ordinal is necessary, qualify the coordinate: "stage 2 of 4" versus "tour step 11 of 46."
|
|
442
486
|
- Treat presenter-generated labels as UI context; do not repeat them in authored prose unless the distinction itself needs explanation.
|
|
443
487
|
|
|
444
|
-
|
|
488
|
+
Use a directory overview only when its inventory answers the scene\u2019s question.
|
|
489
|
+
Otherwise the viewer previews the first step without an active annotation.
|
|
490
|
+
Version 5 requires an explicit purpose:
|
|
445
491
|
|
|
446
492
|
\`\`\`yaml
|
|
447
493
|
overview:
|
|
448
494
|
kind: directory-diff
|
|
495
|
+
purpose: See which web layers changed together before tracing their interaction.
|
|
449
496
|
path: web
|
|
450
497
|
\`\`\`
|
|
451
498
|
|
|
@@ -455,14 +502,11 @@ distinct stack-entry IDs or to \`explanation-baseline\` and
|
|
|
455
502
|
\`explanation-stage-<stage-id>\`. Walkthrough overviews always use the review's
|
|
456
503
|
base-to-head comparison and reject an explicit comparison.
|
|
457
504
|
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
have empty evidence but must provide \`nextCheck\`. Do not add an ad hoc \`notes\`
|
|
464
|
-
key. See \`examples/bygone-history.bygone\` for review notes and
|
|
465
|
-
\`examples/navigation-lab.bygone.yaml\` for independently authored v3 modes.
|
|
505
|
+
Put concepts, boundaries, and tradeoffs beside their code evidence in scene or
|
|
506
|
+
step narrative. Label unresolved questions explicitly and state the next check
|
|
507
|
+
that would resolve them. Never present an unknown as a settled conclusion.
|
|
508
|
+
Do not add a \`review\` block or an ad hoc \`notes\` key. See
|
|
509
|
+
\`examples/navigation-lab.bygone.yaml\` for independently authored modes.
|
|
466
510
|
|
|
467
511
|
Never emit generated line numbers or hunk indexes. Verify candidate snippets against the pinned object when uncertain:
|
|
468
512
|
|
|
@@ -474,38 +518,27 @@ Use \`occurrence\` only when repetition is intentional and stable. Treat rename
|
|
|
474
518
|
|
|
475
519
|
## Validate and repair
|
|
476
520
|
|
|
521
|
+
Use optional v5 \`details.audience\` when the intended reader and purpose are known.
|
|
522
|
+
Read [Expectations and reader feedback](references/expectations-and-feedback.md)
|
|
523
|
+
for those fields or when handling a captured reader concern.
|
|
524
|
+
|
|
477
525
|
Always run validation before presenting or handing off:
|
|
478
526
|
|
|
479
527
|
\`\`\`sh
|
|
480
528
|
bygone tour validate review.bygone --json
|
|
481
529
|
\`\`\`
|
|
482
530
|
|
|
483
|
-
Repair every error. Do not weaken, delete, or redirect an anchor merely to make
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
-
|
|
494
|
-
- important production behavior is not hidden in the complete Files rail;
|
|
495
|
-
- tests are connected to the behavior they prove;
|
|
496
|
-
- connections express causal, contractual, data-flow, ordering, or proof relationships;
|
|
497
|
-
- binary files and omitted patches are surfaced explicitly;
|
|
498
|
-
- every Historical tour excludes synthetic deconstructed scenes, and every
|
|
499
|
-
Deconstructed tour contains at least one deconstructed scene;
|
|
500
|
-
- deconstructed stages cover every included change unit exactly once or record
|
|
501
|
-
an explicit exclusion, contain no unqualified "Stage N" or "Step N"
|
|
502
|
-
references, and keep comparison stages distinct from navigable tour steps;
|
|
503
|
-
- root deconstructed scenes have the required real stack and endpoint
|
|
504
|
-
walkthrough evidence, while mode-specific synthetic scenes do not claim
|
|
505
|
-
that evidence exists;
|
|
506
|
-
- v3 review-note OIDs match the resolved range and evidence links resolve to
|
|
507
|
-
authored root walkthrough steps;
|
|
508
|
-
- the final step supplies proof or a clear reviewer conclusion.
|
|
531
|
+
Repair every error. Do not weaken, delete, or redirect an anchor merely to make
|
|
532
|
+
validation pass. If evidence no longer exists, revise the claim or report the
|
|
533
|
+
broken premise. Validation checks structure and evidence locations, not code
|
|
534
|
+
correctness or comprehension.
|
|
535
|
+
|
|
536
|
+
Read the resulting path against its evidence: does each scene establish a useful
|
|
537
|
+
point, do transitions preserve orientation, and does the conclusion stay within
|
|
538
|
+
what was shown? Check the compiled path where generated focus steps or fallback
|
|
539
|
+
modes could introduce repetition or change the intended sequence. Report material
|
|
540
|
+
omissions and checks actually performed; do not require a scored audit or a
|
|
541
|
+
separate reader-review process for every tour.
|
|
509
542
|
|
|
510
543
|
## Always print the open command
|
|
511
544
|
|
|
@@ -547,20 +580,89 @@ Compiled manifests contain source snapshots. Do not publish or upload them witho
|
|
|
547
580
|
|
|
548
581
|
## Hand off
|
|
549
582
|
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
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)}})();})();
|
|
583
|
+
Provide the tour document path, compiled path if produced, exact range, and open
|
|
584
|
+
command. Briefly report validation, any visual verification, material omissions
|
|
585
|
+
or unresolved claims, and whether artifacts are temporary, uncommitted, committed,
|
|
586
|
+
or pushed. Do not turn the handoff into an inventory of every scene and step.
|
|
587
|
+
|
|
588
|
+
Bygone establishes that cited evidence exists at the pinned revision, not that
|
|
589
|
+
the narrative interpretation or implementation is correct.
|
|
590
|
+
`;var di=`# Expectations and reader feedback
|
|
591
|
+
|
|
592
|
+
Read this reference for optional audience fields or when a reader supplies a
|
|
593
|
+
captured Bygone concern. General writing and review workflows can use this
|
|
594
|
+
skill, but are not prerequisites for authoring a tour.
|
|
595
|
+
|
|
596
|
+
## Handle captured context
|
|
597
|
+
|
|
598
|
+
The capture identifies a passage, mode, pinned range, and authored/displayed
|
|
599
|
+
evidence. It is a snapshot, not proof of the current workspace state. Verify
|
|
600
|
+
which revision the claim concerns before editing. Synthetic panels are teaching
|
|
601
|
+
states, not commits; an excerpt may omit code needed to evaluate the claim.
|
|
602
|
+
|
|
603
|
+
Check the claim against relevant surrounding implementation, tests, and existing
|
|
604
|
+
requirements or explanations. An opening restates an expectation; it does not
|
|
605
|
+
establish that expectation's authority. Label inferred intent and unresolved
|
|
606
|
+
conflicts. Do not change the expectation merely to fit the implementation.
|
|
607
|
+
|
|
608
|
+
Answer the reader's concern and identify any artifact needing repair:
|
|
609
|
+
|
|
610
|
+
- **Implementation code:** incorrect or unnecessarily obscure behavior.
|
|
611
|
+
- **Maintained docs:** missing reusable concepts, usage, or architectural context.
|
|
612
|
+
- **PR explanation:** missing change rationale or tradeoffs.
|
|
613
|
+
- **Tour document:** misleading wording, missing causal links, or a poor evidence path.
|
|
614
|
+
- **Viewer:** navigation, focus, or comparison behavior that prevents inspection.
|
|
615
|
+
|
|
616
|
+
A disputed requirement may need a human decision; missing evidence may need a
|
|
617
|
+
check. A clear answer may need no saved change. Follow existing task authorization
|
|
618
|
+
for repairs; tour feedback alone does not authorize unrelated edits or shared
|
|
619
|
+
communications. Do not use extra tour prose to conceal a defect elsewhere.
|
|
620
|
+
|
|
621
|
+
When repairing a tour, keep the outcome, mechanism, and decisive evidence visible.
|
|
622
|
+
If an authorized implementation repair changes the intended committed range,
|
|
623
|
+
regenerate context, resolve affected anchors, revisit claims, and validate. If
|
|
624
|
+
code remains uncommitted, disclose that the pinned tour does not yet show the fix.
|
|
625
|
+
Historical tours can intentionally retain their original range.
|
|
626
|
+
|
|
627
|
+
Distinguish the agent's answer from edits to the saved tour document. Report the
|
|
628
|
+
actual repair and checks, including unresolved concerns. Validation is evidence
|
|
629
|
+
of structural grounding, not a demonstration of reader understanding.
|
|
630
|
+
|
|
631
|
+
## Describe the reader
|
|
632
|
+
|
|
633
|
+
Use optional v5 \`details.audience\` on the root or an independently authored
|
|
634
|
+
\`tours.historical\` / \`tours.deconstructed\` object. If present, supply:
|
|
635
|
+
|
|
636
|
+
- \`codebase\`: \`none\`, \`some\`, or \`maintainer\`.
|
|
637
|
+
- \`language\`: \`none\`, \`basic\`, \`fluent\`, or \`advanced\`.
|
|
638
|
+
- \`readingDemand\`: \`general\`, \`technical\`, or \`specialist\`.
|
|
639
|
+
- \`purpose\`: \`overview\`, \`explanation\`, or \`review\`.
|
|
640
|
+
- \`scope\`: what this tour explains and any material limit.
|
|
641
|
+
- Optional \`domain\`: concrete prerequisites, and \`estimatedMinutes\`: reading time.
|
|
642
|
+
|
|
643
|
+
Independent modes describe their own readers. These fields set expectations;
|
|
644
|
+
they are not quality grades. Language expertise, codebase familiarity, and prose
|
|
645
|
+
reading demand are distinct. Do not invent an audience or reading-time estimate
|
|
646
|
+
merely to populate Tour details.
|
|
647
|
+
`;var hi=ci.replace("(references/expectations-and-feedback.md)","(#expectations-and-reader-feedback)")+`
|
|
648
|
+
|
|
649
|
+
`+di,xn=["history","compare","historical","deconstructed"],vn={history:"History",compare:"Compare",historical:"Historical tour",deconstructed:"Deconstructed tour"},Fa={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."},Da=new Set(["exact","none","multiple","uncommitted","reversed","divergent","unavailable"]),Ma=0;function pi({container:e,content:t,send:o}={}){if(!e||typeof e.appendChild!="function")throw new TypeError("createWorkspaceControls requires a DOM container.");let a=e.ownerDocument||globalThis.document;if(!a||typeof a.createElement!="function")throw new TypeError("createWorkspaceControls requires a browser document.");let i=typeof o=="function"?o:()=>{},s=++Ma,l=a.createElement("section");l.className="workspace-controls",l.setAttribute("data-workspace-controls","true");let f=a.createElement("nav");f.className="workspace-mode-strip",f.setAttribute("role","tablist"),f.setAttribute("aria-label","Workspace views"),l.appendChild(f);let p=a.createElement("div");p.className="workspace-mode-descriptions",p.setAttribute("aria-hidden","true"),l.appendChild(p);let m=new Map,y=new Map;for(let R of xn){let U=a.createElement("button");U.type="button",U.className="workspace-mode-button",U.id=`bygone-workspace-${s}-${R}-tab`,U.setAttribute("role","tab"),U.setAttribute("data-workspace-mode",R),U.textContent=vn[R];let K=a.createElement("span");K.className="workspace-mode-description visually-hidden";let re=`bygone-workspace-${s}-${R}-description`;K.id=re,p.appendChild(K),U.setAttribute("aria-describedby",re),m.set(R,U),y.set(R,K),f.appendChild(U)}let b=a.createElement("div");b.className="workspace-status",b.setAttribute("role","status"),b.setAttribute("aria-live","polite"),b.setAttribute("aria-atomic","true"),l.appendChild(b);let E=a.createElement("span");E.className="workspace-revision-context",l.appendChild(E);let I=t||e;I.id||(I.id=`bygone-workspace-${s}-view`),I.setAttribute("role","tabpanel");let T=a.createElement("section");T.className="workspace-empty-view",T.setAttribute("data-workspace-empty-tour",""),T.hidden=!0;let v=a.createElement("h2"),x=a.createElement("p"),N=a.createElement("div");N.className="workspace-empty-actions";let B=Oe(a,"Create tour\u2026","create-tour"),M=Oe(a,"Open existing tour\u2026","open-tour");N.append(B,M),T.append(v,x,N),I.appendChild(T);let n=Oa(a,s);l.appendChild(n.dialog),e.appendChild(l);let F=li(),V=!1,O=null,j=null,J=!1,oe="",Q=new Map,ie=new Map;for(let[R,U]of m)U.addEventListener("click",()=>{V||U.disabled||R!==F.mode&&i({type:"workspaceMode",mode:R})}),U.addEventListener("keydown",K=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(K.key))return;let le=[...m.values()].filter(Ge=>!Ge.disabled),Ue=le.indexOf(U),ze=K.key==="Home"?0:K.key==="End"?le.length-1:(Ue+(K.key==="ArrowRight"?1:-1)+le.length)%le.length;K.preventDefault(),le[ze]?.focus(),le[ze]?.click()});return B.addEventListener("click",()=>kn(F.mode,B)),M.addEventListener("click",()=>i({type:"workspaceOpenTour",kind:F.mode})),n.textarea.addEventListener("input",()=>{if(!O)return;let R=Le(O);R.text=n.textarea.value,R.edited=!0}),n.copyButton.addEventListener("click",()=>{if(!O)return;let R=ee(O);Ne(R.text)}),n.resetButton.addEventListener("click",()=>{if(!O)return;let R=Le(O,{reset:!0});n.textarea.value=R.text,Ae(),n.textarea.focus()}),n.saveSkillButton.addEventListener("click",()=>{if(F.nativeSkillFiles){i({type:"workspaceSkillSave"});return}let R=rt(),U=URL.createObjectURL(new Blob([R.text],{type:"text/markdown;charset=utf-8"})),K=a.createElement("a");K.href=U,K.download=R.name||"bygone-tour-skill.md",K.click(),setTimeout(()=>URL.revokeObjectURL(U),1e3),Be("Markdown downloaded. Edit your copy, then choose Use my copy. Attach it alongside the prompt when your agent cannot read local files.")}),n.chooseSkillButton.addEventListener("click",()=>{F.nativeSkillFiles?i({type:"workspaceSkillChoose"}):n.skillFile.click()}),n.skillFile.addEventListener("change",async()=>{let R=n.skillFile.files?.[0],U=F.sessionId;if(n.skillFile.value="",!!R)try{if(!R.name.toLowerCase().endsWith(".md")||R.size>1024*1024)throw new Error("Choose a Markdown file smaller than 1 MiB.");let K=await R.text();if(!K.trim())throw new Error("The instructions file is empty.");if(ie.set(U,{name:R.name,text:K}),V||F.sessionId!==U)return;Ae(),Be("Custom instructions selected. Attach this Markdown file with the prompt.")}catch(K){!V&&F.sessionId===U&&Be(`Could not load instructions: ${K.message}`)}}),n.openExistingButton.addEventListener("click",()=>{if(!O)return;ee(O);let R=O;be(),i({type:"workspaceOpenTour",kind:R})}),n.chooseCompareButton.addEventListener("click",()=>{O&&(ee(O),be(),i({type:"workspaceMode",mode:"compare"}))}),n.closeButton.addEventListener("click",()=>be()),n.dialog.addEventListener("cancel",R=>{R.preventDefault(),be()}),n.dialog.addEventListener("close",()=>{O=null,oe="",J||se()}),de(),{update:de,destroy:wt};function de(R){if(V)return;let U=li(R);U.sessionId!==F.sessionId&&he()&&be(),Ht(U),O&&U.status!==F.status&&(oe=U.status),F=U,X(),zt(),ne(),O&&Ae()}function wt(){V||(V=!0,be(),typeof l.remove=="function"?l.remove():l.parentNode?.removeChild(l),m.clear(),y.clear(),T.remove(),Q.clear(),ie.clear())}function X(){for(let R of xn){let U=m.get(R),K=y.get(R),re=ui(R,F),le=F.mode===R,Ue=(R==="historical"||R==="deconstructed")&&!re,ze=Ue&&!F.canCreateTours,Ge=R==="history"&&F.history.enabled===!1,ve=R==="compare"&&F.compare.enabled===!1,Ve=R==="history"?F.history.label:R==="compare"?F.compare.label:F.modeLabels[R]||vn[R],vt=ze?F.unavailableTourReason:Ue?`No ${Ve} yet. Open this view to create or open a tour.`:Ge?F.history.reason||"History is unavailable for this workspace.":ve?F.compare.reason||"Compare is unavailable for this workspace.":le?`${Ve} is the current workspace mode.`:`Switch to ${Ve}.`;U.textContent=Ve,U.title=vt,U.setAttribute("aria-label",Ve),U.setAttribute("aria-description",vt),K.textContent=vt,U.classList.toggle("is-active",le),U.classList.toggle("is-missing",Ue),U.classList.toggle("is-unavailable",Ge||ve||ze),U.disabled=Ge||ve||ze,U.setAttribute("aria-selected",String(le)),U.setAttribute("aria-controls",I.id),le&&I.setAttribute("aria-labelledby",U.id)}}function zt(){let R=F.mode,U=["historical","deconstructed"].includes(R)&&!ui(R,F);if(T.hidden=!U,B.hidden=!F.canCreateTours,M.hidden=!F.canOpenTours,U){let K=F.modeLabels[R]||vn[R];v.textContent=`No ${K} yet`,x.textContent="Create a tour with your coding agent, or open one you already have."}}function ne(){b.textContent=F.status||"",b.hidden=!F.status,E.textContent=F.revisionContext,E.hidden=!F.revisionContext}function kn(R,U){if(!(V||R!=="historical"&&R!=="deconstructed")){if(O=R,j=U,oe=F.status||"",Ae(),typeof n.dialog.showModal=="function")try{n.dialog.showModal()}catch{n.dialog.setAttribute("open","")}else n.dialog.setAttribute("open","");n.textarea.focus()}}function be(){if(!he()){O=null,se();return}J=!0;try{typeof n.dialog.close=="function"?n.dialog.close():n.dialog.removeAttribute("open"),O=null,oe=""}finally{J=!1,se()}}function se(){let R=j;if(j=null,!(!R||typeof R.focus!="function")&&R.isConnected!==!1)try{R.focus()}catch{}}function he(){return n.dialog.open===!0||n.dialog.hasAttribute("open")}function Ae(){if(!O)return;let R=Le(O),U=rt();n.title.textContent=`${vn[O]} prompt`,n.description.textContent=Fa[O],n.context.textContent=`Current context: ${fi(F.promptContext)}`,R.skillKey!==bt()?(n.draftNotice.hidden=!1,n.draftNotice.textContent="The selected instructions changed. Your edited prompt was preserved; use Reset prompt to reference the selected file, or update its reference yourself."):R.contextKey!==vr(F.promptContext)?(n.draftNotice.hidden=!1,n.draftNotice.textContent=`This draft is based on earlier workspace context: ${R.contextSummary}. Review the repository, revision boundaries, and selected paths before copying.`):(n.draftNotice.hidden=!0,n.draftNotice.textContent=""),n.textarea.value=R.text,n.skillText.value=U.text,n.skillReference.textContent=U.path?`Instructions: ${U.path}. Local agents can read this path; for browser chats, save and attach a copy.`:`Instructions: ${U.name||"bygone-tour-skill.md"} (attachment). Download and attach it with the prompt; browsers do not expose its full local path.`,n.status.textContent=oe,n.status.hidden=!oe}function Ne(R){let U=a.defaultView?.navigator?.clipboard||globalThis.navigator?.clipboard;if(!U||typeof U.writeText!="function"){Be("Could not copy the prompt: clipboard access is unavailable.");return}Promise.resolve().then(()=>U.writeText(R)).then(()=>Be("Prompt copied to the clipboard.")).catch(K=>{let re=K instanceof Error&&K.message?` ${K.message}`:"";Be(`Could not copy the prompt.${re}`)})}function Be(R){oe=R,n.status.textContent=R,n.status.hidden=!R}function ee(R){let U=Le(R);return U.text=n.textarea.value,U.edited=!0,U}function Le(R,{reset:U=!1}={}){let K=Q.get(F.sessionId)||new Map;Q.set(F.sessionId,K);let re=K.get(R);return(U||!re||!re.edited&&re.skillKey!==bt())&&K.set(R,{text:ai(R,F.promptContext,rt()),skillKey:bt(),contextKey:vr(F.promptContext),contextSummary:fi(F.promptContext),edited:!1}),K.get(R)}function rt(){return F.tourSkill||ie.get(F.sessionId)||{name:"bygone-tour-skill.md",text:hi}}function bt(){let R=rt();return JSON.stringify([R.path||"",R.name||"",R.text])}function Ht(R){let U=Q.get(R.sessionId);if(U)for(let K of U.values())K.contextChanged=K.contextKey!==vr(R.promptContext)}}function Oa(e,t){let o=e.createElement("dialog");o.className="workspace-prompt-dialog",o.setAttribute("aria-modal","true");let a=e.createElement("h2");a.id=`bygone-workspace-${t}-prompt-title`,o.setAttribute("aria-labelledby",a.id),o.appendChild(a);let i=e.createElement("p");i.className="workspace-prompt-description",i.id=`bygone-workspace-${t}-prompt-description`,o.setAttribute("aria-describedby",i.id),o.appendChild(i);let s=e.createElement("p");s.className="workspace-prompt-context",o.appendChild(s);let l=e.createElement("p");l.className="workspace-prompt-draft-notice",l.setAttribute("role","status"),l.hidden=!0,o.appendChild(l);let f=e.createElement("label");f.className="workspace-prompt-label";let p=e.createElement("textarea");p.id=`bygone-workspace-${t}-prompt-textarea`,p.rows=9,p.spellcheck=!1,p.setAttribute("aria-label","Tour authoring prompt draft"),f.textContent="Prompt draft",f.appendChild(p),o.appendChild(f);let m=e.createElement("p");m.className="workspace-prompt-context",o.appendChild(m);let y=e.createElement("details"),b=e.createElement("summary");b.textContent="Read instructions (Markdown)";let E=e.createElement("textarea");E.readOnly=!0,E.rows=12,E.setAttribute("aria-label","Tour skill Markdown instructions"),y.append(b,E),o.appendChild(y);let I=e.createElement("div");I.className="workspace-prompt-actions";let T=Oe(e,"Save an editable copy","workspace-skill-save"),v=Oe(e,"Use my copy","workspace-skill-choose"),x=e.createElement("input");x.type="file",x.accept=".md,text/markdown",x.hidden=!0,I.append(T,v,x),o.appendChild(I);let N=e.createElement("p");N.className="workspace-prompt-status",N.setAttribute("role","status"),N.setAttribute("aria-live","polite"),N.setAttribute("aria-atomic","true"),N.hidden=!0,o.appendChild(N);let B=e.createElement("div");B.className="workspace-prompt-actions";let M=Oe(e,"Copy prompt","workspace-prompt-copy"),n=Oe(e,"Reset prompt","workspace-prompt-reset"),F=Oe(e,"Open existing tour","workspace-prompt-open"),V=Oe(e,"Choose revisions in Compare","workspace-prompt-compare"),O=Oe(e,"Close","workspace-prompt-close");return B.append(M,n,F,V,O),o.appendChild(B),{dialog:o,title:a,description:i,context:s,draftNotice:l,textarea:p,skillText:E,skillReference:m,saveSkillButton:T,chooseSkillButton:v,skillFile:x,status:N,copyButton:M,resetButton:n,openExistingButton:F,chooseCompareButton:V,closeButton:O}}function Oe(e,t,o){let a=e.createElement("button");return a.type="button",a.textContent=t,a.title=t,a.setAttribute("data-workspace-prompt-action",o),a}function li(e={}){let t=xn.includes(e?.mode)?e.mode:"compare",o=e?.history&&typeof e.history=="object"?{enabled:e.history.enabled!==!1,label:nt(e.history.label,"History"),reason:nt(e.history.reason,"")}:{enabled:!0,label:"History",reason:""},a=e?.compare&&typeof e.compare=="object"?{enabled:e.compare.enabled!==!1,label:nt(e.compare.label,"Compare"),reason:nt(e.compare.reason,"")}:{enabled:!0,label:"Compare",reason:""},i=Array.isArray(e?.availableTours)?e.availableTours.filter(s=>s==="historical"||s==="deconstructed"):null;return{sessionId:Ua(e?.sessionId),mode:t,modeLabels:e?.modeLabels&&typeof e.modeLabels=="object"?Object.fromEntries(xn.filter(s=>typeof e.modeLabels[s]=="string").map(s=>[s,e.modeLabels[s]])):{},history:o,compare:a,availableTours:i,canCreateTours:e?.canCreateTours!==!1,canOpenTours:e?.canOpenTours!==!1,unavailableTourReason:nt(e?.unavailableTourReason,"This tour is unavailable in this workspace."),revisionContext:nt(e?.revisionContext,""),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:hi}:null,promptContext:Ba(e?.promptContext),status:nt(e?.status,"")}}function Ba(e){let t=e&&typeof e=="object"?e:{};return{...typeof t.repository=="string"?{repository:t.repository}:{},...Array.isArray(t.paths)?{paths:t.paths.filter(o=>typeof o=="string")}:{},...Array.isArray(t.revisions)?{revisions:t.revisions.filter(o=>typeof o=="string")}:{},...Da.has(t.rangeStatus)?{rangeStatus:t.rangeStatus}:{},...typeof t.reason=="string"?{reason:t.reason}:{}}}function ui(e,t){return e==="history"?t.history.enabled!==!1:e==="compare"?t.compare.enabled!==!1:t.availableTours?t.availableTours.includes(e):t.mode===e}function vr(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 fi(e){let t=e.repository||"(not resolved)",o=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 ${t}; paths ${o}; revisions ${a}; range ${e.rangeStatus||"unavailable"}`}function Ua(e){return typeof e=="string"||typeof e=="number"?String(e):"default"}function nt(e,t){return typeof e=="string"?e:t}function mi(e,t){let o={folders:new Map,files:[]};e.forEach((i,s)=>{let l=t(i).split("/"),f=l.pop(),p=o,m="";for(let y of l)m=m?`${m}/${y}`:y,p.folders.has(y)||p.folders.set(y,{name:y,path:m,folders:new Map,files:[]}),p=p.folders.get(y);p.files.push({item:i,index:s,name:f})});let a=i=>{i.folders=[...i.folders.values()].sort((s,l)=>s.name.localeCompare(l.name)),i.files.sort((s,l)=>s.name.localeCompare(l.name)),i.folders.forEach(a)};return a(o),o}function kr(e,t,o=[]){let a=[],i=/\[([^\]\n]+)\]\(((?:https?:\/\/|bygone:\/\/)(?:[^\s()]|\([^\s()]*\))+)\)/gu,s=0;for(let l of t.matchAll(i)){if(l.index>0&&t[l.index-1]==="!")continue;let f;try{f=new URL(l[2])}catch{continue}if(f.protocol==="bygone:")try{Gn(f.href)}catch{continue}else if(f.protocol!=="https:"&&f.protocol!=="http:")continue;a.push(...xr(e,t,s,l.index,o));let p=e.createElement("a");p.href=f.href,p.target="_blank",p.rel="noopener noreferrer";let m=l.index+1;p.replaceChildren(...xr(e,t,m,m+l[1].length,o)),a.push(p),s=l.index+l[0].length}return a.push(...xr(e,t,s,t.length,o)),a}function xr(e,t,o,a,i){let s=[],l=o;for(let f of i){let p=Math.max(o,f.startOffset),m=Math.min(a,f.endOffset);if(p>=m)continue;p>l&&s.push(e.createTextNode(t.slice(l,p)));let y=e.createElement("span");y.className="tour-narration-segment",y.dataset.narrationSegmentId=f.id,y.textContent=t.slice(p,m),s.push(y),l=m}return l<a&&s.push(e.createTextNode(t.slice(l,a))),s}function yt(e,t){let o=document.createElement(e);return o.textContent=t,o}function gi(e,t){e.replaceChildren();let o=t?.details?.audience;if(e.hidden=!o,!o)return;e.append(yt("h2","Audience")),e.append(yt("p",`${o.purpose[0].toUpperCase()+o.purpose.slice(1)}${o.estimatedMinutes?` \xB7 about ${o.estimatedMinutes} min`:""}`)),e.append(yt("p",o.scope));let a=document.createElement("details");a.append(yt("summary","Assumed familiarity"));let i=document.createElement("dl");for(let[s,l]of[["Codebase",{none:"New to this codebase",some:"Some familiarity",maintainer:"Maintainer"}[o.codebase]],["Language",{none:"No prior knowledge",basic:"Basic",fluent:"Fluent",advanced:"Advanced"}[o.language]],["Reading demand",o.readingDemand],["Prerequisites",o.domain?.join("; ")||"None specified"]])i.append(yt("dt",s),yt("dd",l));a.append(i),e.append(a)}function yi(e,t,o){let a=t.kind==="scene"||t.kind==="step"?e.scenes[t.sceneIndex]:void 0,i=t.kind==="step"&&a&&"steps"in a?a.steps[t.stepIndex]:void 0,s=t.kind==="chapter"?e.chapters.find(y=>y.id===t.chapterId):a?e.chapters.find(y=>y.sceneIds.includes(a.id)):void 0,l=t.kind==="title"?e.opening:t.kind==="conclusion"?e.conclusion:t.kind==="chapter"?s:i??a,f=a?.kind==="deconstructed-diff"&&i&&"pairIndex"in i&&!i.body?a.steps.find(y=>y.pairIndex===i.pairIndex&&y.body):void 0,p=fe(e,t,o.mode),m={title:e.title,sourceUrl:e.sourceUrl,mode:o.mode,location:o.location,range:e.range,audience:e.details?.audience,opening:e.opening,section:{kind:t.kind,chapter:s?.id,scene:a?.id,step:i?.id},passage:l&&Object.fromEntries(Object.entries(l).filter(([y])=>["title","summary","body","bullets","takeaway","requirement","overview"].includes(y))),sceneContext:i&&a?{title:a.title,summary:a.summary,takeaway:a.takeaway,overview:"overview"in a?a.overview:void 0}:void 0,sceneRange:a?.kind==="deconstructed-diff"?a.realRange:void 0,stageExplanation:f&&{id:f.id,title:f.title,body:f.body},authoredEvidence:p,displayedEvidence:o.displayedEvidence===void 0?fe(e,t,o.mode,o.activePairIndex):o.displayedEvidence,focus:i&&("focus"in i?i.focus:{path:i.file,pairIndex:i.pairIndex,side:i.side,startLine:i.startLine,endLine:i.endLine}),connection:i&&"connection"in i?i.connection:void 0,image:i&&"image"in i&&i.image?{path:i.image.path,revision:i.image.revision,alt:i.image.alt,displayed:o.imageVisible}:void 0};return JSON.stringify(m,null,2)}function wi(e,t,o){return`${e==="explain"?"Help me understand this tour passage.":"Help me evaluate this change."}
|
|
650
|
+
|
|
651
|
+
My concern:
|
|
652
|
+
${t.trim()||"(No additional note; start with the captured passage.)"}
|
|
653
|
+
|
|
654
|
+
Investigate the concern against implementation code, relevant tests, and existing docs, requirements, or PR rationale. Distinguish intended behavior from the tour's claim and the evidence; label inferred intent and unresolved disagreement. Do not silently weaken an expectation to match the code.
|
|
655
|
+
|
|
656
|
+
Answer the concern, then identify any repair destination: implementation code, maintained documentation, PR explanation, the tour document, or the viewer. Missing evidence may need a check; disputed requirements may need a human decision. More tour prose is not always the remedy, and a clear answer may need no artifact change. Propose the smallest repair within the existing task authorization; this request does not itself authorize implementation edits or shared-system writes. Report what was checked, what remains unverified, and which artifacts actually changed. An agent reply does not update the saved tour document.
|
|
657
|
+
|
|
658
|
+
Captured tour context (a snapshot, not proof of current workspace state; synthetic panels are not commits):
|
|
659
|
+
${o}
|
|
660
|
+
|
|
661
|
+
Verify the pinned and current implementation revisions before acting. If authorized implementation changes affect the tour, revisit its claims and refresh evidence for the intended committed range; do not present working-tree edits as committed evidence. Use the pr-tour-guide skill when authoring or repairing a Bygone tour, if available. The location may require the original repository/server or exported HTML file.
|
|
662
|
+
`}function bi(e,t){let o=t(),a=document.createElement("dialog");a.className="tour-feedback-dialog",a.setAttribute("aria-labelledby","tour-feedback-title");let i=document.createElement("h2");i.id="tour-feedback-title",i.textContent=e==="explain"?"Explain this":"Question this change";let s=document.createElement("p");s.textContent="Describe what is unclear or seems wrong. Copy the request and paste it into your coding agent.";let l=document.createElement("label");l.htmlFor="tour-feedback-concern",l.textContent="Your question or concern";let f=document.createElement("textarea");f.id="tour-feedback-concern",f.rows=3;let p=document.createElement("details"),m=document.createElement("summary");m.textContent="Review the captured context";let y=document.createElement("pre");y.textContent=o,p.append(m,y);let b=document.createElement("textarea");b.readOnly=!0,b.rows=8,b.hidden=!0,b.setAttribute("aria-label","Request to copy manually");let E=document.createElement("p");E.setAttribute("role","status");let I=document.createElement("div");I.className="tour-feedback-actions";let T=document.createElement("button");T.type="button",T.textContent="Copy request";let v=document.createElement("button");v.type="button",v.textContent="Close",v.addEventListener("click",()=>a.close()),f.addEventListener("input",()=>{b.hidden=!0,E.textContent=""}),T.addEventListener("click",async()=>{let x=wi(e,f.value,o);T.disabled=!0,f.readOnly=!0;try{await navigator.clipboard.writeText(x),E.textContent="Copied. Paste into your agent to continue."}catch{b.value=x,b.hidden=!1,b.focus(),b.select(),E.textContent="Clipboard unavailable. Copy the selected request manually."}finally{T.disabled=!1,f.readOnly=!1}}),I.append(T,v),a.append(i,s,l,f,p,b,E,I),a.addEventListener("close",()=>a.remove(),{once:!0}),document.body.append(a),a.showModal(),f.focus()}(function(){let t=oo(),o=window.__BYGONE_EXPORT__,a=o?go(o):null,i={getItem(r){try{return window.localStorage.getItem(r)}catch{return null}},setItem(r,c){try{window.localStorage.setItem(r,c)}catch{}},removeItem(r){try{window.localStorage.removeItem(r)}catch{}}},s=!1,l=!1,f=0,p=Promise.resolve(),m=Promise.resolve(),y="bygone.tourSidebarWidth",b=240,E=600,I="bygone.tourNarrativeHeight",T=180,v=180,x="bygone.tourNarrationVoice",N="bygone.tourNarrationRate",B=new Set([.75,1,1.25,1.5,2]),M="speechSynthesis"in window&&"SpeechSynthesisUtterance"in window,n={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,historyChangedFiles:new Set,historyFiles:null,compare:null,comparisonFocus:null,comparisonCommits:[],comparisonDraftCommits:[],activeSceneIndex:-1,activeStepIndex:0,sceneIntroVisible:!1,narrativeParent:null,readingKey:"title",directoryEvidence:null,activeTourFilePath:null,tourFocusFilePath:null,tourSidebarWidth:Ki(),tourSidebarHidden:!1,tourNarrativeHeight:Gi(),tourNavigatorTab:"tour",showAllFiles:!1,showAllTourFiles:!1,collapsedFileFolders:new Set,revealedFilePath:null,narrationVoiceURI:i.getItem(x)||"",narrationRate:Di(),narrationVoices:[],renderedNarrationUnit:null,workspacePromptStatus:"",historyPrefix:"/history/"},F=null,V=null,O=null,j=[],J=new Map,oe=new Set,Q=null,ie=null,de=new URLSearchParams(window.location.search).get("workspaceEmbedded")==="1",wt=null,X=new wn(Mi(),{claimAudio:Hi,onStateChange:An,onSegmentChange:_i,canNavigateUnit:Ui,navigateUnit:zi});window.__BYGONE_HOST__={environment:"web",linkPreviews:!o,editorWorkerUrl:o?.workers.editor||"/media/editor.worker.js",diffWorkerUrl:o?.workers.diff||"/media/diff.worker.js",postMessage(r){Ri(r)}},window.addEventListener("message",r=>{if(!de||r.source!==window.parent||r.origin!=="null")return;let c=r.data;!c||typeof c!="object"||c.type!=="bygoneWorkspaceTourMode"||c.mode!=="historical"&&c.mode!=="deconstructed"||(wt=c.mode,!(!n.zoom||n.zoom.mode===c.mode||!K().includes(c.mode))&&_e(c.mode).catch(ae))});function zt(){if(Pi(),de){let r=document.getElementById("tour-mode-tabs"),c=document.getElementById("tour-mode-description");r&&(r.hidden=!0),c&&(c.hidden=!0)}Ie("Browser host ready.")}document.readyState!=="loading"?queueMicrotask(zt):window.addEventListener("DOMContentLoaded",zt,{once:!0});function ne(r){(r.type==="showDiff"||r.type==="showMultiDiff"||r.type==="showDirectoryDiff")&&(t.clear(),r={...r,renderRequestId:++he},n.mode==="tour"&&(n.displayedPanels=r.type==="showMultiDiff"?r.panels:n.zoom?.mode==="history"?n.historyPanels:Ci(),r.history||(r.history=Ir()),ve(),it()),se&&(Ae=r.renderRequestId)),window.dispatchEvent(new window.CustomEvent("bygone:host-message",{detail:r}))}let kn=0,be=new Map,se=null,he=0,Ae=null;function Ne(){n.zoomSwitching||(se=null)}function Be(){return new Promise(r=>{let c=++kn,u=h=>{be.delete(c);let g=n.tour?.scenes[n.activeSceneIndex],w=h?.activeMultiPairIndex,k=g&&Re(g)?At(g):[],S=h?.editorStates?.[h.activeMultiPanelId||h.activePaneSide];r({sceneIndex:n.activeSceneIndex,stepIndex:n.activeStepIndex,path:n.activeTourFilePath,view:n.zoom?.mode==="compare"&&!n.activeTourFilePath?"directory":"file",line:S?.selection?.startLineNumber,commit:(n.zoom?.mode==="history"?n.historyCommit:k[w+1]?.oid)||n.authoredTour.range.headOid,navigation:h,focusId:document.activeElement?.id,narrativeParent:n.narrativeParent,sceneIntroVisible:n.sceneIntroVisible,narrativeScroll:document.getElementById("tour-narrative-content")?.scrollTop||0,readingKey:n.readingKey,navigatorTab:n.tourNavigatorTab})},d=window.setTimeout(()=>u(null),1e3);be.set(c,h=>{window.clearTimeout(d),u(h)}),ne({type:"captureNavigationState",requestId:c})})}let ee=0;function Le(r=n.authoredTour){if(r.tours||!r.scenes.some(u=>u.kind==="deconstructed-diff"))return null;let c=r.zoom?.final;return c?.scenes.some(u=>u.kind==="walkthrough")?c:null}let rt={history:"History",compare:"Compare",historical:"Historical tour",deconstructed:"Deconstructed tour"},bt={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 Ht(r){return r==="historical"&&Le()?"Final tour":rt[r]}function R(r){return r==="historical"&&Le()?"The authored walkthrough of the completed endpoint diff.":bt[r]}function U(r=n.authoredTour){if(r.tours)return r.tours;if(!r.scenes.some(d=>d.kind==="deconstructed-diff"))return{historical:{scenes:r.scenes,chapters:r.chapters,opening:r.opening,conclusion:r.conclusion,details:r.details}};let u=Le(r);return{...u?{historical:u}:{},deconstructed:{scenes:r.scenes,chapters:r.chapters,opening:r.opening,conclusion:r.conclusion,details:r.details}}}function K(){return[...re()?["history"]:[],...o||re()?["compare"]:[],...o?Object.keys(U()).filter(r=>U()[r]):["historical","deconstructed"]]}function re(r=n.authoredTour){return o?o.profile==="full":Number(r?.version)>=2}function le(){return o?"Git history is not included in this Minimal export.":"History is unavailable for legacy v1 tours; open a version 2 tour to browse commit history."}function Ue(){return"Compare is unavailable for legacy v1 tours because this tour has no history backend."}function ze(){if(F)return;let r=document.getElementById("tour-mode-controls");if(!r)return;let c=document.getElementById("tour-mode-tabs"),u=document.getElementById("tour-mode-description"),d=document.getElementById("tour-mode-status");c&&(c.hidden=!0),u&&(u.hidden=!0),d&&(d.hidden=!0),V=document.createElement("div"),V.id="workspace-mode-controls",r.prepend(V),document.body.prepend(r);let h=document.createElement("div");h.id="workspace-view";for(let g of["tour-narrative","tour-narrative-resizer","container"]){let w=document.getElementById(g);w&&h.appendChild(w)}document.body.appendChild(h),new ResizeObserver(()=>{document.documentElement.style.setProperty("--workspace-toolbar-height",`${r.offsetHeight}px`)}).observe(r),F=pi({container:V,content:h,send:Ge})}function Ge(r){if(!(!r||typeof r!="object")){if(r.type==="workspaceMode"&&["history","compare","historical","deconstructed"].includes(r.mode)){_e(r.mode).catch(ae);return}r.type==="workspaceOpenTour"&&(r.kind==="historical"||r.kind==="deconstructed")&&Si()}}function ve(){if(!n.zoom||(ze(),!F))return;V.hidden=de;let r=document.getElementById("tour-mode-tabs"),c=document.getElementById("tour-mode-description");r&&(r.dataset.workspaceModeLabel=Ht(n.zoom.mode)),c&&(c.textContent=R(n.zoom.mode));let u=re();F.update({sessionId:Ve(),mode:n.zoom.mode,modeLabels:{historical:Ht("historical")},history:{enabled:u,label:"History",...u?{}:{reason:le()}},compare:{enabled:!!o||u,label:"Compare",...u?{}:{reason:Ue()}},availableTours:Object.keys(U()).filter(d=>d==="historical"||d==="deconstructed"),canCreateTours:!o,canOpenTours:!o,unavailableTourReason:"This tour is not included in the export.",revisionContext:[n.authoredTour?.range?.baseRef||n.authoredTour?.range?.mergeBaseOid,n.authoredTour?.range?.headRef||n.authoredTour?.range?.headOid].filter(Boolean).map(d=>/^[0-9a-f]{40}$/i.test(d)?d.slice(0,7):d).join(" \u2192 "),promptContext:vt(),status:n.workspacePromptStatus})}function Ve(){let r=n.authoredTour;return[r?.repository?.root||"",r?.range?.mergeBaseOid||"",r?.range?.headOid||""].join("\0")||"browser-workspace"}function vt(){let r=n.authoredTour,c=r?.range,u=Array.isArray(n.displayedPanels)?n.displayedPanels:[],d=_t(n.zoom?.mode==="compare"&&n.compare?.commits?n.compare.commits:u.map(S=>S?.commit)),h=u.length>0?d:_t([c?.mergeBaseOid,c?.headOid]),g=_t(u.map(S=>S?.path)),w=g.length>0?g:_t(n.tour?.files?.map(S=>S?.path)),k=vi(h,r);return{...typeof r?.repository?.root=="string"?{repository:r.repository.root}:{},...w.length>0?{paths:w}:{},...h.length>0?{revisions:h}:{},rangeStatus:k.status,...k.reason?{reason:k.reason}:{}}}function vi(r,c){if(r.length===0)return{status:"none",reason:"The browser view has no selected committed revisions."};if(r.length>2)return{status:"multiple",reason:"The displayed comparison contains more than two revision panels."};if(r.length!==2)return{status:"unavailable",reason:"The browser view could not resolve both comparison boundaries."};if(r.some(h=>/^(WORKTREE|INDEX)$/i.test(h)))return{status:"uncommitted",reason:"The browser comparison includes a live working or staged state."};if(!r.every(h=>/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(h)))return{status:"unavailable",reason:"The browser comparison does not expose two full revision identifiers."};let u=c?.range?.mergeBaseOid,d=c?.range?.headOid;return r[0]===u&&r[1]===d?{status:"exact",reason:"The manifest validates its merge-base/head range."}:r[0]===d&&r[1]===u?{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 _t(r){return[...new Set(r.filter(c=>typeof c=="string"&&c.trim()).map(c=>c.trim()))]}function Je(r){n.workspacePromptStatus=r,ve()}function xi(r){try{let c=new URL(r,window.location.href).pathname,u="/tour.json";if(c.endsWith(u))return`${c.slice(0,-u.length)||""}/history/`}catch{}return"/history/"}function ki(){return new Promise(r=>{let c=document.createElement("input");c.type="file",c.accept=".bygone,.yaml,.yml,application/yaml,text/yaml",c.hidden=!0,document.body.appendChild(c);let u=d=>{c.remove(),r(d||null)};c.addEventListener("change",()=>u(c.files?.[0])),c.addEventListener("cancel",()=>u(null)),c.click()})}function Ei(r){let c=n.authoredTour;if(!c)return!1;let u=c.repository?.root,d=c.range?.mergeBaseOid,h=c.range?.headOid,g=typeof r.repository=="string"?r.repository:"",w=typeof r.range?.mergeBaseOid=="string"?r.range.mergeBaseOid:"",k=typeof r.range?.headOid=="string"?r.range.headOid:"";return!!(u&&g&&u!==g||d&&w&&d!==w||h&&k&&h!==k)}function Ii(r){let c=typeof r.repository=="string"&&r.repository?r.repository:"(server-selected repository)",u=typeof r.range?.mergeBaseOid=="string"&&r.range.mergeBaseOid?r.range.mergeBaseOid:"(unknown base)",d=typeof r.range?.headOid=="string"&&r.range.headOid?r.range.headOid:"(unknown head)",h=n.authoredTour?.repository?.root||"(current repository unavailable)",g=n.authoredTour?.range?.mergeBaseOid||"(unknown base)",w=n.authoredTour?.range?.headOid||"(unknown head)";return["Open this authored tour from the server?",`Repository: ${c}`,`Range: ${u} \u2192 ${d}`,`Current browser range: ${h}, ${g} \u2192 ${w}`,"This loads the server-validated tour and does not change a local repository."].join(`
|
|
663
|
+
`)}async function Si(){if(o){Ie("This export contains a fixed snapshot. Open other tours in Bygone.");return}try{let r=await ki();if(!r)return;if(r.size>1024*1024)throw new Error("Choose an authored .bygone or .yaml file no larger than 1 MiB.");let c=typeof r.name=="string"?r.name.toLowerCase():"";if(!/\.(?:bygone|ya?ml)$/.test(c))throw new Error("Choose an authored .bygone or .yaml file.");let u=await r.text(),d=(k=!1)=>fetch("/tour/open",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:u,convertToV4:k})}),h=await d(),g=await h.json().catch(()=>({}));if(h.status===409&&g.conversion){if(!window.confirm(`${g.conversion.message}
|
|
664
|
+
|
|
665
|
+
${g.conversion.detail}
|
|
666
|
+
|
|
667
|
+
The converted copy will be downloaded after opening.`)){Je("Tour conversion canceled.");return}h=await d(!0),g=await h.json().catch(()=>({}))}if(!h.ok)throw new Error(g.error||`Tour upload failed (${h.status}).`);if(!g||typeof g.manifestUrl!="string"||!g.manifestUrl)throw new Error("Tour upload did not return a manifest URL.");if(Ei(g)&&!window.confirm(Ii(g))){Je("Kept the current tour.");return}if(!await Dr(g.manifestUrl)){Je("Could not load the uploaded tour.");return}if(typeof g.convertedSource=="string"){let k=URL.createObjectURL(new Blob([g.convertedSource],{type:"application/yaml"})),S=document.createElement("a");S.href=k,S.download=`${r.name.replace(/(?:\.bygone)?\.ya?ml$|\.bygone$/i,"")}.v4.bygone`,document.body.appendChild(S),S.click(),S.remove(),setTimeout(()=>URL.revokeObjectURL(k),1e3)}Je("")}catch(r){Je(`Could not open existing tour: ${r instanceof Error?r.message:String(r)}`)}}function Y(){return!n.zoom||!!U()[n.zoom.mode]}function xt(r){let c=n.authoredTour;if(U()[r])return{...c,opening:void 0,conclusion:void 0,details:void 0,...U()[r]};let u=r==="compare"&&n.compare?[...new Map([...n.compare.inventory||c.files,...n.compare.files].map(d=>[d.path,d])).values()]:r==="history"&&n.historyFiles||c.files;return{...c,opening:void 0,conclusion:void 0,details:void 0,scenes:[],chapters:[],files:u}}function ot(){let r=document.getElementById("tour-mode-controls");if(r.hidden=!n.zoom||de,!n.zoom)return;ve();let c=document.getElementById("tour-mode-tabs"),u=document.getElementById("tour-mode-description");c&&(c.hidden=!0),u&&(u.hidden=!0);let d=n.zoom.mode==="history",h=re();document.getElementById("tour-history-controls").hidden=!h||n.zoom.mode==="compare",document.getElementById("tour-compare-controls").hidden=!h||n.zoom.mode!=="compare";let g=["historical","deconstructed"].includes(n.zoom.mode)&&!U()[n.zoom.mode];document.body.classList.toggle("workspace-empty-tour",g),document.body.classList.toggle("tour-derived-mode",!Y()),Y()||document.body.classList.remove("tour-discussion");for(let w of["tour-history-parent","tour-history-base"])document.getElementById(w).hidden=!d;it()}function it(){let r=n.comparisonDraftCommits,c=r.length,u=re(),d=[...new Set(In())],h=S=>S.length===c&&S.every(P=>r.includes(P)),g=n.zoom?.mode==="compare"&&h(n.compare?.commits||[]);for(let S of["history","compare"])document.getElementById(`tour-${S}-count`).textContent=`${c} selected`,document.getElementById(`tour-${S}-hint`).textContent=c<2?"Select 2+ revisions":g?"Selection applied":S==="compare"?"Unapplied selection":"Ready to compare",document.getElementById(`tour-${S}-clear`).disabled=!c,document.getElementById(`tour-${S}-reset`).disabled=!d.length||h(d);document.getElementById("tour-history-compare").disabled=c<2||!u;let w=document.getElementById("tour-compare-apply");w.disabled=c<2||!u||g,w.title=g?"These revisions are already displayed":"Apply the selected revisions";let k=document.getElementById("tour-compare-scope");k.textContent=n.compare?.path||"All changed files",k.title=n.compare?.path?`File scope: ${n.compare.path}`:"Comparing across all changed files",document.getElementById("tour-compare-all").hidden=!n.compare?.path;for(let S of["tour-history-parent","tour-history-base"])document.getElementById(S).disabled=!re()||!n.historyCommit}function En(){return[...new Set([...[...n.historyEntries].reverse().map(r=>r.commit),n.authoredTour.range.mergeBaseOid,...n.authoredTour.commits.map(r=>r.oid),n.authoredTour.range.headOid])]}function Er(r){return ii(r,En())}async function pe(r,c,u=n.historyPrefix,d=n.authoredTour){if(a)return a(r,c);if(!re(d))throw new Error(le());let h=await fetch(`${u||"/history/"}${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),g=await h.json();if(!h.ok)throw new Error(g.error||`History request failed (${h.status}).`);return g}function ae(r){let c=r instanceof Error?r.message:String(r),u=document.getElementById("tour-mode-status");u&&(u.textContent=c),F&&Je(c)}function In(){return n.displayedPanels.map(r=>r.commit).filter(Boolean)}function Ci(){let r=n.tour?.scenes[n.activeSceneIndex],c=n.zoom?.mode==="compare"?n.comparisonCommits:[n.authoredTour.range.mergeBaseOid,n.authoredTour.range.headOid];if(n.directoryEvidence&&Re(r)){let u=At(r),d=r.overview?.comparison;c=r.kind==="deconstructed-diff"?[]:[(d?u.find(h=>h.id===d.from):u[0])?.oid,(d?u.find(h=>h.id===d.to):u.at(-1))?.oid]}return["left","right"].map((u,d)=>({id:u,commit:c[d]}))}function Ir(){let r=n.displayedPanels.map(c=>c.commit);return{...kt(Cn({commits:In()}),r,null),navigatorOnly:!0}}async function Ti(r){if(!r||!n.zoom||!re())return[];if(!n.fileHistoryCache.has(r)){let c=pe("list",{path:r,commit:n.authoredTour.range.headOid}).then(u=>u.entries);n.fileHistoryCache.set(r,c),c.catch(()=>n.fileHistoryCache.delete(r))}return n.fileHistoryCache.get(r)}async function $i(r,c){try{let u=await Ti(r);if(c!==he)return;ne({type:"updateCommitMarkers",changedCommits:u.map(d=>d.commit),path:r})}catch(u){c===he&&ae(u)}}async function Ye(r,c,u=!0){if(c=c||n.historyCommit||n.authoredTour.range.headOid,!r)return Ai(c,u);let d=++ee,h=n.historyEntries,g=h.find(A=>A.commit===c);if(n.historyPath===r&&n.historyCommit===c&&n.historyPanels.length){await jt();return}let w=await pe("diff",{path:r,commit:c,head:n.authoredTour.range.headOid});if(d!==ee||n.zoom.mode!=="history")return;if(u&&n.historyPanels.length&&n.historyCommit===c){let A=await Promise.all(n.historyPanels.map(async z=>{let _=z.commit===c?{rightContent:w.rightContent,path:w.path}:z.commit===w.parentCommit?{rightContent:w.leftContent,path:w.previousPath||w.path}:z.commit?await pe("diff",{path:r,commit:z.commit,head:n.authoredTour.range.headOid}):{rightContent:"",path:r};return{...z,content:_.rightContent,path:_.path}}));if(d!==ee||n.zoom.mode!=="history")return;n.historyPanels=A,n.historyPath=r,n.historyDiff=w,await jt(),ye();return}let k=h.findIndex(A=>A.commit===c),P=(k>=0?h[k+1]:null)?.commit||w.parentCommit,L=P&&P!==w.parentCommit?(await pe("diff",{path:r,commit:P,head:n.authoredTour.range.headOid})).rightContent:w.leftContent;if(d!==ee||n.zoom.mode!=="history")return;n.historyPath=r,n.historyCommit=c;let $=Math.max(2,n.historyPanels.length);n.historyDiff=w;let D=(A,z,_)=>({id:`history-${A||"empty"}`,commit:A,content:z,label:_,path:w.path,editable:!1});for(n.historyPanels=[D(P,L,P?.slice(0,7)||"Empty tree"),D(c,w.rightContent,g?`${g.shortCommit} ${g.summary}`:c.slice(0,7))],n.historyFocus=`history-${c}`;n.historyPanels.length<$;){let A=qt(n.historyPanels[0],"left");if(!A)break;let z=await pe("diff",{path:r,commit:A.commit,head:n.authoredTour.range.headOid});if(d!==ee||n.zoom.mode!=="history")return;n.historyPanels.unshift(D(A.commit,z.rightContent,`${A.shortCommit} ${A.summary}`))}await jt(),document.getElementById("tour-mode-status").textContent="",it(),ye()}async function Ai(r=n.historyCommit||n.authoredTour.range.headOid,c=!0){let u=++ee,d=n.historyEntries.find(w=>w.commit===r);if(!d)throw new Error("The selected revision is unavailable in this history.");let h=c&&n.historyCommit===r&&n.historyPanels.length?n.historyPanels:[d.parentCommit||null,r].map(w=>({id:`history-${w||"empty"}`,commit:w,content:"",editable:!1,label:w?w.slice(0,7):"Empty tree"})),g=await pe("changed-files",{commits:h.map(w=>w.commit||null),includeEntries:!0,includeFiles:!0});u!==ee||n.zoom.mode!=="history"||(n.historyCommit=r,n.historyPanels=h,n.historyFocus=h.at(-1).id,n.historyPath=null,n.historyChangedFiles=new Set(g.paths),n.historyFiles=g.files,n.tour.files=g.files,Fn(),n.activeTourFilePath=null,ue(),ne({...nn(h.map(w=>w.label),g.entries),history:kt(Sr(n.historyEntries,r,{}),h.map(w=>w.commit),r)}),qe(g.paths.length?"":"No changed files for the selected revisions."),it(),ye())}function Sr(r,c,u){let d=r.findIndex(g=>g.commit===c),h=r[d];return{fileName:(n.historyPath||u.path||"Changed files").split("/").pop(),canGoBack:d>=0&&d<r.length-1,canGoForward:d>0,positionLabel:`${d+1} / ${r.length}`,leftCommitLabel:n.historyPanels[0]?.commit?.slice(0,7)||"Empty tree",leftTimestamp:"",rightCommitLabel:n.historyPanels.at(-1)?.label||(h?`${h.shortCommit} ${h.summary}`.trim():c.slice(0,7)),rightTimestamp:h?.timestamp||"",workingTreeControls:!1,rail:{activeTabId:"history",tabs:[{id:"history",label:"History"}],itemsByTab:{history:[]}}}}function qt(r,c){let u=En(),d=u.indexOf(r.commit);if(d<0)return null;let h=new Set(n.historyPanels.map(k=>k.commit)),w=(c==="left"?u.slice(0,d).reverse():u.slice(d+1)).find(k=>!h.has(k)&&n.historyEntries.some(S=>S.commit===k));return n.historyEntries.find(k=>k.commit===w)}function kt(r,c,u){return r.rail.itemsByTab.history=ro(n.historyEntries,{displayed:c,active:u,selected:n.comparisonDraftCommits,tourCommits:new Set(n.authoredTour?.commits.map(d=>d.oid)),selectionEnabled:!!n.zoom,missingRevisionSelectionEnabled:!!n.zoom,missingRevisionLabel:d=>d?`${d.slice(0,7)} \xB7 Parent/base revision`:"Empty tree"}).map(d=>({...d,meta:d.parents.length>1?`${d.meta} \xB7 Merge: ${d.parents.map(h=>h.slice(0,7)).join(", ")}`:d.meta})),r}async function jt(){let r=n.historyPanels,c=n.authoredTour,u=ee,d=await pe("changed-files",{commits:r.map(w=>w.commit||null),includeFiles:!0});if(u!==ee||r!==n.historyPanels||c!==n.authoredTour||n.zoom.mode!=="history")return;n.historyChangedFiles=new Set(d.paths),n.historyFiles=d.files,n.tour.files=d.files,Fn();let h=n.historyPanels.map(w=>({...w,addLeftEnabled:!!qt(w,"left"),addRightEnabled:!!qt(w,"right"),removeEnabled:n.historyPanels.length>2})),g=h.find(w=>w.id===n.historyFocus)?.commit;n.activeTourFilePath=n.historyPath,ue(),ne({...rn({panels:h,files:Gt(),activePanelId:n.historyFocus,mutationEnabled:!0,canReturnToDirectory:!0},(w,k)=>we(w.content,k.content)),history:kt(Sr(n.historyEntries,n.historyCommit,n.historyDiff),h.map(w=>w.commit),g)})}async function Ni(r){let c=n.historyPanels.find(u=>u.id===(r.anchorPanelId||r.panelId));if(c){if(r.type==="multiRemovePanel"){if(n.historyPanels.length<=2)return;++ee,n.historyPanels=n.historyPanels.filter(u=>u!==c),n.historyFocus===c.id&&(n.historyFocus=n.historyPanels.at(-1).id)}else{let u=qt(c,r.side);if(!u)return;let d=++ee,h=await pe("diff",{path:n.historyPath,commit:u.commit,head:n.authoredTour.range.headOid});if(d!==ee||n.zoom.mode!=="history")return;let g={id:`history-${u.commit}`,commit:u.commit,content:h.rightContent,label:`${u.shortCommit} ${u.summary}`,path:h.path,editable:!1};n.historyPanels.push(g);let w=En();n.historyPanels.sort((k,S)=>w.indexOf(k.commit)-w.indexOf(S.commit)),n.historyFocus=g.id}await jt()}}function Sn(r){let c=n.historyEntries.findIndex(d=>d.commit===n.historyCommit),u=n.historyEntries[c+r];if(u)return Ye(n.historyPath,u.commit,!1)}function Cn(r){let c=r.commits;return{fileName:(r.path||n.activeTourFilePath||"Comparison").split("/").pop(),canGoBack:!1,canGoForward:!1,positionLabel:`${r.commits.length} loaded panels`,leftCommitLabel:c[0]?.slice(0,7)||"",leftTimestamp:"",rightCommitLabel:c.at(-1)?.slice(0,7)||"",rightTimestamp:"",workingTreeControls:!1,rail:{activeTabId:"history",tabs:[{id:"history",label:"History"}],itemsByTab:{history:[]}}}}function Cr(r,c=null){if(!r||r.kind!=="text-diff")return!1;qe("");let u=r.comparisonPanels;return c=c||n.comparisonFocus,n.comparisonFocus=c,n.activeTourFilePath=r.path,ue(),ne({...rn({panels:u,files:Gt(),activePanelId:c?`compare-${c}`:null,mutationEnabled:!1,reorderEnabled:!1,canReturnToDirectory:!0},(d,h)=>we(d.content,h.content)),history:kt(Cn(n.compare),n.compare.commits,c)}),ye(),!0}async function Tr(r,c=null){let u=++ee;if(!r.comparisonPanels){let d;try{d=await pe("compare-many",{commits:n.compare.commits,path:r.path})}catch(w){if(u!==ee)return!1;throw w}if(u!==ee||n.zoom?.mode!=="compare")return!1;let h=n.tour.files.findIndex(w=>w.path===r.path),g=d.files.find(w=>w.path===r.path)||d.files[0];if(!g)return document.getElementById("tour-mode-status").textContent="This file is absent from the selected revisions.",!1;r={...g,path:r.path},n.tour.files[h]=r,ue(),r.kind==="omitted"&&(document.getElementById("tour-mode-status").textContent=r.reason)}return Cr(r,c)}async function $r(r,c,u=null){r=Er(r);let d=++ee,h=await pe("compare-many",r),g=re()?await pe("changed-files",{commits:r.commits,includeFiles:!0}):null,w=new Set(g?.paths||h.files.map(P=>P.path));for(let P of h.files)P.comparisonPanels?.some(L=>w.has(L.path))&&w.add(P.path);if(d!==ee||n.zoom.mode!=="compare")return;let k=h.files;n.comparisonCommits=r.commits,n.compare={...r,files:k,inventory:g?.files,entries:h.entries,changedPaths:w},n.tour=xt("compare"),n.activeSceneIndex=-1,n.tourFocusFilePath=null,st(),ot(),Xe();let S=n.tour.files.find(P=>P.kind==="text-diff"&&P.path===c)||k.find(P=>P.kind==="text-diff");if(se?.view==="directory")Tn();else if(S){if(!await Tr(S,u))return}else{n.activeTourFilePath=null;let P=r.commits.map(L=>({id:`compare-${L}`,commit:L,path:"No text changes",content:"",label:L.slice(0,7),editable:!1}));ne({...rn({panels:P,files:{paths:[],currentPath:null},mutationEnabled:!1,reorderEnabled:!1,canReturnToDirectory:!0},(L,$)=>we(L.content,$.content)),history:kt(Cn(r),r.commits,null)}),n.activeTourFilePath=null,se=null,ue()}document.getElementById("tour-mode-status").textContent=k.length?S?"":"Changed files cannot be displayed as text. See the file list for details.":"No changes between these revisions.",ye()}async function He(r){if(!re()){Je(Ue());return}n.zoomSwitching||(n.zoom.mode!=="compare"?await _e("compare",r):await $r(r,n.activeTourFilePath),Vt("commits"))}function Tn(){n.compare&&(n.activeTourFilePath=null,ue(),ne(nn(n.compare.commits.map(r=>r.slice(0,7)),n.compare.entries)),qe(n.compare.entries.length?"":"No changed files for the selected comparison."),ye())}function $n(){return{commits:[n.authoredTour.range.mergeBaseOid,n.authoredTour.range.headOid]}}function Ar(){return n.historyEntries.find(r=>r.commit===n.historyCommit)?.path||n.historyPath}function _e(r,c,u){let d=m.then(()=>Li(r,c,u));return m=d.catch(()=>{}),d}async function Li(r,c,u){if(!n.zoom||n.zoomSwitching||r===n.zoom.mode||!K().includes(r))return;n.zoomSwitching=!0,++ee;let d=n.zoom.mode,h;try{h=await Be(),n.zoom.depart(h),X.stop();let g=n.zoom.enter(r,r==="history"?h:null);if(n.tourNavigatorTab=g.restore?g.location.navigatorTab||"commits":Y()?"tour":"commits",n.activeSceneIndex=-1,n.activeStepIndex=0,n.narrativeParent=null,n.directoryEvidence=null,n.sceneIntroVisible=!1,n.tourFocusFilePath=null,n.tour=xt(r),st(),Xe(),ot(),document.getElementById("tour-mode-status").textContent="",se=g.restore&&!c?g.location:null,r==="history")await Ye(u||(g.restore?g.location.path:null),n.historyCommit||g.location.commit);else if(r==="compare")await $r(c||n.compare||$n(),u||g.location.path||h.path);else if(U()[r]&&(me(Math.max(0,g.location.sceneIndex),g.location.stepIndex,{zoomLanding:!0,showIntro:g.restore?g.location.sceneIntroVisible:!0,readingKey:g.restore?g.location.readingKey:"title"}),g.location.path&&n.activeTourFilePath!==g.location.path)){let w=n.tour.files.findIndex(k=>k.path===g.location.path);w>=0&&Tt(w)}if(ye(),l&&!s){let w=new URL(window.location.href);w.hash=Y()?Ze(n.zoom.mode,at(j.find(k=>k.key===n.readingKey))):"",window.history.replaceState(null,"",w)}}catch(g){se=null,n.zoom.enter(d),n.tour=xt(d),h&&(n.activeSceneIndex=h.sceneIndex,n.activeStepIndex=h.stepIndex,n.activeTourFilePath=h.path,n.narrativeParent=h.narrativeParent,n.sceneIntroVisible=h.sceneIntroVisible,n.tourNavigatorTab=h.navigatorTab),st(),ot(),Xe(),h&&Y()&&(se=h,me(h.sceneIndex,h.stepIndex,{zoomLanding:!0,showIntro:h.sceneIntroVisible,readingKey:h.readingKey}),h.path&&n.activeTourFilePath!==h.path&&Tt(n.tour.files.findIndex(w=>w.path===h.path))),ue(),ye(),ae(g)}finally{n.zoomSwitching=!1}}async function Ri(r){if(!(!r||typeof r!="object")){if(r.type==="navigationState"){be.get(r.requestId)?.(r.navigation);return}if(r.type==="renderComplete"&&n.mode==="tour"&&r.renderRequestId===he&&$i(n.activeTourFilePath,he),r.type==="renderComplete"&&se&&r.renderRequestId===Ae){let c=se;se=null,ne({type:"restoreNavigationState",navigation:c.navigation});let u=document.getElementById("tour-narrative-content");u&&(u.scrollTop=c.narrativeScroll||0,Q=u.scrollTop),c.focusId&&document.getElementById(c.focusId)?.focus({preventScroll:!0})}if(r.type==="ready"){let c=new URLSearchParams(window.location.search),u=c.get("manifest");u||o?Dr(u):c.get("demo")==="1"&&Qr();return}if(n.mode==="tour"&&n.directoryEvidence&&Y()){if(r.type==="openDirectoryEntry"){Mn(r.relativePath);return}if(r.type==="returnToDirectory"){Dn();return}}if(n.mode==="tour"){if(n.zoom?.mode==="compare"&&["openDirectoryEntry","returnToDirectory"].includes(r.type)){if(Ne(),r.type==="returnToDirectory")Tn();else{let c=n.compare.files.find(u=>u.path===r.relativePath);c?.kind==="text-diff"?Cr(c):c&&qe(`${c.path}: ${c.reason||"This file cannot be displayed as text."}`)}return}if(r.type==="multiMovePanel")return;if(n.zoom?.mode==="history"&&["openDirectoryEntry","returnToDirectory","navigateFile"].includes(r.type)){Ne();let c=Gt();r.type==="openDirectoryEntry"&&(c.paths=[...n.historyChangedFiles]);let u=no(r,c,!0);u&&Ye(u.path,n.historyCommit).catch(ae);return}if(n.zoom?.mode==="history"&&["multiAddPanel","multiRemovePanel"].includes(r.type)){Ni(r).catch(ae);return}if(r.type==="multiSetActivePair"||r.type==="multiSetActivePanel"){Y()&&Number.isInteger(r.pairIndex)&&(document.getElementById("file-info").textContent=Bn(n.activeTourFilePath,r.pairIndex)),n.zoom?.mode==="history"?n.historyFocus=r.type==="multiSetActivePanel"?r.panelId:n.historyPanels[r.pairIndex]?.id||n.historyFocus:n.zoom?.mode==="compare"&&(n.comparisonFocus=r.type==="multiSetActivePanel"?r.panelId.replace(/^compare-/,""):n.comparisonCommits[r.pairIndex]);return}if(r.type==="historyBack"||r.type==="historyForward"){if(n.zoom?.mode!=="history")return;let c=Sn(r.type==="historyBack"?1:-1);c&&c.catch(ae);return}if(r.type==="toggleHistorySelection"&&Number.isInteger(r.index)){let c=n.displayedPanels.map(h=>h.commit),u=r.index<0?{commit:c[-r.index-1]}:n.historyEntries[r.index];if(!u?.commit)return;let d=n.comparisonDraftCommits.includes(u.commit)?n.comparisonDraftCommits.filter(h=>h!==u.commit):[...n.comparisonDraftCommits,u.commit];n.comparisonDraftCommits=d.length>=2?Er({commits:d}).commits:d,it();return}if(r.type==="compareHistoryEntry"&&Number.isInteger(r.index)){let c=n.historyEntries[r.index];c?.parentCommit&&He({commits:[c.parentCommit,c.commit],path:n.activeTourFilePath}).catch(ae);return}if(r.type==="selectHistoryEntry"&&Number.isInteger(r.index)){let c=n.historyEntries[r.index];if(c&&n.zoom?.mode==="history"){let u=n.historyPanels.find(d=>d.commit===c.commit);u&&n.historyPath?(n.historyFocus=u.id,ne({type:"focusHistoryPanel",panelId:u.id})):Ye(n.historyPath,c.commit,!1).catch(ae)}if(c&&n.zoom?.mode!=="history"){let u=n.displayedPanels.find(d=>d.commit===c.commit);u?ne({type:"focusHistoryPanel",panelId:u.id}):(n.historyCommit=c.commit,n.historyPath=n.activeTourFilePath||n.historyPath,_e("history",void 0,n.activeTourFilePath).catch(ae))}return}}if(r.type==="navigateFile"&&n.mode==="tour"){Hr(r.direction==="previous"?-1:1);return}if(r.type==="navigateTourStep"&&n.mode==="tour"){let c=r.sceneIndex,u=r.stepIndex;Number.isInteger(c)&&Number.isInteger(u)&&me(c,u,{userNavigation:!0,showIntro:!1});return}r.type==="recomputeDiff"&&n.mode==="diff"&&n.left&&n.right&&(n.left.content=r.leftContent,n.right.content=r.rightContent,ne({type:"showDiff",file1:n.left.name,file2:n.right.name,comparisonId:`web-${n.comparisonId}`,leftContent:n.left.content,rightContent:n.right.content,diffModel:we(n.left.content,n.right.content),history:null}))}}function Pi(){let r=(C,q)=>document.getElementById(C)?.addEventListener("click",()=>{Promise.resolve().then(q).catch(ae)});for(let C of["explain","question"])r(`tour-feedback-${C}`,()=>{if(!Y())return;let q=j.find(ge=>ge.key===n.readingKey);q&&bi(C,()=>yi(n.tour,q,{mode:n.zoom?.mode||"historical",location:Gr(at(q)),imageVisible:t.isVisible(),displayedEvidence:document.body.classList.contains("tour-discussion")||t.isVisible()?null:xe?.tour===n.tour?xe.context:null}))});let c=[...document.querySelectorAll(".tour-selection-more")],u=(C,q=!1)=>{C.open=!1,q&&C.querySelector("summary").focus()};for(let C of c)C.addEventListener("click",q=>{q.target.closest("button")&&u(C,!0)});document.addEventListener("click",C=>{for(let q of c)q.open&&!q.contains(C.target)&&u(q)}),document.addEventListener("keydown",C=>{if(C.key==="Escape")for(let q of c)q.open&&(C.preventDefault(),u(q,!0))}),r("tour-history-compare",()=>He({commits:n.comparisonDraftCommits})),r("tour-compare-apply",()=>He({commits:n.comparisonDraftCommits,path:n.compare?.path})),r("tour-history-parent",()=>{let C=n.historyEntries.find(q=>q.commit===n.historyCommit)?.parentCommit;if(!C){ae("This is the first commit; History already shows its comparison with the empty tree.");return}return He({commits:[C,n.historyCommit],path:Ar()})}),r("tour-history-base",()=>He({commits:[n.authoredTour.range.mergeBaseOid,n.historyCommit],path:Ar()})),r("tour-history-final",()=>He($n())),r("tour-compare-final",()=>He($n())),r("tour-compare-all",()=>He({commits:n.compare.commits}));let d=C=>{n.comparisonDraftCommits=C.filter(Boolean),it(),ne({type:"updateHistorySelection",commits:n.comparisonDraftCommits})};for(let C of["history","compare"])r(`tour-${C}-clear`,()=>d([])),r(`tour-${C}-reset`,()=>d(In()));for(let C of["wheel","pointerdown","keydown"])document.addEventListener(C,q=>{!q.isTrusted||q.target?.closest?.("#tour-mode-controls")||q.target?.closest?.(".monaco-editor, .diff-toolbar, #tour-narrative")&&Ne()},{capture:!0,passive:!0});let h=document.getElementById("web-compare-test"),g=document.getElementById("web-open-diff"),w=document.getElementById("web-open-diff3"),k=document.getElementById("web-diff-input"),S=document.getElementById("web-diff3-input"),P=document.getElementById("tour-narration"),L=document.getElementById("tour-return-focus"),$=document.getElementById("tour-search-input"),D=document.getElementById("tour-search-scope"),A=document.getElementById("tour-listen"),z=document.getElementById("tour-stop"),_=document.getElementById("tour-narration-skip-back"),te=document.getElementById("tour-narration-skip-ahead"),H=document.getElementById("tour-narration-voice"),Z=document.getElementById("tour-narration-rate");ji(),document.getElementById("tour-show-all-files")?.addEventListener("change",C=>{Y()?n.showAllTourFiles=C.target.checked:n.showAllFiles=C.target.checked,ue()}),document.getElementById("tour-files")?.addEventListener("toggle",C=>{let q=C.target;!(q instanceof HTMLDetailsElement)||!q.dataset.fileFolder||!q.isConnected||(q.open?n.collapsedFileFolders.delete(q.dataset.fileFolder):n.collapsedFileFolders.add(q.dataset.fileFolder))},!0),Wi(),Vi(),Fi(),document.getElementById("tour-navigator-tabs")?.addEventListener("click",C=>{let q=C.target instanceof Element?C.target.closest("[data-tour-navigator]"):null;q?.dataset.tourNavigator&&Vt(q.dataset.tourNavigator)}),h?.addEventListener("click",()=>{Qr()}),g?.addEventListener("click",()=>{k.value="",k.click()}),w?.addEventListener("click",()=>{S.value="",S.click()}),k?.addEventListener("change",async()=>{let C=Array.from(k.files||[]);if(C.length!==2){Ie("Select exactly 2 files for a diff.");return}await us(C)}),S?.addEventListener("change",async()=>{let C=Array.from(S.files||[]);if(C.length<1){Ie("Select one or more files.");return}await fs(C)}),document.getElementById("tour-title")?.addEventListener("click",()=>Xt("tour")),document.getElementById("tour-narrative-content")?.addEventListener("scroll",as,{passive:!0}),document.getElementById("tour-back")?.addEventListener("click",()=>Wt(-1)),document.getElementById("tour-next")?.addEventListener("click",()=>Wt(1)),P?.addEventListener("click",()=>ns()),L?.addEventListener("click",Xi),document.getElementById("tour-directory-root")?.addEventListener("click",()=>{Xt("scene"),document.getElementById("tour-directory-root").focus({preventScroll:!0})}),$?.addEventListener("input",Xe),D?.addEventListener("change",Xe),A?.addEventListener("click",Nr),z?.addEventListener("click",()=>X.stop()),_?.addEventListener("click",()=>X.skipSegment(-1)),te?.addEventListener("click",()=>X.skipSegment(1)),H?.addEventListener("change",()=>{n.narrationVoiceURI=H.value,i.setItem(x,n.narrationVoiceURI)}),Z&&(Z.value=String(n.narrationRate),Z.addEventListener("change",()=>{let C=Number(Z.value);n.narrationRate=B.has(C)?C:1,Z.value=String(n.narrationRate),i.setItem(N,String(n.narrationRate))})),document.getElementById("tour-search-results")?.addEventListener("click",C=>{let q=C.target instanceof Element?C.target.closest("[data-tour-search-result]"):null;q&&qi(Number(q.getAttribute("data-tour-search-result")))}),window.addEventListener("keydown",C=>{if(n.mode==="tour"&&(C.metaKey||C.ctrlKey)&&C.shiftKey&&C.key.toLocaleLowerCase()==="f"){C.preventDefault(),C.stopImmediatePropagation(),n.tourSidebarHidden&&Ln(!1),Vt("tour"),document.querySelector(".tour-search-disclosure")?.setAttribute("open",""),$?.focus(),$?.select();return}n.mode!=="tour"||C.metaKey||C.ctrlKey||C.altKey||es(C.target)||(C.key==="PageUp"||C.key==="ArrowLeft"?(C.preventDefault(),n.zoom?.mode==="history"?Sn(1)?.catch(ae):Wt(-1)):C.key==="PageDown"||C.key==="ArrowRight"?(C.preventDefault(),n.zoom?.mode==="history"?Sn(-1)?.catch(ae):Wt(1)):n.zoom?.mode==="history"&&["ArrowUp","ArrowDown"].includes(C.key)&&(C.preventDefault(),Hr(C.key==="ArrowUp"?-1:1)))},!0),window.addEventListener("bygone:tour-command",C=>{C.detail==="toggleNarration"&&Nr(),C.detail==="pauseNarration"&&X.pauseForExternalOwner()}),window.addEventListener("beforeunload",()=>X.dispose(),{once:!0}),An(X.state)}function Fi(){let r=document.getElementById("tour-narration-voice"),c=document.getElementById("tour-listen");if(!M){c&&(c.disabled=!0,c.title="Device narration is not supported by this browser."),r&&(r.disabled=!0),Et("Device narration unavailable");return}let u=()=>{if(n.narrationVoices=window.speechSynthesis.getVoices().filter(d=>!o||d.localService).slice().sort((d,h)=>Number(h.default)-Number(d.default)||d.lang.localeCompare(h.lang)||d.name.localeCompare(h.name)),n.narrationVoiceURI&&n.narrationVoices.length>0&&!n.narrationVoices.some(d=>d.voiceURI===n.narrationVoiceURI)&&(n.narrationVoiceURI="",i.removeItem(x)),r){let d=document.createElement("option");d.value="",d.textContent="System default voice",r.replaceChildren(d,...n.narrationVoices.map(h=>{let g=document.createElement("option");return g.value=h.voiceURI,g.textContent=`${h.name} (${h.lang})${h.default?" \u2014 default":""}`,g})),r.value=n.narrationVoiceURI,r.disabled=n.narrationVoices.length===0}};u(),window.speechSynthesis.addEventListener("voiceschanged",u)}function Di(){let r=Number(i.getItem(N));return B.has(r)?r:1}function Mi(){let r=null;return{speak(c,u){if(!M){u.onError("Device narration is not supported by this browser.");return}let d=new window.SpeechSynthesisUtterance(c.speechText),h=n.narrationVoices.find(g=>g.voiceURI===n.narrationVoiceURI)||(o?n.narrationVoices[0]:null);if(o&&!h){u.onError("No local narration voice is available.");return}h&&(d.voice=h),d.rate=n.narrationRate,d.onend=()=>{r===d&&(r=null),u.onEnd()},d.onerror=g=>{r===d&&(r=null),u.onError(Oi(g.error))},r=d,window.speechSynthesis.speak(d)},pause(){M&&window.speechSynthesis.pause()},resume(){M&&window.speechSynthesis.resume()},cancel(){r=null,M&&window.speechSynthesis.cancel()}}}function Oi(r){return r==="not-allowed"?"Device narration needs permission to play audio.":r==="language-unavailable"||r==="voice-unavailable"?"The selected device voice is unavailable.":`Device narration failed${r?`: ${r}`:"."}`}function Bi(){if(!M||n.mode!=="tour")return;let r=Lr("playback-start");r&&(n.renderedNarrationUnit=r,ts(r),X.start(r,!0))}function Nr(){X.state.kind==="playing"||X.state.kind==="paused"?X.togglePause():Bi()}function Lr(r){let c=j.find(u=>u.key===n.readingKey);return n.tour&&c?Qo(n.tour,c,{entry:r}):null}function Ui(r,c){return!!(n.tour&&Ut(j,r.readingKey,c,tt(n.tour)))}function zi(r,c){if(!n.tour)return null;let u=Ut(j,r.readingKey,c,tt(n.tour));return u?me(u.sceneIndex,u.stepIndex,{readingKey:u.key,narrationNavigation:"controller",narrationEntry:"continuous"}):null}function Hi(){o||fetch("/narration/claim",{method:"POST",cache:"no-store"}).catch(()=>{})}function An(r){let c=document.getElementById("tour-listen"),u=document.getElementById("tour-stop"),d=document.getElementById("tour-narration-skip-back"),h=document.getElementById("tour-narration-skip-ahead");if(c){c.disabled=!M||n.mode!=="tour";let g=r.kind==="playing";c.querySelector(".tour-play-pause-icon")?.setAttribute("d",g?"M7 5h4v14H7zM13 5h4v14h-4z":"m8 5 11 7-11 7Z");let w=g?"Pause narration":r.kind==="paused"?"Resume narration":"Listen from the current tour item";c.title=w,c.setAttribute("aria-label",w),document.getElementById("tour-listen-label").textContent=g?"Pause":r.kind==="paused"?"Resume":"Listen"}if(u&&(u.disabled=r.kind!=="playing"&&r.kind!=="paused"),d&&(d.disabled=!X.canSkipSegment(-1)),h&&(h.disabled=!X.canSkipSegment(1)),r.kind==="playing"||r.kind==="paused"){let g=r.segmentIndex+1,w=r.unit.segments.length;Et(`${r.kind==="paused"?"Paused":"Speaking"} \xB7 segment ${g} of ${w}`)}else r.kind==="completed"?Et("Narration complete"):r.kind==="error"?Et(r.message):M&&Et("Device voice ready")}function Et(r){let c=document.getElementById("tour-narration-status");c&&(c.textContent=r)}function _i(r,c){if(document.querySelectorAll(".tour-narration-segment.is-speaking").forEach(k=>{k.classList.remove("is-speaking","is-paused")}),!r)return;let u=[...document.querySelectorAll("[data-narration-segment-id]")].filter(k=>k.dataset.narrationSegmentId===r.id),d=u[0];if(!d||(u.forEach(k=>{k.classList.add("is-speaking"),k.classList.toggle("is-paused",c)}),c))return;let h=document.getElementById("tour-narrative-content");if(!h)return;let g=d.getBoundingClientRect(),w=h.getBoundingClientRect();(g.top<w.top+Zt()||g.bottom>w.bottom)&&(d.scrollIntoView({block:"nearest"}),Q=h.scrollTop)}let It=[];function Xe(){let r=document.getElementById("tour-search-input"),c=document.getElementById("tour-search-scope"),u=document.getElementById("tour-search-status"),d=document.getElementById("tour-search-results");if(!(!n.tour||!r||!c||!u||!d)){if(It=ti(n.tour,r.value,c.value),!r.value.trim()){u.textContent="Cmd/Ctrl+Shift+F",d.replaceChildren();return}u.textContent=`${It.length} result${It.length===1?"":"s"}`,d.replaceChildren(...It.map((h,g)=>{let w=document.createElement("button");w.type="button",w.className="tour-search-result",w.setAttribute("role","option"),w.dataset.tourSearchResult=String(g),w.title=`Open ${h.kind==="code"?`${h.label}:${h.lineNumber}`:h.label}`;let k=document.createElement("span");k.className="tour-search-location",k.textContent=h.kind==="code"?`${h.label}:${h.lineNumber}`:h.label;let S=document.createElement("span");return S.className="tour-search-preview",S.textContent=h.preview.trim(),w.append(k,S),w}))}}function qi(r){let c=It[r];if(c){if(c.kind==="narrative"){Ne(),me(c.sceneIndex,c.stepIndex??0,{readingKey:c.readingKey,showIntro:c.stepIndex===void 0});return}Un(c.fileIndex)&&window.requestAnimationFrame(()=>ne({type:"revealSearchResult",sideIndex:c.sideIndex,lineNumber:c.lineNumber,startColumn:c.startColumn,endColumn:c.endColumn}))}}function ji(){let r=document.getElementById("tour-shell"),c=document.getElementById("tour-sidebar-resizer"),u=document.getElementById("tour-sidebar-hide"),d=document.getElementById("tour-sidebar-show");!r||!c||!u||!d||(Pr(),u.addEventListener("click",()=>Ln(!0)),d.addEventListener("click",()=>Ln(!1)),c.addEventListener("pointerdown",h=>{h.preventDefault(),document.body.classList.add("is-resizing-tour-sidebar"),c.setPointerCapture?.(h.pointerId);let g=k=>Rr(k.clientX),w=()=>{document.body.classList.remove("is-resizing-tour-sidebar"),window.removeEventListener("pointermove",g),window.removeEventListener("pointerup",w),window.removeEventListener("pointercancel",w),i.setItem(y,String(n.tourSidebarWidth))};window.addEventListener("pointermove",g),window.addEventListener("pointerup",w),window.addEventListener("pointercancel",w)}),c.addEventListener("keydown",h=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(h.key))return;h.preventDefault();let g=n.tourSidebarWidth;h.key==="Home"?g=b:h.key==="End"?g=Nn():g+=h.key==="ArrowLeft"?-16:16,Rr(g),i.setItem(y,String(n.tourSidebarWidth))}))}function Ki(){let r=Number.parseInt(i.getItem(y)||"",10);return Number.isFinite(r)?Math.min(E,Math.max(b,r)):300}function Nn(){return Math.max(b,Math.min(E,Math.floor(window.innerWidth*.6)))}function Rr(r){n.tourSidebarWidth=Math.min(Nn(),Math.max(b,Math.round(r))),Pr(),window.dispatchEvent(new Event("resize"))}function Pr(){document.documentElement.style.setProperty("--tour-rail-width",`${n.tourSidebarWidth}px`);let r=document.getElementById("tour-sidebar-resizer");r?.setAttribute("aria-valuemax",String(Nn())),r?.setAttribute("aria-valuenow",String(n.tourSidebarWidth))}function Ln(r){n.tourSidebarHidden=r,document.body.classList.toggle("tour-sidebar-hidden",r);let c=document.getElementById("tour-sidebar-show");c&&(c.hidden=!r),window.dispatchEvent(new Event("resize"))}function Wi(){let r=document.getElementById("tour-narrative-resizer");r&&(Pn(),r.addEventListener("pointerdown",c=>{if(c.button!==0)return;c.preventDefault(),document.body.classList.add("is-resizing-tour-narrative"),r.setPointerCapture?.(c.pointerId),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-start"));let u=document.getElementById("tour-narrative").getBoundingClientRect().top,d=g=>Fr(g.clientY-u),h=()=>{document.body.classList.remove("is-resizing-tour-narrative"),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",h),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-end")),i.setItem(I,String(n.tourNarrativeHeight))};window.addEventListener("pointermove",d),window.addEventListener("pointerup",h),window.addEventListener("pointercancel",h)}),r.addEventListener("keydown",c=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(c.key))return;c.preventDefault();let u=c.key==="Home"?T:c.key==="End"?Rn():n.tourNarrativeHeight+(c.key==="ArrowUp"?-16:16);Fr(u),i.setItem(I,String(n.tourNarrativeHeight))}),window.addEventListener("resize",Pn))}function Gi(){let r=Number.parseInt(i.getItem(I)||"",10);return Number.isFinite(r)?r:Math.min(window.innerHeight*.38,360)}function Rn(){return Math.max(T,window.innerHeight-document.getElementById("tour-mode-controls").offsetHeight-v)}function Fr(r){n.tourNarrativeHeight=r,Pn()}function Pn(){n.tourNarrativeHeight=Math.min(Rn(),Math.max(T,Math.round(n.tourNarrativeHeight))),document.getElementById("tour-narrative").style.height=`${n.tourNarrativeHeight}px`;let r=document.getElementById("tour-narrative-resizer");r?.setAttribute("aria-valuemax",String(Rn())),r?.setAttribute("aria-valuenow",String(n.tourNarrativeHeight)),r&&(r.style.top=`calc(var(--workspace-toolbar-height, 0px) + ${n.tourNarrativeHeight-4}px)`)}function Vi(){let r=document.getElementById("tour-narrative");if(!r)return;let c=()=>{let u=r.hidden?0:Math.ceil(r.getBoundingClientRect().height);document.documentElement.style.setProperty("--tour-narrative-height",`${u}px`),Xr(),Zt(),window.dispatchEvent(new Event("resize"))};new ResizeObserver(c).observe(r),c()}async function Dr(r){Ie("Loading change tour\u2026");let c=xi(r),u={...n,historyEntries:[...n.historyEntries],fileHistoryCache:new Map(n.fileHistoryCache),displayedPanels:[...n.displayedPanels],historyPanels:[...n.historyPanels],comparisonCommits:[...n.comparisonCommits],comparisonDraftCommits:[...n.comparisonDraftCommits]},d=document.body.className,h=document.getElementById("tour-shell")?.hidden,g=document.getElementById("tour-narrative")?.hidden,w=document.getElementById("tour-mode-controls")?.hidden,k=he,S=se,P=Ae,L=ee;try{X.stop();let $=o?.manifest;if(!o){let C=await fetch(r,{cache:"no-store"});if(!C.ok)throw new Error(`Manifest request failed (${C.status}).`);$=await C.json()}let D=Ko($,{exported:!!o}),A=Jn(window.location.hash);A&&Vn(D,A.mode,A.focus);let _=U(D).deconstructed?"deconstructed":"historical",te=re(D)?(await pe("list",{commit:D.range.headOid},c,D)).entries:[];n.tour=D,n.authoredTour=D,n.historyPrefix=c,n.zoom=new bn(_),n.historyEntries=te,n.historyCommit=null,n.historyPath=null,n.historyPanels=[],n.historyFocus=null,n.historyDiff=null,n.historyChangedFiles=new Set,n.historyFiles=null,n.showAllFiles=!1,n.showAllTourFiles=!1,n.collapsedFileFolders=new Set,n.revealedFilePath=null,n.zoom&&(n.tour=xt(_)),n.mode="tour",document.body.classList.add("tour-mode"),st(),ot(),Xe();let H=new URLSearchParams(window.location.search),Z=gr(n.tour.scenes,H.get("scene"),H.get("step"));if(me(Z.sceneIndex,Z.stepIndex,{showIntro:H.get("view")==="overview"||!H.get("step"),readingKey:!H.get("scene")&&!H.get("step")?"title":void 0}),["tour","chapter","conclusion"].includes(H.get("view"))&&Xt(H.get("view")),n.zoom){let q={explanation:"deconstructed",revisions:"historical",final:Le()?"historical":"compare"}[H.get("mode")]||H.get("mode");if(q==="history"&&K().includes("history"))n.historyPath=H.get("file"),n.tourNavigatorTab="commits",n.zoom.enter("history"),n.tour=xt("history"),st(),ot(),await Ye(n.historyPath,H.get("commit"));else if(q==="compare"&&K().includes("compare")){let Se=H.get("commits")?.split(",").filter(Boolean);await _e("compare",{commits:Se?.length?Se:[H.get("from")||n.authoredTour.range.mergeBaseOid,H.get("to")||n.authoredTour.range.headOid],...H.get("scope")?{path:H.get("scope")}:{}},H.get("file")),H.get("view")==="directory"&&Tn()}else if(q&&q!==n.zoom.mode&&K().includes(q)){await _e(q);let Se=gr(n.tour.scenes,H.get("scene"),H.get("step"));me(Se.sceneIndex,Se.stepIndex,{showIntro:H.get("view")==="overview"||!H.get("step"),readingKey:!H.get("scene")&&!H.get("step")?"title":void 0}),["tour","chapter","conclusion"].includes(H.get("view"))&&Xt(H.get("view"))}let ge=wt;wt=null,de&&ge&&ge!==n.zoom.mode&&K().includes(ge)&&await _e(ge)}return n.directoryEvidence&&H.get("file")&&Mn(H.get("file")),An(X.state),n.workspacePromptStatus="",ve(),Ie(""),A?await Vr(A):Y()&&window.history.replaceState(null,"",Ze(n.zoom.mode,at(j.find(C=>C.key===n.readingKey)))),document.getElementById("export-loading")?.remove(),window.__BYGONE_EXPORT_READY__=!!o,l=!0,!0}catch($){let D=document.getElementById("export-loading");D&&(D.textContent=`Could not open export: ${$.message}`),Object.assign(n,u),he=k,se=S,Ae=P,ee=L,document.body.className=d;let A=document.getElementById("tour-shell");A&&h!==void 0&&(A.hidden=h);let z=document.getElementById("tour-narrative");z&&g!==void 0&&(z.hidden=g);let _=document.getElementById("tour-mode-controls");return _&&w!==void 0&&(_.hidden=w),n.mode==="tour"&&n.tour&&(st(),ot(),Xe(),ve()),Ie(`Could not load change tour: ${$ instanceof Error?$.message:String($)}`),!1}}function st(){Jt();let r=n.tour;if(!r)return;let c=document.getElementById("tour-shell"),u=document.getElementById("tour-title"),d=document.getElementById("tour-source"),h=document.getElementById("tour-range"),g=document.getElementById("tour-stats"),w=document.getElementById("tour-authoring-coverage"),k=document.getElementById("tour-scenes"),S=document.getElementById("tour-scene-count"),P=document.getElementById("tour-files"),L=document.getElementById("tour-file-count");if(!c||!u||!d||!h||!g||!w||!k||!S||!P||!L)throw new Error("Presenter UI is incomplete.");c.hidden=!1,u.textContent=r.title,document.title=oi(r),r.sourceUrl?(d.href=r.sourceUrl,d.hidden=!1):(d.removeAttribute("href"),d.hidden=!0);let $=jr(r.range.baseRef),D=jr(r.range.headRef),A=r.range.headOid.slice(0,7);if(h.textContent=`${Y()?"Tour range: ":""}${$} \u2192 ${D}${D===A?"":` \xB7 ${A}`}`,g.textContent=`${Nt(r.summary.changedFiles,"file")} \xB7 +${r.summary.additions} \u2212${r.summary.deletions} \xB7 ${Nt(r.summary.commitCount,"commit")}`,Ji(w,r.authoringCoverage),gi(document.getElementById("tour-audience"),Y()?r:null),S.textContent=Y()&&r.scenes.length?String(r.scenes.length):"",L.textContent=String(r.files.length),k.replaceChildren(),Y()){Hn();let _=je("Intro","Read the introduction and tour route",()=>Ee(j.find(te=>te.kind==="title")));_.className="tour-scene",_.dataset.readingLink="title",k.append(_)}let z=new Map(r.scenes.map(_=>[_.id,_]));for(let _ of r.chapters){let te=Kr(`chapter:${_.id}`,`${r.chapters.indexOf(_)+1}. ${_.title}`,"tour-chapter-link",()=>{let Z=j.find(C=>C.kind==="chapter"&&C.chapterId===_.id)||j.find(C=>C.kind==="scene"&&_.sceneIds.includes(r.scenes[C.sceneIndex]?.id));Z&&Ee(Z)}),H=te.children;k.append(te.group);for(let Z of _.sceneIds){let C=z.get(Z);if(!C)continue;let q=r.scenes.indexOf(C),ge=Kr(`scene:${C.id}`,C.title,"tour-scene",()=>me(q,0,{userNavigation:!0,showIntro:!0})),Se=ge.link;Se.replaceChildren(),Se.dataset.sceneId=C.id,C.kind==="text-diff"&&(Se.dataset.filePath=C.path),ge.link.title=`Open scene: ${C.kind==="text-diff"?C.path:C.title}`;let _n=document.createElement("span");_n.className="tour-scene-copy";for(let[Lt,ct]of[["tour-scene-title",`${q+1}. ${C.title}`],["tour-scene-path",C.kind==="text-diff"?C.path:C.kind==="deconstructed-diff"?`${Nt(C.panels.length-1,"comparison stage")} \xB7 ${Nt(C.steps.length,"tour slide")}`:ke(C)?Nt(C.steps.length,C.steps.every(Pe=>Pe.image)?"image":"step"):"Discussion"],["tour-scene-note",C.takeaway]]){let Pe=document.createElement("span");Pe.className=Lt,Pe.textContent=ct,_n.append(Pe)}if(Se.append(_n),H.append(ge.group),ke(C)){let Lt=ge.children;Lt.classList.add("tour-outline-steps"),Lt.dataset.sceneId=C.id,C.steps.forEach((ct,Pe)=>{let Ke=document.createElement("button");Ke.type="button",Ke.className="tour-outline-step",Ke.dataset.sceneId=C.id,Ke.dataset.stepIndex=String(Pe);let hs=C.kind==="deconstructed-diff"?`Stage ${(ct.stageIndex??ct.pairIndex)+1}: `:"";Ke.textContent=`${Pe+1}. ${ct.title}`,Ke.title=`${hs}${ct.title}`,Ke.addEventListener("click",()=>me(q,Pe,{userNavigation:!0,showIntro:!1})),Lt.append(Ke)})}else ge.toggle.hidden=!0}}if(Y()&&r.conclusion){let _=je("Conclusion",`Read ${r.conclusion.title}`,()=>Ee(j.find(te=>te.kind==="conclusion")));_.className="tour-scene",_.dataset.readingLink="conclusion",k.append(_)}Fn(),Vt(n.tourNavigatorTab)}function Fn(){let r=n.tour,c=document.getElementById("tour-files");document.getElementById("tour-file-count").textContent=String(r.files.length),c.replaceChildren(Mr(mi(r.files,d=>d.path),(d,h,g)=>{let w=document.createElement("button");w.type="button",w.className=`tour-file${d.kind==="omitted"?" is-omitted":""}`,w.dataset.filePath=d.path,w.disabled=d.kind==="omitted",w.title=d.kind==="omitted"?`${d.path}: ${d.reason}`:`Open file: ${d.path}`,d.kind==="text-diff"&&w.addEventListener("click",()=>Tt(h));let k=document.createElement("span");k.className="tour-file-marker",k.textContent=d.kind==="omitted"?"\xD7":zn(d.changeKind);let S=document.createElement("span");S.className="tour-file-copy";let P=document.createElement("span");P.className="tour-file-path",P.textContent=g;let L=document.createElement("span");return L.className="tour-file-meta",L.textContent=d.kind==="omitted"?`Not rendered \xB7 ${d.reason}`:Number.isFinite(d.additions)?`${Yt(d.changeKind)} \xB7 +${d.additions} \u2212${d.deletions}`:Yt(d.changeKind),S.append(P,L),w.append(k,S),w}));let u=document.createElement("div");u.className="history-rail-empty",u.dataset.fileTreeEmpty="",c.append(u),ue()}function Mr(r,c){let u=document.createElement("ul");u.className="file-tree";for(let d of r.folders){let h=document.createElement("li"),g=document.createElement("details");g.dataset.fileFolder=d.path,g.open=!n.collapsedFileFolders.has(d.path);let w=document.createElement("summary"),k=document.createElement("span");k.className="tour-file-path",k.textContent=d.name,w.append(k),w.title=d.path,g.append(w,Mr(d,c)),h.append(g),u.append(h)}for(let{item:d,index:h,name:g}of r.files){let w=document.createElement("li");w.append(c(d,h,g)),u.append(w)}return u}function Ji(r,c){if(r.replaceChildren(),r.hidden=!c,!c)return;let u=[{metric:"walkthrough",label:"Anchored diff hunks",covered:c.walkthrough.coveredUnits,total:c.walkthrough.includedUnits,percent:c.walkthrough.coveragePercent,description:"Distinct change hunks referenced by authored base/head focus anchors. Revision-stack steps are not counted."},...c.explanationAssignments.map(d=>({metric:"assignment",label:c.explanationAssignments.length>1?`Deconstructed assignment \xB7 ${d.sceneId}`:"Deconstructed assignment",covered:d.completeUnits,total:d.totalUnits,percent:d.assignmentPercent,description:`${d.assignedUnits} assigned, ${d.excludedUnits} explicitly excluded.`}))];for(let d of u){let h=document.createElement("div");h.className="tour-coverage-item",h.dataset.metric=d.metric,h.dataset.tooltip=d.description,h.tabIndex=0,h.setAttribute("aria-description",d.description);let g=document.createElement("div");g.className="tour-coverage-heading";let w=document.createElement("span");w.textContent=d.label;let k=document.createElement("strong");k.textContent=`${d.covered}/${d.total} \xB7 ${d.percent}%`,g.append(w,k);let S=document.createElement("div");S.className="tour-coverage-meter",S.setAttribute("role","progressbar"),S.setAttribute("aria-label",d.label),S.setAttribute("aria-valuemin","0"),S.setAttribute("aria-valuemax","100"),S.setAttribute("aria-valuenow",String(d.percent));let P=document.createElement("span");P.style.width=`${d.percent}%`,S.append(P),h.append(g,S),r.append(h)}}let xe=null;function me(r,c=0,u={}){let d=n.tour;if(!d||u.readingKey!=="conclusion"&&(r<0||r>=d.scenes.length))return null;if(t.clear(),u.userNavigation&&Ne(),n.zoom?.mode==="history"&&!n.zoomSwitching){let z=d.scenes[r],_=z.path||z.steps?.[c]?.file||n.activeTourFilePath;return Ye(_,n.historyCommit).catch(te=>{document.getElementById("tour-mode-status").textContent=te.message}),null}let h=xe?.tour===d&&!u.zoomLanding&&!s?xe.context:null;n.directoryEvidence=null,qe(""),Jt(),Hn();let g=j.find(z=>z.key===u.readingKey)||yn(j,r,c,u.showIntro?"overview":null);g&&g.kind!=="step"&&g.kind!=="conclusion"&&g.kind!=="title"&&tt(d)&&(g=yn(j,g.sceneIndex,0)),g&&(r=g.sceneIndex,c=g.stepIndex);let w=d.scenes[r],k=en(d,g);document.body.classList.toggle("tour-discussion",k==="narrative");let S=g.kind==="title"||g.kind==="chapter"||g.kind==="conclusion",P=document.body.classList.contains("tour-bookend")!==S;document.body.classList.toggle("tour-bookend",S),n.readingKey=g?.key||"title",n.sceneIntroVisible=g?.kind!=="step",n.narrativeParent=g?.kind==="conclusion"?"conclusion":g?.kind==="title"?"tour":g?.kind==="chapter"?"chapter":null,n.activeSceneIndex=r,n.activeStepIndex=ke(w)?Math.min(Math.max(c,0),Math.max(w.steps.length-1,0)):0,n.tourFocusFilePath=!w||n.narrativeParent?null:w.kind==="text-diff"?w.path:w.kind==="walkthrough"?w.steps[n.activeStepIndex]?.diff.path??null:Re(w)?w.steps[n.activeStepIndex]?.file??null:null;let L=w?_r(d,r):null;ss();let $=u.preserveNarration&&X.engaged?X.state.unit:Lr(u.narrationEntry||"playback-start");n.renderedNarrationUnit=$,Yr(w,L,$),(!u.fromReadingScroll||P)&&Zr(n.readingKey),$&&!u.zoomLanding&&!u.preserveNarration&&(!n.zoom||Y())&&(u.narrationNavigation==="linear"?X.followLinearNavigation($):u.narrationNavigation!=="controller"&&X.followDirectNavigation($)),ye();let D=fe(d,g,n.zoom?.mode);k==="overview"?xe={tour:d,context:D}:k!=="narrative"?xe=h?{tour:d,context:h}:null:g.kind!=="chapter"&&(xe=null);let A=J.get(g.key)?.querySelector(".tour-scene-orientation");return A&&D&&(A.textContent=qn(h,D)),k==="overview"&&Dn()?$:k==="narrative"?(++he,n.displayedPanels=[],n.activeTourFilePath=null,ne({type:"updateCommitHistory",history:Ir()}),document.body.classList.add("tour-discussion"),n.tourFocusFilePath=null,ue(),ve(),$):(document.body.classList.remove("tour-discussion"),w.kind==="walkthrough"?(Br(w),$):Re(w)?(Ur(w),$):(St(w,Kt(w.path)),$))}function qe(r){let c=document.getElementById("status-banner");c.textContent=r,c.hidden=!r}function Dn(){let r=n.tour?.scenes[n.activeSceneIndex];if(!Y()||!r||tt(n.tour)||n.narrativeParent||!r.overview)return!1;let c=Qt(n.tour,r);n.directoryEvidence=c,n.activeTourFilePath=null,ue(),document.body.classList.remove("tour-discussion");let u=fe(n.tour,j.find(d=>d.key===n.readingKey),n.zoom?.mode);return ne(nn(u.labels,c.entries)),document.getElementById("file-info").textContent=ut(u),qe(c.entries.length?"":"No changed files in this directory for the selected comparison."),ye(),!0}function Mn(r){let c=n.directoryEvidence;if(!c)return!1;let u=c.files.find(d=>d.path===r);if(!u){let d=c.omitted.find(h=>h.path===r);return qe(d?`${r}: ${d.reason}`:"This file has no change in the overview comparison."),!1}return Ne(),qe(""),St(u,[],`directory-${n.tour.scenes[n.activeSceneIndex].id}-${r}`),ye(),!0}function Kt(r){let c=n.tour;return!c||!r?[]:ni(c,r,n.activeSceneIndex,n.activeStepIndex)}function Yi(r,c){let u=n.tour;return!u||!r?[]:ri(u,r,n.activeSceneIndex,n.activeStepIndex,(d,h)=>wr(c?.[d]?.diffModel,h))}function On(r){return`file::${r}`}function St(r,c=[],u=On(r.path),d=null,h=null){if(document.body.classList.remove("tour-discussion"),!n.tour)return;t.clear(),n.activeTourFilePath=n.zoom?.mode==="history"&&n.historyPath||r.path,ue();let w=we(r.leftContent,r.rightContent),k=Or(r,r.leftLabel,n.zoom?.mode==="compare"?"from":"base"),S=Or(r,r.rightLabel,n.zoom?.mode==="compare"?"to":"head"),P=c.find($=>$.active)||h&&{side:h.revision==="head"?"right":"left",startLine:h.startLine},L=r.changeKind==="added"?{left:!1,right:!0}:r.changeKind==="deleted"?{left:!0,right:!1}:{left:!0,right:!0};ne({type:"showDiff",file1:`1. ${k}`,file2:`2. ${S}`,comparisonId:`tour-${u}`,leftContent:r.leftContent,rightContent:r.rightContent,canReturnToDirectory:!!n.directoryEvidence,sourceInfo:{leftPath:r.previousPath||r.path,rightPath:r.path},fileExists:L,diffModel:w,history:d,fileNavigation:{canGoPrevious:!!Ct(-1),canGoNext:!!Ct(1)},editableSides:{left:!1,right:!1},comparisonSummary:Bn(r.path,void 0,!n.directoryEvidence),initialChangeIndex:P?qr(w,P.side,P.startLine):r.focusChangeIndex,tourAnnotations:c})}function Bn(r,c,u=!1){if(!Y())return r;let d=j.find(H=>H.key===n.readingKey),h=d&&fe(n.tour,d,n.zoom?.mode),g=c===void 0?d:{kind:"step",sceneIndex:n.activeSceneIndex,stepIndex:n.activeStepIndex},w=g&&fe(n.tour,g,n.zoom?.mode,c),k=u||!w?eo(n.tour,r):w,S={...k,scope:r,scopeKey:JSON.stringify([r]),overview:!1},P=xe?.tour===n.tour?xe.context:null,L=P&&(P.comparisonKey!==S.comparisonKey||P.scopeKey!==S.scopeKey)?qn(P,S):ut(S);xe={tour:n.tour,context:S};let $=h,D=d&&en(n.tour,d)==="preview"&&$?.scope===r&&$.comparisonKey===k.comparisonKey,A=d&&n.tour.scenes[d.sceneIndex],z=A&&ke(A)?A.steps[d.kind==="step"?d.stepIndex:0]:null;return`${z&&$?.scope===r&&$.comparisonKey===k.comparisonKey?`${D?"Coming up":"Evidence for"}: ${Fe(n.tour,{kind:"step",key:`step:${A.id}:${z.id}`,sceneIndex:d.sceneIndex,stepIndex:d.kind==="step"?d.stepIndex:0})} \xB7 `:""}${L}`}function Or(r,c,u){if(n.zoom?.mode==="history")return c;let d=c.startsWith(r.path)?c.slice(r.path.length).trim():c.trim();return d?`${u} ${d}`:u}function Br(r){let c=r.steps[n.activeStepIndex];if(c){if(c.image){++he,n.displayedPanels=[],n.activeTourFilePath=c.diff.path,t.show(c.image,c.title),ue();return}St(c.diff,n.sceneIntroVisible?[]:Kt(c.diff.path),On(c.diff.path),null,n.sceneIntroVisible?c.focus:null)}}function Ur(r){let c=r.steps[n.activeStepIndex];c&&zr(r,c.file,c)}function zr(r,c,u){document.body.classList.remove("tour-discussion");let d=$t(r,c);if(!u||!d)return;n.activeTourFilePath=d.path,ue();let h=d.panels.map((A,z)=>({id:`${r.id}-${d.path}-${A.id}`,commit:r.kind==="stacked-diff"?At(r)[z].oid:void 0,label:A.label,path:A.path||d.path,content:A.content,savedContent:A.content,dirty:!1,editable:!1,stackId:At(r)[z].id})),g=jn(h,(A,z)=>we(A.content,z.content)),w=n.sceneIntroVisible?[]:Yi(d.path,g),k=w.find(A=>A.active),S=k?.pairIndex??u.pairIndex,P=k?.side??u.side,L=k?.startLine??u.startLine,$=g[S]?.diffModel,D=$&&L?qr($,P,L):0;ne({type:"showMultiDiff",panels:h,pairs:g,activePanelId:h[S+(P==="right"?1:0)]?.id,activePairIndex:S,initialChangeIndex:D,revealFirstChangeInEachPanel:r.kind==="deconstructed-diff",history:null,fileNavigation:{canGoPrevious:!!Ct(-1),canGoNext:!!Ct(1)},mutationEnabled:!1,comparisonSummary:Bn(d.path,S),tourAnnotations:w})}function Wt(r){if(!Y())return!1;let c=Ut(j,n.readingKey,r,tt(n.tour));return c?(Ee(c,!1,!0),!0):!1}function Gt(){return{paths:n.tour.files.filter(r=>r.kind==="text-diff").map(r=>r.path),currentPath:n.activeTourFilePath,changedPaths:n.zoom?.mode==="compare"?n.compare?.changedPaths:n.historyChangedFiles}}function Ct(r){let c=n.tour;if(!c||r!==-1&&r!==1)return null;let u=c.scenes[n.activeSceneIndex];if(n.zoom?.mode==="history"||n.zoom?.mode==="compare"){let d=We(Gt(),r);return d?{fileIndex:c.files.findIndex(h=>h.path===d),path:d}:null}if(n.directoryEvidence){let d=n.directoryEvidence.files,h=d.findIndex(k=>k.path===n.activeTourFilePath),g=d[h+r],w=g?c.files.findIndex(k=>k.path===g.path):-1;return w>=0?{fileIndex:w,path:g.path}:null}if(Re(u)){let d=u.steps[n.activeStepIndex]?.pairIndex;if(!Number.isInteger(d))return null;let h=c.files.flatMap(k=>{if(k.kind!=="text-diff")return[];let S=$t(u,k.path);return S?[S]:[]}),g=Vo(h,d,n.activeTourFilePath,r);if(!g)return null;let w=c.files.findIndex(k=>k.kind==="text-diff"&&k.path===g.path);return w>=0?{fileIndex:w,path:g.path}:null}return Jo(c.files,n.activeTourFilePath,r)}function Hr(r){let c=Ct(r);return c?Tt(c.fileIndex):!1}function Un(r,c=!0){let u=n.tour?.files[r];return!u||u.kind!=="text-diff"?!1:(c&&X.interruptForExploration(),n.directoryEvidence=null,St(u,Kt(u.path),On(u.path)),!0)}function Tt(r){let c=n.tour?.files[r];if(!c||c.kind!=="text-diff")return!1;if(Ne(),n.zoom?.mode==="history")return Ye(c.path,n.historyCommit).catch(d=>{document.getElementById("tour-mode-status").textContent=d.message}),!0;if(n.zoom?.mode==="compare")return Tr(c).catch(d=>{document.getElementById("tour-mode-status").textContent=d.message}),!0;if(n.directoryEvidence&&Y())return Mn(c.path);n.zoomSwitching||X.interruptForExploration();let u=n.tour?.scenes[n.activeSceneIndex];if(Re(u)){let d=u.steps[n.activeStepIndex];return d&&$t(u,c.path)?(zr(u,c.path,d),!0):!1}return Un(r,!1)}function $t(r,c){let u=r?.files?.find(g=>g.path===c);if(u||r?.kind!=="deconstructed-diff")return u;let d=n.tour?.files.find(g=>g.kind==="text-diff"&&g.path===c);if(!d||d.kind!=="text-diff")return null;let h=d.changeKind!=="deleted";return{path:d.path,panels:At(r).map(g=>({id:g.id,label:`${g.label} / ${d.path}${h?"":" (absent)"}`,path:h?d.path:void 0,content:h?d.rightContent:"",exists:h}))}}function Xi(){if(n.narrativeParent)return!!me(n.activeSceneIndex,n.activeStepIndex,{readingKey:n.readingKey,preserveNarration:!0});if(n.directoryEvidence)return Dn();let r=n.tour?.scenes[n.activeSceneIndex];if(!r||!n.tourFocusFilePath)return!1;if(r.kind==="walkthrough")Br(r);else if(Re(r))Ur(r);else if(r.kind==="text-diff")St(r,Kt(r.path));else return!1;return!0}function Vt(r){if(!["tour","files","commits"].includes(r))return;let c=Y()&&!!n.tour?.scenes.length;r==="tour"&&!c&&(r="commits"),n.tourNavigatorTab=r,document.querySelectorAll("[data-tour-navigator]").forEach(u=>{let d=u.dataset.tourNavigator===r;u.disabled=u.dataset.tourNavigator==="tour"&&!c,u.classList.toggle("is-active",d),u.setAttribute("aria-selected",String(d)),u.tabIndex=d?0:-1}),document.querySelectorAll("[data-tour-navigator-panel]").forEach(u=>{u.hidden=u.dataset.tourNavigatorPanel!==r}),window.dispatchEvent(new CustomEvent("bygone:present-navigator-change",{detail:{tab:r}})),window.dispatchEvent(new Event("resize"))}function Jt(){let r=!!(n.directoryEvidence&&Y()),c=r?n.activeTourFilePath:null;document.body.classList.toggle("tour-directory-overview",r),document.body.classList.toggle("tour-directory-file-open",!!c),document.getElementById("tour-directory-breadcrumb").hidden=!r;let u=document.getElementById("tour-directory-root");c?u.removeAttribute("aria-current"):u.setAttribute("aria-current","location"),document.getElementById("tour-directory-separator").hidden=!c;let d=document.getElementById("tour-directory-file");d.textContent=c||"",d.hidden=!c;let h=document.getElementById("tour-directory-narration-context");h.hidden=!c,h.textContent=`Narration describes the ${n.narrativeParent||"overview"}`}function ue(){Jt();let r=n.tour?.scenes[n.activeSceneIndex],c=Re(r)?r.steps[n.activeStepIndex]:null,u=new Map(n.tour?.files.map($=>[$.path,$]));document.querySelectorAll(".tour-file").forEach($=>{let D=$.dataset.filePath;$.classList.toggle("is-active",D===n.activeTourFilePath),$.classList.toggle("is-tour-focus",!n.directoryEvidence&&D===n.tourFocusFilePath),$.classList.remove("is-comparison-changed","is-comparison-empty"),delete $.dataset.comparisonState;let A=u.get(D);$.classList.toggle("is-omitted",A?.kind==="omitted"),$.disabled=A?.kind==="omitted"||!!(n.directoryEvidence&&!n.directoryEvidence.files.some(H=>H.path===D)),D===n.activeTourFilePath?$.setAttribute("aria-current","true"):$.removeAttribute("aria-current");let z=$.querySelector(".tour-file-marker"),_=$.querySelector(".tour-file-meta");if(n.directoryEvidence&&$.disabled&&A?.kind==="text-diff"){let H="Not in this overview comparison";$.setAttribute("title",`${D} \xB7 ${H}`),$.setAttribute("aria-label",`${D}, ${H}`),_&&(_.textContent=H),z&&(z.textContent="\u25CB");return}if(n.directoryEvidence&&A?.kind==="text-diff"){let H=n.directoryEvidence.files.find(C=>C.path===D),Z=`${Yt(H.changeKind)} in overview`;$.setAttribute("title",`${D} \xB7 ${Z}`),$.setAttribute("aria-label",`${D}, ${Z}`),_&&(_.textContent=Z),z&&(z.textContent=zn(H.changeKind));return}let te=n.zoom?.mode==="history"?n.historyChangedFiles:n.zoom?.mode==="compare"?n.compare?.changedPaths:null;if(te&&A?.kind==="text-diff"){let H=te.has(D),Z=H?"Changed in this comparison":"Unchanged in this comparison";$.classList.add(H?"is-comparison-changed":"is-comparison-empty"),$.setAttribute("title",`${D} \xB7 ${Z}`),$.setAttribute("aria-label",`${D}, ${Z}`),_&&(_.textContent=Z),z&&(z.textContent=H?"M":"\u25CB");return}if(c&&A?.kind==="text-diff"){let H=$t(r,D);if(H){let C=mr(H,c.pairIndex),q=Zi(C);$.dataset.comparisonState=C,$.classList.add(q.changed?"is-comparison-changed":"is-comparison-empty"),$.setAttribute("title",`${A.path} \xB7 ${q.label}`),$.setAttribute("aria-label",`${A.path}, ${q.label}`),z&&(z.textContent=q.marker),_&&(_.textContent=q.label);return}$.disabled=!0;let Z="Not included in this tour comparison";$.setAttribute("title",`${D} \xB7 ${Z}`),$.setAttribute("aria-label",`${D}, ${Z}`),z&&(z.textContent="\u25CB"),_&&(_.textContent=Z);return}if(A){let H=A.kind==="omitted"?`${A.path}: ${A.reason}`:`Open file: ${A.path}`;$.setAttribute("title",H),$.setAttribute("aria-label",H),z&&(z.textContent=A.kind==="omitted"?"\xD7":zn(A.changeKind)),_&&(_.textContent=A.kind==="omitted"?`Not rendered \xB7 ${A.reason}`:`${Yt(A.changeKind)} \xB7 +${A.additions} \u2212${A.deletions}`)}});let d=document.getElementById("tour-files"),h=Y(),g=!h||!!(c||n.directoryEvidence),w=!g||(h?n.showAllTourFiles:n.showAllFiles),k=0;d.querySelectorAll(".tour-file").forEach($=>{let D=$.dataset.filePath,A=n.directoryEvidence?n.directoryEvidence.files.some(z=>z.path===D):n.zoom?.mode==="history"?n.historyChangedFiles.has(D):n.zoom?.mode==="compare"?n.compare?.changedPaths.has(D):c?$.classList.contains("is-comparison-changed"):!0;$.parentElement.hidden=!w&&!A,$.parentElement.hidden||k++});for(let $ of[...d.querySelectorAll("details[data-file-folder]")].reverse())$.parentElement.hidden=![...$.querySelector(":scope > ul").children].some(D=>!D.hidden);d.querySelector("[data-file-tree-empty]").hidden=k>0,d.querySelector("[data-file-tree-empty]").textContent=w?"No files":"No changed files",d.setAttribute("aria-label",w?h?"Tour files":o?"Included files":"Files in selected revisions":"Changed files");let S=document.getElementById("tour-file-filter");S.hidden=!g,S.title=h?"Include tour files unchanged in this step comparison":o?"Include unchanged files packaged in this export":"Include unchanged files from the selected revisions",document.getElementById("tour-file-filter-label").textContent=h?"Show unchanged tour files":o?"Show all included files":"Show all files",document.getElementById("tour-show-all-files").checked=h?n.showAllTourFiles:n.showAllFiles,document.getElementById("tour-visible-file-count").textContent=`${k} / ${n.tour.files.length}`;let P=d.querySelector(".tour-file.is-active");if(n.revealedFilePath!==n.activeTourFilePath&&P&&!P.parentElement.hidden){for(let $=P.closest("details");$;$=$.parentElement.closest("details"))$.open=!0,n.collapsedFileFolders.delete($.dataset.fileFolder);P.scrollIntoView({block:"nearest"})}n.revealedFilePath=n.activeTourFilePath;let L=document.getElementById("tour-return-focus");if(L){let $=Y(),D=r?.kind==="walkthrough"&&r.steps[n.activeStepIndex]?.image;L.hidden=!$||!!n.directoryEvidence||(n.narrativeParent?!n.activeTourFilePath:!n.tourFocusFilePath||(D?t.isVisible():n.activeTourFilePath===n.tourFocusFilePath)),L.textContent=n.narrativeParent?"Return to passage":"Return to tour focus"}}function Zi(r){return{"modified-here":{label:"Modified here",marker:"\u2022",changed:!0},"created-here":{label:"Created here",marker:"+",changed:!0},"deleted-here":{label:"Deleted here",marker:"\u2212",changed:!0},"unchanged-here":{label:"Unchanged here",marker:"\u25CB",changed:!1},"not-created-yet":{label:"Not created yet",marker:"\u2026",changed:!1},"already-deleted":{label:"Already deleted",marker:"\xD7",changed:!1}}[r]}function ke(r){return r?.kind==="walkthrough"||r?.kind==="stacked-diff"||r?.kind==="deconstructed-diff"}function Re(r){return r?.kind==="stacked-diff"||r?.kind==="deconstructed-diff"}function At(r){return r.kind==="deconstructed-diff"?r.panels:r.stack}function zn(r){return{added:"+",deleted:"\u2212",renamed:"\u2192",modified:"\u2022"}[r]||"\u2022"}function Yt(r){return`${r.charAt(0).toUpperCase()}${r.slice(1)}`}function _r(r,c){let u=r.scenes[c],d=r.chapters.findIndex(k=>k.sceneIds.includes(u.id)),h=d>=0?r.chapters[d]:null,g=h?h.sceneIds.indexOf(u.id)+1:c+1,w=h?h.sceneIds.length:r.scenes.length;return{chapter:h,chapterIndex:d,chapterNumber:d>=0?d+1:c+1,sceneInChapter:g,scenesInChapter:w,sceneCount:r.scenes.length}}function Qi(r,c){return ke(r)?`${r.title} \xB7 Step ${c+1} of ${r.steps.length}`:r.title}function qr(r,c,u){let h=(c==="left"?r.leftLines:r.rightLines).findIndex(L=>L.lineNumber===u);if(h<0)return 0;let g=c==="left"?"leftStart":"rightStart",w=c==="left"?"leftEnd":"rightEnd",k=r.blocks.findIndex(L=>h>=L[g]&&h<L[w]);if(k>=0)return k;let S=0,P=Number.POSITIVE_INFINITY;return r.blocks.forEach((L,$)=>{let D=Math.min(Math.abs(h-L[g]),Math.abs(h-L[w]));D<P&&(S=$,P=D)}),S}function jr(r){return/^[0-9a-f]{40}$/i.test(r)?r.slice(0,7):r}function Nt(r,c){return`${r} ${r===1?c:`${c}s`}`}function es(r){return r instanceof Element&&!!r.closest('a, button, input, select, summary, textarea, [contenteditable="true"], [role="textbox"], .monaco-editor')}function ts(r){let c=n.tour?.scenes[n.activeSceneIndex];n.tour&&Yr(c,c?_r(n.tour,n.activeSceneIndex):null,r)}function Xt(r){let c=yn(j,n.activeSceneIndex,n.activeStepIndex,r==="scene"?"overview":r==="step"?null:r);c&&Ee(c)}function je(r,c,u){let d=document.createElement("button");return d.type="button",d.textContent=r,d.title=c,d.addEventListener("click",u),d}function Kr(r,c,u,d){let h=document.createElement("div");h.className="tour-outline-group",h.dataset.readingGroup=r;let g=document.createElement("div");g.className="tour-outline-heading";let w=document.createElement("div");w.className="tour-outline-children",w.id=`outline-${encodeURIComponent(r)}`;let k=`${n.zoom?.mode||"tour"}:${r}`,S=je("\u25BE",`Expand or collapse ${c}`,()=>{oe.has(k)?oe.delete(k):oe.add(k),P()});S.className="tour-outline-toggle",S.setAttribute("aria-controls",w.id);let P=()=>{w.hidden=oe.has(k),S.setAttribute("aria-expanded",String(!w.hidden)),S.textContent=w.hidden?"\u25B8":"\u25BE"};P();let L=je(c,`Read ${c}`,d);return L.className=u,L.dataset.readingLink=r,g.append(S,L),h.append(g,w),{group:h,children:w,link:L,toggle:S}}function ns(){let r=document.getElementById("tour-audio-settings");r&&(r.hidden=!r.hidden,Wr())}function Wr(){Jt();for(let[u,d]of[["tour-back",-1],["tour-next",1]]){let h=document.getElementById(u);h&&(h.disabled=!Y()||!Ut(j,n.readingKey,d,tt(n.tour)))}let r=document.getElementById("tour-narration"),c=document.getElementById("tour-audio-settings");if(r){let u=!!(c&&!c.hidden);r.setAttribute("aria-expanded",String(u)),r.textContent=u?"\u203A":"\u2039 Narration",r.title=u?"Hide narration controls":"Show narration controls",r.setAttribute("aria-label",r.title)}}function at(r){if(!r||r.kind==="title")return{part:"title"};if(r.kind==="conclusion")return{part:"conclusion"};if(r.kind==="chapter")return{part:"chapter",chapter:r.chapterId};let c=n.tour.scenes[r.sceneIndex];return r.kind==="scene"?{part:"scene",scene:c.id}:{part:"step",scene:c.id,step:c.steps[r.stepIndex].id}}function rs(r){let c=document.createElement("button");return c.type="button",c.className="tour-copy-location",c.setAttribute("aria-label","Copy link to this section"),c.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true"><path class="tour-link-chain" d="M10 13a5 5 0 0 0 7 .1l3-3a5 5 0 0 0-7-7l-2 2M14 11a5 5 0 0 0-7-.1l-3 3a5 5 0 0 0 7 7l2-2"/><path class="tour-link-check" d="m5 12 4 4L19 6"/></svg>',c.title=o?"Copy location within this export; share the HTML file separately":n.authoredTour?.localSource?"Copy local link to the saved current document; evidence may change":"Copy browser location (requires this presentation server)",c.addEventListener("click",async u=>{u.stopPropagation();let d=Gr(r);try{await navigator.clipboard.writeText(d),c.classList.add("is-copied"),c.setAttribute("aria-label","Link copied"),setTimeout(()=>{c.classList.remove("is-copied"),c.setAttribute("aria-label","Copy link to this section")},1800)}catch{let h=document.createElement("dialog"),g=document.createElement("p");g.textContent="Copy this link:";let w=document.createElement("textarea");w.value=d,w.readOnly=!0,w.setAttribute("aria-label","Link to this tour location");let k=document.createElement("button");k.textContent="Close",k.addEventListener("click",()=>h.close()),h.append(g,w,k),document.body.append(h),h.addEventListener("close",()=>h.remove(),{once:!0}),h.showModal(),w.select()}}),c}function Gr(r){let c=Y()?n.zoom?.mode||"historical":Object.keys(U())[0],u=n.authoredTour.localSource;return u&&!o?co({kind:"tour",...u,mode:c,focus:r}):new URL(Ze(c,r),window.location.href).href}function Vr(r){let c=++f,u=p.then(()=>os(r,c));return p=u.catch(()=>{}),u}async function os(r,c){if(!r||!n.authoredTour)return;let u=Vn(n.authoredTour,r.mode,r.focus);if(c===f){s=!0;try{if(n.zoom.mode!==r.mode&&await _e(r.mode),c!==f)return;if(n.zoom.mode!==r.mode)throw new Error("The requested tour mode could not be opened.");if(se=null,document.getElementById("tour-mode-status").textContent="",me(u.sceneIndex,u.stepIndex,{readingKey:u.key,showIntro:r.focus.part!=="step"}),await new Promise(h=>window.requestAnimationFrame(h)),c!==f)return;let d=J.get(u.key);if(!d)throw new Error("The requested document section could not be rendered.");d.tabIndex=-1,d.focus({preventScroll:!0}),Zr(u.key),d.classList.add("tour-link-target"),window.setTimeout(()=>d.classList.remove("tour-link-target"),1800)}finally{s=!1}}}window.addEventListener("hashchange",()=>{try{Vr(Jn(window.location.hash)).catch(ae)}catch(r){ae(r)}});function ye(){if(o)return;let r=n.tour?.scenes[n.activeSceneIndex],c=new URLSearchParams(window.location.search);for(let d of["from","to","commits","scope","commit","file","panelOrder"])c.delete(d);if(n.zoom&&c.set("mode",n.zoom.mode),n.zoom&&!Y()){for(let d of["scene","step","view"])c.delete(d);n.zoom.mode==="compare"&&n.compare&&(c.set("commits",n.compare.commits.join(",")),n.compare.path&&c.set("scope",n.compare.path),n.activeTourFilePath||c.set("view","directory")),n.zoom.mode==="history"&&n.historyCommit&&c.set("commit",n.historyCommit),n.activeTourFilePath&&c.set("file",n.zoom.mode==="history"?n.historyPath:n.activeTourFilePath),window.history.replaceState(null,"",`${window.location.pathname}?${c.toString()}${window.location.hash}`);return}if(n.readingKey==="conclusion"){c.delete("scene"),c.delete("step"),c.set("view","conclusion"),window.history.replaceState(null,"",`${window.location.pathname}?${c.toString()}${Ze(n.zoom.mode,{part:"conclusion"})}`);return}if(!r)return;c.set("scene",r.id);let u=ke(r)?r.steps[n.activeStepIndex]:null;u?c.set("step",u.id):c.delete("step"),n.directoryEvidence&&n.activeTourFilePath?c.set("file",n.activeTourFilePath):c.delete("file"),n.narrativeParent?c.set("view",n.narrativeParent):u&&n.sceneIntroVisible?c.set("view","overview"):c.delete("view"),window.history.replaceState(null,"",`${window.location.pathname}?${c.toString()}${Ze(n.zoom.mode,at(j.find(d=>d.key===n.readingKey)))}`)}function Jr(r=n.tour?.scenes[n.activeSceneIndex],c=n.activeStepIndex){if(!r||!ke(r))return null;let u=r.steps[c];if(!u)return null;if(r.kind==="walkthrough"){if(u.image)return null;let h=u.focus;return!h?.path||!Number.isInteger(h.startLine)?null:{filePath:h.path,sideIndex:h.revision==="base"?0:1,lineNumber:h.startLine,label:`${h.path}:${h.startLine}`}}let d=u.startLine;if(!Number.isInteger(d)){let h=$t(r,u.file),g=h?.panels?.[u.pairIndex],w=h?.panels?.[u.pairIndex+1];if(g&&w){let k=we(g.content,w.content);d=wr(k,u.side)?.startLine}}return!u.file||!Number.isInteger(d)?null:{filePath:u.file,sideIndex:u.pairIndex+(u.side==="right"?1:0),lineNumber:d,label:`${u.file}:${d}`}}function is(){let r=Jr(),c=n.tour?.scenes[n.activeSceneIndex];if(n.sceneIntroVisible||!r||!c)return!1;if(X.interruptForExploration(),n.activeTourFilePath!==r.filePath){let u=n.tour.files.findIndex(h=>h.kind==="text-diff"&&h.path===r.filePath);if(u<0||!(Re(c)?Tt(u):Un(u,!1)))return!1}return window.requestAnimationFrame(()=>ne({type:"revealSearchResult",sideIndex:r.sideIndex,lineNumber:r.lineNumber,startColumn:1,endColumn:1})),!0}function Yr(r,c,u){Hn(),document.getElementById("tour-narrative").hidden=!1,document.getElementById("tour-breadcrumb").textContent=n.narrativeParent==="tour"?"Intro":n.narrativeParent==="conclusion"?"Conclusion":n.narrativeParent==="chapter"?c.chapter?.title||"":n.sceneIntroVisible?r.title:Qi(r,n.activeStepIndex);let d=r&&J.get(`scene:${r.id}`),h=ke(r)?r.steps[n.activeStepIndex]:null,g=h&&J.get(`step:${r.id}:${h.id}`);for(let w of new Set([d,g,J.get(n.readingKey)].filter(Boolean)))w.querySelectorAll("[data-reading-field]").forEach(k=>{k.closest("[data-reading-key]")===w&&ls(k,k.dataset.readingText,{field:k.dataset.readingField,...k.dataset.itemIndex!==void 0?{itemIndex:Number(k.dataset.itemIndex)}:{}},u)});Wr()}function Hn(){if(O===n.tour)return;O=n.tour,j=ei(n.tour),J.clear();let r=document.getElementById("tour-narrative-content"),c=[],u,d=(k,S,P,L,$,D)=>{let A=document.createElement(S);A.className=P;let z=$&&/^h[1-6]$/.test(S)?document.createElement("span"):A;return z!==A&&A.append(z),z.replaceChildren(...kr(document,L||"")),$&&(z.dataset.readingField=$,z.dataset.readingText=L||"",D!==void 0&&(z.dataset.itemIndex=String(D))),k.append(A),A},h=(k,S,P)=>{if(d(k,"p","tour-narrative-summary",S.summary,P?"summary":null),S.bullets?.length){let L=document.createElement("ul");L.className="tour-narrative-bullets",S.bullets.forEach(($,D)=>d(L,"li","",$,P?"bullet":null,D)),k.append(L)}S.takeaway&&d(k,"p","tour-narrative-takeaway",S.takeaway,P?"takeaway":null)},g=Rt(n.tour),w=(k,S)=>{let P=d(k,"ul","tour-route","");S.forEach(L=>{let $=d(P,"li","",""),D=je("",`Read ${L.title}`,()=>Ee(j.find(A=>A.kind==="scene"&&A.sceneIndex===L.sceneIndex)));D.className="tour-route-link",d(D,"span","tour-route-number",`${L.sceneIndex+1}. `),d(D,"span","",L.title,"route-title",L.sceneIndex),$.append(D)})};for(let k of j){let S=document.createElement("section");S.className="tour-reading-item",S.dataset.readingKey=k.key,S.dataset.readingKind=k.kind,S.dataset.sceneIndex=String(k.sceneIndex),S.dataset.stepIndex=String(k.stepIndex);let P=n.tour.scenes[k.sceneIndex];if(k.kind==="title")d(S,"h1","tour-document-title",n.tour.title,"document-title"),n.tour.opening&&(d(S,"h2","tour-passage-title",n.tour.opening.title,"passage-title"),h(S,n.tour.opening,!0)),d(S,"h2","tour-passage-title","What you'll see"),g.chapters.forEach(L=>{let $=d(S,"section","tour-route-chapter",""),D=d($,"h3","",""),A=je("",`Read ${L.title}`,()=>Ee(j.find(z=>z.kind==="chapter"&&z.chapterId===L.chapterId)||j.find(z=>z.kind==="scene"&&z.sceneIndex===L.scenes[0]?.sceneIndex)));A.className="tour-route-link tour-route-chapter-link",d(A,"span","tour-route-number",`${L.chapterIndex+1}. `),d(A,"span","",L.title,"route-chapter",L.chapterIndex),D.append(A)}),g.chapters.length||w(S,g.scenes);else if(k.kind==="conclusion")d(S,"h2","tour-passage-title",n.tour.conclusion.title,"passage-title"),h(S,n.tour.conclusion,!0);else if(k.kind==="chapter"){let L=g.chapters.find($=>$.chapterId===k.chapterId);d(S,"h2","tour-document-chapter",L.title,"chapter"),d(S,"p","tour-narrative-summary",L.summary,"summary"),w(S,L.scenes)}else if(k.kind==="scene"){S.classList.add("tour-scene-group");let L=d(S,"div","tour-scene-header",""),$=d(L,"h2","tour-scene-heading",Fe(n.tour,k),"scene-title"),D=document.createElement("button");D.className="tour-scene-title-toggle",D.type="button",D.title="Expand or collapse scene overview",D.disabled=!0,D.append(...$.childNodes),$.append(D);let A=document.createElement("details");A.className="tour-scene-context";let z=d(A,"summary","","");z.setAttribute("aria-label",`Scene overview: ${P.title}`),z.dataset.tooltip="Expand or collapse scene overview";let _=d(A,"div","tour-scene-context-body","");_.id=`scene-overview-${k.sceneIndex}`,D.setAttribute("aria-controls",_.id),D.setAttribute("aria-expanded","false"),D.addEventListener("click",C=>{C.target.closest("a")||(A.open=!A.open)}),A.addEventListener("toggle",()=>D.setAttribute("aria-expanded",String(A.open))),h(_,P,!1),L.addEventListener("keydown",C=>{C.key==="Escape"&&A.open&&(C.preventDefault(),C.stopPropagation(),A.open=!1,z.focus({preventScroll:!0}))}),L.append(A);let te=d(S,"div","tour-scene-overview","");h(te,{...P,takeaway:ke(P)?"":P.takeaway},!0),P.overview?.purpose&&d(te,"p","tour-overview-purpose",P.overview.purpose,"overview-purpose");let H=fe(n.tour,k,n.zoom?.mode);H&&d(te,"p","tour-scene-orientation",ut(H));let Z=d(te,"div","tour-narrative-tags","");P.tags.forEach(C=>d(Z,"span","",C))}else{let L=P.steps[k.stepIndex],$=P.kind==="deconstructed-diff"?L.body?`Stage ${(L.stageIndex??L.pairIndex)+1}`:P.panels[L.pairIndex+1].label:"";if($&&d(S,"div","tour-narrative-chapter",$,"stage-title"),d(S,"h3","tour-step-title",Fe(n.tour,k),"step-title"),d(S,"p","tour-step-orientation",tn(n.tour,k.sceneIndex,k.stepIndex),"step-orientation"),L.body&&d(S,"p","tour-step-body",L.body,"step-body"),P.kind==="deconstructed-diff"&&!L.body){let z=P.steps.findIndex(_=>_.pairIndex===L.pairIndex);if(z>=0&&z<k.stepIndex){let _=j.find(H=>H.kind==="step"&&H.sceneIndex===k.sceneIndex&&H.stepIndex===z),te=je("Read stage explanation",`Read ${P.steps[z].title}`,()=>Ee(_));te.className="tour-show-in-code tour-stage-explanation",S.append(te)}}let D=d(S,"div","tour-step-requirement","");ds(D,L.requirement),L.connection&&(d(S,"p","tour-connection",`${L.connection.from.path} \u2192 ${L.connection.to.path}`),d(S,"p","tour-connection",L.connection.label,"connection")),k.stepIndex===P.steps.length-1&&d(S,"p","tour-narrative-takeaway",P.takeaway,"takeaway");let A=Jr(P,k.stepIndex);if(A){let z=d(S,"div","tour-step-code","");d(z,"span","tour-step-code-location",A.label);let _=je("Show in code",`Show ${A.label}`,()=>{Ee(k),is()});_.className="tour-show-in-code",z.append(_)}}S.querySelector("h1, h2, h3").append(rs(at(k))),J.set(k.key,S),k.kind==="step"?u.append(S):(c.push(S),u=k.kind==="scene"?S:null)}r.replaceChildren(...c),Q=r.scrollTop}function ss(){for(let[u,d]of J)d.classList.toggle("is-active",u===n.readingKey);document.querySelectorAll("[data-reading-link], .tour-outline-step, #tour-title").forEach(u=>{let d=n.tour?.scenes[n.activeSceneIndex],h=d&&ke(d)?d.steps[Number(u.dataset.stepIndex)]:null,w=(u.id==="tour-title"?"title":u.dataset.readingLink||(h&&u.dataset.sceneId===d.id?`step:${d.id}:${h.id}`:null))===n.readingKey;u.classList.toggle("is-active",w),w?u.setAttribute("aria-current","location"):u.removeAttribute("aria-current")}),document.querySelectorAll(".tour-outline-group").forEach(u=>{u.classList.toggle("has-active",!!u.querySelector('[aria-current="location"]'))});let r=document.getElementById("tour-scenes"),c=r?.querySelector('[aria-current="location"]');for(;c&&!c.getClientRects().length;)c=c.closest(".tour-outline-children[hidden]")?.parentElement.querySelector(":scope > .tour-outline-heading [data-reading-link]");if(c&&r.clientHeight){let u=r.getBoundingClientRect(),d=c.getBoundingClientRect();d.top<u.top?r.scrollTop+=d.top-u.top:d.bottom>u.bottom&&(r.scrollTop+=d.bottom-u.bottom)}}function Xr(){let r=document.getElementById("tour-narrative"),c=document.getElementById("tour-narrative-content");if(!r||!c||!r.getClientRects().length)return;let u=r.getBoundingClientRect(),d=u.height-c.clientHeight;c.style.setProperty("--tour-reading-viewport",`${c.clientHeight}px`),c.style.setProperty("--tour-bookend-viewport",`${Math.max(0,window.innerHeight-u.top-d)}px`)}function Zr(r){let c=document.getElementById("tour-narrative-content"),u=J.get(r);if(!c||!u)return;Xr();let d=u.dataset.readingKind==="step"?u.closest(".tour-scene-group")?.querySelector(".tour-scene-header"):null;c.scrollTop+=u.getBoundingClientRect().top-c.getBoundingClientRect().top-(d?.getBoundingClientRect().height||0),Q=c.scrollTop,Zt()}function Zt(){let r=document.getElementById("tour-narrative-content"),c=r.getBoundingClientRect().top,u=0;return r.querySelectorAll(".tour-scene-header").forEach(d=>{let h=d.parentElement.getBoundingClientRect(),g=h.top<c-1&&h.bottom>c;d.classList.toggle("is-stuck",g),d.querySelector(".tour-scene-title-toggle").disabled=!g,g?u=Math.max(u,d.getBoundingClientRect().bottom-c):d.querySelector("details").open=!1}),r.style.scrollPaddingTop=`${u}px`,u}function Ee(r,c=!1,u=!1){return!c&&!s&&Y()&&window.history.pushState(null,"",Ze(n.zoom.mode,at(r))),me(r.sceneIndex,r.stepIndex,{readingKey:r.key,showIntro:r.kind!=="step",userNavigation:!0,fromReadingScroll:c,narrationNavigation:u?"linear":void 0,narrationEntry:u?"continuous":"playback-start"})}function as(){ie===null&&(ie=window.requestAnimationFrame(()=>{if(ie=null,!Y()||n.zoomSwitching)return;let r=document.getElementById("tour-narrative-content"),c=Zt();if(Q!==null&&Math.abs(r.scrollTop-Q)<2)return;Q=null;let u=r.getBoundingClientRect().top+c+24,d=j[0];for(let h of j){if(J.get(h.key).getBoundingClientRect().top>u)break;d=h}d&&d.key!==n.readingKey&&Ee(d,!0)}))}function cs(r){let c=[];return r.source&&c.push(r.source),r.confidence&&c.push(`${r.confidence} confidence`),c.join(" \xB7 ")}function ds(r,c){if(!c){r.hidden=!0,r.replaceChildren(),r.removeAttribute("title");return}let u=document.createElement("span");u.className="tour-requirement-chip",u.dataset.status=c.status||"unspecified",u.textContent=c.status?`${c.id} \xB7 ${c.status}`:c.id;let d=document.createElement("span");d.className="tour-requirement-text",d.textContent=c.text;let h=[u,d],g=cs(c);if(g){let w=document.createElement("span");w.className="tour-requirement-meta",w.textContent=g,h.push(w)}r.replaceChildren(...h),r.title=[`${c.id}: ${c.text}`,g].filter(Boolean).join(" \u2014 "),r.hidden=!1}function ls(r,c,u,d,h={}){let g=d?.segments.filter(k=>k.source.field===u.field&&k.source.itemIndex===u.itemIndex)||[],w=[];h.prefix&&w.push(document.createTextNode(h.prefix)),w.push(...kr(document,c,g)),h.suffix&&w.push(document.createTextNode(h.suffix)),r.replaceChildren(...w)}function Qr(){X.stop();let r=Uo();n.mode="diff",n.comparisonId+=1,n.left={name:r.leftFileName,content:r.leftContent},n.right={name:r.rightFileName,content:r.rightContent},Ie("Loaded sample diff."),ne({type:"showDiff",file1:n.left.name,file2:n.right.name,comparisonId:`web-${n.comparisonId}`,leftContent:n.left.content,rightContent:n.right.content,diffModel:we(n.left.content,n.right.content),history:null})}async function us(r){X.stop();let[c,u]=r,[d,h]=await Promise.all([c.text(),u.text()]);n.mode="diff",n.comparisonId+=1,n.left={name:c.name,content:d},n.right={name:u.name,content:h},Ie(`Loaded ${c.name} and ${u.name}.`),ne({type:"showDiff",file1:c.name,file2:u.name,comparisonId:`web-${n.comparisonId}`,leftContent:d,rightContent:h,diffModel:we(d,h),history:null})}async function fs(r){X.stop();let c=await Promise.all(r.map(async(u,d)=>{let h=await u.text();return{id:`web-panel-${d}`,label:u.name,content:h,savedContent:h,dirty:!1,editable:!0}}));n.mode="multi-diff",Ie(`Loaded ${c.length}-panel diff for ${c.map(u=>u.label).join(", ")}.`),ne({type:"showMultiDiff",panels:c,pairs:c.slice(0,-1).map((u,d)=>({leftIndex:d,rightIndex:d+1,diffModel:we(u.content,c[d+1].content)}))})}function Ie(r){let c=document.getElementById("web-status");c&&(c.textContent=r)}})();})();
|
|
566
668
|
//# sourceMappingURL=web-host.js.map
|