@davmash/bygone 0.9.8 → 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.
Files changed (68) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/README.md +74 -1
  3. package/cli/commandSpec.js +2 -0
  4. package/cli/completions.js +3 -3
  5. package/cli/present.js +28 -10
  6. package/cli/tour.js +22 -1
  7. package/cli/tourExport.js +147 -0
  8. package/cli/tourFile.js +109 -4
  9. package/cli/tourHistory.js +31 -1
  10. package/completions/_bygone +1 -1
  11. package/completions/bygone +1 -1
  12. package/completions/bygone.fish +1 -1
  13. package/docs/change-tour-format.md +85 -68
  14. package/docs/explore.md +14 -3
  15. package/docs/generating-change-tours.md +84 -46
  16. package/docs/present.md +103 -14
  17. package/docs/product-surface.md +19 -8
  18. package/docs/sharing-tours.md +95 -0
  19. package/docs/visual-walkthrough/README.md +89 -0
  20. package/docs/visual-walkthrough/build-tour.mjs +54 -0
  21. package/docs/visual-walkthrough/capture-desktop.cjs +42 -0
  22. package/docs/visual-walkthrough/capture-desktop.mjs +21 -0
  23. package/docs/visual-walkthrough/captures.md +49 -0
  24. package/docs/visual-walkthrough/create-demo.mjs +57 -0
  25. package/docs/visual-walkthrough/deconstructed-demo.bygone +100 -0
  26. package/docs/visual-walkthrough/images/01-two-files.png +0 -0
  27. package/docs/visual-walkthrough/images/02-many-panels.png +0 -0
  28. package/docs/visual-walkthrough/images/03-directories.png +0 -0
  29. package/docs/visual-walkthrough/images/04-search.png +0 -0
  30. package/docs/visual-walkthrough/images/05-repository-history.png +0 -0
  31. package/docs/visual-walkthrough/images/06-file-history.png +0 -0
  32. package/docs/visual-walkthrough/images/07-branch-review.png +0 -0
  33. package/docs/visual-walkthrough/images/08-tour-reader.png +0 -0
  34. package/docs/visual-walkthrough/images/09-focused-step.png +0 -0
  35. package/docs/visual-walkthrough/images/10-deconstructed.png +0 -0
  36. package/docs/visual-walkthrough/images/11-exploration.png +0 -0
  37. package/docs/visual-walkthrough/images/12-authoring.png +0 -0
  38. package/docs/visual-walkthrough/images/13-export.png +0 -0
  39. package/docs/visual-walkthrough/images/14-vscode.png +0 -0
  40. package/docs/visual-walkthrough/images/15-cli.png +0 -0
  41. package/docs/visual-walkthrough/narrative.md +134 -0
  42. package/docs/visual-walkthrough/outline.md +52 -0
  43. package/docs/visual-walkthrough/walkthrough.bygone +340 -0
  44. package/docs/walkthrough.md +6 -101
  45. package/examples/bygone-history.bygone +11 -44
  46. package/examples/marker-focus.bygone +116 -0
  47. package/examples/navigation-lab.bygone.yaml +401 -336
  48. package/examples/tour-orientation.bygone +349 -0
  49. package/media/diff.worker.js +13 -3
  50. package/media/webview.css +1 -1
  51. package/media/webview.js +394 -319
  52. package/out/changeTour.js +865 -397
  53. package/out/deepLink.js +167 -0
  54. package/out/historyDirectory.js +66 -0
  55. package/out/standalone-main.js +20514 -16821
  56. package/out/tourCoverage.js +850 -386
  57. package/out/tourDocument.js +97 -0
  58. package/package.json +1 -1
  59. package/schemas/change-tour-source.schema.json +91 -64
  60. package/skills/pr-tour-guide/SKILL.md +144 -128
  61. package/skills/pr-tour-guide/references/expectations-and-feedback.md +57 -0
  62. package/standalone/index.html +10 -25
  63. package/web/export-bootstrap.js +62 -0
  64. package/web/export-licenses.txt +78 -0
  65. package/web/export-runtime.json +12 -0
  66. package/web/index.html +54 -47
  67. package/web/presenter.css +332 -178
  68. 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 s,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},c=a.callback;typeof a=="function"&&(c=a,a={}),this.options=a;var f=this;function p(O){return c?(setTimeout(function(){c(void 0,O)},0),!0):O}r=this.castInput(r),i=this.castInput(i),r=this.removeEmpty(this.tokenize(r)),i=this.removeEmpty(this.tokenize(i));var g=i.length,w=r.length,m=1,t=g+w;a.maxEditLength&&(t=Math.min(t,a.maxEditLength));var b=(s=a.timeout)!==null&&s!==void 0?s:1/0,I=Date.now()+b,N=[{oldPos:-1,lastComponent:void 0}],x=this.extractCommon(N[0],i,r,0);if(N[0].oldPos+1>=w&&x+1>=g)return p([{value:this.join(i),count:i.length}]);var S=-1/0,C=1/0;function $(){for(var O=Math.max(S,-m);O<=Math.min(C,m);O+=2){var z=void 0,R=N[O-1],W=N[O+1];R&&(N[O-1]=void 0);var fe=!1;if(W){var ye=W.oldPos-O;fe=W&&0<=ye&&ye<g}var X=R&&R.oldPos+1<w;if(!fe&&!X){N[O]=void 0;continue}if(!X||fe&&R.oldPos+1<W.oldPos?z=f.addToPath(W,!0,void 0,0):z=f.addToPath(R,void 0,!0,1),x=f.extractCommon(z,i,r,O),z.oldPos+1>=w&&x+1>=g)return p(Ko(f,z.lastComponent,i,r,f.useLongestToken));N[O]=z,z.oldPos+1>=w&&(C=Math.min(C,O-1)),x+1>=g&&(S=Math.max(S,O+1))}m++}if(c)(function O(){setTimeout(function(){if(m>t||Date.now()>I)return c();$()||O()},0)})();else for(;m<=t&&Date.now()<=I;){var P=$();if(P)return P}},addToPath:function(r,i,s,a){var c=r.lastComponent;return c&&c.added===i&&c.removed===s?{oldPos:r.oldPos+a,lastComponent:{count:c.count+1,added:i,removed:s,previousComponent:c.previousComponent}}:{oldPos:r.oldPos+a,lastComponent:{count:1,added:i,removed:s,previousComponent:c}}},extractCommon:function(r,i,s,a){for(var c=i.length,f=s.length,p=r.oldPos,g=p-a,w=0;g+1<c&&p+1<f&&this.equals(i[g+1],s[p+1]);)g++,p++,w++;return w&&(r.lastComponent={count:w,previousComponent:r.lastComponent}),r.oldPos=p,g},equals:function(r,i){return this.options.comparator?this.options.comparator(r,i):r===i||this.options.ignoreCase&&r.toLowerCase()===i.toLowerCase()},removeEmpty:function(r){for(var i=[],s=0;s<r.length;s++)r[s]&&i.push(r[s]);return i},castInput:function(r){return r},tokenize:function(r){return r.split("")},join:function(r){return r.join("")}};function Ko(e,r,i,s,a){for(var c=[],f;r;)c.push(r),f=r.previousComponent,delete r.previousComponent,r=f;c.reverse();for(var p=0,g=c.length,w=0,m=0;p<g;p++){var t=c[p];if(t.removed){if(t.value=e.join(s.slice(m,m+t.count)),m+=t.count,p&&c[p-1].added){var I=c[p-1];c[p-1]=c[p],c[p]=I}}else{if(!t.added&&a){var b=i.slice(w,w+t.count);b=b.map(function(x,S){var C=s[m+S];return C.length>x.length?C:x}),t.value=e.join(b)}else t.value=e.join(i.slice(w,w+t.count));w+=t.count,t.added||(m+=t.count)}}var N=c[g-1];return g>1&&typeof N.value=="string"&&(N.added||N.removed)&&e.equals("",N.value)&&(c[g-2].value+=N.value,c.pop()),c}var Vo=new ge;function nr(e,r,i){return Vo.diff(e,r,i)}var er=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,tr=/\S/,hn=new ge;hn.equals=function(e,r){return this.options.ignoreCase&&(e=e.toLowerCase(),r=r.toLowerCase()),e===r||this.options.ignoreWhitespace&&!tr.test(e)&&!tr.test(r)};hn.tokenize=function(e){for(var r=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),i=0;i<r.length-1;i++)!r[i+1]&&r[i+2]&&er.test(r[i])&&er.test(r[i+2])&&(r[i]+=r[i+2],r.splice(i+1,2),i--);return r};function rr(e,r,i){return hn.diff(e,r,i)}var or=new ge;or.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,`
2
- `));var r=[],i=e.split(/(\n|\r\n)/);i[i.length-1]||i.pop();for(var s=0;s<i.length;s++){var a=i[s];s%2&&!this.options.newlineIsToken?r[r.length-1]+=a:(this.options.ignoreWhitespace&&(a=a.trim()),r.push(a))}return r};var Xo=new ge;Xo.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var Jo=new ge;Jo.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function Tt(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Tt=function(r){return typeof r}:Tt=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Tt(e)}var Yo=Object.prototype.toString,ct=new ge;ct.useLongestToken=!0;ct.tokenize=or.tokenize;ct.castInput=function(e){var r=this.options,i=r.undefinedReplacement,s=r.stringifyReplacer,a=s===void 0?function(c,f){return typeof f>"u"?i:f}:s;return typeof e=="string"?e:JSON.stringify(fn(e,null,null,a),a," ")};ct.equals=function(e,r){return ge.prototype.equals.call(ct,e.replace(/,([\r\n])/g,"$1"),r.replace(/,([\r\n])/g,"$1"))};function fn(e,r,i,s,a){r=r||[],i=i||[],s&&(e=s(a,e));var c;for(c=0;c<r.length;c+=1)if(r[c]===e)return i[c];var f;if(Yo.call(e)==="[object Array]"){for(r.push(e),f=new Array(e.length),i.push(f),c=0;c<e.length;c+=1)f[c]=fn(e[c],r,i,s,a);return r.pop(),i.pop(),f}if(e&&e.toJSON&&(e=e.toJSON()),Tt(e)==="object"&&e!==null){r.push(e),f={},i.push(f);var p=[],g;for(g in e)e.hasOwnProperty(g)&&p.push(g);for(p.sort(),c=0;c<p.length;c+=1)g=p[c],f[g]=fn(e[g],r,i,s,g);r.pop(),i.pop()}else f=e;return f}var $t=new ge;$t.tokenize=function(e){return e.slice()};$t.join=$t.removeEmpty=function(e){return e};function ir(e,r,i){return $t.diff(e,r,i)}var Qo=500,ei=100,sr=Sr("BYGONE_MAX_INLINE_HIGHLIGHT_LINE_LENGTH",Qo),ti=Sr("BYGONE_DIFF_TIMEOUT_MS",ei);function ie(e,r,i={}){let s=ar(e),a=ar(r);if(e===r)return ri(s);let c=ni(s,a),f=ir(c.left,c.right,{timeout:i.timeoutMs??ti});if(!f)return oi(s,a);let p=f.map(x=>({...x,value:x.value.map(S=>c.lines[S])})),g=[],w=[],m=[],t=[],b=1,I=1;for(let x=0;x<p.length;x++){let S=p[x],C=S.removed?S.value:[],$=S.added?S.value:[];if(!S.added&&!S.removed){for(let P of S.value)w.push(le("context",P,b)),m.push(le("context",P,I)),g.push($e(de("context",P,b++),de("context",P,I++)));continue}if(S.removed&&x+1<p.length&&p[x+1].added){let P=p[x+1],O=ii(C,P.value,b,I,g,w,m,t);b=O.left,I=O.right,x++;continue}if(S.removed){let P=w.length,O=m.length;for(let z of C)w.push(le("removed",z,b)),g.push($e(de("removed",z,b++),ze()));t.push(Pt("delete",P,w.length,O,m.length));continue}if(S.added){let P=w.length,O=m.length;for(let z of $)m.push(le("added",z,I)),g.push($e(ze(),de("added",z,I++)));t.push(Pt("insert",P,w.length,O,m.length))}}let N=g.some(x=>x.left.kind!=="context"||x.right.kind!=="context");return{rows:g,leftLines:w,rightLines:m,blocks:t,hasChanges:N,quality:"exact"}}function ni(e,r){let i=new Map,s=[],a=c=>{let f=i.get(c);if(f!==void 0)return f;let p=s.length;return i.set(c,p),s.push(c),p};return{left:e.map(a),right:r.map(a),lines:s}}function ri(e){return{rows:e.map((r,i)=>$e(de("context",r,i+1),de("context",r,i+1))),leftLines:e.map((r,i)=>le("context",r,i+1)),rightLines:e.map((r,i)=>le("context",r,i+1)),blocks:[],hasChanges:!1,quality:"exact"}}function oi(e,r){let i=e.map((f,p)=>le("removed",f,p+1)),s=r.map((f,p)=>le("added",f,p+1)),a=[...e.map((f,p)=>$e(de("removed",f,p+1),ze())),...r.map((f,p)=>$e(ze(),de("added",f,p+1)))],c="replace";return e.length===0?c="insert":r.length===0&&(c="delete"),{rows:a,leftLines:i,rightLines:s,blocks:a.length===0?[]:[Pt(c,0,e.length,0,r.length)],hasChanges:a.length>0,quality:"fallback"}}function ar(e){if(e.length===0)return[];let r=e.replace(/\r\n/g,`
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 ii(e,r,i,s,a,c,f,p){let g=kr(e,r),w=g.filter($=>$.left!==void 0&&$.right!==void 0&&mn($.left,$.right)).length,m=ai(e,r,w),t=g.flatMap($=>$.left===void 0||$.right===void 0||mn($.left,$.right)?[$]:[{left:$.left},{right:$.right}]),b=i,I=s,N,x=c.length,S=f.length,C=()=>{N&&p.push(Pt(N,x,c.length,S,f.length))};for(let{left:$,right:P}of t){let O=m||$!==void 0&&P!==void 0?"replace":$!==void 0?"delete":"insert";N!==O&&(C(),N=O,x=c.length,S=f.length);let z,R;$!==void 0&&(z=le("removed",$,b),c.push(z)),P!==void 0&&(R=le("added",P,I),f.push(R)),z&&R?$i(z,R):m&&(z&&wr(z),R&&wr(R)),a.push($e($===void 0?ze():de("removed",$,b++),P===void 0?ze():de("added",P,I++)))}return C(),{left:b,right:I}}function mn(e,r){if(Ot(e,r).eligible)return!0;let s=dt(e);if(s&&s===dt(r))return!0;let a=new Set(ut(ue(e)).filter(cr));return ut(ue(r)).some(c=>a.has(c)&&cr(c))}var si=new Set(["and","are","for","from","into","that","the","this","to","with"]);function cr(e){return e.length>=3&&/^[\p{L}\p{N}_$]+$/u.test(e)&&!si.has(e)}function ai(e,r,i){if(i===0)return!1;let s=Math.max(e.length,r.length);if(s<=2||i*2>=s)return!0;let a=[...e,...r].map(ci);return a[0]!==null&&a.every(c=>c===a[0])}function ci(e){let r=e.trimStart();return/^[-*+]\s+/.test(r)?"bullet":/^\d+[.)]\s+/.test(r)?"ordered":/^>\s+/.test(r)?"quote":null}var br=1e4,dr=2e3,di=.52,li=.35,vr=.38,ui=.33,xr=.86,Rt=.08,Nt=.05,At=-.12,lr=5e3,fi=2e3,hi=5e7,ur=4,pi=8,pn=4;function kr(e,r){if(e.length===0)return r.map(m=>({right:m}));if(r.length===0)return e.map(m=>({left:m}));let i=e.reduce((m,t)=>m+t.length,0),s=r.reduce((m,t)=>m+t.length,0);if(i*s>hi)return[...e.map(m=>({left:m})),...r.map(m=>({right:m}))];if(e.length===1&&r.length===1){let m=Ot(e[0],r[0]);return(m.eligible||m.score>=li)&&mn(e[0],r[0])&&yn(e[0],r[0])&&lt(ue(e[0]))&&lt(ue(r[0]))?[{left:e[0],right:r[0]}]:[{left:e[0]},{right:r[0]}]}if(e.length*r.length>br)return bi(e,r);let a=mi(e,r),c=Array.from({length:e.length+1},()=>new Array(r.length+1).fill(Number.NEGATIVE_INFINITY)),f=Array.from({length:e.length+1},()=>new Array(r.length+1).fill(null));c[0][0]=0;for(let m=1;m<=e.length;m++)c[m][0]=c[m-1][0]+At,f[m][0]="left";for(let m=1;m<=r.length;m++)c[0][m]=c[0][m-1]+At,f[0][m]="right";for(let m=1;m<=e.length;m++)for(let t=1;t<=r.length;t++){let b=a[m-1][t-1],N=[{move:"left",score:c[m-1][t]+At},{move:"right",score:c[m][t-1]+At},{move:"match",score:b===null?Number.NEGATIVE_INFINITY:c[m-1][t-1]+b}].reduce((x,S)=>S.score>x.score?S:x);c[m][t]=N.score,f[m][t]=N.move}let p=[],g=e.length,w=r.length;for(;g>0||w>0;){let m=f[g][w];m==="match"?p.push({left:e[--g],right:r[--w]}):m==="left"?p.push({left:e[--g]}):p.push({right:r[--w]})}return p.reverse()}function Ot(e,r){let i=ue(e),s=ue(r),a=lt(i),c=lt(s);if(!a||!c||i.length>dr||s.length>dr)return{score:0,eligible:!1,characterSimilarity:0,tokenSimilarity:0,lengthSimilarity:0};if(i===s)return{score:1,eligible:!0,characterSimilarity:1,tokenSimilarity:1,lengthSimilarity:1};let f=ut(i),p=ut(s),g=Ti(i,s),w=Ei(f,p),m=Math.min(i.length,s.length)/Math.max(i.length,s.length),t=Ci(f,p),b=g*.52+w*.32+m*.1+t*.06,I=g>=.52||w>=.45||g>=.48&&w>=.28;return{score:b,eligible:I&&b>=di,characterSimilarity:g,tokenSimilarity:w,lengthSimilarity:m}}function mi(e,r){let i=e.map(x=>r.map(S=>Ot(x,S))),s=Ir(e,r),a=i.map(x=>gn(x)),c=r.map((x,S)=>gn(i.map(C=>C[S]))),f=i.map((x,S)=>x.map((C,$)=>{if(s.has(`${S}:${$}`))return Math.max(C.score,1);if(!C.eligible)return null;let P=a[S],O=c[$],z=C.score===P.best&&C.score===O.best,R=C.score>=xr?Rt/2:Rt,W=P.best-P.second>=R,fe=O.best-O.second>=R;return z&&W&&fe?C.score:null}));if(Math.max(e.length,r.length)>pi||Math.abs(e.length-r.length)>pn)return f;let p=(x,S,C)=>x.score>=vr&&yn(e[S],r[C])&&Math.abs(S-C)<=pn,g=i.map((x,S)=>Lt(x,(C,$)=>p(C,S,$))),w=r.map((x,S)=>Lt(i.map(C=>C[S]),(C,$)=>p(C,$,S))),m=(x,S,C)=>x.score>=ui&&yn(e[S],r[C])&&Math.abs(S-C)<=pn,t=i.map((x,S)=>Lt(x,(C,$)=>m(C,S,$))),b=r.map((x,S)=>Lt(i.map(C=>C[S]),(C,$)=>m(C,$,S))),I=(x,S)=>{let C=i[x][S];if(!p(C,x,S))return!1;let $=g[x],P=w[S];return C.score===$.best&&C.score===P.best&&$.best-$.second>=Nt&&P.best-P.second>=Nt},N=(x,S)=>{let C=i[x][S];if(!m(C,x,S))return!1;let $=t[x],P=b[S];return C.score===$.best&&C.score===P.best&&$.best-$.second>=Nt&&P.best-P.second>=Nt};return f.map((x,S)=>x.map((C,$)=>{if(C!==null)return C;let P=I(S,$)&&(gi(f,S,$)||yi(i,S,$,I)),O=wi(i,S,$,(z,R)=>m(i[z][R],z,R),N);return!P&&!O?null:i[S][$].score}))}function gi(e,r,i){return r>0&&i>0&&e[r-1][i-1]!==null||r+1<e.length&&i+1<e[r+1].length&&e[r+1][i+1]!==null}function yi(e,r,i,s){return r>0&&i>0&&s(r-1,i-1)||r+1<e.length&&i+1<e[r+1].length&&s(r+1,i+1)}function wi(e,r,i,s,a){let c=r,f=i;for(;c>0&&f>0&&s(c-1,f-1);)c--,f--;let p=r,g=i,w=e[r][i].score,m=1;for(;p+1<e.length&&g+1<e[p+1].length&&s(p+1,g+1);)p++,g++,w+=e[p][g].score,m++;for(let t=r-1,b=i-1;t>=c&&b>=f;t--,b--)w+=e[t][b].score,m++;return m>=3&&w/m>=vr&&a(c,f)&&a(p,g)}function Lt(e,r){let i=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY;return e.forEach((a,c)=>{r(a,c)&&(a.score>i?(s=i,i=a.score):a.score>s&&(s=a.score))}),{best:i,second:s}}function gn(e){let r=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let s of e)s.eligible&&(s.score>r?(i=r,r=s.score):s.score>i&&(i=s.score));return{best:r,second:i}}function bi(e,r){let i=vi(e,r),s=[],a=0,c=0;for(let f of i)gr(s,e.slice(a,f.leftIndex),r.slice(c,f.rightIndex)),s.push({left:e[f.leftIndex],right:r[f.rightIndex]}),a=f.leftIndex+1,c=f.rightIndex+1;return gr(s,e.slice(a),r.slice(c)),s}function vi(e,r){let i=xi(e,r);if(i===null)return[];let s=Ir(e,r),a=i.map(({leftIndex:w,rightIndex:m,exact:t})=>({leftIndex:w,rightIndex:m,exact:t,structural:s.has(`${w}:${m}`),match:Ot(e[w],r[m])})).filter(w=>w.exact||w.structural||w.match.eligible),c=pr(a,"leftIndex"),f=pr(a,"rightIndex"),p=a.filter(w=>{if(w.exact||w.structural)return!0;let m=c.get(w.leftIndex),t=f.get(w.rightIndex);if(!m||!t||w.match.score!==m.best||w.match.score!==t.best)return!1;let b=w.match.score>=xr?Rt/2:Rt;return m.best-m.second>=b&&t.best-t.second>=b}),g=Ii(p,r.length);return g.length<=fi?g:[]}function xi(e,r){let i=fr(e,ue),s=fr(r,ue),a=new Map;for(let[p,g]of i){let w=s.get(p);if(!lt(p)||g.length!==1||w?.length!==1)continue;let m=g[0],t=w[0];if(a.set(`${m}:${t}`,{leftIndex:m,rightIndex:t,exact:!0}),a.size>lr)return null}let c=hr(e),f=hr(r);for(let[p,g]of c){let w=f.get(p);if(!(!w||g.length>ur||w.length>ur))for(let m of g)for(let t of w){let b=`${m}:${t}`;if(!a.has(b)&&(a.set(b,{leftIndex:m,rightIndex:t,exact:!1}),a.size>lr))return null}}return[...a.values()]}function fr(e,r){let i=new Map;return e.forEach((s,a)=>{let c=r(s),f=i.get(c)??[];f.push(a),i.set(c,f)}),i}function hr(e){let r=new Map;return e.forEach((i,s)=>{let a=new Set(ut(ue(i)).filter(ki));for(let c of a){let f=r.get(c)??[];f.push(s),r.set(c,f)}}),r}function ki(e){return e.length>=2&&/[\p{L}\p{N}_$]/u.test(e)}function pr(e,r){let i=new Map;for(let s of e){let a=i.get(s[r])??[];a.push(s.match),i.set(s[r],a)}return new Map([...i].map(([s,a])=>[s,gn(a)]))}function Ii(e,r){let i=[...e].sort((w,m)=>w.leftIndex-m.leftIndex||w.rightIndex-m.rightIndex),s=new Array(r+2).fill(0),a=new Array(r+2).fill(-1),c=new Array(i.length).fill(0),f=new Array(i.length).fill(-1);for(let w=0;w<i.length;){let m=w+1;for(;m<i.length&&i[m].leftIndex===i[w].leftIndex;)m++;for(let t=w;t<m;t++){let b=mr(s,a,i[t].rightIndex),I=i[t].exact||i[t].structural?.5:0;c[t]=b.score+i[t].match.score+I,f[t]=b.candidateIndex}for(let t=w;t<m;t++)Si(s,a,i[t].rightIndex+1,c[t],t);w=m}let p=mr(s,a,r+1),g=[];for(let w=p.candidateIndex;w>=0;w=f[w])g.push({leftIndex:i[w].leftIndex,rightIndex:i[w].rightIndex});return g.reverse()}function mr(e,r,i){let s=0,a=-1;for(let c=i;c>0;c-=c&-c)e[c]>s&&(s=e[c],a=r[c]);return{score:s,candidateIndex:a}}function Si(e,r,i,s,a){for(let c=i;c<e.length;c+=c&-c)s>e[c]&&(e[c]=s,r[c]=a)}function gr(e,r,i){if(r.length*i.length<=br){e.push(...kr(r,i));return}e.push(...r.map(s=>({left:s}))),e.push(...i.map(s=>({right:s})))}function ue(e){return e.trim().replace(/\s+/g," ")}function Ir(e,r){let i=yr(e),s=yr(r),a=new Set;for(let[c,f]of i){let p=s.get(c);f.length===1&&p?.length===1&&a.add(`${f[0]}:${p[0]}`)}return a}function yr(e){let r=new Map;return e.forEach((i,s)=>{let a=dt(i);if(!a)return;let c=r.get(a)??[];c.push(s),r.set(a,c)}),r}function yn(e,r){let i=dt(e),s=dt(r);return!i||!s?i===s:i.split(":",1)[0]===s.split(":",1)[0]}function dt(e){let r=ue(e),i=[["function",/^(?:(?:export|default)\s+)*(?:async\s+)?function\s*\*?\s*([\p{L}_$][\p{L}\p{N}_$]*)\s*\(/u],["function",/^(?:async\s+)?def\s+([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["function",/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([\p{L}_][\p{L}\p{N}_]*)\s*(?:<[^>]*>)?\s*\(/u],["function",/^func\s+(?:\([^)]*\)\s*)?([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["class",/^(?:(?:export|default|abstract|public)\s+)*class\s+([\p{L}_$][\p{L}\p{N}_$]*)\b/u]];for(let[s,a]of i){let c=r.match(a);if(c)return`${s}:${c[1]}`}return null}function lt(e){return e.length<3?!1:/[\p{L}\p{N}_$]/u.test(e)&&!/^[\s()[\]{};,.:+\-*/=>|&!?'"`]+$/.test(e)}function ut(e){return e.toLowerCase().match(/[\p{L}_$][\p{L}\p{N}_$]*|\p{N}+(?:\.\p{N}+)?|[^\s\p{L}\p{N}_$]/gu)??[]}function Ei(e,r){if(e.length+r.length===0)return 1;let i=new Map;e.forEach(a=>i.set(a,(i.get(a)??0)+1));let s=0;for(let a of r){let c=i.get(a)??0;c>0&&(s++,i.set(a,c-1))}return 2*s/(e.length+r.length)}function Ci(e,r){if(e.length===0||r.length===0)return 0;let i=e[0]===r[0]?.5:0,s=e[e.length-1]===r[r.length-1]?.5:0;return i+s}function Ti(e,r){let i=e.length+r.length;return i===0?1:2*nr(e,r).filter(a=>!a.added&&!a.removed).reduce((a,c)=>a+c.value.length,0)/i}function $i(e,r){if(e.content.length>sr||r.content.length>sr)return;let{leftSegments:i,rightSegments:s,hasInlineChanges:a}=Ni(e.content,r.content);a&&(e.segments=i,r.segments=s)}function wr(e){/[^\s]/.test(e.content)&&(e.segments=[{kind:e.kind,text:e.content,emphasis:!0}])}function Ni(e,r){let i=rr(e,r),s=[],a=[],c=!1;for(let f of i){let p=f.value;if(!f.added&&!f.removed){let w={kind:"context",text:p,emphasis:!1};s.push(w),a.push(w);continue}let g=/[^\s]/.test(p);c=c||g,f.removed&&s.push({kind:"removed",text:p,emphasis:g}),f.added&&a.push({kind:"added",text:p,emphasis:g})}return{leftSegments:s,rightSegments:a,hasInlineChanges:c}}function ze(){return{kind:"placeholder",content:"",lineNumber:null}}function de(e,r,i){return{kind:e,content:r,lineNumber:i}}function le(e,r,i){return{kind:e,content:r,lineNumber:i}}function $e(e,r){return{left:e,right:r}}function Pt(e,r,i,s,a){return{kind:e,leftStart:r,leftEnd:i,rightStart:s,rightEnd:a}}function Sr(e,r){let i=typeof process<"u"?process.env?.[e]:void 0,s=Number.parseInt(i??"",10);return Number.isFinite(s)&&s>0?s:r}function Er(){return{leftFileName:"test-file-1.js",rightFileName:"test-file-2.js",leftContent:`// Test File 1 - Example JavaScript Code
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 Tr(e,r={}){if(!We(e))throw new Error("review must be an object.");if(je(e,["baseOid","headOid","items"],"review"),Cr(e.baseOid,"review.baseOid"),Cr(e.headOid,"review.headOid"),!Array.isArray(e.items)||e.items.length===0)throw new Error("review.items must be a non-empty array.");if(r.expectedRange){if(Mt(e.baseOid)!==Mt(r.expectedRange.baseOid))throw new Error(`Stale review: review.baseOid ${e.baseOid} does not match the resolved range.mergeBaseOid ${r.expectedRange.baseOid}.`);if(Mt(e.headOid)!==Mt(r.expectedRange.headOid))throw new Error(`Stale review: review.headOid ${e.headOid} does not match the resolved range.headOid ${r.expectedRange.headOid}.`)}let i=new Set;for(let[s,a]of e.items.entries()){let c=`review.items[${s}]`;if(!We(a))throw new Error(`${c} must be an object.`);if(je(a,["id","kind","title","body","evidence","nextCheck"],c),qe(a.id,`${c}.id`),i.has(a.id))throw new Error(`Duplicate review item id: ${a.id}`);if(i.add(a.id),typeof a.kind!="string"||!["concept","boundary","tradeoff","question"].includes(a.kind))throw new Error(`${c}.kind must be concept, boundary, tradeoff, or question.`);if(qe(a.title,`${c}.title`),qe(a.body,`${c}.body`),!Array.isArray(a.evidence))throw new Error(`${c}.evidence must be an array.`);if(a.kind!=="question"&&a.evidence.length===0)throw new Error(`${c}.evidence must contain at least one reference for claims.`);if(a.kind==="question"&&a.nextCheck===void 0)throw new Error(`${c}.nextCheck must be a non-empty string for question items.`);a.nextCheck!==void 0&&qe(a.nextCheck,`${c}.nextCheck`);for(let[f,p]of a.evidence.entries()){let g=`${c}.evidence[${f}]`;if(!We(p))throw new Error(`${g} must be an object.`);if(je(p,["sceneId","stepId"],g),qe(p.sceneId,`${g}.sceneId`),qe(p.stepId,`${g}.stepId`),r.authoredWalkthroughSteps){let w=r.authoredWalkthroughSteps.get(p.sceneId);if(!w)throw new Error(`${g} references unknown authored walkthrough scene ${p.sceneId}.`);if(!w.has(p.stepId))throw new Error(`${g} references unknown authored walkthrough step ${p.sceneId}/${p.stepId}.`)}}}}function $r(e,r){if(e!==void 0){if(!We(e))throw new Error(`${r} must be an object.`);if(je(e,["id","text","status","source","confidence"],r),Ne(e.id,`${r}.id`),Ne(e.text,`${r}.text`),e.status!==void 0&&!["fulfilled","gap"].includes(String(e.status)))throw new Error(`${r}.status must be fulfilled or gap.`);if(Li(e.source,`${r}.source`),e.confidence!==void 0&&!["high","medium","low"].includes(String(e.confidence)))throw new Error(`${r}.confidence must be high, medium, or low.`)}}function Ge(e,r,i={}){if(e!==void 0){if(!We(e))throw new Error(`${r} must be an object.`);if(je(e,["kind","path","comparison"],r),e.kind!=="directory-diff")throw new Error(`${r}.kind must be directory-diff.`);if(e.path!==void 0&&Ai(e.path,`${r}.path`),e.comparison!==void 0){if(i.allowComparison===!1)throw new Error(`${r}.comparison is not supported for walkthrough scenes; use the fixed base-to-head comparison.`);if(!We(e.comparison))throw new Error(`${r}.comparison must be an object.`);if(je(e.comparison,["from","to"],`${r}.comparison`),Ne(e.comparison.from,`${r}.comparison.from`),Ne(e.comparison.to,`${r}.comparison.to`),e.comparison.from===e.comparison.to)throw new Error(`${r}.comparison.from and to must identify distinct endpoints.`);if(i.endpointIds!==void 0){for(let s of[e.comparison.from,e.comparison.to])if(!i.endpointIds.includes(s))throw new Error(`${r}.comparison endpoint ${s} is not defined by this scene.`)}}}}function Ai(e,r){if(Ne(e,r),e.includes("\\"))throw new Error(`${r} must use a relative POSIX directory path without backslashes.`);if(e.startsWith("/")||/^[A-Za-z]:/.test(e))throw new Error(`${r} must be relative to the repository root.`);if(e.split("/").some(i=>i===".."))throw new Error(`${r} must not contain parent-directory traversal.`)}function We(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e,r){if(typeof e!="string"||e.length===0)throw new Error(`${r} must be a non-empty string.`)}function Cr(e,r){if(Ne(e,r),!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(e))throw new Error(`${r} must be a full 40- or 64-character hexadecimal Git OID.`)}function qe(e,r){if(typeof e!="string"||e.trim().length===0)throw new Error(`${r} must be a non-empty string.`)}function Mt(e){return e.toLowerCase()}function Li(e,r){e!==void 0&&Ne(e,r)}function je(e,r,i){let s=Object.keys(e).filter(a=>!r.includes(a));if(s.length>0)throw new Error(`${i} contains unknown field${s.length===1?"":"s"}: ${s.join(", ")}`)}var wn=3;function Ar(e){if(H(e)&&Number.isInteger(e.version)&&Number(e.version)>wn)throw new Error(`This tour uses manifest format version ${e.version}, but this version of Bygone supports up to version ${wn}. Upgrade Bygone to open it.`);if(!H(e)||e.version!==1&&e.version!==2&&e.version!==wn)throw new Error("Unsupported or missing change-tour manifest version.");if(q(e.title,"title"),q(e.generatedAt,"generatedAt"),e.windowTitle!==void 0&&q(e.windowTitle,"windowTitle"),e.sourceUrl!==void 0&&q(e.sourceUrl,"sourceUrl"),!H(e.range))throw new Error("Change-tour manifest range must be an object.");for(let s of["baseRef","headRef","mergeBaseOid","headOid"])q(e.range[s],`range.${s}`);if(!H(e.summary))throw new Error("Change-tour manifest summary must be an object.");for(let s of["changedFiles","includedScenes","additions","deletions","commitCount"])Z(e.summary[s],`summary.${s}`);if(Ve(e.summary.omittedFiles,"summary.omittedFiles"),!Array.isArray(e.commits)||!Array.isArray(e.chapters)||!Array.isArray(e.scenes))throw new Error("Change-tour manifest commits, chapters, and scenes must be arrays.");if(e.files!==void 0&&!Array.isArray(e.files))throw new Error("Change-tour manifest files must be an array.");let r=new Set;for(let[s,a]of e.scenes.entries()){if(Ke(a,s,e.version),r.has(a.id))throw new Error(`Duplicate change-tour scene id: ${a.id}`);r.add(a.id)}for(let[s,a]of e.chapters.entries()){if(!H(a))throw new Error(`chapters[${s}] must be an object.`);q(a.id,`chapters[${s}].id`),q(a.title,`chapters[${s}].title`),Ve(a.sceneIds,`chapters[${s}].sceneIds`);for(let c of a.sceneIds)if(!r.has(c))throw new Error(`Chapter references unknown scene id: ${c}`)}if(e.summary.includedScenes!==e.scenes.length)throw new Error("summary.includedScenes must match the number of scenes.");let i=e.files===void 0?_i(e.scenes):e.files.map((s,a)=>(Bi(s,a),s));if(e.files!==void 0&&e.summary.changedFiles!==i.length)throw new Error("summary.changedFiles must match the number of files.");if(e.authoringCoverage!==void 0&&Pi(e.authoringCoverage,e.version),e.tours!==void 0){if(e.version!==3)throw new Error("Independent tours require manifest version 3.");Oi(e.tours,e.version)}if(e.version!==1&&Mi(e,e.version),e.review!==void 0){if(e.version!==3)throw new Error("Review notes require manifest version 3.");let s=e.version>=2&&H(e.zoom)&&H(e.zoom.final)?e.zoom.final.scenes:e.scenes;Tr(e.review,{expectedRange:{baseOid:String(e.range.mergeBaseOid),headOid:String(e.range.headOid)},authoredWalkthroughSteps:Ri(s)})}return{...e,files:i}}function Ri(e){let r=new Map;if(!Array.isArray(e))return r;for(let i of e){if(!H(i)||i.kind!=="walkthrough"||!Array.isArray(i.steps)||typeof i.id!="string")continue;let s=new Set;for(let a of i.steps)H(a)&&typeof a.id=="string"&&s.add(a.id);r.set(i.id,s)}return r}function Pi(e,r){if(!H(e)||!H(e.walkthrough)||!Array.isArray(e.explanationAssignments))throw new Error("authoringCoverage must contain walkthrough and explanationAssignments.");let i=r>=2?"final":"tour";if(e.walkthrough.scope!==i)throw new Error(`authoringCoverage.walkthrough.scope must be ${i}.`);if(Z(e.walkthrough.coveredUnits,"authoringCoverage.walkthrough.coveredUnits"),Z(e.walkthrough.includedUnits,"authoringCoverage.walkthrough.includedUnits"),Nr(e.walkthrough.coveragePercent,"authoringCoverage.walkthrough.coveragePercent"),e.walkthrough.coveredUnits>e.walkthrough.includedUnits)throw new Error("authoringCoverage.walkthrough.coveredUnits must not exceed includedUnits.");for(let[s,a]of e.explanationAssignments.entries()){let c=`authoringCoverage.explanationAssignments[${s}]`;if(!H(a))throw new Error(`${c} must be an object.`);if(q(a.sceneId,`${c}.sceneId`),Z(a.assignedUnits,`${c}.assignedUnits`),Z(a.excludedUnits,`${c}.excludedUnits`),Z(a.completeUnits,`${c}.completeUnits`),Z(a.totalUnits,`${c}.totalUnits`),Nr(a.assignmentPercent,`${c}.assignmentPercent`),a.assignedUnits+a.excludedUnits!==a.completeUnits||a.completeUnits>a.totalUnits)throw new Error(`${c} contains inconsistent unit counts.`)}}function Oi(e,r){if(!H(e))throw new Error("Change-tour manifest tours must be an object.");if(e.historical===void 0&&e.deconstructed===void 0)throw new Error("Change-tour manifest tours must contain a historical or deconstructed tour.");for(let i of["historical","deconstructed"]){let s=e[i];if(s===void 0)continue;if(!H(s)||!Array.isArray(s.chapters)||!Array.isArray(s.scenes)||s.chapters.length===0||s.scenes.length===0)throw new Error(`Change-tour manifest tours.${i} must contain non-empty chapters and scenes arrays.`);let a=new Set,c=!1;for(let[f,p]of s.scenes.entries()){if(Ke(p,f,r),a.has(p.id))throw new Error(`Duplicate ${i} tour scene id: ${p.id}`);if(a.add(p.id),p.kind==="deconstructed-diff"&&(c=!0),i==="historical"&&p.kind==="deconstructed-diff")throw new Error("Historical tours cannot contain synthetic deconstructed scenes.")}if(i==="deconstructed"&&!c)throw new Error("Deconstructed tours must contain a constructed deconstructed-diff scene.");for(let[f,p]of s.chapters.entries()){if(!H(p))throw new Error(`tours.${i}.chapters[${f}] must be an object.`);q(p.id,`tours.${i}.chapters[${f}].id`),q(p.title,`tours.${i}.chapters[${f}].title`),Ve(p.sceneIds,`tours.${i}.chapters[${f}].sceneIds`);for(let g of p.sceneIds)if(!a.has(g))throw new Error(`tours.${i} chapter references unknown scene id: ${g}`)}}}function Mi(e,r){if(!H(e.repository)||typeof e.repository.root!="string"||!e.repository.root)throw new Error("A v2 tour requires its originating repository.root.");if(!H(e.zoom)||!Array.isArray(e.zoom.revisions)||!H(e.zoom.final))throw new Error("A v2 tour requires zoom metadata and real revision evidence.");let i=e.scenes,s=e.zoom.revisions,a=new Set;for(let[m,t]of s.entries()){if(Ke(t,m,r),t.kind!=="stacked-diff")throw new Error("zoom.revisions must contain real stacked-diff scenes.");if(a.has(t.id))throw new Error(`Duplicate zoom revision scene: ${t.id}`);a.add(t.id);let b=e.range;if(t.stack[0].oid!==b.mergeBaseOid||t.stack[t.stack.length-1].oid!==b.headOid)throw new Error(`Revision scene ${t.id} endpoints must match the final diff range.`)}for(let m of i){if(m.kind!=="deconstructed-diff"&&m.kind!=="stacked-diff")continue;let t=s.find(b=>b.id===m.id);if(!t)throw new Error(`Scene ${m.id} is missing its real revision evidence.`);if(m.kind==="deconstructed-diff"&&(t.stack[0].oid!==m.realRange.baseOid||t.stack[t.stack.length-1].oid!==m.realRange.targetOid))throw new Error(`Deconstructed scene ${m.id} real stack endpoints must match its explanation range.`)}let c=i.some(m=>m.kind==="deconstructed-diff"),f=s.some(m=>m.stack.length>2),p=c?"explanation":f?"revisions":"final",g=[...c?["explanation"]:[],...f?["revisions"]:[],"final","history"];if(e.zoom.authoredDepth!==p||JSON.stringify(e.zoom.modes)!==JSON.stringify(g))throw new Error("zoom depth and modes must match the maximum authored depth.");if(!Array.isArray(e.files))throw new Error("A v2 tour requires final endpoint file evidence.");if(!Array.isArray(e.zoom.final.scenes)||!Array.isArray(e.zoom.final.chapters))throw new Error("A v2 tour requires a non-stacked final tour.");let w=new Set;for(let[m,t]of e.zoom.final.scenes.entries()){if(Ke(t,m,r),t.kind==="stacked-diff"||t.kind==="deconstructed-diff")throw new Error("zoom.final must contain only non-stacked scenes.");if(w.has(t.id))throw new Error(`Duplicate final tour scene: ${t.id}`);w.add(t.id)}for(let[m,t]of e.zoom.final.chapters.entries()){if(!H(t)||!Array.isArray(t.sceneIds))throw new Error(`zoom.final.chapters[${m}] must contain sceneIds.`);q(t.id,`zoom.final.chapters[${m}].id`),q(t.title,`zoom.final.chapters[${m}].title`);for(let b of t.sceneIds)if(q(b,`zoom.final.chapters[${m}].sceneIds`),!w.has(b))throw new Error(`Final tour chapter references unknown scene: ${b}`)}}function Ke(e,r,i){if(!H(e)||!["text-diff","discussion","walkthrough","stacked-diff","deconstructed-diff"].includes(String(e.kind)))throw new Error(`scenes[${r}] must be a text-diff, discussion, walkthrough, stacked-diff, or deconstructed-diff scene.`);for(let s of["id","title"])q(e[s],`scenes[${r}].${s}`);if(e.overview!==void 0&&i!==3)throw new Error(`scenes[${r}].overview requires manifest version 3.`);if(Ui(e,`scenes[${r}]`),e.kind==="discussion"){Ge(e.overview,`scenes[${r}].overview`,{allowComparison:!1});return}if(e.kind==="walkthrough"){if(Ge(e.overview,`scenes[${r}].overview`,{allowComparison:!1}),!Array.isArray(e.steps)||e.steps.length===0)throw new Error(`scenes[${r}].steps must be a non-empty array.`);for(let[s,a]of e.steps.entries()){let c=`scenes[${r}].steps[${s}]`;if(!H(a)||!H(a.focus)||!H(a.diff))throw new Error(`${c} must contain focus and diff objects.`);for(let f of["id","title","body"])q(a[f],`${c}.${f}`);if(a.depth!==void 0&&!["mentioned","explained","contextualized"].includes(String(a.depth)))throw new Error(`${c}.depth must be mentioned, explained, or contextualized.`);if($r(a.requirement,`${c}.requirement`),bn(a.focus,`${c}.focus`),Ke(a.diff,r,i),a.diff.kind!=="text-diff")throw new Error(`${c}.diff must be a text-diff scene.`);if(a.connection!==void 0){if(!H(a.connection))throw new Error(`${c}.connection must be an object.`);q(a.connection.id,`${c}.connection.id`),q(a.connection.label,`${c}.connection.label`),bn(a.connection.from,`${c}.connection.from`),bn(a.connection.to,`${c}.connection.to`)}}return}if(e.kind==="stacked-diff"){Di(e,r),Ge(e.overview,`scenes[${r}].overview`,{endpointIds:e.stack.map(s=>s.id)});return}if(e.kind==="deconstructed-diff"){Fi(e,r),Ge(e.overview,`scenes[${r}].overview`,{endpointIds:e.panels.map(s=>s.id)});return}Ge(e.overview,`scenes[${r}].overview`,{allowComparison:!1});for(let s of["path","leftLabel","rightLabel","leftContent","rightContent"])q(e[s],`scenes[${r}].${s}`);e.previousPath!==void 0&&q(e.previousPath,`scenes[${r}].previousPath`),q(e.changeKind,`scenes[${r}].changeKind`),Z(e.additions,`scenes[${r}].additions`),Z(e.deletions,`scenes[${r}].deletions`),e.focusChangeIndex!==void 0&&Z(e.focusChangeIndex,`scenes[${r}].focusChangeIndex`)}function Di(e,r){if(!Array.isArray(e.stack)||e.stack.length<2||e.stack.length>6)throw new Error(`scenes[${r}].stack must contain between 2 and 6 revisions.`);for(let[i,s]of e.stack.entries()){if(!H(s))throw new Error(`scenes[${r}].stack[${i}] must be an object.`);for(let a of["id","ref","oid","label"])q(s[a],`scenes[${r}].stack[${i}].${a}`)}Lr(e.files,e.stack.length,r),Rr(e.steps,e.stack.length,r,!1)}function Fi(e,r){if(e.stageLabel!=="Explanation stages")throw new Error(`scenes[${r}].stageLabel must be Explanation stages.`);if(!H(e.realRange))throw new Error(`scenes[${r}].realRange must be an object.`);for(let s of["baseRef","targetRef","baseOid","targetOid"])q(e.realRange[s],`scenes[${r}].realRange.${s}`);if(!Array.isArray(e.panels)||e.panels.length<2||e.panels.length>13)throw new Error(`scenes[${r}].panels must contain a baseline and between 1 and 12 stages.`);let i=e.panels;for(let[s,a]of i.entries()){if(!H(a))throw new Error(`scenes[${r}].panels[${s}] must be an object.`);for(let f of["id","label","role"])q(a[f],`scenes[${r}].panels[${s}].${f}`);let c=s===0?"baseline":"stage";if(a.role!==c)throw new Error(`scenes[${r}].panels[${s}].role must be ${c}.`);s>0&&q(a.stageId,`scenes[${r}].panels[${s}].stageId`)}if(Lr(e.files,i.length,r),Rr(e.steps,i.length,r,!0),Array.isArray(e.steps)){let s=-1;e.steps.forEach((a,c)=>{if(!H(a))return;let f=Number(a.pairIndex);if(f<s)throw new Error(`scenes[${r}].steps must remain grouped in explanation stage order.`);if(s=f,a.stageId!==void 0&&q(a.stageId,`scenes[${r}].steps[${c}].stageId`),a.stageIndex!==void 0&&Z(a.stageIndex,`scenes[${r}].steps[${c}].stageIndex`),a.focusIndex!==void 0&&Z(a.focusIndex,`scenes[${r}].steps[${c}].focusIndex`),a.focusCount!==void 0&&ft(a.focusCount,`scenes[${r}].steps[${c}].focusCount`),a.stageIndex!==void 0&&Number(a.stageIndex)!==f)throw new Error(`scenes[${r}].steps[${c}].stageIndex must match pairIndex.`);if(a.focusIndex!==void 0&&a.focusCount!==void 0&&Number(a.focusIndex)>=Number(a.focusCount))throw new Error(`scenes[${r}].steps[${c}].focusIndex must be less than focusCount.`)});for(let a=0;a<i.length-1;a+=1){let c=i[a+1],f=e.steps.filter(w=>H(w)&&Number(w.pairIndex)===a);if(!H(c)||f.length===0)throw new Error(`scenes[${r}].steps must cover every explanation stage.`);let p=f[0],g=H(p)?p.id:void 0;if(f.some(w=>H(w)?(w.stageId??g)!==c.stageId:!0))throw new Error(`scenes[${r}].panels must align with explanation stage ids.`)}}}function Lr(e,r,i){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${i}].files must be non-empty.`);for(let[s,a]of e.entries()){if(!H(a))throw new Error(`scenes[${i}].files[${s}] must be an object.`);if(q(a.path,`scenes[${i}].files[${s}].path`),!Array.isArray(a.panels)||a.panels.length!==r)throw new Error(`scenes[${i}].files[${s}].panels must match panel count.`);for(let[c,f]of a.panels.entries()){if(!H(f))throw new Error(`scenes[${i}].files[${s}].panels[${c}] must be an object.`);for(let p of["id","label","content"])q(f[p],`scenes[${i}].files[${s}].panels[${c}].${p}`);if(f.path!==void 0&&q(f.path,`scenes[${i}].files[${s}].panels[${c}].path`),typeof f.exists!="boolean")throw new Error(`scenes[${i}].files[${s}].panels[${c}].exists must be boolean.`)}}}function Rr(e,r,i,s){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${i}].steps must be non-empty.`);for(let[a,c]of e.entries()){if(!H(c))throw new Error(`scenes[${i}].steps[${a}] must be an object.`);for(let f of["id","title","body","file","side"])q(c[f],`scenes[${i}].steps[${a}].${f}`);if(Z(c.pairIndex,`scenes[${i}].steps[${a}].pairIndex`),Number(c.pairIndex)>=r-1)throw new Error(`scenes[${i}].steps[${a}].pairIndex is outside the panels.`);if(s&&(Ve(c.introducedHunks,`scenes[${i}].steps[${a}].introducedHunks`),c.introducedHunks.length===0))throw new Error(`scenes[${i}].steps[${a}].introducedHunks must be non-empty.`);if(c.side!=="left"&&c.side!=="right")throw new Error(`scenes[${i}].steps[${a}].side must be left or right.`);c.startLine!==void 0&&ft(c.startLine,`scenes[${i}].steps[${a}].startLine`),c.endLine!==void 0&&ft(c.endLine,`scenes[${i}].steps[${a}].endLine`)}}function Bi(e,r){if(!H(e))throw new Error(`files[${r}] must be an object.`);if(e.kind==="text-diff"){Ke(e,r,1);return}if(e.kind!=="omitted")throw new Error(`files[${r}].kind must be text-diff or omitted.`);for(let i of["id","title","path","changeKind","reason"])q(e[i],`files[${r}].${i}`);e.previousPath!==void 0&&q(e.previousPath,`files[${r}].previousPath`),Z(e.additions,`files[${r}].additions`),Z(e.deletions,`files[${r}].deletions`)}function _i(e){let r=new Map;for(let i of e){if(i.kind==="text-diff"){r.has(i.path)||r.set(i.path,i);continue}if(i.kind==="walkthrough")for(let s of i.steps)r.has(s.diff.path)||r.set(s.diff.path,s.diff)}return[...r.values()].sort((i,s)=>i.path.localeCompare(s.path))}function bn(e,r){if(!H(e))throw new Error(`${r} must be an object.`);for(let i of["id","path","revision","excerpt"])q(e[i],`${r}.${i}`);if(e.revision!=="base"&&e.revision!=="head")throw new Error(`${r}.revision must be base or head.`);if(ft(e.startLine,`${r}.startLine`),ft(e.endLine,`${r}.endLine`),Number(e.endLine)<Number(e.startLine))throw new Error(`${r}.endLine must not precede startLine.`)}function Ui(e,r){q(e.summary,`${r}.summary`),Ve(e.bullets,`${r}.bullets`),Ve(e.tags,`${r}.tags`),q(e.takeaway,`${r}.takeaway`)}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function q(e,r){if(typeof e!="string")throw new Error(`${r} must be a string.`)}function Ve(e,r){if(!Array.isArray(e)||e.some(i=>typeof i!="string"))throw new Error(`${r} must be an array of strings.`)}function Z(e,r){if(!Number.isInteger(e)||Number(e)<0)throw new Error(`${r} must be a non-negative integer.`)}function Nr(e,r){if(typeof e!="number"||!Number.isFinite(e)||e<0||e>100)throw new Error(`${r} must be a number from 0 to 100.`)}function ft(e,r){if(!Number.isInteger(e)||Number(e)<1)throw new Error(`${r} must be a positive integer.`)}var Hi=new Set(["modified-here","created-here","deleted-here"]);function vn(e,r){let i=e.panels[r],s=e.panels[r+1];return!i||!s?"unchanged-here":i.exists&&s.exists?i.content===s.content?"unchanged-here":"modified-here":!i.exists&&s.exists?"created-here":i.exists&&!s.exists?"deleted-here":e.panels.slice(0,r).some(f=>f.exists)?"already-deleted":(e.panels.slice(r+2).some(f=>f.exists),"not-created-yet")}function Pr(e,r,i,s){if(s!==-1&&s!==1||!i)return null;let a=e.findIndex(p=>p.path===i);if(a<0)return null;let c=e.map((p,g)=>({file:p,fileIndex:g,state:vn(p,r)})).filter(({state:p})=>Hi.has(p)),f=s<0?[...c].reverse().find(({fileIndex:p})=>p<a):c.find(({fileIndex:p})=>p>a);return f?{pairIndex:r,fileIndex:f.fileIndex,path:f.file.path}:null}function xn(e,r,i){let s=e.findIndex(p=>p.id===r),a=s>=0?s:0,c=e[a];if(!c||c.kind!=="walkthrough"&&c.kind!=="stacked-diff"&&c.kind!=="deconstructed-diff"||!i)return{sceneIndex:a,stepIndex:0};let f=c.steps.findIndex(p=>p.id===i);return{sceneIndex:a,stepIndex:f>=0?f:0}}function kn(e,r,i){let s=e[r.sceneIndex];if(!s)return null;if(i>0)return(s.kind==="walkthrough"||s.kind==="stacked-diff"||s.kind==="deconstructed-diff")&&r.stepIndex<s.steps.length-1?{sceneIndex:r.sceneIndex,stepIndex:r.stepIndex+1}:r.sceneIndex<e.length-1?{sceneIndex:r.sceneIndex+1,stepIndex:0}:null;if((s.kind==="walkthrough"||s.kind==="stacked-diff"||s.kind==="deconstructed-diff")&&r.stepIndex>0)return{sceneIndex:r.sceneIndex,stepIndex:r.stepIndex-1};if(r.sceneIndex===0)return null;let a=e[r.sceneIndex-1];return{sceneIndex:r.sceneIndex-1,stepIndex:a.kind==="walkthrough"||a.kind==="stacked-diff"||a.kind==="deconstructed-diff"?a.steps.length-1:0}}function Or(e,r,i){if(!r)return null;let s=e.map((p,g)=>({file:p,fileIndex:g})).filter(({file:p})=>p.kind==="text-diff"),a=s.findIndex(({file:p})=>p.path===r),c=a+i,f=a>=0?s[c]:null;return f?{fileIndex:f.fileIndex,path:f.file.path}:null}function Dr(e,r,i){let s=e.scenes[r.sceneIndex];if(!s)return null;let a=In(s)?Math.min(Math.max(r.stepIndex,0),s.steps.length-1):0,c={sceneIndex:r.sceneIndex,stepIndex:a},f=In(s)?s.steps[a]:void 0,p=[],g=!f||a===0,w=!!(f&&a>0&&i.entry==="playback-start");if(g){let I=e.chapters.find(N=>N.sceneIds.includes(s.id));I&&p.push({source:{field:"chapter"},text:I.title})}(g||w)&&p.push({source:{field:"scene-title"},text:s.title}),g&&(p.push({source:{field:"summary"},text:s.summary}),s.bullets.forEach((I,N)=>{p.push({source:{field:"bullet",itemIndex:N},text:I})})),f&&(p.push({source:{field:"step-title"},text:f.title}),p.push({source:{field:"step-body"},text:f.body}),"connection"in f&&f.connection?.label&&p.push({source:{field:"connection"},text:f.connection.label})),(!f||In(s)&&a===s.steps.length-1)&&p.push({source:{field:"takeaway"},text:s.takeaway});let m=`${s.id}:${f?.id||"scene"}`,t=i.segmentLimit??240,b=p.flatMap(I=>Wi(m,I,t));return{id:m,position:c,segments:b}}function zi(e,r=240){if(!Number.isInteger(r)||r<40)throw new Error("Narration segment limit must be an integer of at least 40 characters.");return ji(e).flatMap(s=>Gi(e,s.startOffset,s.endOffset,r))}function qi(e){return e.replace(/https?:\/\/\S+/giu," ").replace(/\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*\d)[0-9a-f]+\b/giu," ").replace(/[`*_~]/gu,"").replace(/([\p{Ll}\d])(\p{Lu})/gu,"$1 $2").replace(/([\p{Lu}])(\p{Lu}\p{Ll})/gu,"$1 $2").replace(/\s+/gu," ").trim()}function Wi(e,r,i){let s=r.source.itemIndex===void 0?r.source.field:`${r.source.field}-${r.source.itemIndex}`;return zi(r.text,i).map((a,c)=>({id:`${e}:${s}:${c}`,text:a.text,speechText:qi(a.text),source:r.source,startOffset:a.startOffset,endOffset:a.endOffset})).filter(a=>a.speechText.length>0)}function ji(e){let r=[],i=0;for(let s=0;s<e.length;s+=1){if(!".!?".includes(e[s]))continue;let a=s+1;for(;a<e.length&&`"'\u201D\u2019)]}`.includes(e[a]);)a+=1;a<e.length&&!/\s/u.test(e[a])||(Dt(e,r,i,a),i=a)}return Dt(e,r,i,e.length),r}function Gi(e,r,i,s){let a=[],c=r;for(;i-c>s;){let f=c+s,p=c+Math.floor(s*.55),g=Mr(e,p,f,/[;,:—–-]/u);g<=c&&(g=Mr(e,p,f,/\s/u)),g<=c&&(g=f),Dt(e,a,c,g),c=g}return Dt(e,a,c,i),a}function Mr(e,r,i,s){for(let a=i;a>=r;a-=1)if(s.test(e[a]))return a+1;return-1}function Dt(e,r,i,s){let a=i,c=s;for(;a<c&&/\s/u.test(e[a]);)a+=1;for(;c>a&&/\s/u.test(e[c-1]);)c-=1;a<c&&r.push({text:e.slice(a,c),startOffset:a,endOffset:c})}function In(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function Fr(e){let r=[{kind:"title",key:"title",sceneIndex:0,stepIndex:0}],i=new Map;for(let a of e.chapters)for(let c of a.sceneIds)i.has(c)||i.set(c,a.id);let s=new Set;return e.scenes.forEach((a,c)=>{let f=i.get(a.id);e.chapters.length>1&&f&&!s.has(f)&&(r.push({kind:"chapter",key:`chapter:${f}`,chapterId:f,sceneIndex:c,stepIndex:0}),s.add(f)),r.push({kind:"scene",key:`scene:${a.id}`,sceneIndex:c,stepIndex:0}),Ki(a)&&a.steps.forEach((p,g)=>{r.push({kind:"step",key:`step:${a.id}:${p.id}`,sceneIndex:c,stepIndex:g})})}),r}function Br(e,r,i){if(i!==-1&&i!==1)return null;let s=e.findIndex(a=>a.key===r);return s<0?null:e[s+i]??null}function Ft(e,r,i,s=null){if(s==="tour")return e.find(c=>c.kind==="title")??null;let a=e.findIndex(c=>c.kind==="scene"&&c.sceneIndex===r);if(a<0)return null;if(s==="overview")return e[a]??null;if(s==="chapter"){for(let c=a-1;c>=0;c-=1){let f=e[c];if(f.kind==="chapter")return f;if(f.kind==="title")break}return e.find(c=>c.kind==="title")??null}return e.find(c=>c.kind==="step"&&c.sceneIndex===r&&c.stepIndex===i)??e[a]??null}function Ki(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}var Bt=class{constructor(r,i){this.engine=r;this.callbacks=i;this.generation=0;this.continuous=!0;this.currentState={kind:"idle"}}get state(){return this.currentState}get engaged(){return this.currentState.kind==="playing"||this.currentState.kind==="paused"}start(r,i=!0){if(this.resetEngine(),this.continuous=i,r.segments.length===0){this.finishUnit(r);return}this.callbacks.claimAudio(),this.setState({kind:"playing",unit:r,segmentIndex:0}),this.speakCurrent()}togglePause(){if(this.currentState.kind==="playing"){this.engine.pause();let i={kind:"paused",unit:this.currentState.unit,segmentIndex:this.currentState.segmentIndex,pendingStart:!1};this.setState(i),this.callbacks.onSegmentChange(i.unit.segments[i.segmentIndex]||null,!0);return}if(this.currentState.kind!=="paused")return;this.callbacks.claimAudio();let r=this.currentState;this.setState({kind:"playing",unit:r.unit,segmentIndex:r.segmentIndex}),r.pendingStart?this.speakCurrent():(this.engine.resume(),this.callbacks.onSegmentChange(r.unit.segments[r.segmentIndex]||null,!1))}stop(){this.resetEngine(),this.setState({kind:"idle"}),this.callbacks.onSegmentChange(null,!1)}pauseForExternalOwner(){this.currentState.kind==="playing"&&this.togglePause()}canSkipSegment(r){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return!1;let i=this.currentState.segmentIndex+r;return i>=0&&i<this.currentState.unit.segments.length?!0:this.callbacks.canNavigateUnit(this.currentState.unit,r)}skipSegment(r){if(!this.canSkipSegment(r))return!1;let i=this.currentState,s=i.kind==="paused",a=i.unit,c=i.segmentIndex+r;if(c<0||c>=a.segments.length){let f=this.callbacks.navigateUnit(a,r);if(!f||f.segments.length===0)return!1;a=f,c=r<0?a.segments.length-1:0}return this.resetEngine(),s?(this.setState({kind:"paused",unit:a,segmentIndex:c,pendingStart:!0}),this.callbacks.onSegmentChange(a.segments[c]||null,!0)):(this.setState({kind:"playing",unit:a,segmentIndex:c}),this.speakCurrent()),!0}followLinearNavigation(r){this.currentState.kind==="playing"?this.start(r,this.continuous):this.currentState.kind==="paused"&&this.preparePaused(r)}followDirectNavigation(r){this.engaged&&this.preparePaused(r)}interruptForExploration(){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return;let r=this.currentState;this.resetEngine(),this.setState({kind:"paused",unit:r.unit,segmentIndex:r.segmentIndex,pendingStart:!0}),this.callbacks.onSegmentChange(r.unit.segments[r.segmentIndex]||null,!0)}dispose(){this.stop()}preparePaused(r){this.resetEngine(),this.setState({kind:"paused",unit:r,segmentIndex:0,pendingStart:!0}),this.callbacks.onSegmentChange(r.segments[0]||null,!0)}speakCurrent(){if(this.currentState.kind!=="playing")return;let r=this.generation,i=this.currentState.unit.segments[this.currentState.segmentIndex];if(!i){this.finishUnit(this.currentState.unit);return}this.callbacks.onSegmentChange(i,!1),this.engine.speak(i,{onEnd:()=>{if(r!==this.generation||this.currentState.kind!=="playing")return;let s=this.currentState.segmentIndex+1;s<this.currentState.unit.segments.length?(this.setState({kind:"playing",unit:this.currentState.unit,segmentIndex:s}),this.speakCurrent()):this.finishUnit(this.currentState.unit)},onError:s=>{r===this.generation&&(this.setState({kind:"error",message:s}),this.callbacks.onSegmentChange(null,!1))}})}finishUnit(r){if(this.continuous){let i=this.callbacks.navigateUnit(r,1);if(i){if(this.generation+=1,i.segments.length===0){this.finishUnit(i);return}this.setState({kind:"playing",unit:i,segmentIndex:0}),this.speakCurrent();return}}this.setState({kind:"completed"}),this.callbacks.onSegmentChange(null,!1)}resetEngine(){this.generation+=1,this.engine.cancel()}setState(r){this.currentState=r,this.callbacks.onStateChange(r)}};function Ur(e,r,i="all",s=300){let a=r.trim().toLocaleLowerCase();if(!a||s<=0)return[];let c=[];if(i!=="code"){let f=new Map;e.chapters.forEach(p=>p.sceneIds.forEach(g=>f.set(g,p.title))),e.scenes.forEach((p,g)=>{let w=[f.get(p.id),p.title,p.summary,...p.bullets,...p.tags,p.takeaway],m=_r(w,a);m&&c.push({kind:"narrative",sceneIndex:g,label:p.title,preview:m}),Xi(p)&&p.steps.forEach((t,b)=>{let I=_r([t.title,t.body,"connection"in t?t.connection?.label:void 0],a);I&&c.push({kind:"narrative",sceneIndex:g,stepIndex:b,label:`${p.title} \xB7 ${t.title}`,preview:I})})})}if(i!=="narrative"&&c.length<s)for(let f=0;f<e.files.length;f+=1){let p=e.files[f];if(p.kind==="text-diff"){for(let[g,w]of[[0,p.leftContent],[1,p.rightContent]])for(let m of Vi(w,a))if(c.push({kind:"code",fileIndex:f,sideIndex:g,label:`${p.path} \xB7 ${g===0?"base":"head"}`,...m}),c.length>=s)return c}}return c.slice(0,s)}function _r(e,r){return e.find(i=>i?.toLocaleLowerCase().includes(r))}function Vi(e,r){let i=[];return e.replace(/\r\n/g,`
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((s,a)=>{let c=s.toLocaleLowerCase(),f=0;for(;f<=c.length-r.length;){let p=c.indexOf(r,f);if(p<0)break;i.push({lineNumber:a+1,startColumn:p+1,endColumn:p+r.length+1,preview:s}),f=p+Math.max(r.length,1)}}),i}function Xi(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function Sn(e,r){return Ji(e,0,r)}function Ji(e,r,i){let s=e?.blocks[r],a=i==="left"?e?.leftLines:e?.rightLines;if(!s||!a?.length)return;let c=i==="left"?s.leftStart:s.rightStart,f=i==="left"?s.leftEnd:s.rightEnd,p=a.slice(c,f),g=p[0]?.lineNumber??a[Math.min(c,a.length-1)]?.lineNumber;if(Number.isInteger(g))return{startLine:g,endLine:p.at(-1)?.lineNumber??g}}function Hr(e,r,i,s){let a=[];return e.scenes.forEach((c,f)=>{c.kind==="walkthrough"&&c.steps.forEach((p,g)=>{p.diff.path===r&&a.push({side:p.focus.revision==="base"?"left":"right",startLine:p.focus.startLine,endLine:p.focus.endLine,label:`${c.title} \xB7 ${p.title}: ${p.body}`,active:f===i&&g===s,jumpTarget:{sceneIndex:f,stepIndex:g}})})}),a}function zr(e,r,i,s,a){let c=[];return e.scenes.forEach((f,p)=>{p!==i||f.kind!=="stacked-diff"&&f.kind!=="deconstructed-diff"||f.steps.forEach((g,w)=>{if(g.file!==r)return;let m=g.startLine===void 0?a?.(g.pairIndex,g.side):{startLine:g.startLine,endLine:g.endLine??g.startLine};if(!m)return;let t=g.pairIndex+(g.side==="right"?1:0);c.push({pairIndex:g.pairIndex,panelIndex:t,side:g.side,startLine:m.startLine,endLine:m.endLine,label:`${f.title} \xB7 ${g.title}: ${g.body}`,active:p===i&&w===s,jumpTarget:{sceneIndex:p,stepIndex:w}})})}),c}function Yi(e,r=120){return e.length<=r?e:`${e.slice(0,r-1)}\u2026`}function qr(e,r="Bygone"){let i=e?.windowTitle?.trim()||e?.title?.trim();return i?Yi(i):`${r} Tour`}function Wr(e,r){let i="overview"in r?r.overview:void 0,s=(i?.path||"").split("/").filter(t=>t&&t!==".").join("/"),a=t=>!s||t.startsWith(`${s}/`),c=[e.range.baseRef,e.range.headRef],f,p=[];if(r.kind==="stacked-diff"||r.kind==="deconstructed-diff"){let t=r.kind==="stacked-diff"?r.stack:r.panels,b=i?.comparison?t.findIndex(N=>N.id===i.comparison?.from):0,I=i?.comparison?t.findIndex(N=>N.id===i.comparison?.to):t.length-1;if(!t[b]||!t[I]||b===I)throw new Error(`Scene ${r.id} has invalid overview comparison endpoints.`);c=[t[b].label,t[I].label],f=r.files.flatMap(N=>{if(!a(N.path))return[];let x=N.panels[b],S=N.panels[I];if(!x||!S)return[];if(x.exists===S.exists&&x.content===S.content)return[];let C=x.exists?S.exists?"modified":"deleted":"added";return[{id:`${r.id}-overview-${N.path}`,kind:"text-diff",title:N.path,path:N.path,changeKind:C,leftContent:x.content,rightContent:S.content,leftLabel:c[0],rightLabel:c[1],summary:"",bullets:[],tags:[],takeaway:"",additions:0,deletions:0}]})}else f=e.files.filter(t=>t.kind==="text-diff"&&a(t.path)),p=e.files.filter(t=>t.kind==="omitted"&&a(t.path));let g=new Map;for(let t of[...f,...p]){let b=[t.changeKind!=="added",t.changeKind!=="deleted"],I=t.path.split("/");for(let N=0;N<I.length-1;N++){let x=I.slice(0,N+1).join("/"),S=g.get(x);S?S.sides=S.sides.map((C,$)=>C||b[$]):g.set(x,{relativePath:x,displayName:I[N],depth:N,isDirectory:!0,status:"modified",sides:[...b]})}g.set(t.path,{relativePath:t.path,displayName:I[I.length-1],depth:I.length-1,isDirectory:!1,sides:b,status:b[0]?b[1]?"modified":"left-only":"right-only",gitChangeKind:t.changeKind,...t.previousPath?{previousPath:t.previousPath}:{},...t.kind==="omitted"?{relationSummary:`Unavailable: ${t.reason}`}:{}})}for(let t of g.values())t.isDirectory&&(t.status=t.sides[0]?t.sides[1]?"modified":"left-only":"right-only");let w=[...g.values()].sort((t,b)=>{let I=t.relativePath.split("/"),N=b.relativePath.split("/");for(let x=0;x<Math.min(I.length,N.length);x++){if(I[x]===N[x])continue;let S=x<I.length-1||t.isDirectory,C=x<N.length-1||b.isDirectory;return Number(C)-Number(S)||I[x].localeCompare(N[x])}return I.length-N.length}),m=s?` / ${s}/`:"";return{entries:w,files:f,labels:[c[0]+m,c[1]+m],omitted:p}}function Zi(){return{sceneIndex:0,stepIndex:0,path:null}}var _t=class{constructor(r){this.mode=r;this.cursors=new Map}depart(r){return this.cursors.set(this.mode,r),r}enter(r,i){this.mode=r;let s=this.cursors.get(r);return s?{location:s,restore:!0}:{location:i??Zi(),restore:!1}}};function jr(e,r){let i=new Map;for(let f of r)i.has(f)||i.set(f,i.size);let s=e?.commits,a=Array.isArray(s)?s:[e?.from,e?.to],c=[...new Set(a.filter(f=>typeof f=="string"&&i.has(f)))];if(c.length<2)throw new Error("Select at least two revisions to compare.");return c.sort((f,p)=>i.get(f)-i.get(p)),{commits:c,...typeof e?.path=="string"&&e.path?{path:e.path}:{}}}var Qi=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i,es="bygone-tour-skill.md";function Kr(e,r={},i={}){let s=e==="deconstructed"?"deconstructed":"historical",a=En(r.repository),c=Gr(r.paths),p=a!==void 0&&Array.isArray(r.paths)&&r.paths.length===0?["."]:c.length>0?c:null,g=Gr(r.revisions),w=ts(a,g,r.rangeStatus),m=r.rangeStatus||"unavailable",t=[ns(i),`Create a v3 ${s} tour.`,`Repository: ${JSON.stringify(a??null)}`,`Selected paths: ${JSON.stringify(p)}`,`Base: ${JSON.stringify(w?g[0]:null)}`,`Head: ${JSON.stringify(w?g[1]:null)}`,"Additional context: (optional)"];return w||t.push(`Warning: range status ${JSON.stringify(m)} is not an exact committed range; choose revisions in Compare. Do not silently substitute a merge-base, swap endpoints, or drop revisions.`,`All revisions: ${JSON.stringify(g)}`),t.join(`
151
- `)}function ts(e,r,i){return i==="exact"&&!!e&&r.length===2&&r.every(s=>Qi.test(s))}function ns(e){let r=En(e.path);if(r)return`Read and follow the Bygone tour skill at ${JSON.stringify(r)}.`;let i=En(e.name)||es;return`Read and follow the Bygone tour skill in attached ${JSON.stringify(i)}.`}function Gr(e){return Array.isArray(e)?e.filter(r=>typeof r=="string").filter(r=>r.length>0):[]}function En(e){return typeof e=="string"&&e.trim().length>0?e:void 0}var Cn=`---
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: Act as a PR Tour Guide by generating, validating, compiling, and presenting evidence-grounded Bygone code-change tours from Git ranges. Use for requests such as "Tour this commit for me," or whenever an AI coding agent should explain a pull request, branch, commit, or code change as a guided walkthrough; create or repair a .bygone file; produce an LLM-ready Bygone change context; connect narrative claims to exact source evidence; or turn a diff into a browser-presentable review or demo. Always print the exact \`bygone\` CLI command to open the resulting diff, review, tour, or history view.
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
- Use Bygone as the deterministic evidence and rendering layer. Treat the language model as the narrative planner, never as the authority on Git ranges or source locations.
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 requires the \`bygone\` CLI with \`tour context\`, \`tour schema\`, \`tour validate\`, and \`tour compile\`. Install only when the user asks or when the task cannot proceed without it.
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, stop, share the install commands above, and report that the toolchain is unavailable rather than guessing.
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
- ## Gather ticket and PR framing
288
-
289
- When available, read the ticket and PR context supplied by the user or directly
290
- linked from the change, using accessible read-only sources. Follow relevant
291
- parent-project or review links when they explain the change; keep discovery
292
- bounded to this work. Missing metadata should not block a useful code tour.
293
-
294
- Capture the facts that help a reader understand the change:
295
-
296
- - **Ticket:** identifier, title, problem and requested outcome, relevant details
297
- or acceptance criteria, creator/requester and assignee as distinct roles,
298
- creation date or relevant timeline, and its place in a parent project, epic,
299
- or larger initiative.
300
- - **PR:** number, title, URL, author, relevant creation/merge dates, associated
301
- ticket, and actual review history: who reviewed, when, their recorded outcome,
302
- and consequential feedback or resulting changes.
303
-
304
- Be explicit about whose ticket it was, who authored the PR, and who reviewed
305
- it when the sources establish those roles. Credit implementation contributors
306
- when known; PR authorship alone does not establish sole implementation credit.
307
- A requested reviewer is not an actual reviewer; a comment is not an approval. Do not assume an earlier review
308
- covers the current head or an entire multi-PR range. For stacked work, keep
309
- ticket, author, timing, and review provenance attached to the correct PR.
310
-
311
- Link the supporting ticket, PR, and review sources in the tour's narrative.
312
- Distinguish the ticket's requested outcome and the author's stated intent from
313
- behavior established by code and tests. Do not invent ownership, dates, project
314
- relationships, ticket associations, review status, or approval. Briefly disclose
315
- material gaps or conflicting context where they affect the explanation; omit
316
- irrelevant unavailable fields rather than filling the tour with placeholders.
317
-
318
- ## Plan the explanation
319
-
320
- Begin with an opening slide that summarizes the high-level context before the
321
- implementation: the problem, its place in the larger project, the ticket and
322
- PR relationship, and what this change contributes. Include relevant people,
323
- timing, and review status concisely; put detailed provenance beside the later
324
- claims it explains. If separate authored modes have independent entry points,
325
- give each enough opening context to stand on its own.
326
-
327
- Use the first scene's summary/bullets or equivalent supported narrative fields
328
- for this opening; do not invent a slide kind or metadata keys. Keep source
329
- anchors for code claims and source links for external context distinct.
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
- Scale the structure proportionally:
343
-
344
- - A small commit may need one chapter and one scene.
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
- These are pacing heuristics, not quotas. Preserve asymmetry when one capability deserves substantially more explanation than another.
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
- Use these narrative constraints:
365
+ ## Plan the explanation
352
366
 
353
- - State one reviewer question or thesis per scene.
354
- - Give every chapter a coherent multi-scene arc when the material supports one; allow a single-scene chapter only when that scene is independently substantial.
355
- - Decompose scenes by conceptual need, not a fixed template; do not force every scene to use the same step count.
356
- - Prefer three to seven steps per scene.
357
- - Explain why focused code matters instead of paraphrasing syntax.
358
- - Keep summaries, bullets, annotations, and takeaways distinct; bullets that merely restate the summary are a defect.
359
- - Avoid intent, safety, performance, or runtime claims unsupported by the evidence.
360
- - Do not imply that the authored tour exhaustively reviews every changed file.
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 3 \`.bygone\` file for new tours. The legacy \`.bygone.yaml\`
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 2 remain readable for legacy
376
- inputs; v3 is the format for independent authored modes, directory overviews,
377
- and review notes.
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, v3 derives it from the root chapters by scene identity
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 v3 \`deconstructed-diff\` scene, provide both an explicit real
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
- Version 3 scenes may include a directory Overview:
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
- Use the optional v3 top-level \`review\` block for evidence-linked concepts,
459
- boundaries, tradeoffs, and unresolved questions instead of presenting open
460
- questions as settled scene narration. Pin \`review.baseOid\` and \`review.headOid\`
461
- to the resolved range. \`concept\`, \`boundary\`, and \`tradeoff\` items need at
462
- least one link to a root authored walkthrough scene and step; a \`question\` may
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 validation pass. If evidence no longer exists, revise the claim or report the broken premise.
484
-
485
- After structural validation, check that:
486
-
487
- Treat this as a required self-audit, not a claim the validator can prove. For each item, cite concrete evidence you actually opened or mark it not applicable; the hand-off must distinguish verified findings from interpretation.
488
-
489
- - the opening slide establishes the problem, project context, and available
490
- ticket/PR provenance before the first implementation step;
491
- - ticket ownership, dates, and actual review claims are traceable to opened
492
- sources and scoped to the PR/revision they describe;
493
- - chapter boundaries follow conceptual transitions rather than a fixed count or one-scene-per-chapter pattern;
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
- Report:
551
-
552
- - the exact base and head OIDs;
553
- - the **open command** for the primary artifact (\`bygone present --tour \u2026\`, \`bygone review \u2026\`, \`bygone --git-diff \u2026\`, etc.);
554
- - the source and compiled artifact paths;
555
- - authored root and Historical/Deconstructed chapter, scene, step, and stage
556
- counts, plus compiled counts when generated complete-change or per-mode
557
- scenes change them;
558
- - omitted or unread evidence;
559
- - ticket/PR context sources used and material unavailable or conflicting context;
560
- - validation and visual verification performed;
561
- - whether generated files are temporary, uncommitted, committed, or pushed.
562
-
563
- Distinguish syntactic grounding from interpretive correctness: Bygone proves that cited evidence exists at the pinned revision, not that the narrative's interpretation is unquestionably correct.
564
- `;var Ut=["history","compare","historical","deconstructed"],Tn={history:"History",compare:"Compare",historical:"Historical tour",deconstructed:"Deconstructed tour"},Vr={historical:"No Historical tour is available. Copy a prompt for your coding agent and read or customize its Markdown instructions.",deconstructed:"No Deconstructed tour is available. Copy a prompt for your coding agent and read or customize its Markdown instructions."},os=new Set(["exact","none","multiple","uncommitted","reversed","divergent","unavailable"]),is=0;function Zr({container:e,send:r}={}){if(!e||typeof e.appendChild!="function")throw new TypeError("createWorkspaceControls requires a DOM container.");let i=e.ownerDocument||globalThis.document;if(!i||typeof i.createElement!="function")throw new TypeError("createWorkspaceControls requires a browser document.");let s=typeof r=="function"?r:()=>{},a=++is,c=i.createElement("section");c.className="workspace-controls",c.setAttribute("data-workspace-controls","true");let f=i.createElement("nav");f.className="workspace-mode-strip",f.setAttribute("aria-label","Workspace modes"),c.appendChild(f);let p=i.createElement("div");p.className="workspace-mode-descriptions",p.setAttribute("aria-hidden","true"),c.appendChild(p);let g=new Map,w=new Map;for(let E of Ut){let A=i.createElement("button");A.type="button",A.className="workspace-mode-button",A.setAttribute("data-workspace-mode",E),A.textContent=Tn[E];let B=i.createElement("span");B.className="workspace-mode-description visually-hidden";let Q=`bygone-workspace-${a}-${E}-description`;B.id=Q,p.appendChild(B),A.setAttribute("aria-describedby",Q),g.set(E,A),w.set(E,B),f.appendChild(A)}let m=i.createElement("button");m.type="button",m.className="workspace-back-button",m.textContent="Back to comparison",m.title="Return to the comparison that opened this workspace",m.setAttribute("aria-label","Back to comparison"),m.setAttribute("data-workspace-back","true"),c.appendChild(m);let t=i.createElement("div");t.className="workspace-status",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),c.appendChild(t);let b=ss(i,a);c.appendChild(b.dialog),e.appendChild(c);let I=Xr(),N=!1,x=null,S=null,C=!1,$="",P=new Map,O=new Map;for(let[E,A]of g)A.addEventListener("click",()=>{if(N||A.disabled)return;let B=Jr(E,I);if((E==="historical"||E==="deconstructed")&&!B){ye(E,A);return}s({type:"workspaceMode",mode:E})});return m.addEventListener("click",()=>{!N&&!m.disabled&&s({type:"workspaceBack"})}),b.textarea.addEventListener("input",()=>{if(!x)return;let E=Le(x);E.text=b.textarea.value,E.edited=!0}),b.copyButton.addEventListener("click",()=>{if(!x)return;let E=we(x);Ht(E.text)}),b.resetButton.addEventListener("click",()=>{if(!x)return;let E=Le(x,{reset:!0});b.textarea.value=E.text,se(),b.textarea.focus()}),b.saveSkillButton.addEventListener("click",()=>{if(I.nativeSkillFiles){s({type:"workspaceSkillSave"});return}let E=Re(),A=URL.createObjectURL(new Blob([E.text],{type:"text/markdown;charset=utf-8"})),B=i.createElement("a");B.href=A,B.download=E.name||"bygone-tour-skill.md",B.click(),setTimeout(()=>URL.revokeObjectURL(A),1e3),J("Markdown downloaded. Edit your copy, then choose Use my copy. Attach it alongside the prompt when your agent cannot read local files.")}),b.chooseSkillButton.addEventListener("click",()=>{I.nativeSkillFiles?s({type:"workspaceSkillChoose"}):b.skillFile.click()}),b.skillFile.addEventListener("change",async()=>{let E=b.skillFile.files?.[0],A=I.sessionId;if(b.skillFile.value="",!!E)try{if(!E.name.toLowerCase().endsWith(".md")||E.size>1024*1024)throw new Error("Choose a Markdown file smaller than 1 MiB.");let B=await E.text();if(!B.trim())throw new Error("The instructions file is empty.");if(O.set(A,{name:E.name,text:B}),N||I.sessionId!==A)return;se(),J("Custom instructions selected. Attach this Markdown file with the prompt.")}catch(B){!N&&I.sessionId===A&&J(`Could not load instructions: ${B.message}`)}}),b.openExistingButton.addEventListener("click",()=>{if(!x)return;we(x);let E=x;X(),s({type:"workspaceOpenTour",kind:E})}),b.chooseCompareButton.addEventListener("click",()=>{x&&(we(x),X(),s({type:"workspaceMode",mode:"compare"}))}),b.closeButton.addEventListener("click",()=>X()),b.dialog.addEventListener("cancel",E=>{E.preventDefault(),X()}),b.dialog.addEventListener("close",()=>{x=null,$="",C||ne()}),z(),{update:z,destroy:R};function z(E){if(N)return;let A=Xr(E);A.sessionId!==I.sessionId&&Ee()&&X(),zt(A),x&&A.status!==I.status&&($=A.status),I=A,W(),fe(),x&&se()}function R(){N||(N=!0,X(),typeof c.remove=="function"?c.remove():c.parentNode?.removeChild(c),g.clear(),w.clear(),P.clear(),O.clear())}function W(){for(let E of Ut){let A=g.get(E),B=w.get(E),Q=Jr(E,I),Oe=Q&&I.mode===E,Xe=(E==="historical"||E==="deconstructed")&&!Q,Je=E==="history"&&I.history.enabled===!1,he=E==="compare"&&I.compare.enabled===!1,Me=E==="history"?I.history.label:E==="compare"?I.compare.label:I.modeLabels[E]||Tn[E],Ye=Xe?`${Vr[E]} Opens a prompt dialog without changing the current mode.`:Je?I.history.reason||"History is unavailable for this workspace.":he?I.compare.reason||"Compare is unavailable for this workspace.":Oe?`${Me} is the current workspace mode.`:`Switch to ${Me}.`;A.textContent=Me,A.title=Ye,A.setAttribute("aria-label",Me),A.setAttribute("aria-description",Ye),B.textContent=Ye,A.classList.toggle("is-active",Oe),A.classList.toggle("is-missing",Xe),A.classList.toggle("is-unavailable",Je||he),A.disabled=Je||he,Xe?A.removeAttribute("aria-pressed"):A.setAttribute("aria-pressed",String(Oe))}m.hidden=I.canReturn!==!0,m.disabled=I.canReturn!==!0}function fe(){t.textContent=I.status||"",t.hidden=!I.status}function ye(E,A){if(!(N||E!=="historical"&&E!=="deconstructed")){if(x=E,S=A,$=I.status||"",se(),typeof b.dialog.showModal=="function")try{b.dialog.showModal()}catch{b.dialog.setAttribute("open","")}else b.dialog.setAttribute("open","");b.textarea.focus()}}function X(){if(!Ee()){x=null,ne();return}C=!0;try{typeof b.dialog.close=="function"?b.dialog.close():b.dialog.removeAttribute("open"),x=null,$=""}finally{C=!1,ne()}}function ne(){let E=S;if(S=null,!(!E||typeof E.focus!="function")&&E.isConnected!==!1)try{E.focus()}catch{}}function Ee(){return b.dialog.open===!0||b.dialog.hasAttribute("open")}function se(){if(!x)return;let E=Le(x),A=Re();b.title.textContent=`${Tn[x]} prompt`,b.description.textContent=Vr[x],b.context.textContent=`Current context: ${Yr(I.promptContext)}`,E.skillKey!==Pe()?(b.draftNotice.hidden=!1,b.draftNotice.textContent="The selected instructions changed. Your edited prompt was preserved; use Reset prompt to reference the selected file, or update its reference yourself."):E.contextKey!==$n(I.promptContext)?(b.draftNotice.hidden=!1,b.draftNotice.textContent=`This draft is based on earlier workspace context: ${E.contextSummary}. Review the repository, revision boundaries, and selected paths before copying.`):(b.draftNotice.hidden=!0,b.draftNotice.textContent=""),b.textarea.value=E.text,b.skillText.value=A.text,b.skillReference.textContent=A.path?`Instructions: ${A.path}. Local agents can read this path; for browser chats, save and attach a copy.`:`Instructions: ${A.name||"bygone-tour-skill.md"} (attachment). Download and attach it with the prompt; browsers do not expose its full local path.`,b.status.textContent=$,b.status.hidden=!$}function Ht(E){let A=i.defaultView?.navigator?.clipboard||globalThis.navigator?.clipboard;if(!A||typeof A.writeText!="function"){J("Could not copy the prompt: clipboard access is unavailable.");return}Promise.resolve().then(()=>A.writeText(E)).then(()=>J("Prompt copied to the clipboard.")).catch(B=>{let Q=B instanceof Error&&B.message?` ${B.message}`:"";J(`Could not copy the prompt.${Q}`)})}function J(E){$=E,b.status.textContent=E,b.status.hidden=!E}function we(E){let A=Le(E);return A.text=b.textarea.value,A.edited=!0,A}function Le(E,{reset:A=!1}={}){let B=P.get(I.sessionId)||new Map;P.set(I.sessionId,B);let Q=B.get(E);return(A||!Q||!Q.edited&&Q.skillKey!==Pe())&&B.set(E,{text:Kr(E,I.promptContext,Re()),skillKey:Pe(),contextKey:$n(I.promptContext),contextSummary:Yr(I.promptContext),edited:!1}),B.get(E)}function Re(){return I.tourSkill||O.get(I.sessionId)||{name:"bygone-tour-skill.md",text:Cn}}function Pe(){let E=Re();return JSON.stringify([E.path||"",E.name||"",E.text])}function zt(E){let A=P.get(E.sessionId);if(A)for(let B of A.values())B.contextChanged=B.contextKey!==$n(E.promptContext)}}function ss(e,r){let i=e.createElement("dialog");i.className="workspace-prompt-dialog",i.setAttribute("aria-modal","true");let s=e.createElement("h2");s.id=`bygone-workspace-${r}-prompt-title`,i.setAttribute("aria-labelledby",s.id),i.appendChild(s);let a=e.createElement("p");a.className="workspace-prompt-description",a.id=`bygone-workspace-${r}-prompt-description`,i.setAttribute("aria-describedby",a.id),i.appendChild(a);let c=e.createElement("p");c.className="workspace-prompt-context",i.appendChild(c);let f=e.createElement("p");f.className="workspace-prompt-draft-notice",f.setAttribute("role","status"),f.hidden=!0,i.appendChild(f);let p=e.createElement("label");p.className="workspace-prompt-label";let g=e.createElement("textarea");g.id=`bygone-workspace-${r}-prompt-textarea`,g.rows=9,g.spellcheck=!1,g.setAttribute("aria-label","Tour authoring prompt draft"),p.textContent="Prompt draft",p.appendChild(g),i.appendChild(p);let w=e.createElement("p");w.className="workspace-prompt-context",i.appendChild(w);let m=e.createElement("details"),t=e.createElement("summary");t.textContent="Read instructions (Markdown)";let b=e.createElement("textarea");b.readOnly=!0,b.rows=12,b.setAttribute("aria-label","Tour skill Markdown instructions"),m.append(t,b),i.appendChild(m);let I=e.createElement("div");I.className="workspace-prompt-actions";let N=Ae(e,"Save an editable copy","workspace-skill-save"),x=Ae(e,"Use my copy","workspace-skill-choose"),S=e.createElement("input");S.type="file",S.accept=".md,text/markdown",S.hidden=!0,I.append(N,x,S),i.appendChild(I);let C=e.createElement("p");C.className="workspace-prompt-status",C.setAttribute("role","status"),C.setAttribute("aria-live","polite"),C.setAttribute("aria-atomic","true"),C.hidden=!0,i.appendChild(C);let $=e.createElement("div");$.className="workspace-prompt-actions";let P=Ae(e,"Copy prompt","workspace-prompt-copy"),O=Ae(e,"Reset prompt","workspace-prompt-reset"),z=Ae(e,"Open existing tour","workspace-prompt-open"),R=Ae(e,"Choose revisions in Compare","workspace-prompt-compare"),W=Ae(e,"Close","workspace-prompt-close");return $.append(P,O,z,R,W),i.appendChild($),{dialog:i,title:s,description:a,context:c,draftNotice:f,textarea:g,skillText:b,skillReference:w,saveSkillButton:N,chooseSkillButton:x,skillFile:S,status:C,copyButton:P,resetButton:O,openExistingButton:z,chooseCompareButton:R,closeButton:W}}function Ae(e,r,i){let s=e.createElement("button");return s.type="button",s.textContent=r,s.title=r,s.setAttribute("data-workspace-prompt-action",i),s}function Xr(e={}){let r=Ut.includes(e?.mode)?e.mode:"compare",i=e?.history&&typeof e.history=="object"?{enabled:e.history.enabled!==!1,label:ht(e.history.label,"History"),reason:ht(e.history.reason,"")}:{enabled:!0,label:"History",reason:""},s=e?.compare&&typeof e.compare=="object"?{enabled:e.compare.enabled!==!1,label:ht(e.compare.label,"Compare"),reason:ht(e.compare.reason,"")}:{enabled:!0,label:"Compare",reason:""},a=Array.isArray(e?.availableTours)?e.availableTours.filter(c=>c==="historical"||c==="deconstructed"):null;return{sessionId:cs(e?.sessionId),mode:r,modeLabels:e?.modeLabels&&typeof e.modeLabels=="object"?Object.fromEntries(Ut.filter(c=>typeof e.modeLabels[c]=="string").map(c=>[c,e.modeLabels[c]])):{},history:i,compare:s,availableTours:a,nativeSkillFiles:e?.nativeSkillFiles===!0,tourSkill:e?.tourSkill&&typeof e.tourSkill.path=="string"?{path:e.tourSkill.path,text:typeof e.tourSkill.text=="string"?e.tourSkill.text:Cn}:null,promptContext:as(e?.promptContext),canReturn:e?.canReturn===!0,status:ht(e?.status,"")}}function as(e){let r=e&&typeof e=="object"?e:{};return{...typeof r.repository=="string"?{repository:r.repository}:{},...Array.isArray(r.paths)?{paths:r.paths.filter(i=>typeof i=="string")}:{},...Array.isArray(r.revisions)?{revisions:r.revisions.filter(i=>typeof i=="string")}:{},...os.has(r.rangeStatus)?{rangeStatus:r.rangeStatus}:{},...typeof r.reason=="string"?{reason:r.reason}:{}}}function Jr(e,r){return e==="history"?r.history.enabled!==!1:e==="compare"?r.compare.enabled!==!1:r.availableTours?r.availableTours.includes(e):r.mode===e}function $n(e){return JSON.stringify({repository:e.repository||"",paths:Array.isArray(e.paths)?e.paths:[],revisions:Array.isArray(e.revisions)?e.revisions:[],rangeStatus:e.rangeStatus||"",reason:e.reason||""})}function Yr(e){let r=e.repository||"(not resolved)",i=Array.isArray(e.paths)&&e.paths.length>0?e.paths.join(", "):e.repository&&Array.isArray(e.paths)?". (repository root; full requested scope)":"(scope not supplied)",s=Array.isArray(e.revisions)&&e.revisions.length>0?e.revisions.join(", "):"(none reported)";return`repository ${r}; paths ${i}; revisions ${s}; range ${e.rangeStatus||"unavailable"}`}function cs(e){return typeof e=="string"||typeof e=="number"?String(e):"default"}function ht(e,r){return typeof e=="string"?e:r}function An(e,r,i=[]){let s=[],a=/\[([^\]\n]+)\]\((https?:\/\/(?:[^\s()]|\([^\s()]*\))+)\)/gu,c=0;for(let f of r.matchAll(a)){if(f.index>0&&r[f.index-1]==="!")continue;let p;try{p=new URL(f[2])}catch{continue}if(p.protocol!=="https:"&&p.protocol!=="http:")continue;s.push(...Nn(e,r,c,f.index,i));let g=e.createElement("a");g.href=p.href,g.target="_blank",g.rel="noopener noreferrer";let w=f.index+1;g.replaceChildren(...Nn(e,r,w,w+f[1].length,i)),s.push(g),c=f.index+f[0].length}return s.push(...Nn(e,r,c,r.length,i)),s}function Nn(e,r,i,s,a){let c=[],f=i;for(let p of a){let g=Math.max(i,p.startOffset),w=Math.min(s,p.endOffset);if(g>=w)continue;g>f&&c.push(e.createTextNode(r.slice(f,g)));let m=e.createElement("span");m.className="tour-narration-segment",m.dataset.narrationSegmentId=p.id,m.textContent=r.slice(g,w),c.push(m),f=w}return f<s&&c.push(e.createTextNode(r.slice(f,s))),c}(function(){let r="bygone.tourSidebarWidth",a="bygone.tourNarrativeHeight",p="bygone.tourNarrationVoice",g="bygone.tourNarrationRate",w=new Set([.75,1,1.25,1.5]),m="speechSynthesis"in window&&"SpeechSynthesisUtterance"in window,t={mode:"empty",left:null,right:null,comparisonId:0,tour:null,authoredTour:null,zoom:null,zoomSwitching:!1,historyCommit:null,historyEntries:[],fileHistoryCache:new Map,displayedPanels:[],historyPath:null,historyPanels:[],historyFocus:null,historyDiff:null,compare:null,comparisonFocus:null,comparisonCommits:[],comparisonDraftCommits:[],activeSceneIndex:-1,activeStepIndex:0,sceneIntroVisible:!1,narrativeParent:null,readingKey:"title",directoryEvidence:null,activeTourFilePath:null,tourFocusFilePath:null,tourSidebarWidth:So(),tourSidebarHidden:!1,tourNarrativeHeight:Co(),tourNavigatorTab:"tour",narrationVoiceURI:window.localStorage.getItem(p)||"",narrationRate:po(),narrationVoices:[],renderedNarrationUnit:null,workspacePromptStatus:"",historyPrefix:"/history/"},b=null,I=null,N=null,x=[],S=new Map,C=new Set,$=null,P=null,O=new URLSearchParams(window.location.search).get("workspaceEmbedded")==="1",z=null,R=new Bt(mo(),{claimAudio:vo,onStateChange:Kt,onSegmentChange:xo,canNavigateUnit:wo,navigateUnit:bo});window.__BYGONE_HOST__={environment:"web",editorWorkerUrl:"/media/editor.worker.js",diffWorkerUrl:"/media/diff.worker.js",postMessage(n){uo(n)}},window.addEventListener("message",n=>{if(!O||n.source!==window.parent||n.origin!=="null")return;let o=n.data;!o||typeof o!="object"||o.type!=="bygoneWorkspaceTourMode"||o.mode!=="historical"&&o.mode!=="deconstructed"||(z=o.mode,!(!t.zoom||t.zoom.mode===o.mode||!A().includes(o.mode))&&xe(o.mode).catch(te))}),window.addEventListener("DOMContentLoaded",()=>{if(fo(),O){let n=document.getElementById("tour-mode-tabs"),o=document.getElementById("tour-mode-description");n&&(n.hidden=!0),o&&(o.hidden=!0)}me("Browser host ready.")});function W(n){(n.type==="showDiff"||n.type==="showMultiDiff"||n.type==="showDirectoryDiff")&&(n={...n,renderRequestId:++ne},t.mode==="tour"&&(t.displayedPanels=n.type==="showMultiDiff"?n.panels:io(),n.history||(n.history=Pn()),he()),X&&(Ee=n.renderRequestId)),window.dispatchEvent(new window.CustomEvent("bygone:host-message",{detail:n}))}let fe=0,ye=new Map,X=null,ne=0,Ee=null;function se(){t.zoomSwitching||(X=null)}function Ht(){return new Promise(n=>{let o=++fe,d=u=>{ye.delete(o);let h=t.tour?.scenes[t.activeSceneIndex],y=u?.activeMultiPairIndex,v=h&&ae(h)?ot(h):[],k=u?.editorStates?.[u.activeMultiPanelId||u.activePaneSide];n({sceneIndex:t.activeSceneIndex,stepIndex:t.activeStepIndex,path:t.activeTourFilePath,line:k?.selection?.startLineNumber,commit:(t.zoom?.mode==="history"?t.historyCommit:v[y+1]?.oid)||t.authoredTour.range.headOid,navigation:u,focusId:document.activeElement?.id,narrativeParent:t.narrativeParent,sceneIntroVisible:t.sceneIntroVisible,narrativeScroll:document.getElementById("tour-narrative-content")?.scrollTop||0,readingKey:t.readingKey,navigatorTab:t.tourNavigatorTab})},l=window.setTimeout(()=>d(null),1e3);ye.set(o,u=>{window.clearTimeout(l),d(u)}),W({type:"captureNavigationState",requestId:o})})}let J=0;function we(n=t.authoredTour){if(n.tours||!n.scenes.some(d=>d.kind==="deconstructed-diff"))return null;let o=n.zoom?.final;return o?.scenes.some(d=>d.kind==="walkthrough")?o:null}let Le={history:"History",compare:"Compare",historical:"Historical tour",deconstructed:"Deconstructed tour"},Re={history:"Explore commits and choose revisions to compare.",compare:"Inspect the changes between selected revisions.",historical:"Actual revisions, with explanations of updates, reversals, and decisions.",deconstructed:"The change broken into constructed stages for explanation."};function Pe(n){return n==="historical"&&we()?"Final tour":Le[n]}function zt(n){return n==="historical"&&we()?"The authored walkthrough of the completed endpoint diff.":Re[n]}function E(n=t.authoredTour){if(n.tours)return n.tours;if(!n.scenes.some(l=>l.kind==="deconstructed-diff"))return{historical:{scenes:n.scenes,chapters:n.chapters}};let d=we(n);return{...d?{historical:d}:{},deconstructed:{scenes:n.scenes,chapters:n.chapters}}}function A(){return[...B()?["history","compare"]:[],...Object.keys(E()).filter(n=>E()[n])]}function B(n=t.authoredTour){return Number(n?.version)>=2}function Q(){return"History is unavailable for legacy v1 tours; open a version 2 tour to browse commit history."}function Oe(){return"Compare is unavailable for legacy v1 tours because this tour has no history backend."}function Xe(){if(b)return;let n=document.getElementById("tour-mode-controls");if(!n)return;let o=document.getElementById("tour-mode-tabs"),d=document.getElementById("tour-mode-description"),l=document.getElementById("tour-mode-status");o&&(o.hidden=!0),d&&(d.hidden=!0),l&&(l.hidden=!0),I=document.createElement("div"),I.id="workspace-mode-controls",n.prepend(I),b=Zr({container:I,send:Je})}function Je(n){if(!(!n||typeof n!="object")){if(n.type==="workspaceMode"&&["history","compare","historical","deconstructed"].includes(n.mode)){xe(n.mode).catch(te);return}n.type==="workspaceOpenTour"&&(n.kind==="historical"||n.kind==="deconstructed")&&oo()}}function he(){if(!t.zoom||(Xe(),!b))return;I.hidden=O;let n=document.getElementById("tour-mode-tabs"),o=document.getElementById("tour-mode-description");n&&(n.dataset.workspaceModeLabel=Pe(t.zoom.mode)),o&&(o.textContent=zt(t.zoom.mode));let d=B();b.update({sessionId:Me(),mode:t.zoom.mode,modeLabels:{historical:Pe("historical")},history:{enabled:d,label:"History",...d?{}:{reason:Q()}},compare:{enabled:d,label:"Compare",...d?{}:{reason:Oe()}},availableTours:Object.keys(E()).filter(l=>l==="historical"||l==="deconstructed"),promptContext:Ye(),status:t.workspacePromptStatus})}function Me(){let n=t.authoredTour;return[n?.repository?.root||"",n?.range?.mergeBaseOid||"",n?.range?.headOid||""].join("\0")||"browser-workspace"}function Ye(){let n=t.authoredTour,o=n?.range,d=Array.isArray(t.displayedPanels)?t.displayedPanels:[],l=pt(d.map(k=>k?.commit)),u=d.length>0?l:pt([o?.mergeBaseOid,o?.headOid]),h=pt(d.map(k=>k?.path)),y=h.length>0?h:pt(t.tour?.files?.map(k=>k?.path)),v=Qr(u,n);return{...typeof n?.repository?.root=="string"?{repository:n.repository.root}:{},...y.length>0?{paths:y}:{},...u.length>0?{revisions:u}:{},rangeStatus:v.status,...v.reason?{reason:v.reason}:{}}}function Qr(n,o){if(n.length===0)return{status:"none",reason:"The browser view has no selected committed revisions."};if(n.length>2)return{status:"multiple",reason:"The displayed comparison contains more than two revision panels."};if(n.length!==2)return{status:"unavailable",reason:"The browser view could not resolve both comparison boundaries."};if(n.some(u=>/^(WORKTREE|INDEX)$/i.test(u)))return{status:"uncommitted",reason:"The browser comparison includes a live working or staged state."};if(!n.every(u=>/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(u)))return{status:"unavailable",reason:"The browser comparison does not expose two full revision identifiers."};let d=o?.range?.mergeBaseOid,l=o?.range?.headOid;return n[0]===d&&n[1]===l?{status:"exact",reason:"The manifest validates its merge-base/head range."}:n[0]===l&&n[1]===d?{status:"reversed",reason:"The selected revisions reverse the manifest merge-base/head range."}:{status:"unavailable",reason:"The browser manifest validates only its merge-base/head pair; this displayed pair needs deliberate Compare selection or backend Git validation."}}function pt(n){return[...new Set(n.filter(o=>typeof o=="string"&&o.trim()).map(o=>o.trim()))]}function De(n){t.workspacePromptStatus=n,he()}function eo(n){try{let o=new URL(n,window.location.href).pathname,d="/tour.json";if(o.endsWith(d))return`${o.slice(0,-d.length)||""}/history/`}catch{}return"/history/"}function to(){return new Promise(n=>{let o=document.createElement("input");o.type="file",o.accept=".bygone,.yaml,.yml,application/yaml,text/yaml",o.hidden=!0,document.body.appendChild(o);let d=l=>{o.remove(),n(l||null)};o.addEventListener("change",()=>d(o.files?.[0])),o.addEventListener("cancel",()=>d(null)),o.click()})}function no(n){let o=t.authoredTour;if(!o)return!1;let d=o.repository?.root,l=o.range?.mergeBaseOid,u=o.range?.headOid,h=typeof n.repository=="string"?n.repository:"",y=typeof n.range?.mergeBaseOid=="string"?n.range.mergeBaseOid:"",v=typeof n.range?.headOid=="string"?n.range.headOid:"";return!!(d&&h&&d!==h||l&&y&&l!==y||u&&v&&u!==v)}function ro(n){let o=typeof n.repository=="string"&&n.repository?n.repository:"(server-selected repository)",d=typeof n.range?.mergeBaseOid=="string"&&n.range.mergeBaseOid?n.range.mergeBaseOid:"(unknown base)",l=typeof n.range?.headOid=="string"&&n.range.headOid?n.range.headOid:"(unknown head)",u=t.authoredTour?.repository?.root||"(current repository unavailable)",h=t.authoredTour?.range?.mergeBaseOid||"(unknown base)",y=t.authoredTour?.range?.headOid||"(unknown head)";return["Open this authored tour from the server?",`Repository: ${o}`,`Range: ${d} \u2192 ${l}`,`Current browser range: ${u}, ${h} \u2192 ${y}`,"This loads the server-validated tour and does not change a local repository."].join(`
565
- `)}async function oo(){try{let n=await to();if(!n)return;if(n.size>1024*1024)throw new Error("Choose an authored .bygone or .yaml file no larger than 1 MiB.");let o=typeof n.name=="string"?n.name.toLowerCase():"";if(!/\.(?:bygone|ya?ml)$/.test(o))throw new Error("Choose an authored .bygone or .yaml file.");let d=await n.text(),l=await fetch("/tour/open",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:d})}),u=await l.json().catch(()=>({}));if(!l.ok)throw new Error(u.error||`Tour upload failed (${l.status}).`);if(!u||typeof u.manifestUrl!="string"||!u.manifestUrl)throw new Error("Tour upload did not return a manifest URL.");if(no(u)&&!window.confirm(ro(u))){De("Kept the current tour.");return}if(!await zn(u.manifestUrl)){De("Could not load the uploaded tour.");return}De("")}catch(n){De(`Could not open existing tour: ${n instanceof Error?n.message:String(n)}`)}}function ee(){return!t.zoom||t.zoom.mode==="historical"||t.zoom.mode==="deconstructed"}function Ze(n){let o=t.authoredTour;return E()[n]?{...o,...E()[n]}:{...o,scenes:[],chapters:[],files:n==="compare"&&t.compare?t.compare.files:o.files}}function Fe(){let n=document.getElementById("tour-mode-controls");if(n.hidden=!t.zoom||O,!t.zoom)return;he();let o=document.getElementById("tour-mode-tabs"),d=document.getElementById("tour-mode-description");o&&(o.hidden=!0),d&&(d.hidden=!0);let l=t.zoom.mode==="history",u=B();document.getElementById("tour-history-controls").hidden=!u||t.zoom.mode==="compare",document.getElementById("tour-compare-controls").hidden=!u||t.zoom.mode!=="compare",document.body.classList.toggle("tour-derived-mode",!ee()),ee()||document.body.classList.remove("tour-discussion");for(let h of["tour-history-parent","tour-history-base"])document.getElementById(h).hidden=!l;mt()}function mt(){let n=t.comparisonDraftCommits.length,o=document.getElementById("tour-history-compare");o.textContent=`Compare selected (${n})`,o.disabled=n<2||!B();let d=document.getElementById("tour-compare-apply");d.textContent=`Update comparison (${n})`,d.disabled=n<2||!B(),document.getElementById("tour-compare-scope").textContent=t.compare?.path?`File: ${t.compare.path}`:"All changed files",document.getElementById("tour-compare-all").hidden=!t.compare?.path;for(let l of["tour-history-parent","tour-history-base"])document.getElementById(l).disabled=!B()||!t.historyCommit}function qt(){return[...new Set([...[...t.historyEntries].reverse().map(n=>n.commit),t.authoredTour.range.mergeBaseOid,...t.authoredTour.commits.map(n=>n.oid),t.authoredTour.range.headOid])]}function Ln(n){return jr(n,qt())}async function be(n,o,d=t.historyPrefix,l=t.authoredTour){if(!B(l))throw new Error(Q());let u=await fetch(`${d||"/history/"}${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),h=await u.json();if(!u.ok)throw new Error(h.error||`History request failed (${u.status}).`);return h}function te(n){let o=n instanceof Error?n.message:String(n),d=document.getElementById("tour-mode-status");d&&(d.textContent=o),b&&De(o)}function Rn(){return t.displayedPanels.map(n=>n.commit).filter(Boolean)}function io(){let n=t.tour?.scenes[t.activeSceneIndex],o=t.zoom?.mode==="compare"?t.comparisonCommits:[t.authoredTour.range.mergeBaseOid,t.authoredTour.range.headOid];if(t.directoryEvidence&&ae(n)){let d=ot(n),l=n.overview?.comparison;o=n.kind==="deconstructed-diff"?[]:[(l?d.find(u=>u.id===l.from):d[0])?.oid,(l?d.find(u=>u.id===l.to):d.at(-1))?.oid]}return["left","right"].map((d,l)=>({id:d,commit:o[l]}))}function Pn(){let n=t.displayedPanels.map(o=>o.commit);return{...yt(jt({commits:Rn()},null),n,null),navigatorOnly:!0}}async function so(n){if(!n||!t.zoom||!B())return[];if(!t.fileHistoryCache.has(n)){let o=be("list",{path:n,commit:t.authoredTour.range.headOid}).then(d=>d.entries);t.fileHistoryCache.set(n,o),o.catch(()=>t.fileHistoryCache.delete(n))}return t.fileHistoryCache.get(n)}async function ao(n,o){try{let d=await so(n);if(o!==ne)return;W({type:"updateCommitMarkers",changedCommits:d.map(l=>l.commit),path:n})}catch(d){o===ne&&te(d)}}async function Be(n,o,d=!0){let l=++J,u=t.historyEntries;if(o=o||t.historyCommit||t.authoredTour.range.headOid,!n)throw new Error("Choose a text file to explore its revisions.");let h=u.find(U=>U.commit===o);if(t.historyPath===n&&t.historyCommit===o&&t.historyPanels.length){wt();return}let y=await be("diff",{path:n,commit:o,head:t.authoredTour.range.headOid});if(l!==J||t.zoom.mode!=="history")return;if(d&&t.historyPanels.length&&t.historyCommit===o){let U=await Promise.all(t.historyPanels.map(async V=>{let D=V.commit?await be("diff",{path:n,commit:V.commit,head:t.authoredTour.range.headOid}):{rightContent:"",path:n};return{...V,content:D.rightContent,path:D.path}}));if(l!==J||t.zoom.mode!=="history")return;t.historyPanels=U,t.historyPath=n,t.historyDiff=y,wt(),ce();return}let v=u.findIndex(U=>U.commit===o),L=(v>=0?u[v+1]:null)?.commit||y.parentCommit,F=L&&L!==y.parentCommit?(await be("diff",{path:n,commit:L,head:t.authoredTour.range.headOid})).rightContent:y.leftContent;if(l!==J||t.zoom.mode!=="history")return;t.historyPath=n,t.historyCommit=o;let G=Math.max(2,t.historyPanels.length);t.historyDiff=y;let j=(U,V,D)=>({id:`history-${U||"empty"}`,commit:U,content:V,label:D,path:y.path,editable:!1});for(t.historyPanels=[j(L,F,L?.slice(0,7)||"Empty tree"),j(o,y.rightContent,h?`${h.shortCommit} ${h.summary}`:o.slice(0,7))],t.historyFocus=`history-${o}`;t.historyPanels.length<G;){let U=gt(t.historyPanels[0],"left");if(!U)break;let V=await be("diff",{path:n,commit:U.commit,head:t.authoredTour.range.headOid});if(l!==J||t.zoom.mode!=="history")return;t.historyPanels.unshift(j(U.commit,V.rightContent,`${U.shortCommit} ${U.summary}`))}wt(),document.getElementById("tour-mode-status").textContent="",mt(),ce()}function co(n,o,d){let l=n.findIndex(h=>h.commit===o),u=n[l];return{fileName:(t.historyPath||d.path).split("/").pop(),canGoBack:l>=0&&l<n.length-1,canGoForward:l>0,positionLabel:`${l+1} / ${n.length}`,leftCommitLabel:t.historyPanels[0]?.commit?.slice(0,7)||"Empty tree",leftTimestamp:"",rightCommitLabel:t.historyPanels.at(-1)?.label||(u?`${u.shortCommit} ${u.summary}`.trim():o.slice(0,7)),rightTimestamp:u?.timestamp||"",workingTreeControls:!1,rail:{activeTabId:"history",tabs:[{id:"history",label:"History"}],itemsByTab:{history:n.map((h,y)=>({label:`${h.shortCommit} ${h.summary}`.trim(),meta:h.timestamp,commit:h.commit,summary:h.summary,timestamp:h.timestamp,author:h.author,authorEmail:h.authorEmail,message:h.message,parents:h.parents,active:y===l,selected:t.comparisonDraftCommits.includes(h.commit),kind:"history-entry",index:y}))}}}}function gt(n,o){let d=qt(),l=d.indexOf(n.commit);if(l<0)return null;let u=new Set(t.historyPanels.map(v=>v.commit)),y=(o==="left"?d.slice(0,l).reverse():d.slice(l+1)).find(v=>!u.has(v)&&t.historyEntries.some(k=>k.commit===v));return t.historyEntries.find(v=>v.commit===y)}function yt(n,o,d){let l=n.rail.itemsByTab.history;for(let u of l){u.commit=t.historyEntries[u.index]?.commit;let h=t.historyEntries[u.index];u.inTour=t.authoredTour?.commits.some(y=>y.oid===u.commit),u.selectionEnabled=!!t.zoom,h?.parents?.length>1&&(u.meta+=` \xB7 Merge: ${h.parents.map(y=>y.slice(0,7)).join(", ")}`),u.panelNumber=o.indexOf(u.commit)+1||null,u.active=u.commit===d}return o.forEach((u,h)=>{u!==void 0&&(l.some(y=>y.commit===u)||l.push({label:u?`${u.slice(0,7)} \xB7 Parent/base revision`:"Empty tree",commit:u,selected:t.comparisonDraftCommits.includes(u),selectionEnabled:!!t.zoom,panelNumber:h+1,active:u===d,kind:"panel-revision",index:-h-1}))}),n}function wt(){let n=t.historyPanels.map(d=>({...d,addLeftEnabled:!!gt(d,"left"),addRightEnabled:!!gt(d,"right"),removeEnabled:t.historyPanels.length>2})),o=n.find(d=>d.id===t.historyFocus)?.commit;t.activeTourFilePath=t.historyPath,Te(),W({type:"showMultiDiff",panels:n,pairs:n.slice(0,-1).map((d,l)=>({leftIndex:l,rightIndex:l+1,diffModel:ie(d.content,n[l+1].content)})),activePanelId:t.historyFocus,mutationEnabled:!0,fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(1)},history:yt(co(t.historyEntries,t.historyCommit,t.historyDiff),n.map(d=>d.commit),o)})}async function lo(n){let o=t.historyPanels.find(d=>d.id===(n.anchorPanelId||n.panelId));if(o){if(n.type==="multiRemovePanel"){if(t.historyPanels.length<=2)return;++J,t.historyPanels=t.historyPanels.filter(d=>d!==o),t.historyFocus===o.id&&(t.historyFocus=t.historyPanels.at(-1).id)}else{let d=gt(o,n.side);if(!d)return;let l=++J,u=await be("diff",{path:t.historyPath,commit:d.commit,head:t.authoredTour.range.headOid});if(l!==J||t.zoom.mode!=="history")return;let h={id:`history-${d.commit}`,commit:d.commit,content:u.rightContent,label:`${d.shortCommit} ${d.summary}`,path:u.path,editable:!1};t.historyPanels.push(h);let y=qt();t.historyPanels.sort((v,k)=>y.indexOf(v.commit)-y.indexOf(k.commit)),t.historyFocus=h.id}wt()}}function Wt(n){let o=t.historyEntries.findIndex(l=>l.commit===t.historyCommit),d=t.historyEntries[o+n];if(d)return Be(t.historyPath,d.commit,!1)}function jt(n,o){return{fileName:(n.path||t.activeTourFilePath||"Comparison").split("/").pop(),canGoBack:!1,canGoForward:!1,positionLabel:`${n.commits.length} loaded panels`,leftCommitLabel:n.commits[0]?.slice(0,7)||"",leftTimestamp:"",rightCommitLabel:n.commits.at(-1)?.slice(0,7)||"",rightTimestamp:"",workingTreeControls:!1,rail:{activeTabId:"history",tabs:[{id:"history",label:"History"}],itemsByTab:{history:t.historyEntries.map((d,l)=>({label:`${d.shortCommit} ${d.summary}`.trim(),meta:d.timestamp,commit:d.commit,summary:d.summary,timestamp:d.timestamp,author:d.author,authorEmail:d.authorEmail,message:d.message,parents:d.parents,active:d.commit===o,selected:t.comparisonDraftCommits.includes(d.commit),panelNumber:n.commits.indexOf(d.commit)+1||null,kind:"history-entry",index:l}))}}}}function On(n,o=null){if(!n||n.kind!=="text-diff")return!1;let d=n.comparisonPanels;o=o||t.comparisonFocus,t.comparisonFocus=o;let l=d.slice(0,-1).map((u,h)=>({leftIndex:h,rightIndex:h+1,diffModel:ie(u.content,d[h+1].content)}));return t.activeTourFilePath=n.path,Te(),W({type:"showMultiDiff",panels:d,pairs:l,activePanelId:o?`compare-${o}`:null,history:yt(jt(t.compare,o),t.compare.commits,o),fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(1)},mutationEnabled:!1}),ce(),!0}async function Mn(n,o,d=null){n=Ln(n);let l=++J,u=await be("compare-many",n);if(l!==J||t.zoom.mode!=="compare")return;let h=u.files;t.comparisonCommits=n.commits,t.compare={...n,files:h},t.tour=Ze("compare"),t.activeSceneIndex=-1,t.tourFocusFilePath=null,_e(),Fe(),Ce();let y=h.find(v=>v.kind==="text-diff"&&v.path===o)||h.find(v=>v.kind==="text-diff");if(y)On(y,d);else{t.activeTourFilePath=null;let v=n.commits.map(k=>({id:`compare-${k}`,commit:k,path:"No text changes",content:"",label:k.slice(0,7),editable:!1}));W({type:"showMultiDiff",panels:v,pairs:v.slice(0,-1).map((k,L)=>({leftIndex:L,rightIndex:L+1,diffModel:ie("","")})),mutationEnabled:!1,history:yt(jt(n,null),n.commits,null)}),t.activeTourFilePath=null,X=null}document.getElementById("tour-mode-status").textContent=h.length?y?"":"Changed files cannot be displayed as text. See the file list for details.":"No changes between these revisions.",ce()}async function ve(n){if(!B()){De(Oe());return}t.zoomSwitching||(t.zoom.mode!=="compare"?await xe("compare",n):await Mn(n,t.activeTourFilePath),kt("commits"))}function Gt(){return{commits:[t.authoredTour.range.mergeBaseOid,t.authoredTour.range.headOid]}}function Dn(){return t.historyEntries.find(n=>n.commit===t.historyCommit)?.path||t.historyPath}async function xe(n,o,d){if(!t.zoom||t.zoomSwitching||n===t.zoom.mode||!A().includes(n))return;t.zoomSwitching=!0,++J;let l=t.zoom.mode,u;try{u=await Ht(),t.zoom.depart(u),R.pauseForExternalOwner();let h=t.zoom.enter(n,n==="history"?u:null);if(t.tourNavigatorTab=h.restore?h.location.navigatorTab||"commits":ee()?"tour":"commits",t.activeSceneIndex=-1,t.activeStepIndex=0,t.narrativeParent=null,t.directoryEvidence=null,t.sceneIntroVisible=!1,t.tourFocusFilePath=null,t.tour=Ze(n),_e(),Ce(),Fe(),document.getElementById("tour-mode-status").textContent="",X=h.restore&&!o?h.location:null,n==="history")await Be(t.historyPath||h.location.path||t.tour.files.find(y=>y.kind==="text-diff")?.path,t.historyCommit||h.location.commit);else if(n==="compare")await Mn(o||t.compare||Gt(),d||h.location.path||u.path);else if(oe(Math.max(0,h.location.sceneIndex),h.location.stepIndex,{zoomLanding:!0,showIntro:h.restore?h.location.sceneIntroVisible:!0,readingKey:h.restore?h.location.readingKey:"title"}),h.location.path&&t.activeTourFilePath!==h.location.path){let y=t.tour.files.findIndex(v=>v.path===h.location.path);y>=0&&nt(y)}ce()}catch(h){X=null,t.zoom.enter(l),t.tour=Ze(l),u&&(t.activeSceneIndex=u.sceneIndex,t.activeStepIndex=u.stepIndex,t.activeTourFilePath=u.path,t.narrativeParent=u.narrativeParent,t.sceneIntroVisible=u.sceneIntroVisible,t.tourNavigatorTab=u.navigatorTab),_e(),Fe(),Ce(),u&&ee()&&(X=u,oe(u.sceneIndex,u.stepIndex,{zoomLanding:!0,showIntro:u.sceneIntroVisible,readingKey:u.readingKey}),u.path&&t.activeTourFilePath!==u.path&&nt(t.tour.files.findIndex(y=>y.path===u.path))),Te(),ce(),te(h)}finally{t.zoomSwitching=!1}}async function uo(n){if(!(!n||typeof n!="object")){if(n.type==="navigationState"){ye.get(n.requestId)?.(n.navigation);return}if(n.type==="renderComplete"&&t.mode==="tour"&&n.renderRequestId===ne&&ao(t.activeTourFilePath,ne),n.type==="renderComplete"&&X&&n.renderRequestId===Ee){let o=X;X=null,W({type:"restoreNavigationState",navigation:o.navigation});let d=document.getElementById("tour-narrative-content");d&&(d.scrollTop=o.narrativeScroll||0,$=d.scrollTop),o.focusId&&document.getElementById(o.focusId)?.focus({preventScroll:!0})}if(n.type==="ready"){let o=new URLSearchParams(window.location.search),d=o.get("manifest");d?zn(d):o.get("demo")==="1"&&Qn();return}if(t.mode==="tour"&&t.directoryEvidence&&ee()){if(n.type==="openDirectoryEntry"){Qt(n.relativePath);return}if(n.type==="returnToDirectory"){vt();return}}if(t.mode==="tour"){if(t.zoom?.mode==="history"&&["multiAddPanel","multiRemovePanel"].includes(n.type)){lo(n).catch(te);return}if(n.type==="multiSetActivePair"||n.type==="multiSetActivePanel"){t.zoom?.mode==="history"?t.historyFocus=n.type==="multiSetActivePanel"?n.panelId:t.historyPanels[n.pairIndex]?.id||t.historyFocus:t.zoom?.mode==="compare"&&(t.comparisonFocus=n.type==="multiSetActivePanel"?n.panelId.replace(/^compare-/,""):t.comparisonCommits[n.pairIndex]);return}if(n.type==="historyBack"||n.type==="historyForward"){if(t.zoom?.mode!=="history")return;let o=Wt(n.type==="historyBack"?1:-1);o&&o.catch(te);return}if(n.type==="toggleHistorySelection"&&Number.isInteger(n.index)){let o=t.displayedPanels.map(u=>u.commit),d=n.index<0?{commit:o[-n.index-1]}:t.historyEntries[n.index];if(!d?.commit)return;let l=t.comparisonDraftCommits.includes(d.commit)?t.comparisonDraftCommits.filter(u=>u!==d.commit):[...t.comparisonDraftCommits,d.commit];t.comparisonDraftCommits=l.length>=2?Ln({commits:l}).commits:l,mt();return}if(n.type==="compareHistoryEntry"&&Number.isInteger(n.index)){let o=t.historyEntries[n.index];o?.parentCommit&&ve({commits:[o.parentCommit,o.commit],path:t.activeTourFilePath}).catch(te);return}if(n.type==="selectHistoryEntry"&&Number.isInteger(n.index)){let o=t.historyEntries[n.index];if(o&&t.zoom?.mode==="history"){let d=t.historyPanels.find(l=>l.commit===o.commit);d?(t.historyFocus=d.id,W({type:"focusHistoryPanel",panelId:d.id})):Be(t.historyPath,o.commit,!1).catch(te)}if(o&&t.zoom?.mode!=="history"){let d=t.displayedPanels.find(l=>l.commit===o.commit);d?W({type:"focusHistoryPanel",panelId:d.id}):(t.historyCommit=o.commit,t.historyPath=t.activeTourFilePath||t.historyPath,xe("history").catch(te))}return}}if(n.type==="navigateFile"&&t.mode==="tour"){Gn(n.direction==="previous"?-1:1);return}if(n.type==="navigateTourStep"&&t.mode==="tour"){let o=n.sceneIndex,d=n.stepIndex;Number.isInteger(o)&&Number.isInteger(d)&&oe(o,d,{userNavigation:!0,showIntro:!1});return}n.type==="recomputeDiff"&&t.mode==="diff"&&t.left&&t.right&&(t.left.content=n.leftContent,t.right.content=n.rightContent,W({type:"showDiff",file1:t.left.name,file2:t.right.name,comparisonId:`web-${t.comparisonId}`,leftContent:t.left.content,rightContent:t.right.content,diffModel:ie(t.left.content,t.right.content),history:null}))}}function fo(){document.getElementById("tour-review-toggle")?.addEventListener("click",()=>{bt(document.getElementById("tour-review").hidden)}),document.getElementById("tour-review-close")?.addEventListener("click",()=>bt(!1)),document.getElementById("tour-review")?.addEventListener("keydown",T=>{T.key==="Escape"&&(T.preventDefault(),bt(!1))});let n=(T,K)=>document.getElementById(T)?.addEventListener("click",()=>{Promise.resolve().then(K).catch(te)});n("tour-history-compare",()=>ve({commits:t.comparisonDraftCommits})),n("tour-compare-apply",()=>ve({commits:t.comparisonDraftCommits,path:t.compare?.path})),n("tour-history-parent",()=>{let T=t.historyEntries.find(K=>K.commit===t.historyCommit)?.parentCommit;if(!T){te("This is the first commit; History already shows its comparison with the empty tree.");return}return ve({commits:[T,t.historyCommit],path:Dn()})}),n("tour-history-base",()=>ve({commits:[t.authoredTour.range.mergeBaseOid,t.historyCommit],path:Dn()})),n("tour-history-final",()=>ve(Gt())),n("tour-compare-final",()=>ve(Gt())),n("tour-compare-all",()=>ve({commits:t.compare.commits}));let o=T=>{t.comparisonDraftCommits=T.filter(Boolean),mt(),W({type:"updateHistorySelection",commits:t.comparisonDraftCommits})};for(let T of["history","compare"])n(`tour-${T}-clear`,()=>o([])),n(`tour-${T}-reset`,()=>o(Rn()));for(let T of["wheel","pointerdown","keydown"])document.addEventListener(T,K=>{!K.isTrusted||K.target?.closest?.("#tour-mode-controls")||K.target?.closest?.(".monaco-editor, .diff-toolbar, #tour-narrative")&&se()},{capture:!0,passive:!0});let d=document.getElementById("web-compare-test"),l=document.getElementById("web-open-diff"),u=document.getElementById("web-open-diff3"),h=document.getElementById("web-diff-input"),y=document.getElementById("web-diff3-input"),v=document.getElementById("tour-narration"),k=document.getElementById("tour-return-focus"),L=document.getElementById("tour-search-input"),F=document.getElementById("tour-search-scope"),G=document.getElementById("tour-listen"),j=document.getElementById("tour-stop"),U=document.getElementById("tour-narration-skip-back"),V=document.getElementById("tour-narration-skip-ahead"),D=document.getElementById("tour-narration-voice"),_=document.getElementById("tour-narration-rate");Io(),Eo(),To(),ho(),document.getElementById("tour-navigator-tabs")?.addEventListener("click",T=>{let K=T.target instanceof Element?T.target.closest("[data-tour-navigator]"):null;K?.dataset.tourNavigator&&kt(K.dataset.tourNavigator)}),d?.addEventListener("click",()=>{Qn()}),l?.addEventListener("click",()=>{h.value="",h.click()}),u?.addEventListener("click",()=>{y.value="",y.click()}),h?.addEventListener("change",async()=>{let T=Array.from(h.files||[]);if(T.length!==2){me("Select exactly 2 files for a diff.");return}await Wo(T)}),y?.addEventListener("change",async()=>{let T=Array.from(y.files||[]);if(T.length<1){me("Select one or more files.");return}await jo(T)}),document.getElementById("tour-title")?.addEventListener("click",()=>Et("tour")),document.getElementById("tour-narrative-content")?.addEventListener("scroll",Uo,{passive:!0}),v?.addEventListener("click",()=>Fo()),k?.addEventListener("click",Ro),document.getElementById("tour-directory-root")?.addEventListener("click",()=>{Et("scene"),document.getElementById("tour-directory-root").focus({preventScroll:!0})}),L?.addEventListener("input",Ce),F?.addEventListener("change",Ce),G?.addEventListener("click",Fn),j?.addEventListener("click",()=>R.stop()),U?.addEventListener("click",()=>R.skipSegment(-1)),V?.addEventListener("click",()=>R.skipSegment(1)),D?.addEventListener("change",()=>{t.narrationVoiceURI=D.value,window.localStorage.setItem(p,t.narrationVoiceURI)}),_&&(_.value=String(t.narrationRate),_.addEventListener("change",()=>{let T=Number(_.value);t.narrationRate=w.has(T)?T:1,_.value=String(t.narrationRate),window.localStorage.setItem(g,String(t.narrationRate))})),document.getElementById("tour-search-results")?.addEventListener("click",T=>{let K=T.target instanceof Element?T.target.closest("[data-tour-search-result]"):null;K&&ko(Number(K.getAttribute("data-tour-search-result")))}),window.addEventListener("keydown",T=>{if(t.mode==="tour"&&(T.metaKey||T.ctrlKey)&&T.shiftKey&&T.key.toLocaleLowerCase()==="f"){T.preventDefault(),T.stopImmediatePropagation(),t.tourSidebarHidden&&Xt(!1),kt("tour"),document.querySelector(".tour-search-disclosure")?.setAttribute("open",""),L?.focus(),L?.select();return}t.mode!=="tour"||T.metaKey||T.ctrlKey||T.altKey||Mo(T.target)||T.target.closest?.("#tour-review")||(T.key==="PageUp"||T.key==="ArrowLeft"?(T.preventDefault(),t.zoom?.mode==="history"?Wt(1)?.catch(te):jn(-1)):T.key==="PageDown"||T.key==="ArrowRight"?(T.preventDefault(),t.zoom?.mode==="history"?Wt(-1)?.catch(te):jn(1)):t.zoom?.mode==="history"&&["ArrowUp","ArrowDown"].includes(T.key)&&(T.preventDefault(),Gn(T.key==="ArrowUp"?-1:1)))},!0),window.addEventListener("bygone:tour-command",T=>{T.detail==="toggleNarration"&&Fn(),T.detail==="pauseNarration"&&R.pauseForExternalOwner()}),window.addEventListener("beforeunload",()=>R.dispose(),{once:!0}),Kt(R.state)}function ho(){let n=document.getElementById("tour-narration-voice"),o=document.getElementById("tour-listen");if(!m){o&&(o.disabled=!0,o.title="Device narration is not supported by this browser."),n&&(n.disabled=!0),Qe("Device narration unavailable");return}let d=()=>{if(t.narrationVoices=window.speechSynthesis.getVoices().slice().sort((l,u)=>Number(u.default)-Number(l.default)||l.lang.localeCompare(u.lang)||l.name.localeCompare(u.name)),t.narrationVoiceURI&&t.narrationVoices.length>0&&!t.narrationVoices.some(l=>l.voiceURI===t.narrationVoiceURI)&&(t.narrationVoiceURI="",window.localStorage.removeItem(p)),n){let l=document.createElement("option");l.value="",l.textContent="System default voice",n.replaceChildren(l,...t.narrationVoices.map(u=>{let h=document.createElement("option");return h.value=u.voiceURI,h.textContent=`${u.name} (${u.lang})${u.default?" \u2014 default":""}`,h})),n.value=t.narrationVoiceURI,n.disabled=t.narrationVoices.length===0}};d(),window.speechSynthesis.addEventListener("voiceschanged",d)}function po(){let n=Number(window.localStorage.getItem(g));return w.has(n)?n:1}function mo(){let n=null;return{speak(o,d){if(!m){d.onError("Device narration is not supported by this browser.");return}let l=new window.SpeechSynthesisUtterance(o.speechText),u=t.narrationVoices.find(h=>h.voiceURI===t.narrationVoiceURI);u&&(l.voice=u),l.rate=t.narrationRate,l.onend=()=>{n===l&&(n=null),d.onEnd()},l.onerror=h=>{n===l&&(n=null),d.onError(go(h.error))},n=l,window.speechSynthesis.speak(l)},pause(){m&&window.speechSynthesis.pause()},resume(){m&&window.speechSynthesis.resume()},cancel(){n=null,m&&window.speechSynthesis.cancel()}}}function go(n){return n==="not-allowed"?"Device narration needs permission to play audio.":n==="language-unavailable"||n==="voice-unavailable"?"The selected device voice is unavailable.":`Device narration failed${n?`: ${n}`:"."}`}function yo(){if(!m||t.mode!=="tour")return;let n=Bn("playback-start");if(!n)return;let o=n.segments[0];St(!!(o&&["chapter","scene-title","summary","bullet","takeaway"].includes(o.source.field))),t.renderedNarrationUnit=n,Do(n),R.start(n,!0)}function Fn(){R.state.kind==="playing"||R.state.kind==="paused"?R.togglePause():yo()}function Bn(n){return!t.tour||t.activeSceneIndex<0?null:Dr(t.tour,{sceneIndex:t.activeSceneIndex,stepIndex:t.activeStepIndex},{entry:n})}function wo(n,o){let d=t.tour;return!!(d&&kn(d.scenes,n.position,o))}function bo(n,o){let d=t.tour;if(!d)return null;let l=kn(d.scenes,n.position,o);return l?oe(l.sceneIndex,l.stepIndex,{narrationNavigation:"controller",narrationEntry:"continuous",showIntro:!1}):null}function vo(){fetch("/narration/claim",{method:"POST",cache:"no-store"}).catch(()=>{})}function Kt(n){let o=document.getElementById("tour-listen"),d=document.getElementById("tour-stop"),l=document.getElementById("tour-narration-skip-back"),u=document.getElementById("tour-narration-skip-ahead");if(o){o.disabled=!m||t.mode!=="tour";let h=n.kind==="playing";o.querySelector(".tour-play-pause-icon")?.setAttribute("d",h?"M7 5h4v14H7zM13 5h4v14h-4z":"m8 5 11 7-11 7Z");let y=h?"Pause narration":n.kind==="paused"?"Resume narration":"Listen from the current tour item";o.title=y,o.setAttribute("aria-label",y),document.getElementById("tour-listen-label").textContent=h?"Pause":n.kind==="paused"?"Resume":"Listen"}if(d&&(d.disabled=n.kind!=="playing"&&n.kind!=="paused"),l&&(l.disabled=!R.canSkipSegment(-1)),u&&(u.disabled=!R.canSkipSegment(1)),n.kind==="playing"||n.kind==="paused"){let h=n.segmentIndex+1,y=n.unit.segments.length;Qe(`${n.kind==="paused"?"Paused":"Speaking"} \xB7 segment ${h} of ${y}`)}else n.kind==="completed"?Qe("Narration complete"):n.kind==="error"?Qe(n.message):m&&Qe("Device voice ready")}function Qe(n){let o=document.getElementById("tour-narration-status");o&&(o.textContent=n)}function xo(n,o){if(document.querySelectorAll(".tour-narration-segment.is-speaking").forEach(k=>{k.classList.remove("is-speaking","is-paused")}),!n)return;let d=[...document.querySelectorAll("[data-narration-segment-id]")].filter(k=>k.dataset.narrationSegmentId===n.id),l=d[0];if(!l||(d.forEach(k=>{k.classList.add("is-speaking"),k.classList.toggle("is-paused",o)}),o))return;let u=l.closest("[data-reading-kind]");if(u?.dataset.readingKind==="scene"){let k=["chapter","scene-title","summary","bullet","takeaway"].includes(n.source.field);St(k)}else u?.dataset.readingKind==="step"&&St(!1);let h=document.getElementById("tour-narrative-content");if(!h)return;let y=l.getBoundingClientRect(),v=h.getBoundingClientRect();(y.top<v.top||y.bottom>v.bottom)&&(l.scrollIntoView({block:"nearest"}),$=h.scrollTop)}let et=[];function Ce(){let n=document.getElementById("tour-search-input"),o=document.getElementById("tour-search-scope"),d=document.getElementById("tour-search-status"),l=document.getElementById("tour-search-results");if(!(!t.tour||!n||!o||!d||!l)){if(et=Ur(t.tour,n.value,o.value),!n.value.trim()){d.textContent="Cmd/Ctrl+Shift+F",l.replaceChildren();return}d.textContent=`${et.length} result${et.length===1?"":"s"}`,l.replaceChildren(...et.map((u,h)=>{let y=document.createElement("button");y.type="button",y.className="tour-search-result",y.setAttribute("role","option"),y.dataset.tourSearchResult=String(h),y.title=`Open ${u.kind==="code"?`${u.label}:${u.lineNumber}`:u.label}`;let v=document.createElement("span");v.className="tour-search-location",v.textContent=u.kind==="code"?`${u.label}:${u.lineNumber}`:u.label;let k=document.createElement("span");return k.className="tour-search-preview",k.textContent=u.preview.trim(),y.append(v,k),y}))}}function ko(n){let o=et[n];if(o){if(o.kind==="narrative"){se(),oe(o.sceneIndex,o.stepIndex??0,{showIntro:o.stepIndex===void 0});return}rn(o.fileIndex)&&(St(!1),window.requestAnimationFrame(()=>W({type:"revealSearchResult",sideIndex:o.sideIndex,lineNumber:o.lineNumber,startColumn:o.startColumn,endColumn:o.endColumn})))}}function Io(){let n=document.getElementById("tour-shell"),o=document.getElementById("tour-sidebar-resizer"),d=document.getElementById("tour-sidebar-hide"),l=document.getElementById("tour-sidebar-show");!n||!o||!d||!l||(Un(),d.addEventListener("click",()=>Xt(!0)),l.addEventListener("click",()=>Xt(!1)),o.addEventListener("pointerdown",u=>{u.preventDefault(),document.body.classList.add("is-resizing-tour-sidebar"),o.setPointerCapture?.(u.pointerId);let h=v=>_n(v.clientX),y=()=>{document.body.classList.remove("is-resizing-tour-sidebar"),window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),window.localStorage.setItem(r,String(t.tourSidebarWidth))};window.addEventListener("pointermove",h),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)}),o.addEventListener("keydown",u=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(u.key))return;u.preventDefault();let h=t.tourSidebarWidth;u.key==="Home"?h=240:u.key==="End"?h=Vt():h+=u.key==="ArrowLeft"?-16:16,_n(h),window.localStorage.setItem(r,String(t.tourSidebarWidth))}))}function So(){let n=Number.parseInt(window.localStorage.getItem(r)||"",10);return Number.isFinite(n)?Math.min(600,Math.max(240,n)):300}function Vt(){return Math.max(240,Math.min(600,Math.floor(window.innerWidth*.6)))}function _n(n){t.tourSidebarWidth=Math.min(Vt(),Math.max(240,Math.round(n))),Un(),window.dispatchEvent(new Event("resize"))}function Un(){document.documentElement.style.setProperty("--tour-rail-width",`${t.tourSidebarWidth}px`);let n=document.getElementById("tour-sidebar-resizer");n?.setAttribute("aria-valuemax",String(Vt())),n?.setAttribute("aria-valuenow",String(t.tourSidebarWidth))}function Xt(n){t.tourSidebarHidden=n,document.body.classList.toggle("tour-sidebar-hidden",n);let o=document.getElementById("tour-sidebar-show");o&&(o.hidden=!n),window.dispatchEvent(new Event("resize"))}function Eo(){let n=document.getElementById("tour-narrative-resizer");n&&(Yt(),n.addEventListener("pointerdown",o=>{if(o.button!==0)return;o.preventDefault(),document.body.classList.add("is-resizing-tour-narrative"),n.setPointerCapture?.(o.pointerId),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-start"));let d=document.getElementById("tour-narrative").getBoundingClientRect().top,l=h=>Hn(h.clientY-d),u=()=>{document.body.classList.remove("is-resizing-tour-narrative"),window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",u),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-end")),window.localStorage.setItem(a,String(t.tourNarrativeHeight))};window.addEventListener("pointermove",l),window.addEventListener("pointerup",u),window.addEventListener("pointercancel",u)}),n.addEventListener("keydown",o=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(o.key))return;o.preventDefault();let d=o.key==="Home"?180:o.key==="End"?Jt():t.tourNarrativeHeight+(o.key==="ArrowUp"?-16:16);Hn(d),window.localStorage.setItem(a,String(t.tourNarrativeHeight))}),window.addEventListener("resize",Yt))}function Co(){let n=Number.parseInt(window.localStorage.getItem(a)||"",10);return Number.isFinite(n)?n:Math.min(window.innerHeight*.38,360)}function Jt(){return Math.max(180,window.innerHeight-180)}function Hn(n){t.tourNarrativeHeight=n,Yt()}function Yt(){t.tourNarrativeHeight=Math.min(Jt(),Math.max(180,Math.round(t.tourNarrativeHeight))),document.getElementById("tour-narrative").style.height=`${t.tourNarrativeHeight}px`;let n=document.getElementById("tour-narrative-resizer");n?.setAttribute("aria-valuemax",String(Jt())),n?.setAttribute("aria-valuenow",String(t.tourNarrativeHeight))}function To(){let n=document.getElementById("tour-narrative");if(!n)return;let o=()=>{let d=n.hidden?0:Math.ceil(n.getBoundingClientRect().height);document.documentElement.style.setProperty("--tour-narrative-height",`${d}px`);let l=document.getElementById("tour-narrative-content");l?.style.setProperty("--tour-reading-viewport",`${l.clientHeight}px`),window.dispatchEvent(new Event("resize"))};new ResizeObserver(o).observe(n),o()}async function zn(n){me("Loading change tour\u2026");let o=eo(n),d={...t,historyEntries:[...t.historyEntries],fileHistoryCache:new Map(t.fileHistoryCache),displayedPanels:[...t.displayedPanels],historyPanels:[...t.historyPanels],comparisonCommits:[...t.comparisonCommits],comparisonDraftCommits:[...t.comparisonDraftCommits]},l=document.body.className,u=document.getElementById("tour-shell")?.hidden,h=document.getElementById("tour-narrative")?.hidden,y=document.getElementById("tour-mode-controls")?.hidden,v=ne,k=X,L=Ee,F=J;try{R.stop();let G=await fetch(n,{cache:"no-store"});if(!G.ok)throw new Error(`Manifest request failed (${G.status}).`);let j=Ar(await G.json()),V=E(j).deconstructed?"deconstructed":"historical",D=B(j)?(await be("list",{commit:j.range.headOid},o,j)).entries:[];t.tour=j,t.authoredTour=j,t.historyPrefix=o,t.zoom=new _t(V),t.historyEntries=D,t.zoom&&(t.tour=Ze(V)),t.mode="tour",document.body.classList.add("tour-mode"),_e(),Fe(),Ce();let _=new URLSearchParams(window.location.search),T=xn(t.tour.scenes,_.get("scene"),_.get("step"));if(oe(T.sceneIndex,T.stepIndex,{showIntro:_.get("view")==="overview"||!_.get("step"),readingKey:!_.get("scene")&&!_.get("step")?"title":void 0}),["tour","chapter"].includes(_.get("view"))&&Et(_.get("view")),t.zoom){let M={explanation:"deconstructed",revisions:"historical",final:we()?"historical":"compare"}[_.get("mode")]||_.get("mode");if(M==="history"&&A().includes("history"))t.historyPath=_.get("file"),t.tourNavigatorTab="commits",t.zoom.enter("history"),t.tour=Ze("history"),_e(),Fe(),await Be(t.historyPath||t.tour.files.find(Y=>Y.kind==="text-diff")?.path,_.get("commit"));else if(M==="compare"&&A().includes("compare")){let Y=_.get("commits")?.split(",").filter(Boolean);await xe("compare",{commits:Y?.length?Y:[_.get("from")||t.authoredTour.range.mergeBaseOid,_.get("to")||t.authoredTour.range.headOid],..._.get("scope")?{path:_.get("scope")}:{}},_.get("file"))}else if(M&&M!==t.zoom.mode&&A().includes(M)){await xe(M);let Y=xn(t.tour.scenes,_.get("scene"),_.get("step"));oe(Y.sceneIndex,Y.stepIndex,{showIntro:_.get("view")==="overview"||!_.get("step"),readingKey:!_.get("scene")&&!_.get("step")?"title":void 0}),["tour","chapter"].includes(_.get("view"))&&Et(_.get("view"))}let re=z;z=null,O&&re&&re!==t.zoom.mode&&A().includes(re)&&await xe(re)}return t.directoryEvidence&&_.get("file")&&Qt(_.get("file")),Kt(R.state),t.workspacePromptStatus="",he(),me(""),!0}catch(G){Object.assign(t,d),ne=v,X=k,Ee=L,J=F,document.body.className=l;let j=document.getElementById("tour-shell");j&&u!==void 0&&(j.hidden=u);let U=document.getElementById("tour-narrative");U&&h!==void 0&&(U.hidden=h);let V=document.getElementById("tour-mode-controls");return V&&y!==void 0&&(V.hidden=y),t.mode==="tour"&&t.tour&&(_e(),Fe(),Ce(),he()),me(`Could not load change tour: ${G instanceof Error?G.message:String(G)}`),!1}}function _e(){It();let n=t.tour;if(!n)return;let o=document.getElementById("tour-shell"),d=document.getElementById("tour-title"),l=document.getElementById("tour-source"),u=document.getElementById("tour-range"),h=document.getElementById("tour-stats"),y=document.getElementById("tour-authoring-coverage"),v=document.getElementById("tour-scenes"),k=document.getElementById("tour-scene-count"),L=document.getElementById("tour-files"),F=document.getElementById("tour-file-count");if(!o||!d||!l||!u||!h||!y||!v||!k||!L||!F)throw new Error("Presenter UI is incomplete.");o.hidden=!1,d.textContent=n.title,document.title=qr(n),n.sourceUrl?(l.href=n.sourceUrl,l.hidden=!1):(l.removeAttribute("href"),l.hidden=!0);let G=Ue(n.range.baseRef),j=Ue(n.range.headRef),U=n.range.headOid.slice(0,7);u.textContent=`${G} \u2192 ${j}${j===U?"":` \xB7 ${U}`}`,h.textContent=`${it(n.summary.changedFiles,"file")} \xB7 +${n.summary.additions} \u2212${n.summary.deletions} \xB7 ${it(n.summary.commitCount,"commit")}`,Ao(y,n.authoringCoverage),$o(),k.textContent=String(n.scenes.length),F.textContent=String(n.files.length),v.replaceChildren(),ee()&&dn();let V=new Map(n.scenes.map(D=>[D.id,D]));for(let D of n.chapters){let _=Xn(`chapter:${D.id}`,D.title,"tour-chapter-link",()=>{let K=x.find(M=>M.kind==="chapter"&&M.chapterId===D.id)||x.find(M=>M.kind==="scene"&&D.sceneIds.includes(n.scenes[M.sceneIndex]?.id));K&&st(K)}),T=n.chapters.length>1?_.children:v;n.chapters.length>1&&v.append(_.group);for(let K of D.sceneIds){let M=V.get(K);if(!M)continue;let re=n.scenes.indexOf(M),Y=Xn(`scene:${M.id}`,M.title,"tour-scene",()=>oe(re,0,{userNavigation:!0,showIntro:!0})),Ct=Y.link;Ct.replaceChildren(),Ct.dataset.sceneId=M.id,M.kind==="text-diff"&&(Ct.dataset.filePath=M.path),Y.link.title=`Open scene: ${M.kind==="text-diff"?M.path:M.title}`;let ln=document.createElement("span");ln.className="tour-scene-number",ln.textContent=String(re+1).padStart(2,"0");let un=document.createElement("span");un.className="tour-scene-copy";for(let[at,He]of[["tour-scene-title",M.title],["tour-scene-path",M.kind==="text-diff"?M.path:M.kind==="deconstructed-diff"?`${it(M.panels.length-1,"comparison stage")} \xB7 ${it(M.steps.length,"tour slide")}`:ke(M)?it(M.steps.length,"code step"):"Discussion"],["tour-scene-note",M.takeaway]]){let Ie=document.createElement("span");Ie.className=at,Ie.textContent=He,un.append(Ie)}if(Ct.append(ln,un),T.append(Y.group),ke(M)){let at=Y.children;at.classList.add("tour-outline-steps"),at.dataset.sceneId=M.id,M.steps.forEach((He,Ie)=>{let Se=document.createElement("button");Se.type="button",Se.className="tour-outline-step",Se.dataset.sceneId=M.id,Se.dataset.stepIndex=String(Ie);let Go=M.kind==="deconstructed-diff"?`Stage ${(He.stageIndex??He.pairIndex)+1}: `:"";Se.textContent=`${Ie+1}. ${Go}${He.title}`,Se.title=`Open step ${Ie+1}: ${He.title}`,Se.addEventListener("click",()=>oe(re,Ie,{userNavigation:!0,showIntro:!1})),at.append(Se)})}else Y.toggle.hidden=!0}}L.replaceChildren(...n.files.map((D,_)=>{let T=document.createElement("button");T.type="button",T.className=`tour-file${D.kind==="omitted"?" is-omitted":""}`,T.dataset.filePath=D.path,T.disabled=D.kind==="omitted",T.title=D.kind==="omitted"?`${D.path}: ${D.reason}`:`Open file: ${D.path}`,D.kind==="text-diff"&&T.addEventListener("click",()=>nt(_));let K=document.createElement("span");K.className="tour-file-marker",K.textContent=D.kind==="omitted"?"\xD7":on(D.changeKind);let M=document.createElement("span");M.className="tour-file-copy";let re=document.createElement("span");re.className="tour-file-path",re.textContent=D.path;let Y=document.createElement("span");return Y.className="tour-file-meta",Y.textContent=D.kind==="omitted"?`Not rendered \xB7 ${D.reason}`:`${sn(D.changeKind)} \xB7 +${D.additions} \u2212${D.deletions}`,M.append(re,Y),T.append(K,M),T})),kt(t.tourNavigatorTab)}function bt(n){document.getElementById("tour-review").hidden=!n;let o=document.getElementById("tour-review-toggle");o.setAttribute("aria-expanded",String(n)),(n?document.getElementById("tour-review-close"):o).focus()}function $o(){let n=t.authoredTour,o=n?.review,d=document.getElementById("tour-review-toggle"),l=document.getElementById("tour-review-content");if(d.hidden=!o,l.replaceChildren(),!o){document.getElementById("tour-review").hidden=!0,d.setAttribute("aria-expanded","false");return}d.textContent=`Review notes (${o.items.length})`;let u=document.createElement("p");u.className="tour-review-provenance",u.textContent="Authored interpretations. Linked evidence is checked; conclusions and external checks are not verified.";let h=document.createElement("p");h.className="tour-review-range",h.textContent=`Reviewed snapshot: ${o.baseOid.slice(0,7)} \u2192 ${o.headOid.slice(0,7)}. Evidence opens this range\u2019s final diff.`,h.title=`${o.baseOid} \u2192 ${o.headOid}`,l.append(u,h);let y=n.zoom?.final.scenes||n.scenes;for(let[v,k]of[["concept","Concepts and invariants"],["boundary","Boundaries and prerequisites"],["tradeoff","Complexity tradeoffs"],["question","Open questions"]]){let L=o.items.filter(G=>G.kind===v);if(!L.length)continue;let F=document.createElement("h3");F.textContent=k,l.append(F);for(let G of L){let j=document.createElement("article");j.className="tour-review-item";let U=document.createElement("h4");U.textContent=G.title;let V=document.createElement("p");V.textContent=G.body,j.append(U,V);for(let D of G.evidence){let T=y.find(M=>M.id===D.sceneId).steps.find(M=>M.id===D.stepId),K=document.createElement("button");K.type="button",K.className="tour-review-evidence",K.textContent=`${T.title} \xB7 ${T.focus.path}:${T.focus.startLine} (${T.focus.revision})`,K.title=`Open evidence in the reviewed snapshot: ${T.title}`,K.addEventListener("click",()=>{No(D)}),j.append(K)}if(G.nextCheck){let D=document.createElement("p");D.className="tour-review-next",D.textContent=`Next check: ${G.nextCheck}`,j.append(D)}l.append(j)}}}async function No(n){let o=document.getElementById("tour-review-status");if(o.textContent="",t.zoomSwitching){o.textContent="Wait for the current mode change, then open the evidence again.";return}t.zoom&&t.zoom.mode!=="final"&&await xe("final");let d=t.tour.scenes.findIndex(h=>h.id===n.sceneId),l=t.tour.scenes[d],u=l?.kind==="walkthrough"?l.steps.findIndex(h=>h.id===n.stepId):-1;if(t.zoom&&t.zoom.mode!=="final"||u<0){o.textContent="Could not open the reviewed snapshot. Try switching to Final diff first.";return}X=null,oe(d,u,{userNavigation:!0}),bt(!1)}function Ao(n,o){if(n.replaceChildren(),n.hidden=!o,!o)return;let d=[{metric:"walkthrough",label:"Anchored diff hunks",covered:o.walkthrough.coveredUnits,total:o.walkthrough.includedUnits,percent:o.walkthrough.coveragePercent,description:"Distinct change hunks referenced by authored base/head focus anchors. Revision-stack steps are not counted."},...o.explanationAssignments.map(l=>({metric:"assignment",label:o.explanationAssignments.length>1?`Deconstructed assignment \xB7 ${l.sceneId}`:"Deconstructed assignment",covered:l.completeUnits,total:l.totalUnits,percent:l.assignmentPercent,description:`${l.assignedUnits} assigned, ${l.excludedUnits} explicitly excluded.`}))];for(let l of d){let u=document.createElement("div");u.className="tour-coverage-item",u.dataset.metric=l.metric,u.dataset.tooltip=l.description,u.tabIndex=0,u.setAttribute("aria-description",l.description);let h=document.createElement("div");h.className="tour-coverage-heading";let y=document.createElement("span");y.textContent=l.label;let v=document.createElement("strong");v.textContent=`${l.covered}/${l.total} \xB7 ${l.percent}%`,h.append(y,v);let k=document.createElement("div");k.className="tour-coverage-meter",k.setAttribute("role","progressbar"),k.setAttribute("aria-label",l.label),k.setAttribute("aria-valuemin","0"),k.setAttribute("aria-valuemax","100"),k.setAttribute("aria-valuenow",String(l.percent));let L=document.createElement("span");L.style.width=`${l.percent}%`,k.append(L),u.append(h,k),n.append(u)}}function oe(n,o=0,d={}){let l=t.tour;if(!l||n<0||n>=l.scenes.length)return null;if(d.userNavigation&&se(),t.zoom?.mode==="history"&&!t.zoomSwitching){let k=l.scenes[n],L=k.path||k.steps?.[o]?.file||t.activeTourFilePath;return Be(L,t.historyCommit).catch(F=>{document.getElementById("tour-mode-status").textContent=F.message}),null}t.directoryEvidence=null,It(),dn();let u=x.find(k=>k.key===d.readingKey)||Ft(x,n,o,d.showIntro?"overview":null);u&&(n=u.sceneIndex,o=u.stepIndex);let h=l.scenes[n];t.readingKey=u?.key||"title",t.sceneIntroVisible=u?.kind!=="step",t.narrativeParent=u?.kind==="title"?"tour":u?.kind==="chapter"?"chapter":null,t.activeSceneIndex=n,t.activeStepIndex=ke(h)?Math.min(Math.max(o,0),Math.max(h.steps.length-1,0)):0,t.tourFocusFilePath=h.kind==="text-diff"?h.path:h.kind==="walkthrough"?h.steps[t.activeStepIndex]?.diff.path??null:ae(h)?h.steps[t.activeStepIndex]?.file??null:null;let y=Kn(l,n);Zn();let v=Bn(d.narrationEntry||"playback-start");return t.renderedNarrationUnit=v,Yn(h,y,v),d.fromReadingScroll||_o(t.readingKey),v&&!d.zoomLanding&&(!t.zoom||ee())&&(d.narrationNavigation==="linear"?R.followLinearNavigation(v):d.narrationNavigation!=="controller"&&R.followDirectNavigation(v)),ce(),t.sceneIntroVisible&&vt()?v:h.kind==="discussion"?(++ne,t.displayedPanels=[],t.activeTourFilePath=null,W({type:"updateCommitHistory",history:Pn()}),document.body.classList.add("tour-discussion"),Te(),v):(document.body.classList.remove("tour-discussion"),h.kind==="walkthrough"?(tn(h),v):ae(h)?(nn(h),v):(tt(h,xt(h.path)),v))}function Zt(n){let o=document.getElementById("status-banner");o.textContent=n,o.hidden=!n}function vt(){let n=t.tour?.scenes[t.activeSceneIndex];if(!ee()||!n||!t.narrativeParent&&n.kind==="text-diff")return!1;let o=t.narrativeParent==="tour"?{...n,kind:"discussion",overview:void 0}:n,d=Wr(t.tour,o);return t.directoryEvidence=d,t.activeTourFilePath=null,Te(),document.body.classList.remove("tour-discussion"),W({type:"showDirectoryDiff",leftLabel:d.labels[0],rightLabel:d.labels[1],labels:d.labels,entries:d.entries,canMutate:!1}),Zt(d.entries.length?"":"No changed files in this directory for the selected comparison."),ce(),!0}function Qt(n){let o=t.directoryEvidence;if(!o)return!1;let d=o.files.find(l=>l.path===n);if(!d){let l=o.omitted.find(u=>u.path===n);return Zt(l?`${n}: ${l.reason}`:"This file has no change in the overview comparison."),!1}return se(),Zt(""),tt(d,[],`directory-${t.tour.scenes[t.activeSceneIndex].id}-${n}`),ce(),!0}function xt(n){let o=t.tour;return!o||!n?[]:Hr(o,n,t.activeSceneIndex,t.activeStepIndex)}function Lo(n,o){let d=t.tour;return!d||!n?[]:zr(d,n,t.activeSceneIndex,t.activeStepIndex,(l,u)=>Sn(o?.[l]?.diffModel,u))}function en(n){return`file::${n}`}function tt(n,o=[],d=en(n.path),l=null){if(!t.tour)return;t.activeTourFilePath=t.zoom?.mode==="history"&&t.historyPath||n.path,Te();let h=ie(n.leftContent,n.rightContent),y=qn(n,n.leftLabel,t.zoom?.mode==="compare"?"from":"base"),v=qn(n,n.rightLabel,t.zoom?.mode==="compare"?"to":"head"),k=o.find(F=>F.active),L=n.changeKind==="added"?{left:!1,right:!0}:n.changeKind==="deleted"?{left:!0,right:!1}:{left:!0,right:!0};W({type:"showDiff",file1:`1. ${y}`,file2:`2. ${v}`,comparisonId:`tour-${d}`,leftContent:n.leftContent,rightContent:n.rightContent,canReturnToDirectory:!!t.directoryEvidence,sourceInfo:{leftPath:n.previousPath||n.path,rightPath:n.path},fileExists:L,diffModel:h,history:l,fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(1)},editableSides:{left:!1,right:!1},comparisonSummary:n.takeaway?`${n.path} \xB7 ${n.takeaway}`:n.path,initialChangeIndex:k?Vn(h,k.side,k.startLine):n.focusChangeIndex,tourAnnotations:o})}function qn(n,o,d){if(t.zoom?.mode==="history")return o;let l=o.startsWith(n.path)?o.slice(n.path.length).trim():o.trim();return l?`${d} ${l}`:d}function tn(n){let o=n.steps[t.activeStepIndex];o&&tt(o.diff,xt(o.diff.path),en(o.diff.path))}function nn(n){let o=n.steps[t.activeStepIndex];o&&Wn(n,o.file,o)}function Wn(n,o,d){let l=rt(n,o);if(!d||!l)return;t.activeTourFilePath=l.path,Te();let u=l.panels.map((U,V)=>({id:`${n.id}-${l.path}-${U.id}`,commit:n.kind==="stacked-diff"?ot(n)[V].oid:void 0,label:U.label,path:U.path||l.path,content:U.content,savedContent:U.content,dirty:!1,editable:!1,stackId:ot(n)[V].id})),h=u.slice(0,-1).map((U,V)=>({leftIndex:V,rightIndex:V+1,diffModel:ie(U.content,u[V+1].content)})),y=Lo(l.path,h),v=y.find(U=>U.active),k=v?.pairIndex??d.pairIndex,L=v?.side??d.side,F=v?.startLine??d.startLine,G=h[k]?.diffModel,j=G&&F?Vn(G,L,F):0;W({type:"showMultiDiff",panels:u,pairs:h,activePanelId:u[k+(L==="right"?1:0)]?.id,activePairIndex:k,initialChangeIndex:j,revealFirstChangeInEachPanel:n.kind==="deconstructed-diff",history:null,fileNavigation:{canGoPrevious:!!pe(-1),canGoNext:!!pe(1)},mutationEnabled:!1,comparisonSummary:n.kind==="deconstructed-diff"?`${n.stageLabel} \xB7 ${l.path} \xB7 ${Ue(n.realRange.baseRef)} \u2192 ${Ue(n.realRange.targetRef)}`:`${l.path} \xB7 ${n.takeaway}`,tourAnnotations:y})}function jn(n){if(!ee())return!1;let o=Br(x,t.readingKey,n);return o?(st(o),!0):!1}function pe(n){let o=t.tour;if(!o||n!==-1&&n!==1)return null;let d=o.scenes[t.activeSceneIndex];if(t.directoryEvidence){let l=t.directoryEvidence.files,u=l.findIndex(v=>v.path===t.activeTourFilePath),h=l[u+n],y=h?o.files.findIndex(v=>v.path===h.path):-1;return y>=0?{fileIndex:y,path:h.path}:null}if(ae(d)){let l=d.steps[t.activeStepIndex]?.pairIndex;if(!Number.isInteger(l))return null;let u=o.files.flatMap(v=>{if(v.kind!=="text-diff")return[];let k=rt(d,v.path);return k?[k]:[]}),h=Pr(u,l,t.activeTourFilePath,n);if(!h)return null;let y=o.files.findIndex(v=>v.kind==="text-diff"&&v.path===h.path);return y>=0?{fileIndex:y,path:h.path}:null}return Or(o.files,t.activeTourFilePath,n)}function Gn(n){let o=pe(n);return o?nt(o.fileIndex):!1}function rn(n,o=!0){let d=t.tour?.files[n];return!d||d.kind!=="text-diff"?!1:(o&&R.interruptForExploration(),tt(d,xt(d.path),en(d.path)),!0)}function nt(n){let o=t.tour?.files[n];if(!o||o.kind!=="text-diff")return!1;if(se(),t.zoom?.mode==="history")return Be(o.path,t.historyCommit).catch(l=>{document.getElementById("tour-mode-status").textContent=l.message}),!0;if(t.zoom?.mode==="compare")return On(o);if(t.directoryEvidence&&ee())return Qt(o.path);t.zoomSwitching||R.interruptForExploration();let d=t.tour?.scenes[t.activeSceneIndex];if(ae(d)){let l=d.steps[t.activeStepIndex];return l&&rt(d,o.path)?(Wn(d,o.path,l),!0):!1}return rn(n,!1)}function rt(n,o){let d=n?.files?.find(h=>h.path===o);if(d||n?.kind!=="deconstructed-diff")return d;let l=t.tour?.files.find(h=>h.kind==="text-diff"&&h.path===o);if(!l||l.kind!=="text-diff")return null;let u=l.changeKind!=="deleted";return{path:l.path,panels:ot(n).map(h=>({id:h.id,label:`${h.label} / ${l.path}${u?"":" (absent)"}`,path:u?l.path:void 0,content:u?l.rightContent:"",exists:u}))}}function Ro(){if(t.directoryEvidence)return vt();let n=t.tour?.scenes[t.activeSceneIndex];if(!n||!t.tourFocusFilePath)return!1;if(n.kind==="walkthrough")tn(n);else if(ae(n))nn(n);else if(n.kind==="text-diff")tt(n,xt(n.path));else return!1;return!0}function kt(n){["tour","files","commits"].includes(n)&&(t.tourNavigatorTab=n,document.querySelectorAll("[data-tour-navigator]").forEach(o=>{let d=o.dataset.tourNavigator===n;o.classList.toggle("is-active",d),o.setAttribute("aria-selected",String(d)),o.tabIndex=d?0:-1}),document.querySelectorAll("[data-tour-navigator-panel]").forEach(o=>{o.hidden=o.dataset.tourNavigatorPanel!==n}),window.dispatchEvent(new CustomEvent("bygone:present-navigator-change",{detail:{tab:n}})),window.dispatchEvent(new Event("resize")))}function It(){let n=!!(t.directoryEvidence&&ee()),o=n?t.activeTourFilePath:null;document.body.classList.toggle("tour-directory-overview",n),document.body.classList.toggle("tour-directory-file-open",!!o),document.getElementById("tour-directory-breadcrumb").hidden=!n;let d=document.getElementById("tour-directory-root");o?d.removeAttribute("aria-current"):d.setAttribute("aria-current","location"),document.getElementById("tour-directory-separator").hidden=!o;let l=document.getElementById("tour-directory-file");l.textContent=o||"",l.hidden=!o;let u=document.getElementById("tour-directory-narration-context");u.hidden=!o,u.textContent=`Narration describes the ${t.narrativeParent||"overview"}`}function Te(){It();let n=t.tour?.scenes[t.activeSceneIndex],o=ae(n)?n.steps[t.activeStepIndex]:null;document.querySelectorAll(".tour-file").forEach(l=>{let u=l.dataset.filePath;l.classList.toggle("is-active",u===t.activeTourFilePath),l.classList.toggle("is-tour-focus",!t.directoryEvidence&&u===t.tourFocusFilePath),l.disabled=!!(t.directoryEvidence&&!t.directoryEvidence.files.some(k=>k.path===u)),l.classList.remove("is-comparison-changed","is-comparison-empty"),delete l.dataset.comparisonState;let h=t.tour?.files.find(k=>k.path===u),y=l.querySelector(".tour-file-marker"),v=l.querySelector(".tour-file-meta");if(t.directoryEvidence&&l.disabled&&h?.kind==="text-diff"){let k="Not in this overview comparison";l.setAttribute("title",`${u} \xB7 ${k}`),l.setAttribute("aria-label",`${u}, ${k}`),v&&(v.textContent=k),y&&(y.textContent="\u25CB");return}if(t.directoryEvidence&&h?.kind==="text-diff"){let k=t.directoryEvidence.files.find(F=>F.path===u),L=`${sn(k.changeKind)} in overview`;l.setAttribute("title",`${u} \xB7 ${L}`),l.setAttribute("aria-label",`${u}, ${L}`),v&&(v.textContent=L),y&&(y.textContent=on(k.changeKind));return}if(o&&h?.kind==="text-diff"){let k=rt(n,u);if(k){let L=vn(k,o.pairIndex),F=Po(L);l.dataset.comparisonState=L,l.classList.add(F.changed?"is-comparison-changed":"is-comparison-empty"),l.setAttribute("title",`${h.path} \xB7 ${F.label}`),l.setAttribute("aria-label",`${h.path}, ${F.label}`),y&&(y.textContent=F.marker),v&&(v.textContent=F.label);return}}if(h){let k=h.kind==="omitted"?`${h.path}: ${h.reason}`:`Open file: ${h.path}`;l.setAttribute("title",k),l.setAttribute("aria-label",k),y&&(y.textContent=h.kind==="omitted"?"\xD7":on(h.changeKind)),v&&(v.textContent=h.kind==="omitted"?`Not rendered \xB7 ${h.reason}`:`${sn(h.changeKind)} \xB7 +${h.additions} \u2212${h.deletions}`)}}),document.querySelector(".tour-file.is-active")?.scrollIntoView({block:"nearest"});let d=document.getElementById("tour-return-focus");if(d){let l=ee();d.hidden=!l||!!t.directoryEvidence||!t.tourFocusFilePath||t.activeTourFilePath===t.tourFocusFilePath}}function Po(n){return{"modified-here":{label:"Modified here",marker:"\u2022",changed:!0},"created-here":{label:"Created here",marker:"+",changed:!0},"deleted-here":{label:"Deleted here",marker:"\u2212",changed:!0},"unchanged-here":{label:"Unchanged here",marker:"\u25CB",changed:!1},"not-created-yet":{label:"Not created yet",marker:"\u2026",changed:!1},"already-deleted":{label:"Already deleted",marker:"\xD7",changed:!1}}[n]}function ke(n){return n.kind==="walkthrough"||n.kind==="stacked-diff"||n.kind==="deconstructed-diff"}function ae(n){return n?.kind==="stacked-diff"||n?.kind==="deconstructed-diff"}function ot(n){return n.kind==="deconstructed-diff"?n.panels:n.stack}function on(n){return{added:"+",deleted:"\u2212",renamed:"\u2192",modified:"\u2022"}[n]||"\u2022"}function sn(n){return`${n.charAt(0).toUpperCase()}${n.slice(1)}`}function Kn(n,o){let d=n.scenes[o],l=n.chapters.findIndex(v=>v.sceneIds.includes(d.id)),u=l>=0?n.chapters[l]:null,h=u?u.sceneIds.indexOf(d.id)+1:o+1,y=u?u.sceneIds.length:n.scenes.length;return{chapter:u,chapterIndex:l,chapterNumber:l>=0?l+1:o+1,sceneInChapter:h,scenesInChapter:y,sceneNumber:o+1,sceneCount:n.scenes.length}}function Oo(n,o,d){return ke(o)?`Scene ${n.sceneNumber} of ${n.sceneCount} \xB7 Step ${d+1} of ${o.steps.length}`:`Scene ${n.sceneNumber} of ${n.sceneCount}`}function Vn(n,o,d){let u=(o==="left"?n.leftLines:n.rightLines).findIndex(F=>F.lineNumber===d);if(u<0)return 0;let h=o==="left"?"leftStart":"rightStart",y=o==="left"?"leftEnd":"rightEnd",v=n.blocks.findIndex(F=>u>=F[h]&&u<F[y]);if(v>=0)return v;let k=0,L=Number.POSITIVE_INFINITY;return n.blocks.forEach((F,G)=>{let j=Math.min(Math.abs(u-F[h]),Math.abs(u-F[y]));j<L&&(k=G,L=j)}),k}function Ue(n){return/^[0-9a-f]{40}$/i.test(n)?n.slice(0,7):n}function it(n,o){return`${n} ${n===1?o:`${o}s`}`}function Mo(n){return n instanceof Element&&!!n.closest('a, button, input, select, summary, textarea, [contenteditable="true"], [role="textbox"], .monaco-editor')}function Do(n){let o=t.tour?.scenes[t.activeSceneIndex];!t.tour||!o||Yn(o,Kn(t.tour,t.activeSceneIndex),n)}function St(n){let o=t.tour?.scenes[t.activeSceneIndex];if(!o)return;t.narrativeParent=null,t.sceneIntroVisible=n;let d=Ft(x,t.activeSceneIndex,t.activeStepIndex,n?"overview":null);d&&(t.readingKey=d.key),Zn(),cn(),t.sceneIntroVisible&&!t.directoryEvidence?vt():!t.sceneIntroVisible&&t.directoryEvidence&&(t.directoryEvidence=null,o.kind==="walkthrough"?tn(o):ae(o)&&nn(o)),ce()}function Et(n){let o=Ft(x,t.activeSceneIndex,t.activeStepIndex,n==="scene"?"overview":n==="step"?null:n);o&&st(o)}function an(n,o,d){let l=document.createElement("button");return l.type="button",l.textContent=n,l.title=o,l.addEventListener("click",d),l}function Xn(n,o,d,l){let u=document.createElement("div");u.className="tour-outline-group",u.dataset.readingGroup=n;let h=document.createElement("div");h.className="tour-outline-heading";let y=document.createElement("div");y.className="tour-outline-children",y.id=`outline-${encodeURIComponent(n)}`;let v=`${t.zoom?.mode||"tour"}:${n}`,k=an("\u25BE",`Expand or collapse ${o}`,()=>{C.has(v)?C.delete(v):C.add(v),L()});k.className="tour-outline-toggle",k.setAttribute("aria-controls",y.id);let L=()=>{y.hidden=C.has(v),k.setAttribute("aria-expanded",String(!y.hidden)),k.textContent=y.hidden?"\u25B8":"\u25BE"};L();let F=an(o,`Read ${o}`,l);return F.className=d,F.dataset.readingLink=n,h.append(k,F),u.append(h,y),{group:u,children:y,link:F,toggle:k}}function Fo(){let n=document.getElementById("tour-audio-settings");n&&(n.hidden=!n.hidden,cn())}function cn(){It();let n=document.getElementById("tour-narration"),o=document.getElementById("tour-audio-settings");if(n){let d=!!(o&&!o.hidden);n.setAttribute("aria-expanded",String(d)),n.textContent=d?"\u203A":"\u2039 Narration",n.title=d?"Hide narration controls":"Show narration controls",n.setAttribute("aria-label",n.title)}}function ce(){let n=t.tour?.scenes[t.activeSceneIndex],o=new URLSearchParams(window.location.search);for(let l of["from","to","commits","scope","commit","file"])o.delete(l);if(t.zoom&&o.set("mode",t.zoom.mode),t.zoom&&!ee()){for(let l of["scene","step","view"])o.delete(l);t.zoom.mode==="compare"&&t.compare&&(o.set("commits",t.compare.commits.join(",")),t.compare.path&&o.set("scope",t.compare.path)),t.zoom.mode==="history"&&t.historyCommit&&o.set("commit",t.historyCommit),t.activeTourFilePath&&o.set("file",t.zoom.mode==="history"?t.historyPath:t.activeTourFilePath),window.history.replaceState(null,"",`${window.location.pathname}?${o.toString()}`);return}if(!n)return;o.set("scene",n.id);let d=ke(n)?n.steps[t.activeStepIndex]:null;d?o.set("step",d.id):o.delete("step"),t.directoryEvidence&&t.activeTourFilePath?o.set("file",t.activeTourFilePath):o.delete("file"),t.narrativeParent?o.set("view",t.narrativeParent):d&&t.sceneIntroVisible?o.set("view","overview"):o.delete("view"),window.history.replaceState(null,"",`${window.location.pathname}?${o.toString()}`)}function Jn(n=t.tour?.scenes[t.activeSceneIndex],o=t.activeStepIndex){if(!n||!ke(n))return null;let d=n.steps[o];if(!d)return null;if(n.kind==="walkthrough"){let u=d.focus;return!u?.path||!Number.isInteger(u.startLine)?null:{filePath:u.path,sideIndex:u.revision==="base"?0:1,lineNumber:u.startLine,label:`${u.path}:${u.startLine}`}}let l=d.startLine;if(!Number.isInteger(l)){let u=rt(n,d.file),h=u?.panels?.[d.pairIndex],y=u?.panels?.[d.pairIndex+1];if(h&&y){let v=ie(h.content,y.content);l=Sn(v,d.side)?.startLine}}return!d.file||!Number.isInteger(l)?null:{filePath:d.file,sideIndex:d.pairIndex+(d.side==="right"?1:0),lineNumber:l,label:`${d.file}:${l}`}}function Bo(){let n=Jn(),o=t.tour?.scenes[t.activeSceneIndex];if(t.sceneIntroVisible||!n||!o)return!1;if(R.interruptForExploration(),t.activeTourFilePath!==n.filePath){let d=t.tour.files.findIndex(u=>u.kind==="text-diff"&&u.path===n.filePath);if(d<0||!(ae(o)?nt(d):rn(d,!1)))return!1}return window.requestAnimationFrame(()=>W({type:"revealSearchResult",sideIndex:n.sideIndex,lineNumber:n.lineNumber,startColumn:1,endColumn:1})),!0}function Yn(n,o,d){dn(),document.getElementById("tour-narrative").hidden=!1,document.getElementById("tour-breadcrumb").textContent=t.narrativeParent==="tour"?t.tour.title:t.narrativeParent==="chapter"?o.chapter?.title||"Chapter":t.sceneIntroVisible?`Scene ${o.sceneNumber} of ${o.sceneCount} \xB7 Overview`:Oo(o,n,t.activeStepIndex);let l=S.get(`scene:${n.id}`),u=ke(n)?n.steps[t.activeStepIndex]:null,h=u&&S.get(`step:${n.id}:${u.id}`);for(let y of[l,h].filter(Boolean))y.querySelectorAll("[data-reading-field]").forEach(v=>{qo(v,v.dataset.readingText,{field:v.dataset.readingField,...v.dataset.itemIndex!==void 0?{itemIndex:Number(v.dataset.itemIndex)}:{}},d)});cn()}function dn(){if(N===t.tour)return;N=t.tour,x=Fr(t.tour),S.clear();let n=document.getElementById("tour-narrative-content"),o=(l,u,h,y,v,k)=>{let L=document.createElement(u);return L.className=h,L.replaceChildren(...An(document,y||"")),v&&(L.dataset.readingField=v,L.dataset.readingText=y||"",k!==void 0&&(L.dataset.itemIndex=String(k))),l.append(L),L},d=(l,u,h)=>{if(o(l,"p","tour-narrative-summary",u.summary,h?"summary":null),u.bullets.length){let y=document.createElement("ul");y.className="tour-narrative-bullets",u.bullets.forEach((v,k)=>o(y,"li","",v,h?"bullet":null,k)),l.append(y)}u.takeaway&&o(l,"p","tour-narrative-takeaway",u.takeaway,h?"takeaway":null)};for(let l of x){let u=document.createElement("section");u.className="tour-reading-item",u.dataset.readingKey=l.key,u.dataset.readingKind=l.kind,u.dataset.sceneIndex=String(l.sceneIndex),u.dataset.stepIndex=String(l.stepIndex);let h=t.tour.scenes[l.sceneIndex];if(l.kind==="title")o(u,"h1","tour-document-title",t.tour.title),o(u,"p","tour-document-meta",`${Ue(t.tour.range.mergeBaseOid)} \u2192 ${Ue(t.tour.range.headOid)}`);else if(l.kind==="chapter")o(u,"h2","tour-document-chapter",t.tour.chapters.find(y=>y.id===l.chapterId)?.title);else if(l.kind==="scene"){o(u,"h2","tour-scene-heading",h.title,"scene-title"),d(u,h,!0);let y=o(u,"div","tour-narrative-tags","");h.tags.forEach(v=>o(y,"span","",v))}else{let y=h.steps[l.stepIndex],v=document.createElement("details");v.className="tour-step-context",o(v,"summary","",`Scene context \xB7 ${h.title}`);let k=o(v,"div","tour-step-context-body","");d(k,h,!1),u.append(v);let L=h.kind==="deconstructed-diff"?`Stage ${(y.stageIndex??y.pairIndex)+1} \xB7 `:"";L&&o(u,"div","tour-narrative-chapter",L),o(u,"h3","tour-step-title",y.title,"step-title"),o(u,"p","tour-step-body",y.body,"step-body");let F=o(u,"div","tour-step-requirement","");zo(F,y.requirement),y.connection&&(o(u,"p","tour-connection",`${y.connection.from.path} \u2192 ${y.connection.to.path}`),o(u,"p","tour-connection",y.connection.label,"connection"));let G=Jn(h,l.stepIndex);if(G){let j=o(u,"div","tour-step-code","");o(j,"span","tour-step-code-location",G.label);let U=an("Show in code",`Show ${G.label}`,()=>{st(l),Bo()});U.className="tour-show-in-code",j.append(U)}}S.set(l.key,u)}n.replaceChildren(...S.values()),$=n.scrollTop}function Zn(){for(let[d,l]of S)l.classList.toggle("is-active",d===t.readingKey);document.querySelectorAll("[data-reading-link], .tour-outline-step, #tour-title").forEach(d=>{let l=t.tour?.scenes[t.activeSceneIndex],u=l&&ke(l)?l.steps[Number(d.dataset.stepIndex)]:null,y=(d.id==="tour-title"?"title":d.dataset.readingLink||(u&&d.dataset.sceneId===l.id?`step:${l.id}:${u.id}`:null))===t.readingKey;d.classList.toggle("is-active",y),y?d.setAttribute("aria-current","location"):d.removeAttribute("aria-current")}),document.querySelectorAll(".tour-outline-group").forEach(d=>{d.classList.toggle("has-active",!!d.querySelector('[aria-current="location"]'))});let n=document.getElementById("tour-scenes"),o=n?.querySelector('[aria-current="location"]');for(;o&&!o.getClientRects().length;)o=o.closest(".tour-outline-children[hidden]")?.parentElement.querySelector(":scope > .tour-outline-heading [data-reading-link]");if(o&&n.clientHeight){let d=n.getBoundingClientRect(),l=o.getBoundingClientRect();l.top<d.top?n.scrollTop+=l.top-d.top:l.bottom>d.bottom&&(n.scrollTop+=l.bottom-d.bottom)}}function _o(n){let o=document.getElementById("tour-narrative-content"),d=S.get(n);!o||!d||(o.scrollTop+=d.getBoundingClientRect().top-o.getBoundingClientRect().top,$=o.scrollTop)}function st(n,o=!1){return oe(n.sceneIndex,n.stepIndex,{readingKey:n.key,showIntro:n.kind!=="step",userNavigation:!0,fromReadingScroll:o})}function Uo(){P===null&&(P=window.requestAnimationFrame(()=>{if(P=null,!ee()||t.zoomSwitching)return;let n=document.getElementById("tour-narrative-content");if($!==null&&Math.abs(n.scrollTop-$)<2)return;$=null;let o=n.getBoundingClientRect().top+24,d=x[0];for(let l of x){if(S.get(l.key).getBoundingClientRect().top>o)break;d=l}d&&d.key!==t.readingKey&&st(d,!0)}))}function Ho(n){let o=[];return n.source&&o.push(n.source),n.confidence&&o.push(`${n.confidence} confidence`),o.join(" \xB7 ")}function zo(n,o){if(!o){n.hidden=!0,n.replaceChildren(),n.removeAttribute("title");return}let d=document.createElement("span");d.className="tour-requirement-chip",d.dataset.status=o.status||"unspecified",d.textContent=o.status?`${o.id} \xB7 ${o.status}`:o.id;let l=document.createElement("span");l.className="tour-requirement-text",l.textContent=o.text;let u=[d,l],h=Ho(o);if(h){let y=document.createElement("span");y.className="tour-requirement-meta",y.textContent=h,u.push(y)}n.replaceChildren(...u),n.title=[`${o.id}: ${o.text}`,h].filter(Boolean).join(" \u2014 "),n.hidden=!1}function qo(n,o,d,l,u={}){let h=l?.segments.filter(v=>v.source.field===d.field&&v.source.itemIndex===d.itemIndex)||[],y=[];u.prefix&&y.push(document.createTextNode(u.prefix)),y.push(...An(document,o,h)),u.suffix&&y.push(document.createTextNode(u.suffix)),n.replaceChildren(...y)}function Qn(){R.stop();let n=Er();t.mode="diff",t.comparisonId+=1,t.left={name:n.leftFileName,content:n.leftContent},t.right={name:n.rightFileName,content:n.rightContent},me("Loaded sample diff."),W({type:"showDiff",file1:t.left.name,file2:t.right.name,comparisonId:`web-${t.comparisonId}`,leftContent:t.left.content,rightContent:t.right.content,diffModel:ie(t.left.content,t.right.content),history:null})}async function Wo(n){R.stop();let[o,d]=n,[l,u]=await Promise.all([o.text(),d.text()]);t.mode="diff",t.comparisonId+=1,t.left={name:o.name,content:l},t.right={name:d.name,content:u},me(`Loaded ${o.name} and ${d.name}.`),W({type:"showDiff",file1:o.name,file2:d.name,comparisonId:`web-${t.comparisonId}`,leftContent:l,rightContent:u,diffModel:ie(l,u),history:null})}async function jo(n){R.stop();let o=await Promise.all(n.map(async(d,l)=>{let u=await d.text();return{id:`web-panel-${l}`,label:d.name,content:u,savedContent:u,dirty:!1,editable:!0}}));t.mode="multi-diff",me(`Loaded ${o.length}-panel diff for ${o.map(d=>d.label).join(", ")}.`),W({type:"showMultiDiff",panels:o,pairs:o.slice(0,-1).map((d,l)=>({leftIndex:l,rightIndex:l+1,diffModel:ie(d.content,o[l+1].content)}))})}function me(n){let o=document.getElementById("web-status");o&&(o.textContent=n)}})();})();
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