@inkeep/open-knowledge 0.0.0-dev-20260428030816 → 0.0.0-dev-20260428055023

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 (39) hide show
  1. package/dist/cli.mjs +4 -4
  2. package/dist/constants-D9m8dzHP.mjs +2 -0
  3. package/dist/{dist-DlLqW1l-.mjs → dist-CC_QsyED.mjs} +1 -1
  4. package/dist/{dist-BVi1kLgS.mjs → dist-DoVDgyml.mjs} +11 -11
  5. package/dist/index.mjs +1 -1
  6. package/dist/init-D-fChIzY.mjs +1 -0
  7. package/dist/init-D3711KPb.mjs +1 -0
  8. package/dist/{init-lR-iOYyJ.mjs → init-DNs9ffRY.mjs} +3 -3
  9. package/dist/{init-DzmV7EWn.mjs → init-DVCAi_du.mjs} +2 -2
  10. package/dist/loader-Bc5pJk1m.mjs +1 -0
  11. package/dist/{loader-Dftbh71h.mjs → loader-C9LBHYiT.mjs} +2 -2
  12. package/dist/paths-CDgE-NKk.mjs +1 -0
  13. package/dist/{paths-9SFXgdez.mjs → paths-zc2uvZxY.mjs} +2 -2
  14. package/dist/{preview-BWEEPmtf.mjs → preview-CPxqdDCe.mjs} +2 -2
  15. package/dist/preview-EfkiZS-n.mjs +1 -0
  16. package/dist/public/assets/{ActivityModeContent-QSE28ToP.js → ActivityModeContent-JeYMJ8N-.js} +1 -1
  17. package/dist/public/assets/{DocumentContext-C7zXwLGg.js → DocumentContext-D9TYylem.js} +1 -1
  18. package/dist/public/assets/McpConsentDialogBody-BNfu0z8x.js +1 -0
  19. package/dist/public/assets/{SourceEditor-B5_U1uud.js → SourceEditor-DBzpEf4D.js} +2 -2
  20. package/dist/public/assets/{clipboard-BcHcwwH2.js → clipboard-C0HbTlCM.js} +3 -3
  21. package/dist/public/assets/{index-CfLPPlu0.js → index-CjMTCid5.js} +72 -72
  22. package/dist/public/index.html +3 -3
  23. package/dist/server-lock-QiPvrcO9-A3jWEIJ6.mjs +2 -0
  24. package/dist/server-lock-QiPvrcO9-CB330FUa.mjs +1 -0
  25. package/dist/src-CccGTsc2.mjs +1 -0
  26. package/dist/{start-YQGf2koi.mjs → start-BnROvKwD.mjs} +2 -2
  27. package/dist/start-DdFbQnn0.mjs +1 -0
  28. package/package.json +1 -1
  29. package/dist/constants-BFC8WUGR.mjs +0 -2
  30. package/dist/init-CpubW-xy.mjs +0 -1
  31. package/dist/init-Kk_OD9gS.mjs +0 -1
  32. package/dist/loader-BVRsmTqA.mjs +0 -1
  33. package/dist/paths-tkdx_ODM.mjs +0 -1
  34. package/dist/preview-BJIwF_YN.mjs +0 -1
  35. package/dist/public/assets/McpConsentDialogBody-FBruOF3J.js +0 -1
  36. package/dist/server-lock-CH0GCP_4-DXqutMlt.mjs +0 -2
  37. package/dist/server-lock-CH0GCP_4-MazZqjDk.mjs +0 -1
  38. package/dist/src-CEe0tBjV.mjs +0 -1
  39. package/dist/start-Bt3IMsVN.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{t as require_dist$1}from"./dist-BCyi1oM7.mjs";import{A as normalizeBridge,C as getFrontmatter,D as iconFromClientName,E as getWikiLinkText,F as toWikiLinkSlug,M as resolveInternalHref,N as sharedExtensions,O as isOrphanMode,P as stripFrontmatter,S as defaultScheduler,T as getParseHealth,Z as string,_ as applyIncrementalDiff,_t as Fragment,a as CC1BranchSwitchedPayloadSchema,b as colorFromSeed,c as CC1ServerInfoPayloadSchema,d as CC1_CHANNEL_SERVER_INFO,f as MarkdownManager,g as applyFastDiff,gt as PluginKey,h as SYSTEM_DOC_NAME,ht as getSchema,i as BridgeMergeContentLossError,j as prependFrontmatter,k as mergeThreeWay,l as CC1_CHANNEL_BRANCH_SWITCHED,n as ALLOWED_IMAGE_MIME_TYPES,o as CC1DerivedViewPayloadSchema,p as OK_DIR,q as object,r as ASSET_EXTENSIONS,s as CC1DiskAckPayloadSchema,t as AGENT_ICON_COLORS,u as CC1_CHANNEL_DISK_ACK,v as classifyMarkdownHref,vt as VFileMessage,w as getHeadingSlug,x as createCodeFenceTracker,y as classifyWikiLinkTarget}from"./dist-DRC09WNZ.mjs";import{a as isProcessAlive,c as readServerLock,f as updateProcessLockPort,i as acquireServerLock,l as releaseProcessLock,r as acquireProcessLock,s as readProcessLock,t as ProcessLockCollisionError,u as releaseServerLock}from"./server-lock-CH0GCP_4-DXqutMlt.mjs";import{a as require_src$15,i as esm_default,r as withParentLock,t as createGitInstance}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BFkWzFey.mjs";import{r as diffLines,t as createPatch}from"./libesm-DC4M2SkF.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import{basename,dirname,extname,join,posix,relative,resolve,sep}from"node:path";import{closeSync,createReadStream,createWriteStream,existsSync,lstatSync,mkdirSync,openSync,readFileSync,readdirSync,realpathSync,renameSync,rmSync,statSync,unlinkSync,writeFileSync,writeSync}from"node:fs";import{homedir,hostname,tmpdir}from"node:os";import{promisify}from"node:util";import{Readable}from"stream";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import*as zlib$1 from"zlib";import{setTimeout as setTimeout$1}from"node:timers/promises";import{mkdir,readFile,readdir,realpath,rename,writeFile}from"node:fs/promises";import{createServer}from"node:http";var require_err_helpers=__commonJSMin$1(((e,t)=>{let n=e=>e&&typeof e.message==`string`,r=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return n(t)?t:void 0}else return n(t)?t:void 0},i=(e,t)=>{if(!n(e))return``;let a=e.stack||``;if(t.has(e))return a+`
1
+ import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{t as require_dist$1}from"./dist-BCyi1oM7.mjs";import{A as normalizeBridge,C as getFrontmatter,D as iconFromClientName,E as getWikiLinkText,F as toWikiLinkSlug,M as resolveInternalHref,N as sharedExtensions,O as isOrphanMode,P as stripFrontmatter,S as defaultScheduler,T as getParseHealth,Z as string,_ as applyIncrementalDiff,_t as Fragment,a as CC1BranchSwitchedPayloadSchema,b as colorFromSeed,c as CC1ServerInfoPayloadSchema,d as CC1_CHANNEL_SERVER_INFO,f as MarkdownManager,g as applyFastDiff,gt as PluginKey,h as SYSTEM_DOC_NAME,ht as getSchema,i as BridgeMergeContentLossError,j as prependFrontmatter,k as mergeThreeWay,l as CC1_CHANNEL_BRANCH_SWITCHED,n as ALLOWED_IMAGE_MIME_TYPES,o as CC1DerivedViewPayloadSchema,p as OK_DIR,q as object,r as ASSET_EXTENSIONS,s as CC1DiskAckPayloadSchema,t as AGENT_ICON_COLORS,u as CC1_CHANNEL_DISK_ACK,v as classifyMarkdownHref,vt as VFileMessage,w as getHeadingSlug,x as createCodeFenceTracker,y as classifyWikiLinkTarget}from"./dist-DRC09WNZ.mjs";import{a as isProcessAlive,c as readServerLock,f as updateProcessLockPort,i as acquireServerLock,l as releaseProcessLock,r as acquireProcessLock,s as readProcessLock,t as ProcessLockCollisionError,u as releaseServerLock}from"./server-lock-QiPvrcO9-A3jWEIJ6.mjs";import{a as require_src$15,i as esm_default,r as withParentLock,t as createGitInstance}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BFkWzFey.mjs";import{r as diffLines,t as createPatch}from"./libesm-DC4M2SkF.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import{basename,dirname,extname,join,posix,relative,resolve,sep}from"node:path";import{closeSync,createReadStream,createWriteStream,existsSync,lstatSync,mkdirSync,openSync,readFileSync,readdirSync,realpathSync,renameSync,rmSync,statSync,unlinkSync,writeFileSync,writeSync}from"node:fs";import{homedir,hostname,tmpdir}from"node:os";import{promisify}from"node:util";import{Readable}from"stream";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import*as zlib$1 from"zlib";import{setTimeout as setTimeout$1}from"node:timers/promises";import{mkdir,readFile,readdir,realpath,rename,writeFile}from"node:fs/promises";import{createServer}from"node:http";var require_err_helpers=__commonJSMin$1(((e,t)=>{let n=e=>e&&typeof e.message==`string`,r=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return n(t)?t:void 0}else return n(t)?t:void 0},i=(e,t)=>{if(!n(e))return``;let a=e.stack||``;if(t.has(e))return a+`
2
2
  causes have become circular...`;let o=r(e);return o?(t.add(e),a+`
3
3
  caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?``:e.message||``;if(t.has(e))return a+`: ...`;let s=r(e);if(s){t.add(e);let n=typeof e.cause==`function`;return a+(n?``:`: `)+o(s,t,n)}else return a};t.exports={isErrorLike:n,getErrorCause:r,stackWithCauses:a,messageWithCauses:e=>o(e,new Set)}})),require_err_proto=__commonJSMin$1(((e,t)=>{let n=Symbol(`circular-ref-tag`),r=Symbol(`pino-raw-err-ref`),i=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[r]},set:function(e){this[r]=e}}});Object.defineProperty(i,r,{writable:!0,value:{}}),t.exports={pinoErrProto:i,pinoErrorSymbols:{seen:n,rawSymbol:r}}})),require_err=__commonJSMin$1(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=require_err_helpers(),{pinoErrProto:a,pinoErrorSymbols:o}=require_err_proto(),{seen:s}=o,{toString:c}=Object.prototype;function l(e){if(!i(e))return e;e[s]=void 0;let t=Object.create(a);t.type=c.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=n(e),t.stack=r(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>l(e)));for(let n in e)if(t[n]===void 0){let r=e[n];i(r)?n!==`cause`&&!Object.prototype.hasOwnProperty.call(r,s)&&(t[n]=l(r)):t[n]=r}return delete e[s],t.raw=e,t}})),require_err_with_cause=__commonJSMin$1(((e,t)=>{t.exports=s;let{isErrorLike:n}=require_err_helpers(),{pinoErrProto:r,pinoErrorSymbols:i}=require_err_proto(),{seen:a}=i,{toString:o}=Object.prototype;function s(e){if(!n(e))return e;e[a]=void 0;let t=Object.create(r);t.type=o.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>s(e))),n(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,a)&&(t.cause=s(e.cause));for(let r in e)if(t[r]===void 0){let i=e[r];n(i)?Object.prototype.hasOwnProperty.call(i,a)||(t[r]=s(i)):t[r]=i}return delete e[a],t.raw=e,t}})),require_req=__commonJSMin$1(((e,t)=>{t.exports={mapHttpRequest:a,reqSerializer:i};let n=Symbol(`pino-raw-req-ref`),r=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=e.info||e.socket,n=Object.create(r);if(n.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),n.method=e.method,e.originalUrl)n.url=e.originalUrl;else{let t=e.path;n.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(n.query=e.query),e.params&&(n.params=e.params),n.headers=e.headers,n.remoteAddress=t&&t.remoteAddress,n.remotePort=t&&t.remotePort,n.raw=e.raw||e,n}function a(e){return{req:i(e)}}})),require_res=__commonJSMin$1(((e,t)=>{t.exports={mapHttpResponse:a,resSerializer:i};let n=Symbol(`pino-raw-res-ref`),r=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=Object.create(r);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function a(e){return{res:i(e)}}})),require_pino_std_serializers=__commonJSMin$1(((e,t)=>{let n=require_err(),r=require_err_with_cause(),i=require_req(),a=require_res();t.exports={err:n,errWithCause:r,mapHttpRequest:i.mapHttpRequest,mapHttpResponse:a.mapHttpResponse,req:i.reqSerializer,res:a.resSerializer,wrapErrorSerializer:function(e){return e===n?e:function(t){return e(n(t))}},wrapRequestSerializer:function(e){return e===i.reqSerializer?e:function(t){return e(i.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===a.resSerializer?e:function(t){return e(a.resSerializer(t))}}}})),require_caller=__commonJSMin$1(((e,t)=>{function n(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=n;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),i=[];for(let e of r)e&&i.push(e.getFileName());return i}})),require_redact=__commonJSMin$1(((e,t)=>{function n(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let r=0;r<e.length;r++)t[r]=n(e[r]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=n(e[r]));return t}return e}function r(e){let t=[],n=``,r=!1,i=!1,a=``;for(let o=0;o<e.length;o++){let s=e[o];!r&&s===`.`?n&&=(t.push(n),``):s===`[`?(n&&=(t.push(n),``),r=!0):s===`]`&&r?(t.push(n),n=``,r=!1,i=!1):(s===`"`||s===`'`)&&r?i?s===a?(i=!1,a=``):n+=s:(i=!0,a=s):n+=s}return n&&t.push(n),t}function i(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(typeof r!=`object`||!r||!(n in r)||typeof r[n]!=`object`||r[n]===null)return!1;r=r[n]}let i=t[t.length-1];if(i===`*`){if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=n;else if(typeof r==`object`&&r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=n)}else typeof r==`object`&&r&&i in r&&Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n);return!0}function a(e,t){let n=e;for(let e=0;e<t.length-1;e++){let r=t[e];if(typeof n!=`object`||!n||!(r in n)||typeof n[r]!=`object`||n[r]===null)return!1;n=n[r]}let r=t[t.length-1];if(r===`*`){if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=void 0;else if(typeof n==`object`&&n)for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&delete n[e]}else typeof n==`object`&&n&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}let o=Symbol(`PATH_NOT_FOUND`);function s(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n||!(e in n))return o;n=n[e]}return n}function c(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n)return;n=n[e]}return n}function l(e,t,n,c=!1){for(let l of t){let t=r(l);if(t.includes(`*`))u(e,t,n,l,c);else if(c)a(e,t);else{let r=s(e,t);if(r===o)continue;i(e,t,typeof n==`function`?n(r,t):n)}}}function u(e,t,n,r,i=!1){let a=t.indexOf(`*`);if(a===t.length-1){let r=t.slice(0,-1),a=e;for(let e of r){if(typeof a!=`object`||!a||!a)return;a=a[e]}if(Array.isArray(a))if(i)for(let e=0;e<a.length;e++)a[e]=void 0;else for(let e=0;e<a.length;e++){let t=[...r,e.toString()],i=typeof n==`function`?n(a[e],t):n;a[e]=i}else if(typeof a==`object`&&a)if(i){let e=[];for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&e.push(t);for(let t of e)delete a[t]}else for(let e in a){let t=[...r,e],i=typeof n==`function`?n(a[e],t):n;a[e]=i}}else d(e,t,n,a,r,i)}function d(e,t,n,r,o,s=!1){let l=t.slice(0,r),d=t.slice(r+1),f=[];function p(e,t){if(t===l.length){if(Array.isArray(e))for(let n=0;n<e.length;n++)f[t]=n.toString(),p(e[n],t+1);else if(typeof e==`object`&&e)for(let n in e)f[t]=n,p(e[n],t+1)}else if(t<l.length){let n=l[t];e&&typeof e==`object`&&e&&n in e&&(f[t]=n,p(e[n],t+1))}else d.includes(`*`)?u(e,d,typeof n==`function`?(e,r)=>n(e,[...f.slice(0,t),...r]):n,o,s):s?a(e,d):i(e,d,typeof n==`function`?n(c(e,d),[...f.slice(0,t),...d]):n)}if(l.length===0)p(e,0);else{let t=e;for(let e=0;e<l.length;e++){let n=l[e];if(typeof t!=`object`||!t||!t)return;t=t[n],f[e]=n}t!=null&&p(t,l.length)}}function f(e){if(e.length===0)return null;let t=new Map;for(let n of e){let e=r(n),i=t;for(let t=0;t<e.length;t++){let n=e[t];i.has(n)||i.set(n,new Map),i=i.get(n)}}return t}function p(e,t){if(!t)return e;function n(e,t,r=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let r=[];for(let i=0;i<e.length;i++){let a=i.toString();t.has(a)||t.has(`*`)?r[i]=n(e[i],t.get(a)||t.get(`*`)):r[i]=e[i]}return r}let i=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t.has(r)||t.has(`*`)?i[r]=n(e[r],t.get(r)||t.get(`*`)):i[r]=e[r]);return i}return n(e,t)}function m(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,n=!1,r=``;for(let i=0;i<e.length;i++){let a=e[i];if((a===`"`||a===`'`)&&t>0)n?a===r&&(n=!1,r=``):(n=!0,r=a);else if(a===`[`&&!n)t++;else if(a===`]`&&!n&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function h(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)m(t)}function g(e={}){let{paths:t=[],censor:r=`[REDACTED]`,serialize:i=JSON.stringify,strict:a=!0,remove:o=!1}=e;h(t);let s=f(t);return function(e){if(a&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return i?i(e):e;let c=p(e,s),u=e,d=r;return typeof r==`function`&&(d=r),l(c,t,d,o),i===!1?(c.restore=function(){return n(u)},c):typeof i==`function`?i(c):JSON.stringify(c)}}t.exports=g})),require_symbols=__commonJSMin$1(((e,t)=>{let n=Symbol(`pino.setLevel`),r=Symbol(`pino.getLevel`),i=Symbol(`pino.levelVal`),a=Symbol(`pino.levelComp`),o=Symbol(`pino.useLevelLabels`),s=Symbol(`pino.useOnlyCustomLevels`),c=Symbol(`pino.mixin`),l=Symbol(`pino.lsCache`),u=Symbol(`pino.chindings`),d=Symbol(`pino.asJson`),f=Symbol(`pino.write`),p=Symbol(`pino.redactFmt`),m=Symbol(`pino.time`),h=Symbol(`pino.timeSliceIndex`),g=Symbol(`pino.stream`),_=Symbol(`pino.stringify`),v=Symbol(`pino.stringifySafe`),y=Symbol(`pino.stringifiers`),b=Symbol(`pino.end`),x=Symbol(`pino.formatOpts`),S=Symbol(`pino.messageKey`),C=Symbol(`pino.errorKey`),w=Symbol(`pino.nestedKey`),T=Symbol(`pino.nestedKeyStr`),E=Symbol(`pino.mixinMergeStrategy`),D=Symbol(`pino.msgPrefix`),O=Symbol(`pino.wildcardFirst`),k=Symbol.for(`pino.serializers`),A=Symbol.for(`pino.formatters`),j=Symbol.for(`pino.hooks`);t.exports={setLevelSym:n,getLevelSym:r,levelValSym:i,levelCompSym:a,useLevelLabelsSym:o,mixinSym:c,lsCacheSym:l,chindingsSym:u,asJsonSym:d,writeSym:f,serializersSym:k,redactFmtSym:p,timeSym:m,timeSliceIndexSym:h,streamSym:g,stringifySym:_,stringifySafeSym:v,stringifiersSym:y,endSym:b,formatOptsSym:x,messageKeySym:S,errorKeySym:C,nestedKeySym:w,wildcardFirstSym:O,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:s,formattersSym:A,hooksSym:j,nestedKeyStrSym:T,mixinMergeStrategySym:E,msgPrefixSym:D}})),require_redaction=__commonJSMin$1(((e,t)=>{let n=require_redact(),{redactFmtSym:r,wildcardFirstSym:i}=require_symbols(),a=/[^.[\]]+|\[([^[\]]*?)\]/g,o=`[Redacted]`,s=!1;function c(e,t){let{paths:o,censor:s,remove:c}=l(e),u=o.reduce((e,t)=>{a.lastIndex=0;let n=a.exec(t),r=a.exec(t),o=n[1]===void 0?n[0]:n[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(o===`*`&&(o=i),r===null)return e[o]=null,e;if(e[o]===null)return e;let{index:s}=r,c=`${t.substr(s,t.length-1)}`;return e[o]=e[o]||[],o!==i&&e[o].length===0&&e[o].push(...e[i]||[]),o===i&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(c)}),e[o].push(c),e},{}),d={[r]:n({paths:o,censor:s,serialize:t,strict:!1,remove:c})},f=(...e)=>t(typeof s==`function`?s(...e):s);return[...Object.keys(u),...Object.getOwnPropertySymbols(u)].reduce((e,r)=>{if(u[r]===null)e[r]=e=>f(e,[r]);else{let i=typeof s==`function`?(e,t)=>s(e,[r,...t]):s;e[r]=n({paths:u[r],censor:i,serialize:t,strict:!1,remove:c})}return e},d)}function l(e){if(Array.isArray(e))return e={paths:e,censor:o},e;let{paths:t,censor:n=o,remove:r}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return r===!0&&(n=void 0),{paths:t,censor:n,remove:r}}t.exports=c})),require_time$4=__commonJSMin$1(((e,t)=>{let n=()=>``,r=()=>`,"time":${Date.now()}`,i=()=>`,"time":${Math.round(Date.now()/1e3)}`,a=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,o=1000000n,s=1000000000n,c=BigInt(Date.now())*1000000n,l=process.hrtime.bigint();t.exports={nullTime:n,epochTime:r,unixTime:i,isoTime:a,isoTimeNano:()=>{let e=c+(process.hrtime.bigint()-l),t=e/s,n=e%s,r=Number(t*1000n+n/1000000n),i=new Date(r);return`,"time":"${i.getUTCFullYear()}-${(i.getUTCMonth()+1).toString().padStart(2,`0`)}-${i.getUTCDate().toString().padStart(2,`0`)}T${i.getUTCHours().toString().padStart(2,`0`)}:${i.getUTCMinutes().toString().padStart(2,`0`)}:${i.getUTCSeconds().toString().padStart(2,`0`)}.${n.toString().padStart(9,`0`)}Z"`}}})),require_quick_format_unescaped=__commonJSMin$1(((e,t)=>{function n(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=r;function r(e,t,r){var i=r&&r.stringify||n,a=1;if(typeof e==`object`&&e){var o=t.length+a;if(o===1)return e;var s=Array(o);s[0]=i(e);for(var c=1;c<o;c++)s[c]=i(t[c]);return s.join(` `)}if(typeof e!=`string`)return e;var l=t.length;if(l===0)return e;for(var u=``,d=1-a,f=-1,p=e&&e.length||0,m=0;m<p;){if(e.charCodeAt(m)===37&&m+1<p){switch(f=f>-1?f:0,e.charCodeAt(m+1)){case 100:case 102:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Number(t[d]),f=m+2,m++;break;case 105:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Math.floor(Number(t[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||t[d]===void 0)break;f<m&&(u+=e.slice(f,m));var h=typeof t[d];if(h===`string`){u+=`'`+t[d]+`'`,f=m+2,m++;break}if(h===`function`){u+=t[d].name||`<anonymous>`,f=m+2,m++;break}u+=i(t[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=e.slice(f,m)),u+=String(t[d]),f=m+2,m++;break;case 37:f<m&&(u+=e.slice(f,m)),u+=`%`,f=m+2,m++,d--;break}++d}++m}return f===-1?e:(f<p&&(u+=e.slice(f)),u)}})),require_atomic_sleep=__commonJSMin$1(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function n(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=n}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),require_sonic_boom=__commonJSMin$1(((e,t)=>{let n=__require$1(`fs`),r=__require$1(`events`),i=__require$1(`util`).inherits,a=__require$1(`path`),o=require_atomic_sleep(),s=__require$1(`assert`),c=100,l=Buffer.allocUnsafe(0),u=16*1024,d=`buffer`,f=`utf8`,[p,m]=(process.versions.node||`0.0`).split(`.`).map(Number),h=p>=22&&m>=7;function g(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(n,r){if(n){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,n)}):t.emit(`error`,n);return}let i=t._reopening;t.fd=r,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():i&&process.nextTick(()=>t.emit(`drain`)))}let i=t.append?`a`:`w`,o=t.mode;if(t.sync)try{t.mkdir&&n.mkdirSync(a.dirname(e),{recursive:!0}),r(null,n.openSync(e,i,o))}catch(e){throw r(e),e}else t.mkdir?n.mkdir(a.dirname(e),{recursive:!0},t=>{if(t)return r(t);n.open(e,i,o,r)}):n.open(e,i,o,r)}function _(e){if(!(this instanceof _))return new _(e);let{fd:t,dest:r,minLength:i,maxLength:a,maxWrite:s,periodicFlush:c,sync:u,append:p=!0,mkdir:m,retryEAGAIN:h,fsync:b,contentMode:C,mode:j}=e||{};t||=r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=a||0,this.maxWrite=s||16384,this._periodicFlush=c||0,this._periodicFlushTimer=void 0,this.sync=u||!1,this.writable=!0,this._fsync=b||!1,this.append=p||!1,this.mode=j,this.retryEAGAIN=h||(()=>!0),this.mkdir=m||!1;let M,N;if(C===d)this._writingBuf=l,this.write=S,this.flush=T,this.flushSync=D,this._actualWrite=k,M=()=>n.writeSync(this.fd,this._writingBuf),N=()=>n.write(this.fd,this._writingBuf,this.release);else if(C===void 0||C===f)this._writingBuf=``,this.write=x,this.flush=w,this.flushSync=E,this._actualWrite=O,M=()=>Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`),N=()=>Buffer.isBuffer(this._writingBuf)?n.write(this.fd,this._writingBuf,this.release):n.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${f}" and "${d}", but passed ${C}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)g(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{o(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(N,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let r=v(this._writingBuf,this._len,t);if(this._len=r.len,this._writingBuf=r.writingBuf,this._writingBuf.length){if(!this.sync){N();return}try{do{let e=M(),t=v(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&n.fsyncSync(this.fd);let i=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):i>this.minLength?this._actualWrite():this._ending?i>0?this._actualWrite():(this._writing=!1,A(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(y,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function v(e,t,n){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-n,0),e=e.subarray(n),{writingBuf:e,len:t}}function y(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}i(_,r);function b(e,t){return e.length===0?l:e.length===1?e[0]:Buffer.concat(e,t)}function x(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),n=this._len+t,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+t>this.maxWrite?r.push(e):r[r.length-1]+=e,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function S(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,n=this._bufs,r=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(n.length===0||r[r.length-1]+e.length>this.maxWrite?(n.push([e]),r.push(e.length)):(n[n.length-1].push(e),r[r.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function C(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{n.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,r)},r=n=>{this._flushPending=!1,e(n),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,r)}function w(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&C.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function T(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&C.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}_.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&n.close(t,e=>{if(e)return this.emit(`error`,e)})}),g(this.file,this)},_.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():A(this)))};function E(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?n.writeSync(this.fd,e):n.writeSync(this.fd,e,`utf8`),r=v(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}try{n.fsyncSync(this.fd)}catch{}}function D(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=l);let e=l;for(;this._bufs.length||e.length;){e.length<=0&&(e=b(this._bufs[0],this._lens[0]));try{let t=n.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}}_.prototype.destroy=function(){this.destroyed||A(this)};function O(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else n.write(this.fd,this._writingBuf,e)}function k(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:b(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,n.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else h&&(this._writingBuf=Buffer.from(this._writingBuf)),n.write(this.fd,this._writingBuf,e)}function A(e){if(e.fd===-1){e.once(`ready`,A.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],s(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{n.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?n.close(e.fd,r):r()}function r(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}_.SonicBoom=_,_.default=_,t.exports=_})),require_on_exit_leak_free=__commonJSMin$1(((e,t)=>{let n={exit:[],beforeExit:[]},r={exit:c,beforeExit:l},i;function a(){i===void 0&&(i=new FinalizationRegistry(d))}function o(e){n[e].length>0||process.on(e,r[e])}function s(e){n[e].length>0||(process.removeListener(e,r[e]),n.exit.length===0&&n.beforeExit.length===0&&(i=void 0))}function c(){u(`exit`)}function l(){u(`beforeExit`)}function u(e){for(let t of n[e]){let n=t.deref(),r=t.fn;n!==void 0&&r(n,e)}n[e]=[]}function d(e){for(let t of[`exit`,`beforeExit`]){let r=n[t].indexOf(e);n[t].splice(r,r+1),s(t)}}function f(e,t,r){if(t===void 0)throw Error(`the object can't be undefined`);o(e);let s=new WeakRef(t);s.fn=r,a(),i.register(t,s),n[e].push(s)}function p(e,t){f(`exit`,e,t)}function m(e,t){f(`beforeExit`,e,t)}function h(e){if(i!==void 0){i.unregister(e);for(let t of[`exit`,`beforeExit`])n[t]=n[t].filter(t=>{let n=t.deref();return n&&n!==e}),s(t)}}t.exports={register:p,registerBeforeExit:m,unregister:h}})),require_package=__commonJSMin$1(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),require_wait=__commonJSMin$1(((e,t)=>{let n=1e4;function r(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{let i=Atomics.load(e,t);if(i===r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let c=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),l=Atomics.waitAsync(e,t,i,c);l.async?l.value.then(s):setImmediate(s)};s()}function i(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{if(Atomics.load(e,t)!==r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let i=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),c=Atomics.waitAsync(e,t,r,i);c.async?c.value.then(s):setImmediate(s)};s()}t.exports={wait:r,waitDiff:i}})),require_indexes=__commonJSMin$1(((e,t)=>{let n=4,r=8;t.exports={WRITE_INDEX:4,READ_INDEX:8}})),require_thread_stream=__commonJSMin$1(((e,t)=>{let{version:n}=require_package(),{EventEmitter:r}=__require$1(`events`),{Worker:i}=__require$1(`worker_threads`),{join:a}=__require$1(`path`),{pathToFileURL:o}=__require$1(`url`),{wait:s}=require_wait(),{WRITE_INDEX:c,READ_INDEX:l}=require_indexes(),u=__require$1(`buffer`),d=__require$1(`assert`),f=Symbol(`kImpl`),p=u.constants.MAX_STRING_LENGTH;var m=class{constructor(e){this._value=e}deref(){return this._value}},h=class{register(){}unregister(){}};let g=process.env.NODE_V8_COVERAGE?h:global.FinalizationRegistry||h,_=process.env.NODE_V8_COVERAGE?m:global.WeakRef||m,v=new g(e=>{e.exited||e.terminate()});function y(e,t){let{filename:r,workerData:s}=t,c=new i((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||a(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf(`file://`)===0?r:o(r).href,dataBuf:e[f].dataBuf,stateBuf:e[f].stateBuf,workerData:{$context:{threadStreamVersion:n},...s}}});return c.stream=new m(e),c.on(`message`,S),c.on(`exit`,C),v.register(e,c),c}function b(e){d(!e[f].sync),e[f].needDrain&&(e[f].needDrain=!1,e.emit(`drain`))}function x(e){let t=Atomics.load(e[f].state,c),n=e[f].data.length-t;if(n>0){if(e[f].buf.length===0){e[f].flushing=!1,e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e);return}let t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);r<=n?(e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);r>e[f].data.length;)n/=2,t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))}})}else if(n===0){if(t===0&&e[f].buf.length===0)return;e.flush(()=>{Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l),x(e)})}else E(e,Error(`overwritten`))}function S(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new _(t),t.flush(()=>{t[f].ready=!0,t.emit(`ready`)});break;case`ERROR`:E(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:E(t,Error(`this should not happen: `+e.code))}}function C(e){let t=this.stream.deref();t!==void 0&&(v.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,C),E(t,e===0?null:Error(`the worker thread exited`)))}var w=class extends r{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[f]={},this[f].stateBuf=new SharedArrayBuffer(128),this[f].state=new Int32Array(this[f].stateBuf),this[f].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[f].data=Buffer.from(this[f].dataBuf),this[f].sync=e.sync||!1,this[f].ending=!1,this[f].ended=!1,this[f].needDrain=!1,this[f].destroyed=!1,this[f].flushing=!1,this[f].ready=!1,this[f].finished=!1,this[f].errored=null,this[f].closed=!1,this[f].buf=``,this.worker=y(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[f].destroyed)return T(this,Error(`the worker has exited`)),!1;if(this[f].ending)return T(this,Error(`the worker is ending`)),!1;if(this[f].flushing&&this[f].buf.length+e.length>=p)try{k(this),this[f].flushing=!0}catch(e){return E(this,e),!1}if(this[f].buf+=e,this[f].sync)try{return k(this),!0}catch(e){return E(this,e),!1}return this[f].flushing||(this[f].flushing=!0,setImmediate(x,this)),this[f].needDrain=this[f].data.length-this[f].buf.length-Atomics.load(this[f].state,c)<=0,!this[f].needDrain}end(){this[f].destroyed||(this[f].ending=!0,O(this))}flush(e){if(this[f].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[f].state,c);s(this[f].state,l,t,1/0,(t,n)=>{if(t){E(this,t),process.nextTick(e,t);return}if(n===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[f].destroyed||(k(this),A(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[f].ready}get destroyed(){return this[f].destroyed}get closed(){return this[f].closed}get writable(){return!this[f].destroyed&&!this[f].ending}get writableEnded(){return this[f].ending}get writableFinished(){return this[f].finished}get writableNeedDrain(){return this[f].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[f].errored}};function T(e,t){setImmediate(()=>{e.emit(`error`,t)})}function E(e,t){e[f].destroyed||(e[f].destroyed=!0,t&&(e[f].errored=t,T(e,t)),e.worker.exited?setImmediate(()=>{e[f].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[f].closed=!0,e.emit(`close`)}))}function D(e,t,n){let r=Atomics.load(e[f].state,c),i=Buffer.byteLength(t);return e[f].data.write(t,r),Atomics.store(e[f].state,c,r+i),Atomics.notify(e[f].state,c),n(),!0}function O(e){if(!(e[f].ended||!e[f].ending||e[f].flushing)){e[f].ended=!0;try{e.flushSync();let t=Atomics.load(e[f].state,l);Atomics.store(e[f].state,c,-1),Atomics.notify(e[f].state,c);let n=0;for(;t!==-1;){if(Atomics.wait(e[f].state,l,t,1e3),t=Atomics.load(e[f].state,l),t===-2){E(e,Error(`end() failed`));return}if(++n===10){E(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[f].finished=!0,e.emit(`finish`)})}catch(t){E(e,t)}}}function k(e){let t=()=>{e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e)};for(e[f].flushing=!1;e[f].buf.length!==0;){let n=Atomics.load(e[f].state,c),r=e[f].data.length-n;if(r===0){A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);continue}else if(r<0)throw Error(`overwritten`);let i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);if(a<=r)e[f].buf=e[f].buf.slice(r),D(e,i,t);else{for(A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);a>e[f].buf.length;)r/=2,i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);e[f].buf=e[f].buf.slice(r),D(e,i,t)}}}function A(e){if(e[f].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[f].state,c),n=0;for(;;){let r=Atomics.load(e[f].state,l);if(r===-2)throw Error(`_flushSync failed`);if(r!==t)Atomics.wait(e[f].state,l,r,1e3);else break;if(++n===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=w})),require_transport=__commonJSMin$1(((e,t)=>{let{createRequire:n}=__require$1(`module`),{existsSync:r}=__require$1(`node:fs`),i=require_caller(),{join:a,isAbsolute:o,sep:s}=__require$1(`node:path`),{fileURLToPath:c}=__require$1(`node:url`),l=require_atomic_sleep(),u=require_on_exit_leak_free(),d=require_thread_stream();function f(e){u.register(e,v),u.registerBeforeExit(e,y),e.on(`close`,function(){u.unregister(e)})}function p(){let e=process.execArgv;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--import`||n===`--require`||n===`-r`||n.startsWith(`--import=`)||n.startsWith(`--require=`)||n.startsWith(`-r=`))return!0}return!1}function m(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let n=[],r=!1;for(let e=0;e<t.length;e++){let i=t[e];if(i===`--require`||i===`-r`||i===`--import`){let a=t[e+1];if(a&&h(a)){r=!0,e++;continue}n.push(i),a&&(n.push(a),e++);continue}if((i.startsWith(`--require=`)||i.startsWith(`-r=`)||i.startsWith(`--import=`))&&h(i.slice(i.indexOf(`=`)+1))){r=!0;continue}n.push(i)}return r?n.join(` `):e}function h(e){let t=g(e);if(!t)return!1;let n=t;if(n.startsWith(`file://`))try{n=c(n)}catch{return!1}return o(n)&&!r(n)}function g(e){let t=e[0],n=e[e.length-1];return t===`"`&&n===`"`||t===`'`&&n===`'`?e.slice(1,-1):e}function _(e,t,n,r,i){if(!n.execArgv&&p()&&__require$1.main===void 0&&(n={...n,execArgv:[]}),!n.env&&process.env.NODE_OPTIONS){let e=m(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(n={...n,env:{...process.env,NODE_OPTIONS:e}})}n={...n,name:i};let a=new d({filename:e,workerData:t,workerOpts:n,sync:r});a.on(`ready`,o),a.on(`close`,function(){process.removeListener(`exit`,s)}),process.on(`exit`,s);function o(){process.removeListener(`exit`,s),a.unref(),n.autoEnd!==!1&&f(a)}function s(){a.closed||(a.flushSync(),l(100),a.end())}return a}function v(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function y(e){e.flushSync()}function b(e){let{pipeline:t,targets:r,levels:c,dedupe:l,worker:u={},caller:d=i(),sync:f=!1}=e,p={...e.options},m=typeof d==`string`?[d]:d,h=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),g=e.target;if(g&&r)throw Error(`only one of target or targets can be specified`);r?(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.targets=r.filter(e=>e.target).map(e=>({...e,target:y(e.target)})),p.pipelines=r.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:y(t.target)})))):t&&(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.pipelines=[t.map(e=>({...e,target:y(e.target)}))]),c&&(p.levels=c),l&&(p.dedupe=l),p.pinoWillSendConfig=!0;let v=r||t?`pino.transport`:g;return _(y(g),p,u,f,v);function y(e){if(e=h[e]||e,o(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return a(__dirname,`..`,`file.js`);let t;for(let r of m)try{t=n(r===`node:repl`?process.cwd()+s:r).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=b})),require_tools=__commonJSMin$1(((e,t)=>{let n=__require$1(`node:diagnostics_channel`),r=require_quick_format_unescaped(),{mapHttpRequest:i,mapHttpResponse:a}=require_pino_std_serializers(),o=require_sonic_boom(),s=require_on_exit_leak_free(),{lsCacheSym:c,chindingsSym:l,writeSym:u,serializersSym:d,formatOptsSym:f,endSym:p,stringifiersSym:m,stringifySym:h,stringifySafeSym:g,wildcardFirstSym:_,nestedKeySym:v,formattersSym:y,messageKeySym:b,errorKeySym:x,nestedKeyStrSym:S,msgPrefixSym:C}=require_symbols(),{isMainThread:w}=__require$1(`worker_threads`),T=require_transport(),[E]=process.versions.node.split(`.`).map(e=>Number(e)),D=n.tracingChannel(`pino_asJson`),O=E>=25?e=>JSON.stringify(e):j;function k(){}function A(e,t){if(!t)return n;return function(...r){t.call(this,r,n,e)};function n(t,...n){if(typeof t==`object`){let o=t;t!==null&&(t.method&&t.headers&&t.socket?t=i(t):typeof t.setHeader==`function`&&(t=a(t)));let s;o===null&&n.length===0?s=[null]:(o=n.shift(),s=n),typeof this[C]==`string`&&o!=null&&(o=this[C]+o),this[u](t,r(o,s,this[f]),e)}else{let i=t===void 0?n.shift():t;typeof this[C]==`string`&&i!=null&&(i=this[C]+i),this[u](null,r(i,n,this[f]),e)}}}function j(e){let t=``,n=0,r=!1,i=255,a=e.length;if(a>100)return JSON.stringify(e);for(var o=0;o<a&&i>=32;o++)i=e.charCodeAt(o),(i===34||i===92)&&(t+=e.slice(n,o)+`\\`,n=o,r=!0);return r?t+=e.slice(n):t=e,i<32?JSON.stringify(e):`"`+t+`"`}function M(e,t,n,r){if(D.hasSubscribers===!1)return N.call(this,e,t,n,r);let i={instance:this,arguments};return D.traceSync(N,i,this,e,t,n,r)}function N(e,t,n,r){let i=this[h],a=this[g],o=this[m],s=this[p],u=this[l],f=this[d],C=this[y],w=this[b],T=this[x],E=this[c][n]+r;E+=u;let D;C.log&&(e=C.log(e));let k=o[_],A=``;for(let t in e)if(D=e[t],Object.prototype.hasOwnProperty.call(e,t)&&D!==void 0){f[t]?D=f[t](D):t===T&&f.err&&(D=f.err(D));let e=o[t]||k;switch(typeof D){case`undefined`:case`function`:continue;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D));break;case`string`:D=(e||O)(D);break;default:D=(e||i)(D,a)}if(D===void 0)continue;let n=O(t);A+=`,`+n+`:`+D}let j=``;if(t!==void 0){D=f[w]?f[w](t):t;let e=o[w]||k;switch(typeof D){case`function`:break;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D)),j=`,"`+w+`":`+D;break;case`string`:D=(e||O)(D),j=`,"`+w+`":`+D;break;default:D=(e||i)(D,a),j=`,"`+w+`":`+D}}return this[v]&&A?E+this[S]+A.slice(1)+`}`+j+s:E+A+j+s}function P(e,t){let n,r=e[l],i=e[h],a=e[g],o=e[m],s=o[_],c=e[d],u=e[y].bindings;t=u(t);for(let e in t)if(n=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&n!==void 0)===!0){if(n=c[e]?c[e](n):n,n=(o[e]||s||i)(n,a),n===void 0)continue;r+=`,"`+e+`":`+n}return r}function F(e){return e.write!==e.constructor.prototype.write}function I(e){let t=new o(e);return t.on(`error`,n),!e.sync&&w&&(s.register(t,L),t.on(`close`,function(){s.unregister(t)})),t;function n(e){if(e.code===`EPIPE`){t.write=k,t.end=k,t.flushSync=k,t.destroy=k;return}t.removeListener(`error`,n),t.emit(`error`,e)}}function L(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function R(e){return function(t,n,r={},i){if(typeof r==`string`)i=I({dest:r}),r={};else if(typeof i==`string`){if(r&&r.transport)throw Error(`only one of option.transport or stream can be specified`);i=I({dest:i})}else if(r instanceof o||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof o||r.transport.writable||r.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;r.customLevels&&(e=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=T({caller:n,...r.transport,levels:e})}if(r=Object.assign({},e,r),r.serializers=Object.assign({},e.serializers,r.serializers),r.formatters=Object.assign({},e.formatters,r.formatters),r.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:a,onChild:s}=r;return a===!1&&(r.level=`silent`),s||(r.onChild=k),i||=F(process.stdout)?process.stdout:I({fd:process.stdout.fd||1}),{opts:r,stream:i}}}function z(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[g])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function B(e,t,n){return{level:e,bindings:t,log:n}}function V(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:k,buildSafeSonicBoom:I,asChindings:P,asJson:M,genLog:A,createArgsNormalizer:R,stringify:z,buildFormatters:B,normalizeDestFileDescriptor:V}})),require_constants$7=__commonJSMin$1(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),require_levels=__commonJSMin$1(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=require_symbols(),{noop:l,genLog:u}=require_tools(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=require_constants$7(),p={fatal:e=>{let t=u(d.fatal,e);return function(...e){let n=this[a];if(t.call(this,...e),typeof n.flushSync==`function`)try{n.flushSync()}catch{}}},error:e=>u(d.error,e),warn:e=>u(d.warn,e),info:e=>u(d.info,e),debug:e=>u(d.debug,e),trace:e=>u(d.trace,e)},m=Object.keys(d).reduce((e,t)=>(e[d[t]]=t,e),{}),h=Object.keys(m).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function g(e){let t=e[o].level,{labels:r}=e.levels,i={};for(let e in r){let n=t(r[e],Number(e));i[e]=JSON.stringify(n).slice(0,-1)}return e[n]=i,e}function _(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function v(e){let{labels:t,values:n}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(n[e]===void 0)throw Error(`unknown level `+e);let a=this[r],o=this[r]=n[e],d=this[i],f=this[c],m=this[s].logMethod;for(let e in n){if(f(n[e],o)===!1){this[e]=l;continue}this[e]=_(e,d)?p[e](m):u(n[e],m)}this.emit(`level-change`,e,o,t[a],a,this)}function y(e){let{levels:t,levelVal:n}=this;return t&&t.labels?t.labels[n]:``}function b(e){let{values:t}=this.levels,n=t[e];return n!==void 0&&this[c](n,this[r])}function x(e,t,n){return e===f.DESC?t<=n:t>=n}function S(e){return typeof e==`string`?x.bind(null,e):e}function C(e=null,t=!1){let n=e?Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:m,n),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:d,e)}}function w(e,t,n){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),n?[]:Object.keys(m).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:d,t)))throw Error(`default level:${e} must be included in custom levels`)}function T(e,t){let{labels:n,values:r}=e;for(let e in t){if(e in r)throw Error(`levels cannot be overridden`);if(t[e]in n)throw Error(`pre-existing level values cannot be used for new levels`)}}function E(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(f).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:h,genLsCache:g,levelMethods:p,getLevel:y,setLevel:v,isLevelEnabled:b,mappings:C,assertNoLevelCollisions:T,assertDefaultLevelFound:w,genLevelComparison:S,assertLevelComparison:E}})),require_meta=__commonJSMin$1(((e,t)=>{t.exports={version:`10.3.1`}})),require_proto=__commonJSMin$1(((e,t)=>{let{EventEmitter:n}=__require$1(`node:events`),{lsCacheSym:r,levelValSym:i,setLevelSym:a,getLevelSym:o,chindingsSym:s,mixinSym:c,asJsonSym:l,writeSym:u,mixinMergeStrategySym:d,timeSym:f,timeSliceIndexSym:p,streamSym:m,serializersSym:h,formattersSym:g,errorKeySym:_,messageKeySym:v,useOnlyCustomLevelsSym:y,needsMetadataGsym:b,redactFmtSym:x,stringifySym:S,formatOptsSym:C,stringifiersSym:w,msgPrefixSym:T,hooksSym:E}=require_symbols(),{getLevel:D,setLevel:O,isLevelEnabled:k,mappings:A,initialLsCache:j,genLsCache:M,assertNoLevelCollisions:N}=require_levels(),{asChindings:P,asJson:F,buildFormatters:I,stringify:L,noop:R}=require_tools(),{version:z}=require_meta(),B=require_redaction(),V={constructor:class{},child:U,bindings:W,setBindings:G,flush:J,isLevelEnabled:k,version:z,get level(){return this[o]()},set level(e){this[a](e)},get levelVal(){return this[i]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[T]},get[Symbol.toStringTag](){return`Pino`},[r]:j,[u]:q,[l]:F,[o]:D,[a]:O};Object.setPrototypeOf(V,n.prototype),t.exports=function(){return Object.create(V)};let H=e=>e;function U(e,t){if(!e)throw Error(`missing bindings for child Pino`);let n=this[h],r=this[g],i=Object.create(this);if(t==null)return i[g].bindings!==H&&(i[g]=I(r.level,H,r.log)),i[s]=P(i,e),this.onChild!==R&&this.onChild(i),i;if(t.hasOwnProperty(`serializers`)===!0){i[h]=Object.create(null);for(let e in n)i[h][e]=n[e];let e=Object.getOwnPropertySymbols(n);for(var o=0;o<e.length;o++){let t=e[o];i[h][t]=n[t]}for(let e in t.serializers)i[h][e]=t.serializers[e];let r=Object.getOwnPropertySymbols(t.serializers);for(var c=0;c<r.length;c++){let e=r[c];i[h][e]=t.serializers[e]}}else i[h]=n;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:n,log:a}=t.formatters;i[g]=I(e||r.level,n||H,a||r.log)}else i[g]=I(r.level,H,r.log);if(t.hasOwnProperty(`customLevels`)===!0&&(N(this.levels,t.customLevels),i.levels=A(t.customLevels,i[y]),M(i)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){i.redact=t.redact;let e=B(i.redact,L),n={stringify:e[x]};i[S]=L,i[w]=e,i[C]=n}if(typeof t.msgPrefix==`string`&&(i[T]=(this[T]||``)+t.msgPrefix),i[s]=P(i,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;i[a](e)}return this.onChild(i),i}function W(){let e=`{${this[s].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function G(e){this[s]=P(this,e)}function K(e,t){return Object.assign(t,e)}function q(e,t,n){let r=this[f](),i=this[c],a=this[_],o=this[v],s=this[d]||K,u,h=this[E].streamWrite;e==null?u={}:e instanceof Error?(u={[a]:e},t===void 0&&(t=e.message)):(u=e,t===void 0&&e[o]===void 0&&e[a]&&(t=e[a].message)),i&&(u=s(u,i(u,n,this)));let g=this[l](u,t,n,r),y=this[m];y[b]===!0&&(y.lastLevel=n,y.lastObj=u,y.lastMsg=t,y.lastTime=r.slice(this[p]),y.lastLogger=this),y.write(h?h(g):g)}function J(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[m];typeof t.flush==`function`?t.flush(e||R):e&&e()}})),require_safe_stable_stringify=__commonJSMin$1(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=_();r.configure=_,r.stringify=r,r.default=r,e.stringify=r,e.configure=_,t.exports=r;let i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function a(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let n=e[t],r=t;for(;r!==0&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}let s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return s.call(e)!==void 0&&e.length!==0}function l(e,t,n){e.length<n&&(n=e.length);let r=t===`,`?``:` `,i=`"0":${r}${e[0]}`;for(let a=1;a<n;a++)i+=`${t}"${a}":${r}${e[a]}`;return i}function u(e){if(n.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function d(e){let t;if(n.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function f(e,t){let r;if(n.call(e,t)&&(r=e[t],typeof r!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return r===void 0?!0:r}function p(e,t){let r;if(n.call(e,t)){if(r=e[t],typeof r!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw TypeError(`The "${t}" argument must be an integer`);if(r<1)throw RangeError(`The "${t}" argument must be >= 1`)}return r===void 0?1/0:r}function m(e){return e===1?`1 item`:`${e} items`}function h(e){let t=new Set;for(let n of e)(typeof n==`string`||typeof n==`number`)&&t.add(String(n));return t}function g(e){if(n.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function _(e){e={...e};let t=g(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let n=u(e),r=f(e,`bigint`),i=d(e),s=typeof i==`function`?i:void 0,_=p(e,`maximumDepth`),v=p(e,`maximumBreadth`);function y(e,l,u,d,f,p){let h=l[e];switch(typeof h==`object`&&h&&typeof h.toJSON==`function`&&(h=h.toJSON(e)),h=d.call(l,e,h),typeof h){case`string`:return a(h);case`object`:{if(h===null)return`null`;if(u.indexOf(h)!==-1)return n;let e=``,t=`,`,r=p;if(Array.isArray(h)){if(h.length===0)return`[]`;if(_<u.length+1)return`"[Array]"`;u.push(h),f!==``&&(p+=f,e+=`\n${p}`,t=`,\n${p}`);let n=Math.min(h.length,v),i=0;for(;i<n-1;i++){let n=y(String(i),h,u,d,f,p);e+=n===void 0?`null`:n,e+=t}let a=y(String(i),h,u,d,f,p);if(e+=a===void 0?`null`:a,h.length-1>v){let n=h.length-v-1;e+=`${t}"... ${m(n)} not stringified"`}return f!==``&&(e+=`\n${r}`),u.pop(),`[${e}]`}let l=Object.keys(h),g=l.length;if(g===0)return`{}`;if(_<u.length+1)return`"[Object]"`;let b=``,x=``;f!==``&&(p+=f,t=`,\n${p}`,b=` `);let S=Math.min(g,v);i&&!c(h)&&(l=o(l,s)),u.push(h);for(let n=0;n<S;n++){let r=l[n],i=y(r,h,u,d,f,p);i!==void 0&&(e+=`${x}${a(r)}:${b}${i}`,x=t)}if(g>v){let n=g-v;e+=`${x}"...":${b}"${m(n)} not stringified"`,x=t}return f!==``&&x.length>1&&(e=`\n${p}${e}\n${r}`),u.pop(),`{${e}}`}case`number`:return isFinite(h)?String(h):t?t(h):`null`;case`boolean`:return h===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(h);default:return t?t(h):void 0}}function b(e,i,o,s,c,l){switch(typeof i==`object`&&i&&typeof i.toJSON==`function`&&(i=i.toJSON(e)),typeof i){case`string`:return a(i);case`object`:{if(i===null)return`null`;if(o.indexOf(i)!==-1)return n;let e=l,t=``,r=`,`;if(Array.isArray(i)){if(i.length===0)return`[]`;if(_<o.length+1)return`"[Array]"`;o.push(i),c!==``&&(l+=c,t+=`\n${l}`,r=`,\n${l}`);let n=Math.min(i.length,v),a=0;for(;a<n-1;a++){let e=b(String(a),i[a],o,s,c,l);t+=e===void 0?`null`:e,t+=r}let u=b(String(a),i[a],o,s,c,l);if(t+=u===void 0?`null`:u,i.length-1>v){let e=i.length-v-1;t+=`${r}"... ${m(e)} not stringified"`}return c!==``&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(i);let u=``;c!==``&&(l+=c,r=`,\n${l}`,u=` `);let d=``;for(let e of s){let n=b(e,i[e],o,s,c,l);n!==void 0&&(t+=`${d}${a(e)}:${u}${n}`,d=r)}return c!==``&&d.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case`number`:return isFinite(i)?String(i):t?t(i):`null`;case`boolean`:return i===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(i);default:return t?t(i):void 0}}function x(e,u,d,f,p){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return x(e,u,d,f,p);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=p;if(Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u),p+=f;let e=`\n${p}`,n=`,\n${p}`,r=Math.min(u.length,v),i=0;for(;i<r-1;i++){let t=x(String(i),u[i],d,f,p);e+=t===void 0?`null`:t,e+=n}let a=x(String(i),u[i],d,f,p);if(e+=a===void 0?`null`:a,u.length-1>v){let t=u.length-v-1;e+=`${n}"... ${m(t)} not stringified"`}return e+=`\n${t}`,d.pop(),`[${e}]`}let r=Object.keys(u),h=r.length;if(h===0)return`{}`;if(_<d.length+1)return`"[Object]"`;p+=f;let g=`,\n${p}`,y=``,b=``,S=Math.min(h,v);c(u)&&(y+=l(u,g,v),r=r.slice(u.length),S-=u.length,b=g),i&&(r=o(r,s)),d.push(u);for(let e=0;e<S;e++){let t=r[e],n=x(t,u[t],d,f,p);n!==void 0&&(y+=`${b}${a(t)}: ${n}`,b=g)}if(h>v){let e=h-v;y+=`${b}"...": "${m(e)} not stringified"`,b=g}return b!==``&&(y=`\n${p}${y}\n${t}`),d.pop(),`{${y}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function S(e,u,d){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return S(e,u,d);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=``,r=u.length!==void 0;if(r&&Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u);let e=Math.min(u.length,v),n=0;for(;n<e-1;n++){let e=S(String(n),u[n],d);t+=e===void 0?`null`:e,t+=`,`}let r=S(String(n),u[n],d);if(t+=r===void 0?`null`:r,u.length-1>v){let e=u.length-v-1;t+=`,"... ${m(e)} not stringified"`}return d.pop(),`[${t}]`}let f=Object.keys(u),p=f.length;if(p===0)return`{}`;if(_<d.length+1)return`"[Object]"`;let h=``,g=Math.min(p,v);r&&c(u)&&(t+=l(u,`,`,v),f=f.slice(u.length),g-=u.length,h=`,`),i&&(f=o(f,s)),d.push(u);for(let e=0;e<g;e++){let n=f[e],r=S(n,u[n],d);r!==void 0&&(t+=`${h}${a(n)}:${r}`,h=`,`)}if(p>v){let e=p-v;t+=`${h}"...":"${m(e)} not stringified"`}return d.pop(),`{${t}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function C(e,t,n){if(arguments.length>1){let r=``;if(typeof n==`number`?r=` `.repeat(Math.min(n,10)):typeof n==`string`&&(r=n.slice(0,10)),t!=null){if(typeof t==`function`)return y(``,{"":e},[],t,r,``);if(Array.isArray(t))return b(``,e,[],h(t),r,``)}if(r.length!==0)return x(``,e,[],r,``)}return S(``,e,[])}return C}})),require_multistream=__commonJSMin$1(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=require_constants$7(),i=r.info;function a(e,t){e||=[],t||={dedupe:!1};let a=Object.create(r);a.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{a[e]=t.levels[e]});let u={write:d,add:m,remove:h,emit:f,flushSync:p,end:g,minLevel:0,lastId:0,streams:[],clone:_,[n]:!0,streamLevels:a};return Array.isArray(e)?e.forEach(m,u):m.call(u,e),e=null,u;function d(e){let r,i=this.lastLevel,{streams:a}=this,o=0,u;for(let d=s(a.length,t.dedupe);l(d,a.length,t.dedupe);d=c(d,t.dedupe))if(r=a[d],r.level<=i){if(o!==0&&o!==r.level)break;if(u=r.stream,u[n]){let{lastTime:e,lastMsg:t,lastObj:n,lastLogger:r}=this;u.lastLevel=i,u.lastTime=e,u.lastMsg=t,u.lastObj=n,u.lastLogger=r}u.write(e),t.dedupe&&(o=r.level)}else if(!t.dedupe)break}function f(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function p(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function m(e){if(!e)return u;let t=typeof e.write==`function`||e.stream,n=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:r,streamLevels:a}=this,s;s=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?a[e.level]:typeof e.level==`number`?e.level:i;let c={stream:n,level:s,levelVal:void 0,id:++u.lastId};return r.unshift(c),r.sort(o),this.minLevel=r[0].level,u}function h(e){let{streams:t}=this,n=t.findIndex(t=>t.id===e);return n>=0&&(t.splice(n,1),t.sort(o),this.minLevel=t.length>0?t[0].level:-1),u}function g(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function _(e){let t=Array(this.streams.length);for(let n=0;n<t.length;n++)t[n]={level:e,stream:this.streams[n].stream};return{write:d,add:m,remove:h,minLevel:e,streams:t,clone:_,emit:f,flushSync:p,[n]:!0}}}function o(e,t){return e.level-t.level}function s(e,t){return t?e-1:0}function c(e,t){return t?e-1:e+1}function l(e,t,n){return n?e>=0:e<t}t.exports=a})),require_pino=__commonJSMin$1(((e,t)=>{let n=__require$1(`node:os`),r=require_pino_std_serializers(),i=require_caller(),a=require_redaction(),o=require_time$4(),s=require_proto(),c=require_symbols(),{configure:l}=require_safe_stable_stringify(),{assertDefaultLevelFound:u,mappings:d,genLsCache:f,genLevelComparison:p,assertLevelComparison:m}=require_levels(),{DEFAULT_LEVELS:h,SORTING_ORDER:g}=require_constants$7(),{createArgsNormalizer:_,asChindings:v,buildSafeSonicBoom:y,buildFormatters:b,stringify:x,normalizeDestFileDescriptor:S,noop:C}=require_tools(),{version:w}=require_meta(),{chindingsSym:T,redactFmtSym:E,serializersSym:D,timeSym:O,timeSliceIndexSym:k,streamSym:A,stringifySym:j,stringifySafeSym:M,stringifiersSym:N,setLevelSym:P,endSym:F,formatOptsSym:I,messageKeySym:L,errorKeySym:R,nestedKeySym:z,mixinSym:B,levelCompSym:V,useOnlyCustomLevelsSym:H,formattersSym:U,hooksSym:W,nestedKeyStrSym:G,mixinMergeStrategySym:K,msgPrefixSym:q}=c,{epochTime:J,nullTime:Y}=o,{pid:X}=process,Z=n.hostname(),Q=r.err,ee=_({level:`info`,levelComparison:g.ASC,levels:h,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:X,hostname:Z},serializers:Object.assign(Object.create(null),{err:Q}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:J,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),te=Object.assign(Object.create(null),r);function ne(...e){let t={},{opts:n,stream:r}=ee(t,i(),...e);n.level&&typeof n.level==`string`&&h[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:o,crlf:c,serializers:g,timestamp:_,messageKey:y,errorKey:S,nestedKey:w,base:X,name:Z,level:Q,customLevels:te,levelComparison:ne,mixin:re,mixinMergeStrategy:ie,useOnlyCustomLevels:ae,formatters:oe,hooks:se,depthLimit:ce,edgeLimit:le,onChild:ue,msgPrefix:de}=n,fe=l({maximumDepth:ce,maximumBreadth:le}),pe=b(oe.level,oe.bindings,oe.log),me=x.bind({[M]:fe}),he=o?a(o,me):{},ge=o?{stringify:he[E]}:{stringify:me},_e=`}`+(c?`\r
4
4
  `:`
@@ -69,7 +69,7 @@ To resolve the conflict:`,(0,r.getConflictResolutionRecipe)(i,e))),a=o):n.diag.w
69
69
  `).filter(e=>e.length>0)}catch{return 0}let r=[],i={server:0,"human-":0,upstream:0};for(let e of n){let t=e.split(`/`);if(t.length<4)continue;let n=t.slice(3).join(`/`);parseWriterId(n).classification===`unknown`&&(n===`server`?(r.push(e),i.server++):n.startsWith(`human-`)?(r.push(e),i[`human-`]++):n===`upstream`&&(r.push(e),i.upstream++))}if(r.length===0)return 0;for(let e of r)try{await t.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[shadow-migration] failed to delete legacy ref ${e}:`,t)}let a=r.length;return incrementShadowMigrationLegacyRefsDeleted(a),console.warn(`[shadow-migration] deleted ${a} legacy refs: server=${i.server} human-=${i[`human-`]} upstream=${i.upstream}`),a}async function commitWip(e,t,n,r,i=`main`){return withSpan(`shadow.commitWip`,{attributes:{"shadow.writer":t.id,"shadow.branch":i}},async()=>commitWipInner(e,t,n,r,i))}async function commitWipInner(e,t,n,r,i=`main`){let a=resolve(e.gitDir,`index-wip-${t.id}`),o=`refs/wip/${i}/${t.id}`,s=shadowGit(e),c=n||`.`;try{try{let t=(await s.raw(`rev-parse`,`${o}^{tree}`)).trim();await s.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw console.error(`[shadow-repo] Unexpected error seeding index for ${o}:`,e),e}await s.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:a}).raw(`add`,c);let n=(await s.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`write-tree`)).trim(),i=null;try{i=(await s.raw(`rev-parse`,o)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${o}:`,e),e}let l=[`commit-tree`,n,`-m`,r];i&&l.push(`-p`,i);let u=(await s.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...l)).trim();return await s.raw(`update-ref`,o,u),u}finally{try{rmSync(a)}catch{}}}function sweepOrphanedTmpIndexFiles(e){let t=0;try{for(let n of readdirSync(e.gitDir))if(n.startsWith(`index-wip-fanout-`))try{rmSync(resolve(e.gitDir,n)),t++}catch{}}catch{}return t}async function buildWipTree(e,t){let n=resolve(e.gitDir,`index-wip-fanout-${randomUUID()}`),r=shadowGit(e),i=t||`.`;try{return await r.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:n}).raw(`add`,i),(await r.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:n}).raw(`write-tree`)).trim()}finally{try{rmSync(n)}catch{}}}async function commitWipFromTree(e,t,n,r,i=`main`){return withSpan(`shadow.commitWipFromTree`,{attributes:{"shadow.writer":t.id,"shadow.branch":i,"shadow.tree":n.slice(0,8)}},async()=>commitWipFromTreeInner(e,t,n,r,i))}async function commitWipFromTreeInner(e,t,n,r,i=`main`){let a=`refs/wip/${i}/${t.id}`,o=shadowGit(e),s=null;try{s=(await o.raw(`rev-parse`,a)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${a}:`,e),e}let c=[`commit-tree`,n,`-m`,r];s&&c.push(`-p`,s);let l=(await o.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...c)).trim();return await o.raw(`update-ref`,a,l),l}const FILE_SYSTEM_WRITER={id:`file-system`,name:`File System`,email:`file-system@openknowledge.local`},GIT_UPSTREAM_WRITER={id:`git-upstream`,name:`Git (upstream)`,email:`git@openknowledge.local`},SERVICE_WRITER={id:`openknowledge-service`,name:`Open Knowledge (service)`,email:`service@openknowledge.local`},UPSTREAM_WRITER=GIT_UPSTREAM_WRITER;async function commitUpstreamImport(e,t,n,r,i=`main`){return withSpan(`shadow.commitUpstreamImport`,{attributes:{"shadow.branch":i,"shadow.new_head":r.slice(0,8)}},async()=>commitUpstreamImportInner(e,t,n,r,i))}async function commitUpstreamImportInner(e,t,n,r,i=`main`){return commitWip(e,UPSTREAM_WRITER,t,`${formatImportSubject(n,r)}\n\n${formatOkActor({v:1,writer_id:UPSTREAM_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:UPSTREAM_WRITER.name,color_seed:UPSTREAM_WRITER.id,docs:[]})}`,i)}const SAFETY_WRITER=SERVICE_WRITER;async function safetyCheckpoint(e,t,n,r=`main`){return commitWip(e,SAFETY_WRITER,t,`${formatCheckpointSubject(`pre-${n.action}`)}\n\n${formatOkActor({v:1,writer_id:SAFETY_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SAFETY_WRITER.name,color_seed:SAFETY_WRITER.id,docs:[]})}`,r)}async function saveInMemoryCheckpoint(e,t,n){let r=n.branch??`main`,i=shadowGit(e),a=randomUUID(),o=resolve(e.gitDir,`index-checkpoint-${a}`),s=resolve(e.gitDir,`tmp-checkpoint-blob-${a}`),c=t?`${t.replace(/\/$/,``)}/${n.docName}`:n.docName,l=Buffer.byteLength(n.contents,`utf-8`),u=formatCheckpointBodyLine(n.kind===`bridge-merge-loss`?{kind:`bridge-merge-loss`,docName:n.docName,size:l,metadata:n.metadata}:{kind:`external-change-rescue`,docName:n.docName,size:l,metadata:n.metadata}),d=`checkpoint: ${n.label}\n\n${u}`;try{tracedWriteFileSync(s,n.contents,`utf-8`);let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,s)).trim();await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${t},${c}`);let a=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),l=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(`commit-tree`,a,`-m`,d)).trim();return await i.raw(`update-ref`,`refs/checkpoints/${r}/${l}`,l),l}finally{try{rmSync(o)}catch{}try{rmSync(s)}catch{}}}async function listRescueCheckpoints(e,t=`main`){let n=shadowGit(e),r;try{r=await n.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let i=r.trim().split(`
70
70
  `).filter(e=>e.length===40);if(i.length===0)return[];let a;try{a=await n.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%s%x00%B%x1e`,...i)}catch{return[]}let o=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[r=``,i=``,a=``,s=``]=t.split(`\0`),c=parseCheckpoint(s);if(c?.kind!==`external-change-rescue`)continue;let l=c.docName??``,u=c.size??0;if(!l)try{let e=(await n.raw(`ls-tree`,`-r`,`--long`,r)).trim().split(`
71
71
  `)[0];if(e){let t=e.split(/\s+/),n=4,r=3;u===0&&(u=Number(t[3]??`0`)),l=(t[4]??``).replace(/\.mdx?$/,``).split(`/`).slice(-1)[0]??``}}catch{}l&&o.push({docName:l,timestamp:i,size:u,sha:r,label:a.replace(/^checkpoint:\s*/,``),incomingDiskSha:c.metadata.incomingDiskSha})}return o}async function parkBranch(e,t,n,r,i){return r.length===0?null:withSpan(`shadow.parkBranch`,{attributes:{"shadow.branch":t,"shadow.new_branch":i??``,"shadow.doc_count":r.length}},async()=>parkBranchInner(e,t,n,r,i))}async function parkBranchInner(e,t,n,r,i){let a=shadowGit(e),o=resolve(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),s=`refs/wip/${t}/${n}`,c=resolve(e.gitDir,`tmp-park-blob`);try{for(let t of r){tracedWriteFileSync(c,t.markdown,`utf-8`);let n=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,c)).trim();await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${n},${t.docName}`),tracedWriteFileSync(c,t.diskSnapshot,`utf-8`);let r=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,c)).trim();await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${r},.park-base/${t.docName}`)}let n=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),l=null;try{l=(await a.raw(`rev-parse`,s)).trim()}catch{}let u={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:r.map(e=>e.docName)},d=[`commit-tree`,n,`-m`,`${formatParkSubject(t,i??t)}\n\n${formatOkActor(u)}`];l&&d.push(`-p`,l);let f=(await a.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...d)).trim();return await a.raw(`update-ref`,s,f),f}finally{try{rmSync(o)}catch{}try{rmSync(c)}catch{}}}async function readParkedState(e,t,n,r){let i=shadowGit(e),a=`refs/wip/${t}/${n}`,o;try{o=(await i.raw(`rev-parse`,a)).trim()}catch{return null}try{return(await i.raw(`log`,`-1`,`--format=%s`,o)).trim().startsWith(`park:`)?{markdown:(await i.raw(`show`,`${o}:${r}`)).trim(),diskSnapshot:(await i.raw(`show`,`${o}:.park-base/${r}`)).trim()}:null}catch(e){throw console.error(`[shadow] Failed to read parked state for ${r} from ${a}:`,e),e}}async function saveVersion(e,t,n,r=`main`){return withSpan(`shadow.saveVersion`,{attributes:{"shadow.branch":r,"shadow.writer_count":n.length}},async()=>saveVersionInner(e,t,n,r))}async function saveVersionInner(e,t,n,r=`main`){let i=shadowGit(e),a=t||`.`,o=resolve(e.gitDir,`index-checkpoint`);try{await i.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:o}).raw(`add`,a);let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),s=[];for(let e of[...n,GIT_UPSTREAM_WRITER])try{let t=(await i.raw(`rev-parse`,`refs/wip/${r}/${e.id}`)).trim();s.push(t)}catch{}let c=[...new Set(s)];if(c.length===0)try{let e=(await i.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
72
- `).filter(Boolean);e[0]&&c.push(e[0])}catch{}let l={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},u=[`commit-tree`,t,`-m`,`${formatCheckpointSubject(`Checkpoint version`)}\n\n${formatOkActor(l)}`];for(let e of c)u.push(`-p`,e);let d=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...u)).trim(),f=`refs/checkpoints/${r}/${d}`;await i.raw(`update-ref`,f,d);for(let e of n)try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/${e.id}`)}catch{}try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/${GIT_UPSTREAM_WRITER.id}`)}catch{}return{checkpointRef:f}}finally{try{rmSync(o)}catch{}}}const log$4=getLogger(`persistence`);function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.source===`local`){let e=n.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(n.source===`connection`){let e=n.connection?.context;if(typeof e?.principalId==`string`){let n=e.principalId,r=t?.();return r&&r.id===n&&r.display_name&&r.display_email?{id:r.id,name:r.display_name,email:r.display_email}:{id:n,name:`Local User`,email:`${n}@openknowledge.local`}}return SERVICE_WRITER}return null}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=resolve(t,`${e}${getDocExtension(e)}`);if(!n.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return n}function isWithinContentDir(e,t){return e===t||e.startsWith(t+sep)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),n;try{n=realpathSync(t)}catch{n=t}let r=e?.projectDir??process.cwd(),i=e?.shadowRef,a=e?.contentRoot??(relative(r,n)||`content`),o=e?.backlinkIndex,s=e?.getPrincipal,c=e?.onAgentCommit,l=e?.onDiskFlush,u=new Map,d=e?.gitEnabled??!0,f=e?.commitDebounceMs??15e3,p=e?.wipRef??`refs/wip/main`,m=e?.getCurrentBranch,h=null,g=0,_=null,v=!1;async function y(){D();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await b()).finally(()=>{E?.record((Date.now()-e)/1e3)})}async function b(){let e=i?.current;if(e){let t=swapContributors(),n=m?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},r=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,a,r,n);g=0,log$4.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`)}catch(e){g++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:g},`[persistence] Shadow commit failed (attempt ${g})`),g>=3&&log$4.error({attempt:g},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let r;try{r=await buildWipTree(e,a)}catch(e){restoreContributors(t),g++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:g},`[persistence] Shadow WIP tree build failed (attempt ${g})`);return}let i=!1;for(let[a,o]of t){let t={id:a,name:o.displayName,email:`${a}@openknowledge.local`},s=[...o.docs],l=o.actor,u=[...o.summaries],d={v:1,writer_id:a,principal:l?.principalId??null,agent_session:a.startsWith(`agent-`)?a.slice(6):null,agent_type:l?.agentType??null,client_name:l?.clientName??null,client_version:l?.clientVersion??null,label:l?.label??null,display_name:o.displayName,color_seed:o.colorSeed,docs:s,...u.length>0?{summaries:u}:{}},f=`${composeCommitSubject(o.subjectOverride??formatWipSubject(s),u)}\n\n${formatOkActor(d)}`;try{let o=await commitWipFromTree(e,t,r,f,n);i=!0,log$4.info({sha:o.slice(0,8),writer:a,tree:r.slice(0,8)},`[persistence] Shadow WIP commit: ${o.slice(0,8)} on refs/wip/${a}`),a.startsWith(`agent-`)&&c?.()}catch(e){restoreContributorEntry(a,o),incrementGitWriterCommitFailure(),log$4.error({err:e,writer:a},`[persistence] Per-writer shadow commit failed for ${a}`)}}i?g=0:(g++,incrementGitAutoSaveFailure(),g>=3&&log$4.error({attempt:g},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(r,`.git`),workTree:r}),n=resolve(r,`.git/index-wip`),o={GIT_INDEX_FILE:n};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(o).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$4.info({},`[persistence] Empty repo — starting with empty index`):log$4.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(o).raw(`add`,a);let e=(await t.env(o).raw(`write-tree`)).trim(),n=null;try{n=(await t.raw(`rev-parse`,p)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let r=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];n&&r.push(`-p`,n);let i=(await t.raw(...r)).trim();await t.raw(`update-ref`,p,i),g=0,log$4.info({sha:i.slice(0,8),wipRef:p},`[persistence] Git commit: ${i.slice(0,8)} on ${p}`)}catch(e){g++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:g},`[persistence] Git commit failed (attempt ${g})`),g>=3&&log$4.error({attempt:g},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(n)}catch{}}}function x(e){if(e<=0)return f;let t=2**Math.min(e,5),n=Math.random()*.25*f;return f*t+n}function S(){d&&(isBatchInProgress()||(h&&clearTimeout(h),h=setTimeout(()=>{if(h=null,_){v=!0;return}_=y().finally(()=>{_=null,v&&(v=!1,S())})},x(g))))}async function C(){h&&(clearTimeout(h),h=null,_||=y().finally(()=>{_=null,v&&(v=!1,S())})),_&&await _}let w=null,T=null,E=null;function D(){if(w)return;let e=getMeter();w=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),T=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),E=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}let O={async onLoadDocument({document:e,documentName:t,context:r}){if(isSystemDoc(t))return;D();let i=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":t}},async()=>{log$4.info({documentName:t,connections:e.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${t} (connections: ${e.getConnectionsCount?.()??`?`})`);let r=safeContentPath(t,n);if(!existsSync(r))return;try{let e=realpathSync(r);if(!isWithinContentDir(e,n)){console.warn(`[persistence] symlink-escape on load: ${r} → ${e}, refusing`);return}}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${r}, refusing`);return}}let{frontmatter:i,body:a}=stripFrontmatter(readFileSync(r,`utf-8`));i&&(u.set(t,i),e.getMap(`metadata`).set(`frontmatter`,i));let o=e.getXmlFragment(`default`);log$4.info({documentName:t,fragmentLength:o.length},`[persistence] onLoadDocument ${t}: fragment.length=${o.length} before update`);let s=mdManager.parseWithFallback(a);o.length===0?(updateYFragment(e,o,schema.nodeFromJSON(s),{mapping:new Map,isOMark:new Map}),log$4.info({filePath:r,children:o.length},`[persistence] Loaded ${r} into Y.Doc (${o.length} children)`),o.observeDeep(()=>{log$4.info({documentName:t,fragmentLength:o.length},`[persistence] MUTATION on ${t}: fragment.length=${o.length}`)})):log$4.info({documentName:t,children:o.length},`[persistence] Skipped load for ${t} — fragment already has ${o.length} children`),setReconciledBase(t,prependFrontmatter(i,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(o,schema).toJSON())))}).finally(()=>{w?.record((Date.now()-i)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:r,lastContext:i}){if(isSystemDoc(t)||isBatchInProgress())return;D();let a=Date.now();return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":t}},async()=>{let{sv:i,json:a}=captureDocSnapshotForPersistence(e),c=mdManager.serialize(a),d=e.getMap(`metadata`).get(`frontmatter`),f=prependFrontmatter(typeof d==`string`?d:u.get(t)||``,c),p=getReconciledBase(t);if(p!==void 0&&normalizeBridge(f)===normalizeBridge(p)){contributorCount()>0&&S();return}let m=resolveWriterFromOrigin(r,s);m&&m.id!==SERVICE_WRITER.id&&(hasContributor(m.id)||recordContributor(t,m.id,m.name,m.id)),p&&f.length>p.length*1.5&&(log$4.warn({documentName:t,markdownLength:f.length,baseLength:p.length},`[persistence] WARNING: serialized content is ${f.length} bytes vs base ${p.length} bytes for ${t} — possible duplication`),log$4.warn({documentName:t,children:e.getXmlFragment(`default`).length},`[persistence] Fragment children: ${e.getXmlFragment(`default`).length}`));let h=safeContentPath(t,n);await tracedMkdir(dirname(h),{recursive:!0});let g;try{g=await realpath(h)}catch(e){let n=e.code;if(n===`ENOENT`){let e=!1;try{e=lstatSync(h).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$4.warn({err:e,path:h},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),g=h}else if(n===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${h}`),Error(`Symlink cycle detected at ${h}`);else throw e}if(!isWithinContentDir(g,n)){let e=`symlink-escape: ${h} resolves to ${g} outside ${n}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:h,canonical:g,contentDir:n}),Error(e)}let _=`${g}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(_,f,`utf-8`),await tracedRename(_,g),registerWrite(g,contentHash(f)),incrementPersistenceDiskWrite(),l?.(t,i)}catch(e){try{tracedUnlinkSync(_)}catch{}throw log$4.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}log$4.info({filePath:g,bytes:f.length},`[persistence] Wrote ${g} (${f.length} bytes)`),setReconciledBase(t,f),o&&(o.updateDocumentFromMarkdown(t,f),o.saveToDisk().catch(e=>{log$4.warn({err:e,documentName:t},`[backlinks] Failed to persist cache for ${t}`)})),setActiveSpanAttributes({"persistence.bytes":f.length}),S()}).finally(()=>{T?.record((Date.now()-a)/1e3)})}};async function k(){_&&await _}return{extension:O,flushPendingGitCommit:C,waitForPendingCommits:k}}const CONFLICT_MARKER_RE=/^(<{7} |={7}$|>{7} |\|{7} )/m;function containsConflictMarkers(e){return CONFLICT_MARKER_RE.test(e)}function splitMarkdownBlocks(e){let t=e.replace(/\n+$/,``);if(!t)return[];let n=t.split(`
72
+ `).filter(Boolean);e[0]&&c.push(e[0])}catch{}let l={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},u=[`commit-tree`,t,`-m`,`${formatCheckpointSubject(`Checkpoint version`)}\n\n${formatOkActor(l)}`];for(let e of c)u.push(`-p`,e);let d=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...u)).trim(),f=`refs/checkpoints/${r}/${d}`;await i.raw(`update-ref`,f,d);for(let e of n)try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/${e.id}`)}catch{}try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/${GIT_UPSTREAM_WRITER.id}`)}catch{}return{checkpointRef:f}}finally{try{rmSync(o)}catch{}}}const log$4=getLogger(`persistence`);function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.source===`local`){let e=n.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(n.source===`connection`){let e=n.connection?.context;if(typeof e?.principalId==`string`){let n=e.principalId,r=t?.();return r&&r.id===n&&r.display_name&&r.display_email?{id:r.id,name:r.display_name,email:r.display_email}:{id:n,name:`Local User`,email:`${n}@openknowledge.local`}}return SERVICE_WRITER}return null}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=resolve(t,`${e}${getDocExtension(e)}`);if(!n.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return n}function isWithinContentDir(e,t){return e===t||e.startsWith(t+sep)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),n;try{n=realpathSync(t)}catch{n=t}let r=e?.projectDir??process.cwd(),i=e?.shadowRef,a=e?.contentRoot??(relative(r,n)||`.`),o=e?.backlinkIndex,s=e?.getPrincipal,c=e?.onAgentCommit,l=e?.onDiskFlush,u=new Map,d=e?.gitEnabled??!0,f=e?.commitDebounceMs??15e3,p=e?.wipRef??`refs/wip/main`,m=e?.getCurrentBranch,h=null,g=0,_=null,v=!1;async function y(){D();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await b()).finally(()=>{E?.record((Date.now()-e)/1e3)})}async function b(){let e=i?.current;if(e){let t=swapContributors(),n=m?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},r=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,a,r,n);g=0,log$4.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`)}catch(e){g++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:g},`[persistence] Shadow commit failed (attempt ${g})`),g>=3&&log$4.error({attempt:g},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let r;try{r=await buildWipTree(e,a)}catch(e){restoreContributors(t),g++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:g},`[persistence] Shadow WIP tree build failed (attempt ${g})`);return}let i=!1;for(let[a,o]of t){let t={id:a,name:o.displayName,email:`${a}@openknowledge.local`},s=[...o.docs],l=o.actor,u=[...o.summaries],d={v:1,writer_id:a,principal:l?.principalId??null,agent_session:a.startsWith(`agent-`)?a.slice(6):null,agent_type:l?.agentType??null,client_name:l?.clientName??null,client_version:l?.clientVersion??null,label:l?.label??null,display_name:o.displayName,color_seed:o.colorSeed,docs:s,...u.length>0?{summaries:u}:{}},f=`${composeCommitSubject(o.subjectOverride??formatWipSubject(s),u)}\n\n${formatOkActor(d)}`;try{let o=await commitWipFromTree(e,t,r,f,n);i=!0,log$4.info({sha:o.slice(0,8),writer:a,tree:r.slice(0,8)},`[persistence] Shadow WIP commit: ${o.slice(0,8)} on refs/wip/${a}`),a.startsWith(`agent-`)&&c?.()}catch(e){restoreContributorEntry(a,o),incrementGitWriterCommitFailure(),log$4.error({err:e,writer:a},`[persistence] Per-writer shadow commit failed for ${a}`)}}i?g=0:(g++,incrementGitAutoSaveFailure(),g>=3&&log$4.error({attempt:g},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(r,`.git`),workTree:r}),n=resolve(r,`.git/index-wip`),o={GIT_INDEX_FILE:n};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(o).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$4.info({},`[persistence] Empty repo — starting with empty index`):log$4.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(o).raw(`add`,a);let e=(await t.env(o).raw(`write-tree`)).trim(),n=null;try{n=(await t.raw(`rev-parse`,p)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let r=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];n&&r.push(`-p`,n);let i=(await t.raw(...r)).trim();await t.raw(`update-ref`,p,i),g=0,log$4.info({sha:i.slice(0,8),wipRef:p},`[persistence] Git commit: ${i.slice(0,8)} on ${p}`)}catch(e){g++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:g},`[persistence] Git commit failed (attempt ${g})`),g>=3&&log$4.error({attempt:g},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(n)}catch{}}}function x(e){if(e<=0)return f;let t=2**Math.min(e,5),n=Math.random()*.25*f;return f*t+n}function S(){d&&(isBatchInProgress()||(h&&clearTimeout(h),h=setTimeout(()=>{if(h=null,_){v=!0;return}_=y().finally(()=>{_=null,v&&(v=!1,S())})},x(g))))}async function C(){h&&(clearTimeout(h),h=null,_||=y().finally(()=>{_=null,v&&(v=!1,S())})),_&&await _}let w=null,T=null,E=null;function D(){if(w)return;let e=getMeter();w=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),T=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),E=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}let O={async onLoadDocument({document:e,documentName:t,context:r}){if(isSystemDoc(t))return;D();let i=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":t}},async()=>{log$4.info({documentName:t,connections:e.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${t} (connections: ${e.getConnectionsCount?.()??`?`})`);let r=safeContentPath(t,n);if(!existsSync(r))return;try{let e=realpathSync(r);if(!isWithinContentDir(e,n)){console.warn(`[persistence] symlink-escape on load: ${r} → ${e}, refusing`);return}}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${r}, refusing`);return}}let{frontmatter:i,body:a}=stripFrontmatter(readFileSync(r,`utf-8`));i&&(u.set(t,i),e.getMap(`metadata`).set(`frontmatter`,i));let o=e.getXmlFragment(`default`);log$4.info({documentName:t,fragmentLength:o.length},`[persistence] onLoadDocument ${t}: fragment.length=${o.length} before update`);let s=mdManager.parseWithFallback(a);o.length===0?(updateYFragment(e,o,schema.nodeFromJSON(s),{mapping:new Map,isOMark:new Map}),log$4.info({filePath:r,children:o.length},`[persistence] Loaded ${r} into Y.Doc (${o.length} children)`),o.observeDeep(()=>{log$4.info({documentName:t,fragmentLength:o.length},`[persistence] MUTATION on ${t}: fragment.length=${o.length}`)})):log$4.info({documentName:t,children:o.length},`[persistence] Skipped load for ${t} — fragment already has ${o.length} children`),setReconciledBase(t,prependFrontmatter(i,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(o,schema).toJSON())))}).finally(()=>{w?.record((Date.now()-i)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:r,lastContext:i}){if(isSystemDoc(t)||isBatchInProgress())return;D();let a=Date.now();return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":t}},async()=>{let{sv:i,json:a}=captureDocSnapshotForPersistence(e),c=mdManager.serialize(a),d=e.getMap(`metadata`).get(`frontmatter`),f=prependFrontmatter(typeof d==`string`?d:u.get(t)||``,c),p=getReconciledBase(t);if(p!==void 0&&normalizeBridge(f)===normalizeBridge(p)){contributorCount()>0&&S();return}let m=resolveWriterFromOrigin(r,s);m&&m.id!==SERVICE_WRITER.id&&(hasContributor(m.id)||recordContributor(t,m.id,m.name,m.id)),p&&f.length>p.length*1.5&&(log$4.warn({documentName:t,markdownLength:f.length,baseLength:p.length},`[persistence] WARNING: serialized content is ${f.length} bytes vs base ${p.length} bytes for ${t} — possible duplication`),log$4.warn({documentName:t,children:e.getXmlFragment(`default`).length},`[persistence] Fragment children: ${e.getXmlFragment(`default`).length}`));let h=safeContentPath(t,n);await tracedMkdir(dirname(h),{recursive:!0});let g;try{g=await realpath(h)}catch(e){let n=e.code;if(n===`ENOENT`){let e=!1;try{e=lstatSync(h).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$4.warn({err:e,path:h},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),g=h}else if(n===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${h}`),Error(`Symlink cycle detected at ${h}`);else throw e}if(!isWithinContentDir(g,n)){let e=`symlink-escape: ${h} resolves to ${g} outside ${n}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:h,canonical:g,contentDir:n}),Error(e)}let _=`${g}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(_,f,`utf-8`),await tracedRename(_,g),registerWrite(g,contentHash(f)),incrementPersistenceDiskWrite(),l?.(t,i)}catch(e){try{tracedUnlinkSync(_)}catch{}throw log$4.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}log$4.info({filePath:g,bytes:f.length},`[persistence] Wrote ${g} (${f.length} bytes)`),setReconciledBase(t,f),o&&(o.updateDocumentFromMarkdown(t,f),o.saveToDisk().catch(e=>{log$4.warn({err:e,documentName:t},`[backlinks] Failed to persist cache for ${t}`)})),setActiveSpanAttributes({"persistence.bytes":f.length}),S()}).finally(()=>{T?.record((Date.now()-a)/1e3)})}};async function k(){_&&await _}return{extension:O,flushPendingGitCommit:C,waitForPendingCommits:k}}const CONFLICT_MARKER_RE=/^(<{7} |={7}$|>{7} |\|{7} )/m;function containsConflictMarkers(e){return CONFLICT_MARKER_RE.test(e)}function splitMarkdownBlocks(e){let t=e.replace(/\n+$/,``);if(!t)return[];let n=t.split(`
73
73
  `),r=[],i=[],a=null;for(let e of n){let t=e.match(/^(`{3,}|~{3,})/);if(t){let e=t[1][0];a?e===a&&(a=null):a=e}a===null&&e.trim()===``&&i.length>0?(r.push(i.join(`
74
74
  `).trim()),i=[]):i.push(e)}if(i.length>0){let e=i.join(`
75
75
  `).trim();e&&r.push(e)}return r}function reconcile(e){if(isSystemDoc(e.docName))return{kind:`noop`};let{base:t,ours:n,theirs:r}=e;return containsConflictMarkers(r)?{kind:`refused`,reason:`conflict-markers`}:r===t?{kind:`noop`}:n===t?{kind:`clean`,newContent:r}:mergeBlocks(splitMarkdownBlocks(t),splitMarkdownBlocks(n),splitMarkdownBlocks(r))}function mergeBlocks(e,t,n){let r=computeEditOps(e,t),i=computeEditOps(e,n),a=[],o=[];for(let t=0;t<e.length;t++){let n=e[t],s=r.get(t),c=i.get(t),l=s?.insertsBefore??[],u=c?.insertsBefore??[];a.push(...l,...u);let d=s?.action??`keep`,f=c?.action??`keep`;if(d===`keep`&&f===`keep`)a.push(n);else if(d===`keep`&&f!==`keep`)f===`modify`&&c?.newContent!==void 0&&a.push(c.newContent);else if(d!==`keep`&&f===`keep`)d===`modify`&&s?.newContent!==void 0&&a.push(s.newContent);else{let e=d===`modify`?s?.newContent:null,r=f===`modify`?c?.newContent:null;e===r||o.push({blockIndex:t,base:n,ours:e??``,theirs:r??``}),e!=null&&a.push(e)}}let s=r.get(e.length),c=i.get(e.length);s?.insertsBefore&&a.push(...s.insertsBefore),c?.insertsBefore&&a.push(...c.insertsBefore);let l=a.length>0?`${a.join(`
@@ -107,21 +107,21 @@ What to log:
107
107
  `,t-1)),i=[e.indexOf(`.`,n),e.indexOf(`?`,n),e.indexOf(`!`,n),e.indexOf(`
108
108
  `,n)].filter(e=>e>=0),a=r>=0?r+1:Math.max(0,t-60),o=i.length>0?Math.min(...i)+1:Math.min(e.length,n+60),s=a>0?`…`:``,c=o<e.length?`…`:``,l=normalizeSnippet(e.slice(a,o));return l?`${s}${l}${c}`:null}function matchFence(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function isFenceClose(e,t){let n=e.trimStart();if(e.length-n.length>3)return!1;let r=0;for(;n[r]===t.char;)r+=1;return r<t.length?!1:n.slice(r).trim().length===0}function leadingMarkdownPrefixLength(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n,i=r;for(;i<e.length;){if(e[i]!=="`"){i+=1;continue}let t=0;for(;e[i+t]==="`";)t+=1;if(t===n)return{text:e.slice(r,i),nextIndex:i+n};i+=t}return null}function readWikiLink(e,t){WIKI_LINK_RE.lastIndex=t;let n=WIKI_LINK_RE.exec(e);if(!n)return null;let r=n[1]??``,i=r.trim(),a=n[2]?.trim()||null,o=n[3]??null,s=o?.trim()||null;if(!i)return null;let c=s??i,l=s?o:r,u=s?n[0].lastIndexOf(o??``):2,d=l?.indexOf(c)??0;return{target:i,alias:s,anchor:a,label:c,labelStart:t+u+Math.max(d,0),nextIndex:t+n[0].length}}function normalizeMarkdownHref(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function readMarkdownLink(e,t){MD_LINK_RE.lastIndex=t;let n=MD_LINK_RE.exec(e);return n?{text:n[1]??``,href:normalizeMarkdownHref(n[2]??``),nextIndex:t+n[0].length}:null}function readMarkdownImage(e,t){MD_IMAGE_RE.lastIndex=t;let n=MD_IMAGE_RE.exec(e);return n?{alt:n[1]??``,nextIndex:t+n[0].length}:null}function isWordBoundaryChar(e){return!e||!WORD_CHAR_RE.test(e)}function hasWholeWordBoundaries(e,t,n){return isWordBoundaryChar(e[t-1])&&isWordBoundaryChar(e[n])}function prepareSearchLabels(e){let t=[],n=new Set;for(let r of e.matchLabels){let e=r.trim();if(!e)continue;let i=e.toLocaleLowerCase();n.has(i)||(n.add(i),t.push({raw:e,lower:i,length:e.length}))}return t.sort((e,t)=>t.length===e.length?e.raw.localeCompare(t.raw):t.length-e.length)}function findSegmentMatches(e,t){let n=e.toLocaleLowerCase(),r=[];for(let i of t){let t=0;for(;t<=n.length-i.length;){let a=n.indexOf(i.lower,t);if(a===-1)break;let o=a+i.length;hasWholeWordBoundaries(e,a,o)&&r.push({start:a,end:o}),t=a+1}}r.sort((e,t)=>{if(e.start!==t.start)return e.start-t.start;let n=e.end-e.start,r=t.end-t.start;return r===n?e.end-t.end:r-n});let i=[],a=null;for(let e of r)a&&e.start<a.end||(i.push(e),a=e);return i}function contiguousOffsets(e,t){let n=[];for(let r=0;r<t.length;r+=1)n.push(e+r);return n}function wikiLinkResolvesToTarget(e,t){let n=e.trim();return n?n===t||toWikiLinkSlug(n)===t:!1}function scanLineForMentions(e,t,n,r,i){let a=``,o=[],s=``,c=[];function l(){s&&(o.push({flatStart:a.length,text:s,sourceOffsets:c}),a+=s,s=``,c=[])}function u(e,t){s+=e,c.push(t)}function d(e){l(),a+=e}function f(e,t){l(),e&&(o.push({flatStart:a.length,text:e,sourceOffsets:t}),a+=e)}let p=leadingMarkdownPrefixLength(e);for(;p<e.length;){if(e[p]===`\\`&&p+1<e.length){u(e[p+1]??``,t+p+1),p+=2;continue}if(e[p]==="`"){let t=readInlineCode(e,p);if(t){d(t.text),p=t.nextIndex;continue}}if(e[p]===`!`&&e[p+1]===`[`){let t=readMarkdownImage(e,p);if(t){d(t.alt),p=t.nextIndex;continue}}if(e[p]===`[`&&e[p+1]===`[`){let n=readWikiLink(e,p);if(n){let e=n.label;wikiLinkResolvesToTarget(n.target,r)?d(e):f(e,contiguousOffsets(t+n.labelStart,e)),p=n.nextIndex;continue}}if(e[p]===`[`&&e[p-1]!==`!`){let i=readMarkdownLink(e,p);if(i){resolveInternalHref(i.href,n)?.docName===r?d(i.text):f(i.text,contiguousOffsets(t+p+1,i.text)),p=i.nextIndex;continue}}u(e[p]??``,t+p),p+=1}l();let m=[];for(let e of o){let t=findSegmentMatches(e.text,i);for(let n of t){let t=e.flatStart+n.start,r=e.flatStart+n.end,i=snippetAround(a,t,r)??e.text.slice(n.start,n.end),o=e.sourceOffsets[n.start];typeof o==`number`&&m.push({excerpt:i,offset:o})}}return m}function scanMarkdownForMentions(e,t,n,r){let{frontmatter:i,body:a}=stripFrontmatter(e),o=i.length,s=[],c=null,l=0,u=0;for(;u<=a.length;){let e=a[u];if(!(u===a.length||e===`
109
109
  `||e===`\r`)){u+=1;continue}let i=a.slice(l,u);if(c)isFenceClose(i,c)&&(c=null);else{let e=matchFence(i);e?c=e:s.push(...scanLineForMentions(i,o+l,t,n,r))}if(u===a.length)break;if(e===`\r`&&a[u+1]===`
110
- `){u+=2,l=u;continue}u+=1,l=u}return s}function serializeLiveDocument$1(e){let t=e.getXmlFragment(`default`),n=mdManager.serialize(yXmlFragmentToProseMirrorRootNode(t,schema).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return prependFrontmatter(typeof r==`string`?r:``,n)}async function readDocumentMarkdown(e,t,n){let r=e.documents.get(t);if(r)try{return serializeLiveDocument$1(r)}catch(e){return log$3.warn({docName:t,err:e},`[suggest-links] Failed live serialization, falling back to live source text`),r.getText(`source`).toString()}return await readFile(n.canonicalPath,`utf-8`)}function toPublicTarget(e){return{docName:e.docName,title:e.title,aliases:e.aliases}}async function suggestLinks(e){let{hocuspocus:t,fileIndex:n,docName:r,scanBudgetMs:i=500,now:a=()=>Date.now(),onComplete:o}=e,s=a(),c=n.get(r);if(!c)throw new SuggestLinksTargetNotFoundError(r);let l=extractPageIdentity(await readDocumentMarkdown(t,r,c),r),u=prepareSearchLabels(l),d=[...n.keys()].filter(e=>e!==r).sort((e,t)=>e.localeCompare(t)),f=new Map,p=!1;for(let e of d){if(a()-s>i){p=!0;break}let o=n.get(e);if(!o)continue;let c;try{c=await readDocumentMarkdown(t,e,o)}catch(t){log$3.warn({docName:e,err:t},`[suggest-links] Failed to read source doc`);continue}let l=scanMarkdownForMentions(c,e,r,u).map(t=>({source:e,excerpt:t.excerpt,offset:t.offset}));l.length>0&&f.set(e,l)}let m=[...f.entries()].sort(([e,t],[n,r])=>r.length===t.length?e===n?(t[0]?.offset??2**53-1)-(r[0]?.offset??2**53-1):e.localeCompare(n):r.length-t.length).flatMap(([,e])=>e),h=a()-s,g={durationMs:h,corpusDocCount:d.length,candidateCount:m.length,truncated:p};return log$3.info({docName:r,durationMs:h,corpusDocCount:d.length,candidateCount:m.length,truncated:p,labelCount:u.length,normalizedTarget:toWikiLinkSlug(l.title)},`[suggest-links] scan completed`),o?.(g),{target:toPublicTarget(l),mentions:m,truncated:p}}const GIT_LOG_FORMAT=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,EMPTY={entries:[],total:0,hasMore:!1};function classifyType(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`import:`)||e.startsWith(`upstream:`)?`upstream`:`wip`}function parseGitLogOutput(e){return e.trim()?e.split(``).map(e=>{let t=e.trimStart();if(!t)return null;let[n=``,r=``,i=``,a=``,o=``,s=``]=t.split(`\0`),c=classifyType(o);return{sha:n.trim(),timestamp:r,author:i,authorEmail:a,type:c,message:o,contributors:readContributors(s),checkpoint:c===`checkpoint`?parseCheckpoint(s):null}}).filter(e=>e!==null&&e.sha.length===40):[]}function toArray(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}function matchesAuthor(e,t){return t.length===0?!0:t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}async function getDocumentHistory(e,t,n=`content`){if(!existsSync(e.workTree)||!existsSync(e.gitDir))return EMPTY;let r=t.branch??`main`,i=Math.max(1,t.limit??50),a=Math.max(0,t.offset??0),o=toArray(t.type),s=toArray(t.author),c=toArray(t.excludeAuthor),l=n.replace(/^\.\//,``),u=t.docName?l?`${l}/${t.docName}${getDocExtension(t.docName)}`:`${t.docName}${getDocExtension(t.docName)}`:void 0;try{let t=shadowGit(e);if(o.length===1&&o[0]===`checkpoint`){let e=(await t.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
110
+ `){u+=2,l=u;continue}u+=1,l=u}return s}function serializeLiveDocument$1(e){let t=e.getXmlFragment(`default`),n=mdManager.serialize(yXmlFragmentToProseMirrorRootNode(t,schema).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return prependFrontmatter(typeof r==`string`?r:``,n)}async function readDocumentMarkdown(e,t,n){let r=e.documents.get(t);if(r)try{return serializeLiveDocument$1(r)}catch(e){return log$3.warn({docName:t,err:e},`[suggest-links] Failed live serialization, falling back to live source text`),r.getText(`source`).toString()}return await readFile(n.canonicalPath,`utf-8`)}function toPublicTarget(e){return{docName:e.docName,title:e.title,aliases:e.aliases}}async function suggestLinks(e){let{hocuspocus:t,fileIndex:n,docName:r,scanBudgetMs:i=500,now:a=()=>Date.now(),onComplete:o}=e,s=a(),c=n.get(r);if(!c)throw new SuggestLinksTargetNotFoundError(r);let l=extractPageIdentity(await readDocumentMarkdown(t,r,c),r),u=prepareSearchLabels(l),d=[...n.keys()].filter(e=>e!==r).sort((e,t)=>e.localeCompare(t)),f=new Map,p=!1;for(let e of d){if(a()-s>i){p=!0;break}let o=n.get(e);if(!o)continue;let c;try{c=await readDocumentMarkdown(t,e,o)}catch(t){log$3.warn({docName:e,err:t},`[suggest-links] Failed to read source doc`);continue}let l=scanMarkdownForMentions(c,e,r,u).map(t=>({source:e,excerpt:t.excerpt,offset:t.offset}));l.length>0&&f.set(e,l)}let m=[...f.entries()].sort(([e,t],[n,r])=>r.length===t.length?e===n?(t[0]?.offset??2**53-1)-(r[0]?.offset??2**53-1):e.localeCompare(n):r.length-t.length).flatMap(([,e])=>e),h=a()-s,g={durationMs:h,corpusDocCount:d.length,candidateCount:m.length,truncated:p};return log$3.info({docName:r,durationMs:h,corpusDocCount:d.length,candidateCount:m.length,truncated:p,labelCount:u.length,normalizedTarget:toWikiLinkSlug(l.title)},`[suggest-links] scan completed`),o?.(g),{target:toPublicTarget(l),mentions:m,truncated:p}}const GIT_LOG_FORMAT=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,EMPTY={entries:[],total:0,hasMore:!1};function classifyType(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`import:`)||e.startsWith(`upstream:`)?`upstream`:`wip`}function parseGitLogOutput(e){return e.trim()?e.split(``).map(e=>{let t=e.trimStart();if(!t)return null;let[n=``,r=``,i=``,a=``,o=``,s=``]=t.split(`\0`),c=classifyType(o);return{sha:n.trim(),timestamp:r,author:i,authorEmail:a,type:c,message:o,contributors:readContributors(s),checkpoint:c===`checkpoint`?parseCheckpoint(s):null}}).filter(e=>e!==null&&e.sha.length===40):[]}function toArray(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}function matchesAuthor(e,t){return t.length===0?!0:t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}async function getDocumentHistory(e,t,n=`.`){if(!existsSync(e.workTree)||!existsSync(e.gitDir))return EMPTY;let r=t.branch??`main`,i=Math.max(1,t.limit??50),a=Math.max(0,t.offset??0),o=toArray(t.type),s=toArray(t.author),c=toArray(t.excludeAuthor),l=n===`.`?``:n.replace(/^\.\//,``),u=t.docName?l?`${l}/${t.docName}${getDocExtension(t.docName)}`:`${t.docName}${getDocExtension(t.docName)}`:void 0;try{let t=shadowGit(e);if(o.length===1&&o[0]===`checkpoint`){let e=(await t.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
111
111
  `).filter(e=>e.length===40),n=[];if(r!==`main`)try{n=(await t.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
112
112
  `).filter(e=>e.length===40)}catch{}let o=[...e,...n];if(o.length===0)return EMPTY;let l=parseGitLogOutput(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...o)).map(e=>({...e,type:`checkpoint`}));if(u){let e=await Promise.all(l.map(async e=>{try{return await t.raw(`cat-file`,`-e`,`${e.sha}:${u}`),!0}catch{return!1}}));l=l.filter((t,n)=>e[n])}if(r!==`main`&&e.length>0&&n.length>0){let t=new Set(e),n=l.filter(e=>t.has(e.sha)),r=l.filter(e=>!t.has(e.sha)),i=n.reduce((e,t)=>Math.min(e,new Date(t.timestamp).getTime()),1/0);l=[...n,...r.filter(e=>new Date(e.timestamp).getTime()<i)]}let d=l.filter(e=>matchesAuthor(e,s)&&(c.length===0||!matchesAuthor(e,c))),f=d.length;return{entries:d.slice(a,a+i),total:f,hasMore:a+i<f}}let n=[],l=[],d=r!==`main`;try{let e=(await t.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
113
113
  `).filter(e=>e.length===40);n.push(...e)}catch{}let f=[];if(d)try{f=(await t.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
114
114
  `).filter(e=>e.length===40)}catch{}try{let e=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/${r}/`)).trim().split(`
115
115
  `).filter(Boolean);l.push(...e)}catch{}if(d&&l.length===0)try{let e=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/main/`)).trim().split(`
116
- `).filter(Boolean);l.push(...e)}catch{}if(l.length===0&&n.length===0&&f.length===0)return EMPTY;let p=[...n,...f],m=[];if(p.length>0){let e=parseGitLogOutput(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...p)).map(e=>({...e,type:`checkpoint`}));if(u){let n=await Promise.all(e.map(async e=>{try{return await t.raw(`cat-file`,`-e`,`${e.sha}:${u}`),!0}catch{return!1}}));e=e.filter((e,t)=>n[t])}if(d&&n.length>0&&f.length>0){let t=new Set(n),r=e.filter(e=>t.has(e.sha)),i=e.filter(e=>!t.has(e.sha)),a=r.reduce((e,t)=>{let n=new Date(t.timestamp).getTime();return n<e?n:e},1/0);m=[...r,...i.filter(e=>new Date(e.timestamp).getTime()<a)]}else m=e}let h=[...l];for(let e of p)h.push(e);let g=[];h.length>0&&(g=parseGitLogOutput(await t.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...h,...u?[`--`,u]:[])));let _=[...m,...g],v=new Set,y=[];for(let e of _)v.has(e.sha)||(v.add(e.sha),y.push(e));y.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let b=y;o.length>0&&(b=b.filter(e=>o.includes(e.type))),s.length>0&&(b=b.filter(e=>matchesAuthor(e,s))),c.length>0&&(b=b.filter(e=>!matchesAuthor(e,c)));let x=b.length;return{entries:b.slice(a,a+i),total:x,hasMore:a+i<x}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of attach-preview-once hints emitted on write-tool responses when no editor is attached to __system__`}),_hintEmittedCounter}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$2=getLogger(`api`);function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name`};let n=t.replace(/^\.\//,``),r=getDocExtension(e);return{path:n?`${n}/${e}${r}`:`${e}${r}`}}const MAX_BODY_BYTES=1048576,MAX_UPLOAD_BYTES=10*1024*1024,ALLOWED_MIME_TYPES=new Set(ALLOWED_IMAGE_MIME_TYPES),GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i;function sanitizeFilename(e){let t=e.replace(/[/\\]/g,``),n=extname(t);return(t.slice(0,t.length-n.length).replace(/[^a-zA-Z0-9_\-.]/g,`_`)||`upload`)+n.replace(/[^a-zA-Z0-9_.]/g,``)}function writeUploadAtomic(e,t,n){let r=extname(t),i=t.slice(0,t.length-r.length),a=[t,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let t of a){let r=resolve(e,t);try{let e=openSync(r,`wx`);try{writeSync(e,n)}finally{closeSync(e)}return t}catch(e){if(e.code===`EEXIST`)continue;throw e}}throw Error(`Could not find available filename after 100 attempts`)}function readUploadBody(e,t){return new Promise((n,r)=>{let i;try{i=(0,import_lib.default)({headers:e.headers,limits:{fileSize:t,files:1}})}catch(e){r(e);return}let a=!1,o=`upload`,s=``,c=``,l=[],u=!1;i.on(`field`,(e,t)=>{e===`parentDocName`&&(c=t)}),i.on(`file`,(t,n,c)=>{o=c.filename||`upload`,s=c.mimeType||``,n.on(`data`,e=>{l.push(e)}),n.on(`limit`,()=>{u=!0,e.unpipe(i),a||(a=!0,r(Error(`Payload too large`)))}),n.on(`error`,e=>{a||(a=!0,r(e))})}),i.on(`finish`,()=>{if(!a){if(u){a=!0,r(Error(`Payload too large`));return}if(!s&&l.length===0){a=!0,r(Error(`No file received`));return}a=!0,n({filename:o,mimeType:s,buffer:Buffer.concat(l),parentDocName:c})}}),i.on(`error`,e=>{a||(a=!0,r(e))}),e.pipe(i)})}function safeSubdir(e,t){let n=resolve(e,t);if(n!==e&&!n.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return n}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function listAffectedDocNames(e,t,n){let r=[...e.keys()].filter(e=>t===`file`?e===n:e===n||e.startsWith(`${n}/`));return r.sort((e,t)=>e.localeCompare(t)),r}function remapDocNameForRename(e,t,n,r){return t===`file`||e===n?r:`${r}${e.slice(n.length)}`}function rewriteSupportedLinksForDocumentRename(e,t,n,r){let{frontmatter:i,body:a}=stripFrontmatter(e),o=rewriteWikiLinksForDocumentRename(a,n,r),s=rewriteMarkdownLinksForDocumentRename(o.markdown,t,n,r);return{markdown:prependFrontmatter(i,s.markdown),rewrites:o.rewrites+s.rewrites}}function assertNoSymlinkEscape(e,t){let n;try{n=realpathSync(t)}catch{return}let r=e;for(;;)try{if(!isWithinContentDir(realpathSync(r),n))throw Error(`symlink-escape: path resolves outside content directory`);return}catch(e){let n=e.code;if(n===`ELOOP`)throw Error(`symlink-escape: symlink cycle in path`);if(n!==`ENOENT`)throw e;let i=dirname(r);if(i===r||i!==t&&!i.startsWith(`${t}${sep}`))throw e;r=i}}function resolveContentEntryPath(e,t,n){if(!isValidRelativeContentPath(n))throw Error(`path must be a relative content path`);let r=resolve(e),i=resolve(r,t===`file`?`${n}${getDocExtension(n)}`:n);if(i!==r&&!i.startsWith(`${r}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(i,r),i}function toGitRelativePath(e,t){let n=resolve(e),r=resolve(t);return r!==n&&!r.startsWith(`${n}${sep}`)?null:relative(n,r).split(sep).join(`/`)}async function renameTrackedPathInGit(e,t,n){if(!e)return!1;let r=toGitRelativePath(e,t),i=toGitRelativePath(e,n);return!r||!i?!1:await withParentLock(async()=>{let t=esm_default({baseDir:e,timeout:{block:15e3}});if(!(await t.raw(`ls-files`,`--`,r)).trim())return!1;mkdirSync(dirname(n),{recursive:!0});try{return await t.raw(`mv`,`--`,r,i),!0}catch(e){return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}async function readBody(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>MAX_BODY_BYTES)throw Error(`Payload too large`);t.push(r)}return Buffer.concat(t)}function json(e,t,n,r){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`,...r}),e.end(JSON.stringify(n))}function extractHeadings(e){let t=e;if(e.startsWith(`---
116
+ `).filter(Boolean);l.push(...e)}catch{}if(l.length===0&&n.length===0&&f.length===0)return EMPTY;let p=[...n,...f],m=[];if(p.length>0){let e=parseGitLogOutput(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...p)).map(e=>({...e,type:`checkpoint`}));if(u){let n=await Promise.all(e.map(async e=>{try{return await t.raw(`cat-file`,`-e`,`${e.sha}:${u}`),!0}catch{return!1}}));e=e.filter((e,t)=>n[t])}if(d&&n.length>0&&f.length>0){let t=new Set(n),r=e.filter(e=>t.has(e.sha)),i=e.filter(e=>!t.has(e.sha)),a=r.reduce((e,t)=>{let n=new Date(t.timestamp).getTime();return n<e?n:e},1/0);m=[...r,...i.filter(e=>new Date(e.timestamp).getTime()<a)]}else m=e}let h=[...l];for(let e of p)h.push(e);let g=[];h.length>0&&(g=parseGitLogOutput(await t.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...h,...u?[`--`,u]:[])));let _=[...m,...g],v=new Set,y=[];for(let e of _)v.has(e.sha)||(v.add(e.sha),y.push(e));y.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let b=y;o.length>0&&(b=b.filter(e=>o.includes(e.type))),s.length>0&&(b=b.filter(e=>matchesAuthor(e,s))),c.length>0&&(b=b.filter(e=>!matchesAuthor(e,c)));let x=b.length;return{entries:b.slice(a,a+i),total:x,hasMore:a+i<x}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of attach-preview-once hints emitted on write-tool responses when no editor is attached to __system__`}),_hintEmittedCounter}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$2=getLogger(`api`);function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name`};let n=t===`.`?``:t.replace(/^\.\//,``),r=getDocExtension(e);return{path:n?`${n}/${e}${r}`:`${e}${r}`}}const MAX_BODY_BYTES=1048576,MAX_UPLOAD_BYTES=10*1024*1024,ALLOWED_MIME_TYPES=new Set(ALLOWED_IMAGE_MIME_TYPES),GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i;function sanitizeFilename(e){let t=e.replace(/[/\\]/g,``),n=extname(t);return(t.slice(0,t.length-n.length).replace(/[^a-zA-Z0-9_\-.]/g,`_`)||`upload`)+n.replace(/[^a-zA-Z0-9_.]/g,``)}function writeUploadAtomic(e,t,n){let r=extname(t),i=t.slice(0,t.length-r.length),a=[t,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let t of a){let r=resolve(e,t);try{let e=openSync(r,`wx`);try{writeSync(e,n)}finally{closeSync(e)}return t}catch(e){if(e.code===`EEXIST`)continue;throw e}}throw Error(`Could not find available filename after 100 attempts`)}function readUploadBody(e,t){return new Promise((n,r)=>{let i;try{i=(0,import_lib.default)({headers:e.headers,limits:{fileSize:t,files:1}})}catch(e){r(e);return}let a=!1,o=`upload`,s=``,c=``,l=[],u=!1;i.on(`field`,(e,t)=>{e===`parentDocName`&&(c=t)}),i.on(`file`,(t,n,c)=>{o=c.filename||`upload`,s=c.mimeType||``,n.on(`data`,e=>{l.push(e)}),n.on(`limit`,()=>{u=!0,e.unpipe(i),a||(a=!0,r(Error(`Payload too large`)))}),n.on(`error`,e=>{a||(a=!0,r(e))})}),i.on(`finish`,()=>{if(!a){if(u){a=!0,r(Error(`Payload too large`));return}if(!s&&l.length===0){a=!0,r(Error(`No file received`));return}a=!0,n({filename:o,mimeType:s,buffer:Buffer.concat(l),parentDocName:c})}}),i.on(`error`,e=>{a||(a=!0,r(e))}),e.pipe(i)})}function safeSubdir(e,t){let n=resolve(e,t);if(n!==e&&!n.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return n}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function listAffectedDocNames(e,t,n){let r=[...e.keys()].filter(e=>t===`file`?e===n:e===n||e.startsWith(`${n}/`));return r.sort((e,t)=>e.localeCompare(t)),r}function remapDocNameForRename(e,t,n,r){return t===`file`||e===n?r:`${r}${e.slice(n.length)}`}function rewriteSupportedLinksForDocumentRename(e,t,n,r){let{frontmatter:i,body:a}=stripFrontmatter(e),o=rewriteWikiLinksForDocumentRename(a,n,r),s=rewriteMarkdownLinksForDocumentRename(o.markdown,t,n,r);return{markdown:prependFrontmatter(i,s.markdown),rewrites:o.rewrites+s.rewrites}}function assertNoSymlinkEscape(e,t){let n;try{n=realpathSync(t)}catch{return}let r=e;for(;;)try{if(!isWithinContentDir(realpathSync(r),n))throw Error(`symlink-escape: path resolves outside content directory`);return}catch(e){let n=e.code;if(n===`ELOOP`)throw Error(`symlink-escape: symlink cycle in path`);if(n!==`ENOENT`)throw e;let i=dirname(r);if(i===r||i!==t&&!i.startsWith(`${t}${sep}`))throw e;r=i}}function resolveContentEntryPath(e,t,n){if(!isValidRelativeContentPath(n))throw Error(`path must be a relative content path`);let r=resolve(e),i=resolve(r,t===`file`?`${n}${getDocExtension(n)}`:n);if(i!==r&&!i.startsWith(`${r}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(i,r),i}function toGitRelativePath(e,t){let n=resolve(e),r=resolve(t);return r!==n&&!r.startsWith(`${n}${sep}`)?null:relative(n,r).split(sep).join(`/`)}async function renameTrackedPathInGit(e,t,n){if(!e)return!1;let r=toGitRelativePath(e,t),i=toGitRelativePath(e,n);return!r||!i?!1:await withParentLock(async()=>{let t=esm_default({baseDir:e,timeout:{block:15e3}});if(!(await t.raw(`ls-files`,`--`,r)).trim())return!1;mkdirSync(dirname(n),{recursive:!0});try{return await t.raw(`mv`,`--`,r,i),!0}catch(e){return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}async function readBody(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>MAX_BODY_BYTES)throw Error(`Payload too large`);t.push(r)}return Buffer.concat(t)}function json(e,t,n,r){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`,...r}),e.end(JSON.stringify(n))}function extractHeadings(e){let t=e;if(e.startsWith(`---
117
117
  `)||e.startsWith(`---\r
118
118
  `)){let n=e.indexOf(`
119
119
  ---`,3);n!==-1&&(t=e.slice(n+4))}let n=[],r=new Map,i=createCodeFenceTracker();for(let e of t.split(`
120
- `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=getHeadingSlug(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function createApiExtension(e){let{hocuspocus:t,sessionManager:n,contentDir:r,serverInstanceId:i,getFileIndex:a,getAliasMap:o,enableTestRoutes:s=!1,shadowRef:c,flushGitCommit:l,getCurrentBranch:u,getDiskAckSVs:d,contentRoot:f,backlinkIndex:p,signalChannel:m,agentFocusBroadcaster:h,agentPresenceBroadcaster:g,onAgentWrite:_,getSyncEngine:v,localOpCliArgs:y=[`open-knowledge`],projectDir:b,getPrincipal:x,installedAgentsProbe:S}=e,C=createConcurrencyGuard(),w=createInstalledAgentsProbe({probe:S??createOsProbe(process.platform)});function T(e){if(!isSafeDocName(e))return null;let t=resolve(r),n=resolve(t,`${e}${getDocExtension(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function E(e){let t=T(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}let D={cluster:void 0,category:void 0,tags:void 0};function O(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return parseFrontmatterMetadata(e)}}catch{}try{let t=T(e);if(!t||!existsSync(t))return D;let{frontmatter:n}=stripFrontmatter(readFileSync(t,`utf-8`));return n?parseFrontmatterMetadata(n):D}catch{return D}}function k(e){if(p)try{if(p.getBacklinks(e).length>0)return;let t=performance.now(),n=findHubCandidates(e,a()),r=performance.now()-t;return r>5&&log$2.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function A(e){return o?.().get(e)??e}function j(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function M(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function N(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>l?.()).catch(e=>{log$2.warn({err:e},`[${n}] post-write flush failed`)})}function P(){let e=new Set;for(let[t,n]of a()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function F(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let I=F();function L(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function R(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);deleteReconciledBase(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function z(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=safeContentPath(i,r),a=t.get(n);typeof a==`string`&&writeFileSync(e,a,`utf-8`);let o=typeof a==`string`?a:existsSync(e)?readFileSync(e,`utf-8`):null;typeof o==`string`&&registerWrite(e,contentHash(o))}}function B(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=safeContentPath(e,r);if(!existsSync(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:readFileSync(i,`utf-8`)}})}function V(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=resolveContentEntryPath(r,`file`,e);return existsSync(i)?readFileSync(i,`utf-8`):null}function H(e,t){let n=resolveContentEntryPath(r,`file`,e);mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),registerWrite(n,contentHash(t)),setReconciledBase(e,t);let i=a();i instanceof Map&&updateFileIndex({kind:`update`,path:n,docName:e,content:t},i)}function U(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=rewriteSupportedLinksForDocumentRename(s,e,n,r),a.rewrites===0)return;let{body:c}=stripFrontmatter(a.markdown),l=mdManager.parseWithFallback(c);updateYFragment(i,t,schema.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),applyFastDiff(o,s,a.markdown)},MANAGED_RENAME_ORIGIN),a}async function W(e,n){return I(async()=>{if(!p)throw Error(`Managed rename requires backlink index support`);let i=resolveContentEntryPath(r,`file`,e),o=resolveContentEntryPath(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(p.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],d=[];for(let t of[e,...c]){if(l.has(t))continue;let n=V(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&d.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let f=createManagedRenameRecoveryJournal({sourceDocName:e,destinationDocName:n,snapshots:B([...l.keys()],l)}),h=[];return await withManagedRenameRecovery(r,f,async()=>{for(let e of d)p.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?U(r,e,n):rewriteSupportedLinksForDocumentRename(l.get(r)??``,r,e,n);i.rewrites>0&&(H(r,i.markdown),h.push({docName:r,rewrites:i.rewrites})),p.updateDocumentFromMarkdown(r,i.markdown)}let r=rewriteSupportedLinksForDocumentRename((await R([e])).get(e)??l.get(e)??readFileSync(i,`utf-8`),e,e,n);await renameTrackedPathInGit(b,i,o)||(mkdirSync(dirname(o),{recursive:!0}),renameSync(i,o)),z(s,new Map([[e,r.markdown]])),setReconciledBase(n,r.markdown);let c=a();c instanceof Map&&updateFileIndex({kind:`rename`,oldPath:i,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),p.renameDocument(e,n,r.markdown),r.rewrites>0&&h.push({docName:n,rewrites:r.rewrites})}),p.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),m?.(`files`),m?.(`backlinks`),m?.(`graph`),h.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:h}})}let G=128;function K(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!AGENT_ID_RE.test(t)&&(t=void 0);let n=t?toBroadcasterKey(t):`claude-1`,r=typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=sanitizeGitIdentity(i));let a=typeof e.clientVersion==`string`?e.clientVersion:void 0;a!==void 0&&(a=sanitizeGitIdentity(a));let o=typeof e.label==`string`?e.label:void 0;o!==void 0&&(o=sanitizeGitIdentity(o));let s=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:s,clientName:i,clientVersion:a,label:o}}function q(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function J(e){return{principalId:x?.()?.id,agentType:q(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Y(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function X(e){return{value:e.value}}function Z(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}async function Q(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let o=A(a);if(isSystemDoc(o)){json(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:d,label:f}=K(i),p=normalizeSummary(i.summary);if(p.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let m=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),h=new Date().toISOString(),v=typeof i.content==`string`?i.content:`Hello from the agent! ${h}`,{response:y,stored:b}=Y(p);try{let e=iconFromClientName(u),t=AGENT_ICON_COLORS[e]??colorFromSeed(l??s);g?.setPresence(s,{displayName:c,icon:e,color:t,currentDoc:o,mode:`writing`,ts:Date.now()}),captureEffect(m.dc.document.getText(`source`),s,l,u),m.dc.document.transact(()=>{applyAgentMarkdownWrite(m.dc.document,`${v}\n`,`append`),m.dc.document.getMap(`agent-flash`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${v.slice(0,50)}`})},m.origin),recordContributor(o,s,c,l,void 0,J({clientName:u,clientVersion:d,label:f}),b),incrementAgentWriteCalls(),Z(p)}finally{g?.touchMode(s,`idle`)}N(o,`agent-write`),_?.(),json(t,200,{ok:!0,timestamp:h,...y?{summary:y}:{}})}catch(e){log$2.error({err:e},`[agent-write] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function ee(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){json(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!isSafeDocName(l)){json(t,400,{ok:!1,error:`Invalid docName`});return}let u=A(l);if(isSystemDoc(u)){json(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:p,clientName:m,clientVersion:v,label:y}=K(i),b=normalizeSummary(i.summary);if(b.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{response:x,stored:S}=Y(b),C=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),w=new Date().toISOString();try{let e=iconFromClientName(m),t=AGENT_ICON_COLORS[e]??colorFromSeed(p??d);g?.setPresence(d,{displayName:f,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),d,p,m),C.dc.document.transact(()=>{applyAgentMarkdownWrite(C.dc.document,a,s),C.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},C.origin),recordContributor(u,d,f,p,void 0,J({clientName:m,clientVersion:v,label:y}),S),incrementAgentWriteCalls(),Z(b)}finally{g?.touchMode(d,`idle`)}N(u,`agent-write-md`),h?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),_?.();let T=k(u),E=j(u),D=M();D===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":q(m)}),json(t,200,{ok:!0,timestamp:w,subscriberCount:E,systemSubscriberCount:D,...T?{hints:T}:{},...x?{summary:x}:{}})}catch(e){log$2.error({err:e},`[agent-write-md] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function te(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}let i=A(r);if(isSystemDoc(i)){json(n,400,{ok:!1,error:`'${i}' is a reserved document name`});return}let a=await t.openDirectConnection(i);try{let e=a.document;if(!e){json(n,500,{ok:!1,error:`Document not available`});return}json(n,200,{ok:!0,docName:i,content:e.getText(`source`).toString()})}finally{await a.disconnect()}}catch(e){console.error(`[document-read]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function ne(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{safeSubdir(r,n)}catch{json(t,400,{ok:!1,error:`Invalid directory parameter`});return}let i=a(),o=[];for(let[e,t]of i)if(!(n&&!e.startsWith(`${n}/`)&&e!==n)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=relative(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function re(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,backlinks:p.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:E(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),json(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function ie(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){json(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(r[t]=p.getBacklinkCount(t))}json(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),json(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function ae(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,forwardLinks:p.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:E(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),json(t,500,{ok:!1,error:`Failed to read forward links`})}}async function oe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!isSafeDocName(r)){json(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){json(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){json(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=p.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=p.getLinkGraph());json(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=O(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:E(e.docName),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o})}catch(e){console.error(`[link-graph]`,e),json(t,500,{ok:!1,error:`Failed to read link graph`})}}async function se(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(n)){json(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}json(t,200,{ok:!0,orphans:p.getOrphans([...a().keys()],n).map(e=>({docName:e,title:E(e)}))})}catch(e){console.error(`[orphans]`,e),json(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function ce(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;json(t,200,{ok:!0,hubs:p.getHubs(i).map(e=>({docName:e.docName,title:E(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),json(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function le(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!isSafeDocName(e))){json(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>A(e)))]:void 0;json(t,200,{ok:!0,deadLinks:p.getDeadLinks(P(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:E(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),json(t,500,{ok:!1,error:`Failed to read dead links`})}}async function ue(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){json(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){json(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),u;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}u=c}let d=typeof s==`string`&&s.length>0?s:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=A(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let{agentId:p,agentName:m,colorSeed:v,clientName:y,clientVersion:b,label:x}=K(i),S=normalizeSummary(i.summary);if(S.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let C=await n.getSession(f,p,{displayName:m,colorSeed:v,clientName:y}),w=new Date().toISOString(),T=!1,E=!1;try{let e=iconFromClientName(y),t=AGENT_ICON_COLORS[e]??colorFromSeed(v??p);if(g?.setPresence(p,{displayName:m,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),p,v,y),C.dc.document.transact(()=>{let e=C.dc.document.getXmlFragment(`default`),t=C.dc.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=prependFrontmatter(n,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(e,schema).toJSON())),i=u==null?r.indexOf(a):r.slice(u,u+a.length)===a?u:-1;if(i===-1){u==null?T=!0:E=!0;return}let{frontmatter:s,body:c}=stripFrontmatter(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),applyAgentMarkdownWrite(C.dc.document,c,`replace`),C.dc.document.getMap(`agent-flash`).set(p,{agentId:p,timestamp:Date.now(),type:`insert`,description:`Patched (${m}): ${a.slice(0,50)}`})},C.origin),!T&&!E){let{stored:e}=Y(S);recordContributor(f,p,m,v,void 0,J({clientName:y,clientVersion:b,label:x}),e),incrementAgentWriteCalls(),Z(S)}}finally{g?.touchMode(p,`idle`)}if(E){json(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(T){json(t,404,{ok:!1,error:`Text not found in document`});return}N(f,`agent-patch`),h?.setFocus(p,{agentName:m,currentDoc:f,writeKind:`edit`,ts:Date.now()}),_?.();let D=j(f),O=M();O===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":q(y)});let{response:k}=Y(S);json(t,200,{ok:!0,timestamp:w,subscriberCount:D,systemSubscriberCount:O,...k?{summary:k}:{}})}catch(e){log$2.error({err:e},`[agent-patch] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function de(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=K(i),d=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=A(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let p=typeof i.connectionId==`string`?i.connectionId:void 0;if(!p){json(t,400,{ok:!1,error:`connectionId required`});return}let m=i.scope,_=m===`session`||m===`file`?`session`:`last`;if(!n.hasSession(f,p)){json(t,404,{ok:!1,error:`No active session for this connectionId and docName`});return}let v=await n.getSession(f,p),y=!1;try{let e=iconFromClientName(c),t=AGENT_ICON_COLORS[e]??colorFromSeed(s??a);g?.setPresence(a,{displayName:o,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),y=applyAgentUndo(v,_),y&&recordContributor(f,p,o,s,void 0,J({clientName:c,clientVersion:l,label:u}))}finally{g?.touchMode(a,`idle`)}y&&N(f,`agent-undo`),h?.setFocus(p,{agentName:p,currentDoc:f,writeKind:`undo`,ts:Date.now()}),json(t,200,{ok:!0,docName:f,scope:_,undone:y})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function fe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(r===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}json(t,200,{ok:!0,...listAgentActivity(n,r)})}catch(e){log$2.error({err:e},`[agent-activity] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function pe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=validateAgentId(r.searchParams.get(`agentId`)),a=r.searchParams.get(`docName`),o=r.searchParams.get(`stackIndex`);if(i===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}if(!a||a.trim()===``){json(t,400,{ok:!1,error:`docName required`});return}if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let s=A(a);if(isSystemDoc(s)){json(t,400,{ok:!1,error:`'${s}' is a reserved document name`});return}if(!o||Number.isNaN(Number(o))){json(t,400,{ok:!1,error:`stackIndex must be a number`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`stackIndex must be a non-negative integer`});return}let l=n.getLiveSession(s,i);if(!l){json(t,404,{ok:!1,error:`No active session for this agentId and docName`});return}let u=l.um;if(c>=u.undoStack.length){json(t,404,{ok:!1,error:`stackIndex ${c} out of range (stack has ${u.undoStack.length} items)`});return}let d=u.undoStack[c];json(t,200,{ok:!0,diff:synthesizeStackItemDiffText(d,l.dc.document.getText(`source`),s),generatedAt:Date.now()})}catch(e){log$2.error({err:e},`[agent-burst-diff] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function me(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=A(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=safeContentPath(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),json(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await t.unloadDocument(c),writeFileSync(o,``,`utf-8`),p&&(p.deleteDocument(a),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),json(i,500,{ok:!1,error:`Internal server error`})}}async function he(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}p.rebuildFromDisk(),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),m?.(`backlinks`),m?.(`graph`),json(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function ge(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o,s={},c,l;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}s=e,typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}}));let n=e.principal;if(n&&typeof n==`object`&&!Array.isArray(n)){let e=n;typeof e.name==`string`&&e.name.trim()&&(c=sanitizeGitIdentity(e.name.trim())),typeof e.email==`string`&&e.email.trim()&&(l=sanitizeGitIdentity(e.email.trim()))}}let{rawAgentId:u,agentId:d,agentName:p,clientName:m}=K(s);a.length===0&&(a=u===void 0?[SERVICE_WRITER]:[{id:d,name:m?`${p} (${m})`:p,email:`${d}@openknowledge.local`}]);let h=f??`content`,g=await saveVersion(n,h,a);console.log(`[history] checkpoint ${g.checkpointRef}`);let _=swapContributors(),v;if(b){let e=!1;try{await esm_default({baseDir:b,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{v=await withParentLock(async()=>{let e=esm_default({baseDir:b,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=`openknowledge`,i=`noreply@openknowledge.local`;if(c&&l)r=c,i=l;else try{let e=await resolveGitIdentity(b);e&&(r=e.name,i=e.email)}catch{}let a=[];for(let e of _.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;a.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let s=formatCheckpointSubject(o??`Checkpoint v${t}`),u=a.length>0?`${s}\n\n${a.join(`
121
- `)}`:s,d=h||`.`;return await e.add(d),await e.env({GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i}).commit(u,[`--allow-empty`]),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}}json(t,200,{ok:!0,checkpointRef:g.checkpointRef,...v?{versionTag:v}:{}})}catch(e){console.error(`[save-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function _e(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??u?.()??`main`;if(!i){json(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){json(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),s=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),d=Number.isFinite(s)?s:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await getDocumentHistory(n,{docName:i,branch:a,limit:l,offset:d,type:p,author:m,excludeAuthor:h},f??`content`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),json(t,200,{ok:!0,...e})}catch(e){console.error(`[shadow]`,e),json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ve(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=c?.current;if(!r){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=safeDocPath(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,f??`content`);if(`error`in i){json(t,400,{ok:!1,error:i.error});return}let a=i.path,o=shadowGit(r);if(!/^[0-9a-f]{40}$/i.test(n)){json(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{json(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);json(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[shadow-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function ye(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,s=i.searchParams.get(`to`)??``;if(!s||!/^[0-9a-f]{40}$/i.test(s)){json(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=safeDocPath(a,f??`content`);if(`error`in l){json(n,400,{ok:!1,error:l.error});return}let u=l.path,d=shadowGit(r);try{let e;try{e=await d.raw(`show`,`${s}:${u}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await d.raw(`show`,`${o}:${u}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=stripFrontmatter(r).body,c=stripFrontmatter(e).body,l=diffLines(i,c),f=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
122
- `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)f.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}json(n,200,{ok:!0,lines:f,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function be(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await readBody(e)}catch{json(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{json(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:l,clientName:u,clientVersion:d,label:p}=K(a),{docName:m,commitSha:g,versionTag:_}=a,v=typeof m==`string`?m:``,y=typeof g==`string`?g:``,x=typeof _==`string`?_:void 0;if(!v){json(n,400,{ok:!1,error:`docName required`});return}if(!y||!/^[0-9a-f]{40}$/i.test(y)){json(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let S=a,C=typeof S.agentId==`string`&&S.agentId.length>0,w=normalizeSummary(S.summary);if(w.kind===`invalid`){json(n,400,{ok:!1,error:`summary must be a string`});return}let T=f??`content`,E=safeDocPath(v,T);if(`error`in E){json(n,400,{ok:!1,error:E.error});return}let D=E.path,O=shadowGit(r),k=Date.now();try{try{await O.raw(`cat-file`,`-e`,`${y}:${D}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await O.raw(`show`,`${y}:${D}`),i=new Date().toISOString();await safetyCheckpoint(r,T,{action:`rollback`,context:{docName:v,targetSha:y}});let a=t.documents.get(v);if(!a){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:c,body:m}=stripFrontmatter(e),g=mdManager.parseWithFallback(m),_=schema.nodeFromJSON(g),S=a.getXmlFragment(`default`);a.transact(()=>{updateYFragment(a,S,_,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,c)},ROLLBACK_ORIGIN);let E;if(C){let e=y.slice(0,8),t=w.kind===`value`,n=t?w:normalizeSummary(`Restored to ${e}`),r=Y(n);E=t||!r.response?r.response:X(r.response),recordContributor(v,o,s,l,formatRollbackSubject(v,y),J({clientName:u,clientVersion:d,label:p}),r.stored),incrementAgentWriteCalls(),Z(n,!t)}N(v,`rollback`);let A=Date.now()-k;if(console.log(`[rollback] docName=${v} from=${y.slice(0,8)} duration=${A}ms`),b){let e=`Restored to ${x??y.slice(0,8)}: ${v}`,t=f??`content`;withParentLock(async()=>{let n=esm_default({baseDir:b,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}C&&h?.setFocus(o,{agentName:s,currentDoc:v,writeKind:`rollback-apply`,ts:Date.now()}),json(n,200,{ok:!0,restoredFrom:y,timestamp:i,...E?{summary:E}:{}})}catch(e){console.error(`[rollback]`,e),json(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function xe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getMetrics())}async function Se(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getParseHealth())}async function Ce(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=getActiveBranch(),r=d?.();json(t,200,{ok:!0,serverInstanceId:i,currentBranch:n,...r===void 0?{}:{currentDiskAckSVs:r}},{"Cache-Control":`no-store`})}async function we(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=x?.()??null;if(!n){json(t,404,{error:`Principal not available`});return}json(t,200,n)}async function Te(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=g?.getPresenceMap()??{},r=Date.now(),i={};for(let[e,t]of Object.entries(n))r-t.ts<2e4&&(i[e]=t);json(t,200,{presence:i})}async function Ee(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=resolve(r),i=n,a=!0;try{i=realpathSync(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),json(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}json(t,200,{ok:!0,contentDir:i,pathSeparator:sep,symlinkResolved:a})}let De=1440*60*1e3;async function Oe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){json(t,200,[]);return}let n=Date.now(),r=[],i=resolve(c.current.gitDir,`rescue`);if(existsSync(i))try{let e=readdirSync(i).filter(e=>isSupportedDocFile(e));for(let t of e){let e=resolve(i,t),a=statSync(e);if(n-a.mtimeMs>De){try{unlinkSync(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:stripDocExtension(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=u?.()??`main`,t=await listRescueCheckpoints(c.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}json(t,200,r)}async function ke(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){t.writeHead(404),t.end(`Not found`);return}let r=resolve(c.current.gitDir,`rescue`),i=resolve(r,`${n}${getDocExtension(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(existsSync(i)){let e=statSync(i);if(Date.now()-e.mtimeMs>De)try{unlinkSync(i)}catch{}else{let e=readFileSync(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=u?.()??`main`,r=(await listRescueCheckpoints(c.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=shadowGit(c.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
120
+ `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=getHeadingSlug(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function createApiExtension(e){let{hocuspocus:t,sessionManager:n,contentDir:r,serverInstanceId:i,getFileIndex:a,getAliasMap:o,enableTestRoutes:s=!1,shadowRef:c,flushGitCommit:l,getCurrentBranch:u,getDiskAckSVs:d,contentRoot:f,backlinkIndex:p,signalChannel:m,agentFocusBroadcaster:h,agentPresenceBroadcaster:g,onAgentWrite:_,getSyncEngine:v,localOpCliArgs:y=[`open-knowledge`],projectDir:b,getPrincipal:x,installedAgentsProbe:S}=e,C=createConcurrencyGuard(),w=createInstalledAgentsProbe({probe:S??createOsProbe(process.platform)});function T(e){if(!isSafeDocName(e))return null;let t=resolve(r),n=resolve(t,`${e}${getDocExtension(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function E(e){let t=T(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}let D={cluster:void 0,category:void 0,tags:void 0};function O(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return parseFrontmatterMetadata(e)}}catch{}try{let t=T(e);if(!t||!existsSync(t))return D;let{frontmatter:n}=stripFrontmatter(readFileSync(t,`utf-8`));return n?parseFrontmatterMetadata(n):D}catch{return D}}function k(e){if(p)try{if(p.getBacklinks(e).length>0)return;let t=performance.now(),n=findHubCandidates(e,a()),r=performance.now()-t;return r>5&&log$2.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function A(e){return o?.().get(e)??e}function j(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function M(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function N(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>l?.()).catch(e=>{log$2.warn({err:e},`[${n}] post-write flush failed`)})}function P(){let e=new Set;for(let[t,n]of a()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function F(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let I=F();function L(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function R(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);deleteReconciledBase(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function z(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=safeContentPath(i,r),a=t.get(n);typeof a==`string`&&writeFileSync(e,a,`utf-8`);let o=typeof a==`string`?a:existsSync(e)?readFileSync(e,`utf-8`):null;typeof o==`string`&&registerWrite(e,contentHash(o))}}function B(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=safeContentPath(e,r);if(!existsSync(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:readFileSync(i,`utf-8`)}})}function V(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=resolveContentEntryPath(r,`file`,e);return existsSync(i)?readFileSync(i,`utf-8`):null}function H(e,t){let n=resolveContentEntryPath(r,`file`,e);mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),registerWrite(n,contentHash(t)),setReconciledBase(e,t);let i=a();i instanceof Map&&updateFileIndex({kind:`update`,path:n,docName:e,content:t},i)}function U(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=rewriteSupportedLinksForDocumentRename(s,e,n,r),a.rewrites===0)return;let{body:c}=stripFrontmatter(a.markdown),l=mdManager.parseWithFallback(c);updateYFragment(i,t,schema.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),applyFastDiff(o,s,a.markdown)},MANAGED_RENAME_ORIGIN),a}async function W(e,n){return I(async()=>{if(!p)throw Error(`Managed rename requires backlink index support`);let i=resolveContentEntryPath(r,`file`,e),o=resolveContentEntryPath(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(p.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],d=[];for(let t of[e,...c]){if(l.has(t))continue;let n=V(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&d.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let f=createManagedRenameRecoveryJournal({sourceDocName:e,destinationDocName:n,snapshots:B([...l.keys()],l)}),h=[];return await withManagedRenameRecovery(r,f,async()=>{for(let e of d)p.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?U(r,e,n):rewriteSupportedLinksForDocumentRename(l.get(r)??``,r,e,n);i.rewrites>0&&(H(r,i.markdown),h.push({docName:r,rewrites:i.rewrites})),p.updateDocumentFromMarkdown(r,i.markdown)}let r=rewriteSupportedLinksForDocumentRename((await R([e])).get(e)??l.get(e)??readFileSync(i,`utf-8`),e,e,n);await renameTrackedPathInGit(b,i,o)||(mkdirSync(dirname(o),{recursive:!0}),renameSync(i,o)),z(s,new Map([[e,r.markdown]])),setReconciledBase(n,r.markdown);let c=a();c instanceof Map&&updateFileIndex({kind:`rename`,oldPath:i,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),p.renameDocument(e,n,r.markdown),r.rewrites>0&&h.push({docName:n,rewrites:r.rewrites})}),p.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),m?.(`files`),m?.(`backlinks`),m?.(`graph`),h.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:h}})}let G=128;function K(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!AGENT_ID_RE.test(t)&&(t=void 0);let n=t?toBroadcasterKey(t):`claude-1`,r=typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=sanitizeGitIdentity(i));let a=typeof e.clientVersion==`string`?e.clientVersion:void 0;a!==void 0&&(a=sanitizeGitIdentity(a));let o=typeof e.label==`string`?e.label:void 0;o!==void 0&&(o=sanitizeGitIdentity(o));let s=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:s,clientName:i,clientVersion:a,label:o}}function q(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function J(e){return{principalId:x?.()?.id,agentType:q(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Y(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function X(e){return{value:e.value}}function Z(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}async function Q(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let o=A(a);if(isSystemDoc(o)){json(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:d,label:f}=K(i),p=normalizeSummary(i.summary);if(p.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let m=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),h=new Date().toISOString(),v=typeof i.content==`string`?i.content:`Hello from the agent! ${h}`,{response:y,stored:b}=Y(p);try{let e=iconFromClientName(u),t=AGENT_ICON_COLORS[e]??colorFromSeed(l??s);g?.setPresence(s,{displayName:c,icon:e,color:t,currentDoc:o,mode:`writing`,ts:Date.now()}),captureEffect(m.dc.document.getText(`source`),s,l,u),m.dc.document.transact(()=>{applyAgentMarkdownWrite(m.dc.document,`${v}\n`,`append`),m.dc.document.getMap(`agent-flash`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${v.slice(0,50)}`})},m.origin),recordContributor(o,s,c,l,void 0,J({clientName:u,clientVersion:d,label:f}),b),incrementAgentWriteCalls(),Z(p)}finally{g?.touchMode(s,`idle`)}N(o,`agent-write`),_?.(),json(t,200,{ok:!0,timestamp:h,...y?{summary:y}:{}})}catch(e){log$2.error({err:e},`[agent-write] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function ee(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){json(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!isSafeDocName(l)){json(t,400,{ok:!1,error:`Invalid docName`});return}let u=A(l);if(isSystemDoc(u)){json(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:p,clientName:m,clientVersion:v,label:y}=K(i),b=normalizeSummary(i.summary);if(b.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{response:x,stored:S}=Y(b),C=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),w=new Date().toISOString();try{let e=iconFromClientName(m),t=AGENT_ICON_COLORS[e]??colorFromSeed(p??d);g?.setPresence(d,{displayName:f,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),d,p,m),C.dc.document.transact(()=>{applyAgentMarkdownWrite(C.dc.document,a,s),C.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},C.origin),recordContributor(u,d,f,p,void 0,J({clientName:m,clientVersion:v,label:y}),S),incrementAgentWriteCalls(),Z(b)}finally{g?.touchMode(d,`idle`)}N(u,`agent-write-md`),h?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),_?.();let T=k(u),E=j(u),D=M();D===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":q(m)}),json(t,200,{ok:!0,timestamp:w,subscriberCount:E,systemSubscriberCount:D,...T?{hints:T}:{},...x?{summary:x}:{}})}catch(e){log$2.error({err:e},`[agent-write-md] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function te(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}let i=A(r);if(isSystemDoc(i)){json(n,400,{ok:!1,error:`'${i}' is a reserved document name`});return}let a=await t.openDirectConnection(i);try{let e=a.document;if(!e){json(n,500,{ok:!1,error:`Document not available`});return}json(n,200,{ok:!0,docName:i,content:e.getText(`source`).toString()})}finally{await a.disconnect()}}catch(e){console.error(`[document-read]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function ne(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{safeSubdir(r,n)}catch{json(t,400,{ok:!1,error:`Invalid directory parameter`});return}let i=a(),o=[];for(let[e,t]of i)if(!(n&&!e.startsWith(`${n}/`)&&e!==n)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=relative(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function re(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,backlinks:p.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:E(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),json(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function ie(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){json(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(r[t]=p.getBacklinkCount(t))}json(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),json(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function ae(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,forwardLinks:p.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:E(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),json(t,500,{ok:!1,error:`Failed to read forward links`})}}async function oe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!isSafeDocName(r)){json(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){json(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){json(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=p.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=p.getLinkGraph());json(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=O(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:E(e.docName),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o})}catch(e){console.error(`[link-graph]`,e),json(t,500,{ok:!1,error:`Failed to read link graph`})}}async function se(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(n)){json(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}json(t,200,{ok:!0,orphans:p.getOrphans([...a().keys()],n).map(e=>({docName:e,title:E(e)}))})}catch(e){console.error(`[orphans]`,e),json(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function ce(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;json(t,200,{ok:!0,hubs:p.getHubs(i).map(e=>({docName:e.docName,title:E(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),json(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function le(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!isSafeDocName(e))){json(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>A(e)))]:void 0;json(t,200,{ok:!0,deadLinks:p.getDeadLinks(P(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:E(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),json(t,500,{ok:!1,error:`Failed to read dead links`})}}async function ue(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){json(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){json(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),u;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}u=c}let d=typeof s==`string`&&s.length>0?s:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=A(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let{agentId:p,agentName:m,colorSeed:v,clientName:y,clientVersion:b,label:x}=K(i),S=normalizeSummary(i.summary);if(S.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let C=await n.getSession(f,p,{displayName:m,colorSeed:v,clientName:y}),w=new Date().toISOString(),T=!1,E=!1;try{let e=iconFromClientName(y),t=AGENT_ICON_COLORS[e]??colorFromSeed(v??p);if(g?.setPresence(p,{displayName:m,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),p,v,y),C.dc.document.transact(()=>{let e=C.dc.document.getXmlFragment(`default`),t=C.dc.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=prependFrontmatter(n,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(e,schema).toJSON())),i=u==null?r.indexOf(a):r.slice(u,u+a.length)===a?u:-1;if(i===-1){u==null?T=!0:E=!0;return}let{frontmatter:s,body:c}=stripFrontmatter(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),applyAgentMarkdownWrite(C.dc.document,c,`replace`),C.dc.document.getMap(`agent-flash`).set(p,{agentId:p,timestamp:Date.now(),type:`insert`,description:`Patched (${m}): ${a.slice(0,50)}`})},C.origin),!T&&!E){let{stored:e}=Y(S);recordContributor(f,p,m,v,void 0,J({clientName:y,clientVersion:b,label:x}),e),incrementAgentWriteCalls(),Z(S)}}finally{g?.touchMode(p,`idle`)}if(E){json(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(T){json(t,404,{ok:!1,error:`Text not found in document`});return}N(f,`agent-patch`),h?.setFocus(p,{agentName:m,currentDoc:f,writeKind:`edit`,ts:Date.now()}),_?.();let D=j(f),O=M();O===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":q(y)});let{response:k}=Y(S);json(t,200,{ok:!0,timestamp:w,subscriberCount:D,systemSubscriberCount:O,...k?{summary:k}:{}})}catch(e){log$2.error({err:e},`[agent-patch] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function de(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=K(i),d=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=A(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let p=typeof i.connectionId==`string`?i.connectionId:void 0;if(!p){json(t,400,{ok:!1,error:`connectionId required`});return}let m=i.scope,_=m===`session`||m===`file`?`session`:`last`;if(!n.hasSession(f,p)){json(t,404,{ok:!1,error:`No active session for this connectionId and docName`});return}let v=await n.getSession(f,p),y=!1;try{let e=iconFromClientName(c),t=AGENT_ICON_COLORS[e]??colorFromSeed(s??a);g?.setPresence(a,{displayName:o,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),y=applyAgentUndo(v,_),y&&recordContributor(f,p,o,s,void 0,J({clientName:c,clientVersion:l,label:u}))}finally{g?.touchMode(a,`idle`)}y&&N(f,`agent-undo`),h?.setFocus(p,{agentName:p,currentDoc:f,writeKind:`undo`,ts:Date.now()}),json(t,200,{ok:!0,docName:f,scope:_,undone:y})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function fe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(r===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}json(t,200,{ok:!0,...listAgentActivity(n,r)})}catch(e){log$2.error({err:e},`[agent-activity] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function pe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=validateAgentId(r.searchParams.get(`agentId`)),a=r.searchParams.get(`docName`),o=r.searchParams.get(`stackIndex`);if(i===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}if(!a||a.trim()===``){json(t,400,{ok:!1,error:`docName required`});return}if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let s=A(a);if(isSystemDoc(s)){json(t,400,{ok:!1,error:`'${s}' is a reserved document name`});return}if(!o||Number.isNaN(Number(o))){json(t,400,{ok:!1,error:`stackIndex must be a number`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`stackIndex must be a non-negative integer`});return}let l=n.getLiveSession(s,i);if(!l){json(t,404,{ok:!1,error:`No active session for this agentId and docName`});return}let u=l.um;if(c>=u.undoStack.length){json(t,404,{ok:!1,error:`stackIndex ${c} out of range (stack has ${u.undoStack.length} items)`});return}let d=u.undoStack[c];json(t,200,{ok:!0,diff:synthesizeStackItemDiffText(d,l.dc.document.getText(`source`),s),generatedAt:Date.now()})}catch(e){log$2.error({err:e},`[agent-burst-diff] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function me(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=A(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=safeContentPath(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),json(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await t.unloadDocument(c),writeFileSync(o,``,`utf-8`),p&&(p.deleteDocument(a),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),json(i,500,{ok:!1,error:`Internal server error`})}}async function he(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}p.rebuildFromDisk(),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),m?.(`backlinks`),m?.(`graph`),json(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function ge(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o,s={},c,l;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}s=e,typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}}));let n=e.principal;if(n&&typeof n==`object`&&!Array.isArray(n)){let e=n;typeof e.name==`string`&&e.name.trim()&&(c=sanitizeGitIdentity(e.name.trim())),typeof e.email==`string`&&e.email.trim()&&(l=sanitizeGitIdentity(e.email.trim()))}}let{rawAgentId:u,agentId:d,agentName:p,clientName:m}=K(s);a.length===0&&(a=u===void 0?[SERVICE_WRITER]:[{id:d,name:m?`${p} (${m})`:p,email:`${d}@openknowledge.local`}]);let h=f??`.`,g=await saveVersion(n,h,a);console.log(`[history] checkpoint ${g.checkpointRef}`);let _=swapContributors(),v;if(b){let e=!1;try{await esm_default({baseDir:b,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{v=await withParentLock(async()=>{let e=esm_default({baseDir:b,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=`openknowledge`,i=`noreply@openknowledge.local`;if(c&&l)r=c,i=l;else try{let e=await resolveGitIdentity(b);e&&(r=e.name,i=e.email)}catch{}let a=[];for(let e of _.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;a.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let s=formatCheckpointSubject(o??`Checkpoint v${t}`),u=a.length>0?`${s}\n\n${a.join(`
121
+ `)}`:s,d=h||`.`;return await e.add(d),await e.env({GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i}).commit(u,[`--allow-empty`]),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}}json(t,200,{ok:!0,checkpointRef:g.checkpointRef,...v?{versionTag:v}:{}})}catch(e){console.error(`[save-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function _e(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??u?.()??`main`;if(!i){json(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){json(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),s=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),d=Number.isFinite(s)?s:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await getDocumentHistory(n,{docName:i,branch:a,limit:l,offset:d,type:p,author:m,excludeAuthor:h},f??`.`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),json(t,200,{ok:!0,...e})}catch(e){console.error(`[shadow]`,e),json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ve(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=c?.current;if(!r){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=safeDocPath(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,f??`.`);if(`error`in i){json(t,400,{ok:!1,error:i.error});return}let a=i.path,o=shadowGit(r);if(!/^[0-9a-f]{40}$/i.test(n)){json(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{json(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);json(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[shadow-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function ye(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,s=i.searchParams.get(`to`)??``;if(!s||!/^[0-9a-f]{40}$/i.test(s)){json(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=safeDocPath(a,f??`.`);if(`error`in l){json(n,400,{ok:!1,error:l.error});return}let u=l.path,d=shadowGit(r);try{let e;try{e=await d.raw(`show`,`${s}:${u}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await d.raw(`show`,`${o}:${u}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=stripFrontmatter(r).body,c=stripFrontmatter(e).body,l=diffLines(i,c),f=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
122
+ `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)f.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}json(n,200,{ok:!0,lines:f,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function be(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await readBody(e)}catch{json(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{json(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:l,clientName:u,clientVersion:d,label:p}=K(a),{docName:m,commitSha:g,versionTag:_}=a,v=typeof m==`string`?m:``,y=typeof g==`string`?g:``,x=typeof _==`string`?_:void 0;if(!v){json(n,400,{ok:!1,error:`docName required`});return}if(!y||!/^[0-9a-f]{40}$/i.test(y)){json(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let S=a,C=typeof S.agentId==`string`&&S.agentId.length>0,w=normalizeSummary(S.summary);if(w.kind===`invalid`){json(n,400,{ok:!1,error:`summary must be a string`});return}let T=f??`.`,E=safeDocPath(v,T);if(`error`in E){json(n,400,{ok:!1,error:E.error});return}let D=E.path,O=shadowGit(r),k=Date.now();try{try{await O.raw(`cat-file`,`-e`,`${y}:${D}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await O.raw(`show`,`${y}:${D}`),i=new Date().toISOString();await safetyCheckpoint(r,T,{action:`rollback`,context:{docName:v,targetSha:y}});let a=t.documents.get(v);if(!a){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:c,body:m}=stripFrontmatter(e),g=mdManager.parseWithFallback(m),_=schema.nodeFromJSON(g),S=a.getXmlFragment(`default`);a.transact(()=>{updateYFragment(a,S,_,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,c)},ROLLBACK_ORIGIN);let E;if(C){let e=y.slice(0,8),t=w.kind===`value`,n=t?w:normalizeSummary(`Restored to ${e}`),r=Y(n);E=t||!r.response?r.response:X(r.response),recordContributor(v,o,s,l,formatRollbackSubject(v,y),J({clientName:u,clientVersion:d,label:p}),r.stored),incrementAgentWriteCalls(),Z(n,!t)}N(v,`rollback`);let A=Date.now()-k;if(console.log(`[rollback] docName=${v} from=${y.slice(0,8)} duration=${A}ms`),b){let e=`Restored to ${x??y.slice(0,8)}: ${v}`,t=f??`.`;withParentLock(async()=>{let n=esm_default({baseDir:b,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}C&&h?.setFocus(o,{agentName:s,currentDoc:v,writeKind:`rollback-apply`,ts:Date.now()}),json(n,200,{ok:!0,restoredFrom:y,timestamp:i,...E?{summary:E}:{}})}catch(e){console.error(`[rollback]`,e),json(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function xe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getMetrics())}async function Se(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getParseHealth())}async function Ce(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=getActiveBranch(),r=d?.();json(t,200,{ok:!0,serverInstanceId:i,currentBranch:n,...r===void 0?{}:{currentDiskAckSVs:r}},{"Cache-Control":`no-store`})}async function we(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=x?.()??null;if(!n){json(t,404,{error:`Principal not available`});return}json(t,200,n)}async function Te(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=g?.getPresenceMap()??{},r=Date.now(),i={};for(let[e,t]of Object.entries(n))r-t.ts<2e4&&(i[e]=t);json(t,200,{presence:i})}async function Ee(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=resolve(r),i=n,a=!0;try{i=realpathSync(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),json(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}json(t,200,{ok:!0,contentDir:i,pathSeparator:sep,symlinkResolved:a})}let De=1440*60*1e3;async function Oe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){json(t,200,[]);return}let n=Date.now(),r=[],i=resolve(c.current.gitDir,`rescue`);if(existsSync(i))try{let e=readdirSync(i).filter(e=>isSupportedDocFile(e));for(let t of e){let e=resolve(i,t),a=statSync(e);if(n-a.mtimeMs>De){try{unlinkSync(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:stripDocExtension(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=u?.()??`main`,t=await listRescueCheckpoints(c.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}json(t,200,r)}async function ke(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){t.writeHead(404),t.end(`Not found`);return}let r=resolve(c.current.gitDir,`rescue`),i=resolve(r,`${n}${getDocExtension(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(existsSync(i)){let e=statSync(i);if(Date.now()-e.mtimeMs>De)try{unlinkSync(i)}catch{}else{let e=readFileSync(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=u?.()??`main`,r=(await listRescueCheckpoints(c.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=shadowGit(c.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
123
123
  `)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function Ae(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=K(i),{path:f}=i;if(!f||typeof f!=`string`||f.length===0){json(t,400,{ok:!1,error:`path is required`});return}if(!isSupportedDocFile(f)){json(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(f.includes(`..`)||f.startsWith(`/`)||f.includes(`\0`)||f.includes(`\\`)){json(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let h=resolve(r),g=resolve(h,f);if(!g.startsWith(`${h}/`)&&g!==h){json(t,400,{ok:!1,error:`path must not escape content directory`});return}let _=stripDocExtension(f);if(isSystemDoc(_)){json(t,400,{ok:!1,error:`'${_}' is a reserved document name`});return}mkdirSync(dirname(g),{recursive:!0});let v=``;try{writeFileSync(g,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){json(t,409,{ok:!1,error:`File already exists`});return}throw e}let y=stripDocExtension(f);recordContributor(y,o,s,c,void 0,J({clientName:l,clientVersion:u,label:d}));let b=typeof a==`function`?a():null;b instanceof Map&&updateFileIndex({kind:`create`,path:g,docName:y,content:``},b),p&&(p.updateDocumentFromMarkdown(y,``),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${y}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(t,200,{ok:!0,docName:y})}catch(e){console.error(`[create-page]`,e),json(t,500,{ok:!1,error:`Failed to create page`})}}async function je(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}let r=T(n);if(!r){json(t,400,{ok:!1,error:`Invalid docName`});return}if(!existsSync(r)){json(t,404,{ok:!1,error:`Page not found`});return}json(t,200,{ok:!0,docName:n,headings:extractHeadings(readFileSync(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),json(t,500,{ok:!1,error:`Failed to read headings`})}}async function Me(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=K(i),{docName:d,newDocName:f}=i;if(typeof d!=`string`||typeof f!=`string`){json(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!isValidRelativeContentPath(d)||!isValidRelativeContentPath(f)){json(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(isSystemDoc(d)||isSystemDoc(f)){json(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(d===f){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!p){json(t,503,{ok:!1,error:`Backlink index unavailable`});return}let m=i,h=typeof m.agentId==`string`&&m.agentId.length>0,g=normalizeSummary(m.summary);if(g.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let _=resolveContentEntryPath(r,`file`,d),v=resolveContentEntryPath(r,`file`,f);if(!existsSync(_)){json(t,404,{ok:!1,error:`Document does not exist`});return}if(existsSync(v)){json(t,409,{ok:!1,error:`Destination already exists`});return}let y=await W(d,f),b;if(h){let e=g.kind===`value`,t=e?g:normalizeSummary(`Renamed ${d} → ${f}`),n=Y(t);b=e||!n.response?n.response:X(n.response),recordContributor(f,a,o,s,formatRenameSubject(d,f),J({clientName:c,clientVersion:l,label:u}),n.stored),incrementAgentWriteCalls(),Z(t,!e),N(f,`rename`)}json(t,200,{ok:!0,renamed:y.renamed,rewrittenDocs:y.rewrittenDocs,...b?{summary:b}:{}})}catch(e){console.error(`[rename]`,e),json(t,500,{ok:!1,error:L(e)})}}async function Ne(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}K(i);let{kind:o,fromPath:s,toPath:c}=i;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){json(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!isValidRelativeContentPath(s)||!isValidRelativeContentPath(c)){json(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){json(t,200,{ok:!0,renamed:[]});return}let l=resolveContentEntryPath(r,o,s),u=resolveContentEntryPath(r,o,c);if(!existsSync(l)){json(t,404,{ok:!1,error:`${o} does not exist`});return}if(existsSync(u)){json(t,409,{ok:!1,error:`Destination already exists`});return}let d=statSync(l);if(o===`file`&&!d.isFile()||o===`folder`&&!d.isDirectory()){json(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let f=listAffectedDocNames(a(),o,s),h=o===`file`?[{fromDocName:s,toDocName:c}]:f.map(e=>({fromDocName:e,toDocName:remapDocNameForRename(e,o,s,c)})),g=await R(h.map(({fromDocName:e})=>e)),_=async()=>{await renameTrackedPathInGit(b,l,u)||(mkdirSync(dirname(u),{recursive:!0}),renameSync(l,u)),z(h,g)};if(o===`file`)await withManagedRenameRecovery(r,createManagedRenameRecoveryJournal({sourceDocName:s,destinationDocName:c,snapshots:B(h.map(({fromDocName:e})=>e),g)}),_);else{await _();let e=a();for(let{fromDocName:t,toDocName:n}of h)updateFileIndex({kind:`rename`,oldPath:resolveContentEntryPath(r,`file`,t),newPath:resolveContentEntryPath(r,`file`,n),oldDocName:t,newDocName:n,content:g.get(t)??readFileSync(resolveContentEntryPath(r,`file`,n),`utf-8`)},e);if(p){for(let{fromDocName:e,toDocName:t}of h)p.renameDocument(e,t,g.get(e)??readFileSync(resolveContentEntryPath(r,`file`,t),`utf-8`));p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist folder rename cache for ${s} -> ${c}:`,e)}),m?.(`backlinks`),m?.(`graph`)}m?.(`files`)}json(t,200,{ok:!0,renamed:h})}catch(e){console.error(`[rename-path]`,e),json(t,500,{ok:!1,error:`Failed to rename path`})}}async function Pe(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}K(i);let{kind:o,path:s}=i;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!isValidRelativeContentPath(s)){json(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=resolveContentEntryPath(r,o,s);if(!existsSync(c)){json(t,404,{ok:!1,error:`${o} does not exist`});return}let l=statSync(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){json(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:listAffectedDocNames(a(),o,s);await R(u),o===`file`?unlinkSync(c):rmSync(c,{recursive:!0,force:!1}),json(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),json(t,500,{ok:!1,error:`Failed to delete path`})}}async function Fe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=a(),n=[];for(let[t,i]of e){let e=t;try{e=extractPageTitle(readFileSync(resolve(r,`${t}${getDocExtension(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),json(t,500,{ok:!1,error:`Failed to list pages`})}}async function Ie(e,n){if(e.method!==`GET`){json(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){json(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}if(isSystemDoc(r)){json(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}json(n,200,{ok:!0,...await suggestLinks({hocuspocus:t,fileIndex:a(),docName:r})})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){json(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),json(n,500,{ok:!1,error:`Failed to suggest links`})}}async function Le(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await readUploadBody(e,MAX_UPLOAD_BYTES)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?json(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?json(t,400,{ok:!1,error:`No file received`}):json(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:i,buffer:a,parentDocName:o}=n;if(K(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),!o){json(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){json(t,400,{ok:!1,error:`path-escape`});return}let s=resolve(r),c=resolve(s,dirname(o));if(!isWithinContentDir(c,s)){json(t,400,{ok:!1,error:`path-escape`});return}try{let e=realpathSync(c),n;try{n=realpathSync(s)}catch{n=s}if(!isWithinContentDir(e,n)){json(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){json(t,400,{ok:!1,error:`path-escape`});return}}let l=await fileTypeFromBuffer(a),u=l?.mime,d=l?.ext;if(!u){let e=a.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(u=`image/svg+xml`,d=`svg`)}if(!u||!d||!ALLOWED_MIME_TYPES.has(u)){json(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!i||i===`upload`||GENERIC_PASTE_NAMES.test(i)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:sanitizeFilename(i),mkdirSync(c,{recursive:!0});try{let e=writeUploadAtomic(c,f,a),n=relative(r,resolve(c,e));console.log(`[upload] ok ${n} ${a.length}`),json(t,200,{ok:!0,src:e})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${f} ${a.length} ${n}`),json(t,500,{ok:!1,error:`Failed to save file`})}}let Re=`/api/local-op/clone`,ze=`/api/local-op/open`,Be=600*1e3,Ve=45e3;async function He(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){json(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isAllowedGitUrl(n)){json(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!isSafeLocalPath(r)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!C.tryAcquire(Re)){json(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=expandTilde(r),[a,...o]=y,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=spawn(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},Be);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
124
- `);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){C.release(Re);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&log$2.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await Ue(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),C.release(Re)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),C.release(Re)})}async function Ue(e){let t=resolve(expandTilde(e)),n=resolve(t,`.open-knowledge`),r=readUiLock(n);if(r&&r.port>0)return{port:r.port};let i=readServerLock(n),[a,...o]=y,s=i&&i.port>0?`ui`:`start`,c=spawn(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),log$2.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await setTimeout$1(500);let e=readUiLock(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function We(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isSafeLocalPath(n)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!C.tryAcquire(ze)){json(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await Ue(n);`port`in e?json(t,200,{port:e.port}):json(t,504,{ok:!1,error:e.error})}finally{C.release(ze)}}let Ge=`/api/local-op/auth/login`,Ke=`/api/local-op/auth/status`,qe=`/api/local-op/auth/repos`,Je=`/api/local-op/auth/signout`,Ye=`/api/local-op/auth/pat`;async function Xe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(Ge)){json(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=y,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},Be),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
124
+ `);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){C.release(Re);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&log$2.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await Ue(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),C.release(Re)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),C.release(Re)})}async function Ue(e){let t=resolve(expandTilde(e)),n=resolve(t,`.open-knowledge`),r=readUiLock(n);if(r&&r.port>0)return{port:r.port};let i=readServerLock(n),[a,...o]=y,s=i&&i.port>0?`ui`:`start`,c=spawn(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`,OK_PARENT_PID:String(process.pid)}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),log$2.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await setTimeout$1(500);let e=readUiLock(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function We(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isSafeLocalPath(n)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!C.tryAcquire(ze)){json(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await Ue(n);`port`in e?json(t,200,{port:e.port}):json(t,504,{ok:!1,error:e.error})}finally{C.release(ze)}}let Ge=`/api/local-op/auth/login`,Ke=`/api/local-op/auth/status`,qe=`/api/local-op/auth/repos`,Je=`/api/local-op/auth/signout`,Ye=`/api/local-op/auth/pat`;async function Xe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(Ge)){json(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=y,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},Be),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
125
125
  `);c=n.pop()??``;for(let e of n)if(e.trim())try{let t=JSON.parse(e);(t.type===`complete`||t.type===`error`)&&(s=!0)}catch{}}),l.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/login] stderr`)}),l.on(`close`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(e===0&&!s?t.write(`${JSON.stringify({type:`complete`,host:n,login:``})}\n`):e!==0&&t.write(`${JSON.stringify({type:`error`,message:`auth login exited with code ${e}`})}\n`)),t.end()),C.release(Ge)}),l.on(`error`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),C.release(Ge)})}async function Ze(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(Ke)){json(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=y,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=spawn(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
126
126
  `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}o===null?json(t,200,{authenticated:!1}):json(t,200,o)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{C.release(Ke)}}async function Qe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(qe)){json(t,429,{ok:!1,error:`An auth repos operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=y,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},Be);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),s.on(`close`,e=>{clearTimeout(c),o||(o=!0,e!==0&&!t.writableEnded&&t.write(`${JSON.stringify({type:`error`,message:`auth repos exited with code ${e}`})}\n`),t.end()),C.release(qe)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),C.release(qe)})}async function $e(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(Je)){json(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=y,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=spawn(e,i,{stdio:`ignore`,env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{C.release(Je)}}async function et(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){json(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(Ye)){json(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=y,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=spawn(e,a,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),o=setTimeout(()=>{i.kill(`SIGTERM`)},3e4);i.stdin.write(`${r}\n`),i.stdin.end();let s=[];i.stdout.on(`data`,e=>s.push(e)),i.on(`close`,e=>{clearTimeout(o),e===0?t(Buffer.concat(s).toString(`utf-8`)):n(Error(`auth pat exited with code ${e}`))}),i.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
127
127
  `).map(e=>e.trim()).filter(Boolean),s=null;for(let e=o.length-1;e>=0;e--)try{s=JSON.parse(o[e]);break}catch{}s===null?json(t,200,{ok:!0}):json(t,200,s)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{C.release(Ye)}}async function tt(e,t){if(checkLocalOpSecurity(e,t,json)){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!b){json(t,400,{ok:!1,error:`No project directory configured`});return}try{json(t,200,{ok:!0,identity:await resolveGitIdentity(b)})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let nt=`/api/local-op/auth/set-identity`;async function rt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){json(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){json(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!b){json(t,400,{ok:!1,error:`No project directory configured`});return}if(!C.tryAcquire(nt)){json(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{writeGitIdentity(b,n,r),v?.()?.refreshIdentity().catch(()=>{}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{C.release(nt)}}async function it(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,200,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1});return}json(t,200,n.getStatus())}async function at(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await readBody(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}json(t,202,{ok:!0,op:r}),n.trigger(r)}async function ot(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await readBody(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){json(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),json(t,200,{ok:!0,status:n.getStatus()})}async function st(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();json(t,200,{conflicts:n?n.getConflicts():[]})}async function ct(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await readBody(e);r=JSON.parse(t.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){json(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){json(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function lt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!b){json(t,503,{ok:!1,error:`Project repo not configured`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!n){json(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){json(t,400,{ok:!1,error:`Invalid file path`});return}let r=esm_default({baseDir:b,timeout:{block:15e3}});async function i(e){try{return await r.raw([`show`,`:${e}:${n}`])}catch{return``}}try{let[e,r,a]=await Promise.all([i(1),i(2),i(3)]);json(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ut(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=new URL(e.url??`/`,`http://localhost`).searchParams.get(`rootDir`)??void 0;try{json(t,200,{ok:!0,plan:await planSeed({projectDir:r,rootDir:n})})}catch(e){if(e instanceof SeedPrerequisiteError){json(t,200,{ok:!1,error:{kind:`prerequisite-missing`,message:e.message}});return}if(e instanceof SeedRootDirError){json(t,200,{ok:!1,error:{kind:`invalid-root`,message:e.message}});return}json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function dt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(!i.plan||typeof i.plan!=`object`){json(t,400,{ok:!1,error:`Missing or invalid plan`});return}n=i.plan}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}try{json(t,200,{ok:!0,result:await applySeed(n,{projectDir:r})})}catch(e){json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function ft(e,t){if(checkLocalOpSecurity(e,t,json))return handleInstalledAgents(e,t,w.probeAll)}async function pt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let mt={"/api/document":te,"/api/documents":ne,"/api/backlinks":re,"/api/backlink-counts":ie,"/api/forward-links":ae,"/api/link-graph":oe,"/api/dead-links":le,"/api/orphans":se,"/api/hubs":ce,"/api/pages":Fe,"/api/suggest-links":Ie,"/api/page-headings":je,"/api/create-page":Ae,"/api/rename":Me,"/api/rename-path":Ne,"/api/delete-path":Pe,"/api/upload-image":Le,"/api/agent-write":Q,"/api/agent-write-md":ee,"/api/agent-patch":ue,"/api/agent-undo":de,"/api/agent-activity":fe,"/api/agent-burst-diff":pe,"/api/save-version":ge,"/api/history":_e,"/api/diff":ye,"/api/rollback":be,"/api/metrics/reconciliation":xe,"/api/metrics/parse-health":Se,"/api/metrics/agent-presence":Te,"/api/server-info":Ce,"/api/principal":we,"/api/rescue":Oe,"/api/workspace":Ee,"/api/sync/status":it,"/api/sync/trigger":at,"/api/sync/set-enabled":ot,"/api/sync/conflicts":st,"/api/sync/conflict-content":lt,"/api/sync/resolve-conflict":ct,"/api/sync/abort-merge":pt,"/api/local-op/clone":He,"/api/local-op/open":We,"/api/local-op/auth/login":Xe,"/api/local-op/auth/status":Ze,"/api/local-op/auth/repos":Qe,"/api/local-op/auth/signout":$e,"/api/local-op/auth/pat":et,"/api/local-op/auth/identity":tt,"/api/local-op/auth/set-identity":rt,"/api/installed-agents":ft,"/api/seed/plan":ut,"/api/seed/apply":dt};return s&&(mt[`/api/test-reset`]=me,mt[`/api/test-rescan-backlinks`]=he),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!isAllowedApiOrigin(n)){typeof t.setHeader==`function`&&t.setHeader(`Content-Type`,`application/json`),t.writeHead(403),t.end(JSON.stringify({ok:!1,error:`origin-not-allowed`}));return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(!n.startsWith(`/api/`))return;let r=propagation.extract(context.active(),e.headers),i=e.method??`GET`,a=n;n.startsWith(`/api/rescue/`)?a=`/api/rescue/:docName`:n.startsWith(`/api/history/`)&&(a=`/api/history/:sha`);let o=getTracer(),s=Date.now();await context.with(r,()=>o.startActiveSpan(`HTTP ${i} ${a}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_URL_PATH]:n,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async r=>{try{let i=mt[n];if(i)await i(e,t);else if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await ke(e,t,r)}else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await ve(e,t,r)}let a=t.statusCode;r.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,a),a>=500&&r.setStatus({code:SpanStatusCode.ERROR,message:`status ${a}`})}catch(e){throw r.recordException(e),r.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),e}finally{r.end();let e=(Date.now()-s)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}const HocuspocusAuthTokenSchema=object({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional()}).loose();var HocuspocusAuthRejection=class extends Error{reason;constructor(e,t){super(t),this.name=`HocuspocusAuthRejection`,this.reason=e}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=HocuspocusAuthTokenSchema.safeParse(t);return n.success?n.data:void 0}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,n=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}const BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`]);function createContentFilter(e){let{projectDir:t,contentDir:n,includePatterns:r,excludePatterns:i}=e,a=(0,import_picomatch.default)(r,{dot:!0}),o=(0,import_ignore.default)();o.add(`.git`);let s=join(t,`.gitignore`),c=[];if(existsSync(s))try{let e=parseGitignorePatterns(readFileSync(s,`utf-8`));c.push(...e),o.add(e)}catch(e){console.warn(`[content-filter] Failed to read .gitignore at ${s}:`,e)}let l=relative(t,n),u=l.startsWith(`..`);if(i.length>0&&(l?o.add(i.map(e=>`${l}/${e}`)):o.add(i)),l){let e=join(n,`.gitignore`);if(existsSync(e))try{let t=parseGitignorePatterns(readFileSync(e,`utf-8`)).map(e=>e.startsWith(`!`)?`!${l}/${e.slice(1)}`:`${l}/${e}`);o.add(t)}catch(t){console.warn(`[content-filter] Failed to read .gitignore at ${e}:`,t)}}loadNestedGitignores(n,t,o);let d=[...c,...i].filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),f=new Map;function p(e){if(u)return!1;let t=l?`${l}/${e}`:e;return o.ignores(t)}return populateDirCount(n,``,a,p,f),{isExcluded(e){if(isSystemDoc(stripDocExtension(e))||!u&&p(e))return!0;if(a(e))return!1;let t=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(t)){let t=dirname(e),n=t===`.`?``:t;if((f.get(n)??0)>0)return!1}return!0},isDirExcluded(e){let t=e.split(`/`)[0];if(BUILTIN_SKIP_DIRS.has(t))return!0;if(u)return!1;let n=l?`${l}/${e}`:e;return o.ignores(n)||o.ignores(`${n}/`)},getWatcherIgnoreGlobs(){return d},incrementMdDir(e){let t=e===`.`?``:e;f.set(t,(f.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,n=f.get(t)??0;n<=1?f.delete(t):f.set(t,n-1)}}}function populateDirCount(e,t,n,r,i){let a;try{a=readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){if(BUILTIN_SKIP_DIRS.has(o.name)||r(a)||r(`${a}/`))continue;populateDirCount(join(e,o.name),a,n,r,i)}else if(o.isFile()&&isSupportedDocFile(o.name)&&n(a)&&!r(a)){let e=t===``?``:t;i.set(e,(i.get(e)??0)+1)}}}function parseGitignorePatterns(e){return e.split(`
@@ -134,9 +134,9 @@ What to log:
134
134
  `):[]){let t=e.trim();if(!t)continue;let n=join(this.projectDir,t),r=relative(this.contentDir,n);!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&a.add(t)}}catch{}if(t.length>0){let n=100;for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...r])}}let o=new Set(t.map(e=>e.projectRelPath)),s=[...a].filter(e=>!o.has(e));s.length>0&&await e.git.raw([`rm`,`--cached`,`--`,...s]);let c=(await e.git.raw([`write-tree`])).trim(),l=``;try{l=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(l&&l===c){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){log.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.transitionTo(`idle`);return}log.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let u=[];try{let n=(await e.git.raw([`diff-tree`,`--name-only`,`-r`,i,c])).trim();if(n){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n.split(`
135
135
  `)){let n=t.trim();if(!n)continue;let r=e.get(n)??relative(this.contentDir,join(this.projectDir,n));r&&!r.startsWith(`..`)&&u.push(r)}}}catch{u=t.map(e=>e.contentRelPath)}let d=this.buildCommitMessage(u),f=await resolveGitIdentity(this.projectDir),p=f===null;this.identityUnresolved!==p&&(this.identityUnresolved=p,this.cc1Broadcaster?.signal(`sync-status`));let m=f?.name??`Open Knowledge`,h=f?.email??`sync@open-knowledge.local`;e.git.env({GIT_AUTHOR_NAME:m,GIT_AUTHOR_EMAIL:h,GIT_COMMITTER_NAME:m,GIT_COMMITTER_EMAIL:h});let g=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,d])).trim();if(!g||!SHA_HEX_40.test(g)){log.warn({raw:g},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}if(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,g,i]),t.length>0){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),n=100;for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}}let _=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),_=!0}catch{}_?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=g}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.error=void 0,this.schedulePull(0)))}catch(t){let n=classifyGitError(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){log.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});this.setBatchInProgress?.(!0);try{if(await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e)){this.setBatchInProgress?.(!1);return}await e.git.merge([`origin/${this.currentBranch}`])}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}log.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n)}finally{try{unlinkSync(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync();if(n.length===0)return null;let r=join(tmpdir(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),i=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:r});try{await i.git.raw([`read-tree`,t]);let r=100;for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await i.git.raw([`add`,`--`,...t])}let a=(await i.git.raw([`write-tree`])).trim();if(a===(await i.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let o=await resolveGitIdentity(this.projectDir),s=o?.name??`Open Knowledge`,c=o?.email??`sync@open-knowledge.local`;i.git.env({GIT_AUTHOR_NAME:s,GIT_AUTHOR_EMAIL:c,GIT_COMMITTER_NAME:s,GIT_COMMITTER_EMAIL:c});let l=(await i.git.raw([`commit-tree`,a,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();if(!l||!SHA_HEX_40.test(l))return log.warn({raw:l},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null;await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,l,t]);for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}return l}finally{try{unlinkSync(r)}catch{}}}async pauseIfNonContentDirty(e){let t=``;try{t=(await e.git.raw([`diff-index`,`--name-only`,`HEAD`])).trim()}catch{return!0}if(!t)return!0;let n=t.split(`
136
136
  `).map(e=>e.trim()).filter(Boolean);return n.length===0?!0:(this.error=`External changes pending: ${n.slice(0,3).join(`, `)}${n.length>3?`, +${n.length-3} more`:``}`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log.warn({files:n},`[sync] paused — non-content tracked files dirty`),!1)}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=join(n,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`.git`||i.name.startsWith(`.`)&&i.name!==`.open-knowledge`)continue;t(r)}else if(i.isFile()){let t=relative(this.contentDir,r);if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=relative(this.projectDir,r);e.push({contentRelPath:t,projectRelPath:n})}}}};return existsSync(this.contentDir)&&t(this.contentDir),e}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t=[];try{let n=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=n?n.split(`
137
- `).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=join(this.projectDir,e),i=relative(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log.info({},`[sync] merge aborted`)}catch(e){log.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,log.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};writeFileSync(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){log.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log.warn({err:e},`[sync] failed to load sync state`)}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,enableTestRoutes:l=!1,shadowRepo:u,contentRoot:d,includePatterns:f=[`**/*.md`,`**/*.mdx`],excludePatterns:p=[],destroyTimeoutMs:m=1e4,localOpCliArgs:h}=e,g=getLogger(`server`);initTelemetry();let _=randomUUID(),v=resolve(t,`.open-knowledge`);acquireServerLock(v,{port:e.port??0,worktreeRoot:n});let y,b,x,S,C,w,T=null,E=null,D=null,O=null;function k(e){T?.signal(e)}try{y=createContentFilter({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),b=new BacklinkIndex({projectDir:n,contentDir:t,contentFilter:y}),x={current:u},S=createPersistenceExtension({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:x,contentRoot:d,backlinkIndex:b,getCurrentBranch:()=>B?.getLastKnownBranch()??null,getPrincipal:()=>O,onAgentCommit:()=>T?.signal(`session-activity`),onDiskFlush:(e,t)=>T?.emitDiskAck(e,t)}),C=new Hocuspocus({quiet:r,debounce:i,maxDebounce:a,extensions:[S.extension]}),T=new CC1Broadcaster(C),E=new AgentFocusBroadcaster(C),D=new AgentPresenceBroadcaster(C),w=new AgentSessionManager(C);let m=createLiveDerivedIndexExtension({backlinkIndex:b,signalChannel:k});C.configuration.extensions.push(m),C.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=parseHocuspocusAuthToken(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==_)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${_}`);let i=n?.expectedBranch,a=getActiveBranch();if(typeof i==`string`&&i.length>0&&i!==a)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(O&&n.principalId===O.id?o.principalId=O.id:O?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:O.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),C.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let g=createApiExtension({hocuspocus:C,sessionManager:w,contentDir:t,serverInstanceId:_,getFileIndex:()=>z?z.getFileIndex():new Map,getAliasMap:()=>z?z.getAliasMap():new Map,enableTestRoutes:l,shadowRef:x,flushGitCommit:()=>S.flushPendingGitCommit(),getCurrentBranch:()=>B?.getLastKnownBranch()??null,getDiskAckSVs:()=>T?.getLatestDiskAckSVsAsBase64()??{},contentRoot:d,backlinkIndex:b,signalChannel:k,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>V,localOpCliArgs:h,projectDir:n,getPrincipal:()=>O});C.configuration.extensions.push(g),C.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:x,contentRoot:d,getCurrentBranch:()=>B?.getLastKnownBranch()??null}))}catch(e){throw releaseServerLock(v),e}let A=null;function j(e,t){let n=resolve(e,`rescue`),r=resolve(n,`${t}${getDocExtension(t)}`);return r.startsWith(`${n}/`)?r:null}function M(e){let t=C.documents.get(e);if(!t)return null;let n=yXmlFragmentToProseMirrorRootNode(t.getXmlFragment(`default`),schema).toJSON(),r=mdManager.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return prependFrontmatter(typeof i==`string`?i:``,r)}let N=(e,t)=>applyExternalChange(C,e,t);function P(e){return e.kind===`rename`?e.newDocName:e.docName}async function F(e){try{switch(e.kind){case`create`:g.info({docName:e.docName},`[reconcile] create: ${e.docName}`),b.updateDocumentFromMarkdown(e.docName,e.content),b.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),k(`files`),k(`backlinks`),k(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=C.documents.get(t);if(!r){b.updateDocumentFromMarkdown(t,n),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),k(`backlinks`),k(`graph`);return}let i=getReconciledBase(t)??``,a=M(t)??i,o=reconcile({docName:t,base:i,ours:a,theirs:n}),s=contentHash(i).slice(0,6),c=contentHash(a).slice(0,6),l=contentHash(n).slice(0,6);switch(g.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:b.updateDocumentFromMarkdown(t,n),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),k(`backlinks`),k(`graph`);break;case`clean`:try{N(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),b.updateDocumentFromMarkdown(t,n),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`merged`:try{N(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),b.updateDocumentFromMarkdown(t,n),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`conflicts`:try{N(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),incrementConflict(),b.updateDocumentFromMarkdown(t,n),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`refused`:{incrementConflict();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=C.documents.get(t);if(!n){b.deleteDocument(t),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),k(`files`),k(`backlinks`),k(`graph`);return}let r=getReconciledBase(t)??``,i=M(t)??``,a=i!==r;if(a&&x.current){let e=x.current,n=B?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,d??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),g.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{g.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),b.deleteDocument(t),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),g.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),C.closeConnections(t),await C.unloadDocument(n),k(`files`),k(`backlinks`),k(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=C.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(n,r),b.renameDocument(t,n,r),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}g.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),k(`files`),k(`backlinks`),k(`graph`);break}case`conflict`:{let{docName:t}=e,n=C.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),g.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){g.error({err:t,kind:e.kind,docName:P(e)},`[reconcile] failed to handle ${e.kind} for ${P(e)}`)}}let I=[];async function L(e){if(isBatchInProgress()){I.push(e);return}await F(e)}async function R(){let e=I.splice(0,I.length);for(let t of e)await F(t)}let z=null,B=null,V=null,H=null;async function U(e){if(C.documents.size===0)return;let t=!1,n=new Promise(e=>{C.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(C.documents.keys());C.closeConnections(),C.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(C.documents.keys()),i=[],o=[];if(x.current){for(let e of n)if(!isSystemDoc(e))try{let t=M(e);if(t===null){g.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=j(x.current.gitDir,e);if(!n){g.warn({docName:e,gitDir:x.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),incrementRescueBuffer(),i.push(e),g.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),g.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else g.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function W(){return H||(H=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([q.then(()=>`completed`,e=>(g.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&g.warn({},`[server] init did not complete within 5s during shutdown`);let a=C.documents.size;try{try{try{B&&=(await B.unsubscribe(),null),z&&=(await z.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{T?.destroy(),D?.destroy(),A&&=(await A.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await w.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await U(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await S.flushPendingGitCommit(),await S.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{V&&=(await V.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(x.current){try{let e=(await esm_default({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(x.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(x.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?g.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):g.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(v)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),H)}let G=[];async function K(){try{O=await loadPrincipal(t),g.info({principalId:O.id},`[server] principal loaded`)}catch(e){g.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!x.current)try{x.current=await initShadowRepo(n),g.info({gitDir:x.current.gitDir},`[server] history repo initialized at ${x.current.gitDir}`)}catch(e){g.error({err:e},`[server] history repo init failed`),G.push(`shadow-repo`)}if(x.current)try{await shadowGit(x.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){g.warn({},`[server] history repo appears corrupted — reinitializing`);try{x.current=await initShadowRepo(n)}catch(e){g.error({err:e},`[server] history repo reinit failed`),x.current=void 0,G.includes(`shadow-repo`)||G.push(`shadow-repo`)}}else g.error({err:e},`[server] history repo check failed (transient?)`)}if(x.current)try{let e=resolve(x.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await esm_default({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await esm_default({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}g.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await commitUpstreamImport(x.current,d??``,t,r,e),incrementUpstreamImport()}catch(e){g.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else g.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{writeFileSync(e,r,`utf-8`)}catch(e){g.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){g.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);e.recovered&&e.journal&&g.warn({sourceDocName:e.journal.sourceDocName,destinationDocName:e.journal.destinationDocName,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${e.journal.sourceDocName} -> ${e.journal.destinationDocName}`)}catch(e){g.error({err:e},`[server] managed rename recovery failed`),G.push(`managed-rename-recovery`)}try{A=await C.openDirectConnection(SYSTEM_DOC_NAME),T?.emitServerInfo(_,getActiveBranch())}catch(e){g.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),G.push(`cc1-push`)}let e=resolveGitDir(n),r=e?readBranchFromHead(e)??`main`:`main`;switchReconciledBaseScope(r),b.switchBranch(r);try{z=await startWatcher(t,L,y),b.rebuildFromDisk(getActiveBranch()),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${getActiveBranch()}:`,e)})}catch(e){g.error({err:e},`[server] disk bridge watcher failed to start`),G.push(`file-watcher`)}try{B=await startHeadWatcher(n,async({trigger:e})=>{if(g.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),C.flushPendingStores(),await S.flushPendingGitCommit(),setBatchInProgress(!0),x.current){let e=getActiveBranch(),t=resolveGitDir(n),r=t?readBranchFromHead(t)??e:e,i=[];for(let[e,t]of C.documents){if(isSystemDoc(e))continue;let n=null;if(t.transact(()=>{n=M(e)},PARK_SNAPSHOT_ORIGIN),n===null)continue;let r=getReconciledBase(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await parkBranch(x.current,e,SERVICE_WRITER.id,i,r);t&&(incrementPark(),g.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){g.error({err:e},`[shadow] park failed`)}}},async e=>{let n=I.length,r=e.newBranch??`main`;if(setBatchInProgress(!1),g.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)await R();else{incrementBranchSwitch(),I.splice(0,I.length),switchReconciledBaseScope(r),b.switchBranch(r);for(let[e,n]of C.documents)if(!isSystemDoc(e))try{let i=safeContentPath(e,t);if(!existsSync(i)){let t=getReconciledBase(e)??``,i=M(e)??``;if(i!==t&&x.current){let t=x.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,d??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),g.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{g.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),g.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=readFileSync(i,`utf-8`);N(e,a),setReconciledBase(e,a),g.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){g.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(g.info({branch:r,docCount:C.documents.size},`[branch-switch] loaded branch ${r} (${C.documents.size} docs)`),b.rebuildFromDisk(r),b.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),x.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of C.documents)if(!isSystemDoc(t))try{let n=await readParkedState(x.current,r,SERVICE_WRITER.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=getReconciledBase(t);if(!i)continue;let a=reconcile({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:N(t,a.newContent),setReconciledBase(t,a.newContent),e++;break;case`conflicts`:N(t,a.newContent),setReconciledBase(t,a.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){g.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&g.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&x.current)try{let t=shadowGit(x.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
138
- `))e&&await t.raw(`update-ref`,`-d`,e);g.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){g.error({err:e},`[branch-switch] detached cleanup failed`)}T?.emitBranchSwitched(r)}if(e.headMoved&&e.newHead&&x.current&&n>0){let t=d??`content`;try{let n=await commitUpstreamImport(x.current,t,e.oldHead,e.newHead,r);incrementUpstreamImport(),g.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){g.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){g.error({err:e},`[server] HEAD watcher failed to start`),G.push(`head-watcher`)}let i=h?.[0]??`open-knowledge`,a=[`-c`,`credential.helper=!${h&&h.length>1?h.join(` `):i} auth git-credential`];try{V=new SyncEngine({projectDir:n,contentDir:t,contentFilter:y,contentRoot:d,credentialArgs:a,cc1Broadcaster:T,setBatchInProgress,onStateChange:e=>{g.info({state:e},`[sync] state → ${e}`)}}),await V.start()}catch(e){g.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),V=null}}let q=K();return{hocuspocus:C,sessionManager:w,cc1Broadcaster:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,contentFilter:y,serverInstanceId:_,destroy:W,ready:q,degraded:G,lockDir:v,get syncEngine(){return V}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3;async function bootServer(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??getLogger(`boot`);initTelemetry();let{createServer:a}=await import(`node:http`),{WebSocketServer:o}=await import(`./wrapper-BTT6637Z.mjs`),{updateServerLockPort:s}=await import(`./server-lock-CH0GCP_4-MazZqjDk.mjs`).then(e=>e.a),c=!1;!t&&e.ensureProjectGitFn&&(c=!!(await e.ensureProjectGitFn()).didInit);let l=!1;if(!t&&e.autoInitFn)try{l=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let u=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,includePatterns:e.includePatterns,excludePatterns:e.excludePatterns,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite}),{hocuspocus:d,destroy:f,ready:p,degraded:m,lockDir:h,agentPresenceBroadcaster:g}=u,_=a((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){d.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),v=new o({noServer:!0});v.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)});let y=e.keepaliveGraceMs??1e4,b=new Map,x=new Set,S=!1;_.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive socket error`)}),v.handleUpgrade(e,t,n,t=>{let n=parseKeepaliveConnectionId(e.url);if(n){let e=b.get(n);e!==void 0&&(clearTimeout(e),b.delete(n),i.info({connectionId:n},`[keepalive] reconnect during grace — timer cancelled`))}let r=setInterval(()=>{try{t.ping()}catch{}},3e4);r.unref?.();let a=n?setInterval(()=>{g?.bumpPresenceTs(toBroadcasterKey(n))},3e3):null;a?.unref?.(),t.on(`close`,()=>{if(clearInterval(r),a!==null&&clearInterval(a),!n)return;let e=setTimeout(()=>{if(b.delete(n),S)return;let e=(async()=>{i.info({connectionId:n},`[keepalive] grace expired — cleaning up sessions`);try{await u.sessionManager.closeAllForAgent(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] closeAllForAgent failed`)}try{u.agentFocusBroadcaster?.clearFocus(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearFocus failed`)}try{g?.clearPresence(toBroadcasterKey(n))}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearPresence failed`)}})();x.add(e),e.finally(()=>x.delete(e))},y);e.unref?.(),b.set(n,e),i.info({connectionId:n,graceMs:y},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`Upgrade socket error`)}),v.handleUpgrade(e,t,n,t=>{let n=d.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let C=null;r!==null&&(C=attachIdleShutdown({httpServer:_,thresholdMs:r??DEFAULT_IDLE_THRESHOLD_MS,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await f()})})),await new Promise((t,n)=>{let r=e=>n(e);_.once(`error`,r),_.listen(e.port,e.host,()=>{_.removeListener(`error`,r),t()})});let w=_.address(),T=typeof w==`object`&&w?w.port:e.port??0;if(s(h,T),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:h,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let E=!1;return{httpServer:_,destroy:async()=>{if(!E){E=!0,S=!0,C?.detach();for(let e of b.values())clearTimeout(e);b.clear(),x.size>0&&await Promise.allSettled([...x]),await new Promise(e=>{_.close(()=>e())}),await f(),await shutdownTelemetry()}},lockDir:h,contentDir:e.contentDir,port:T,ready:p,degraded:m,didAutoInit:l,didGitInit:c,serverInstance:u}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_ZIP_BYTES=102400;function resolveBundledSkillDir(){let e=[`../assets/skills/open-knowledge`,`./assets/skills/open-knowledge`],t=[];for(let n of e){let e=fileURLToPath(new URL(n,import.meta.url));if(existsSync(e))return e;t.push(e)}throw Error(`Bundled skill asset directory not found. Tried: ${t.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function readCliVersion(){for(let e of[`../../cli/package.json`,`../package.json`]){let t=fileURLToPath(new URL(e,import.meta.url));if(!existsSync(t))continue;let n=await readFile(t,`utf-8`),r=JSON.parse(n);if(r.name===`@inkeep/open-knowledge`&&typeof r.version==`string`)return r.version}throw Error(`Could not resolve @inkeep/open-knowledge CLI version — no package.json with matching name found in candidate paths.`)}async function*walkFiles(e,t=e){let n=await readdir(e,{withFileTypes:!0});for(let r of n){let n=join(e,r.name);r.isDirectory()?yield*walkFiles(n,t):r.isFile()&&(yield relative(t,n))}}async function zipDirectory(e,t){let n=e.split(`/`).pop()??`open-knowledge`,r=new import_yazl.ZipFile;r.addEmptyDirectory(`${n}/`);let i=[];for await(let t of walkFiles(e))i.push(t);i.sort();for(let t of i){let i=join(e,t),a=`${n}/${t}`;r.addFile(i,a)}r.end(),await new Promise((e,n)=>{let i=createWriteStream(t);r.outputStream.pipe(i),i.on(`close`,()=>e()),i.on(`error`,n),r.outputStream.on(`error`,n)})}async function sha256OfFile(e){return new Promise((t,n)=>{let r=createHash(`sha256`),i=createReadStream(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>t(r.digest(`hex`))),i.on(`error`,n)})}function extractMetadataVersion(e){let t=e.indexOf(`
137
+ `).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=join(this.projectDir,e),i=relative(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log.info({},`[sync] merge aborted`)}catch(e){log.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,log.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};writeFileSync(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){log.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log.warn({err:e},`[sync] failed to load sync state`)}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,enableTestRoutes:l=!1,shadowRepo:u,contentRoot:d,includePatterns:f=[`**/*.md`,`**/*.mdx`],excludePatterns:p=[],destroyTimeoutMs:m=1e4,localOpCliArgs:h}=e,g=getLogger(`server`);initTelemetry();let _=randomUUID(),v=resolve(t,`.open-knowledge`);acquireServerLock(v,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,...e.parentPid!==void 0&&{parentPid:e.parentPid},capabilities:[`http`,`ws`]});let y,b,x,S,C,w,T=null,E=null,D=null,O=null;function k(e){T?.signal(e)}try{y=createContentFilter({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),b=new BacklinkIndex({projectDir:n,contentDir:t,contentFilter:y}),x={current:u},S=createPersistenceExtension({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:x,contentRoot:d,backlinkIndex:b,getCurrentBranch:()=>B?.getLastKnownBranch()??null,getPrincipal:()=>O,onAgentCommit:()=>T?.signal(`session-activity`),onDiskFlush:(e,t)=>T?.emitDiskAck(e,t)}),C=new Hocuspocus({quiet:r,debounce:i,maxDebounce:a,extensions:[S.extension]}),T=new CC1Broadcaster(C),E=new AgentFocusBroadcaster(C),D=new AgentPresenceBroadcaster(C),w=new AgentSessionManager(C);let m=createLiveDerivedIndexExtension({backlinkIndex:b,signalChannel:k});C.configuration.extensions.push(m),C.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=parseHocuspocusAuthToken(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==_)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${_}`);let i=n?.expectedBranch,a=getActiveBranch();if(typeof i==`string`&&i.length>0&&i!==a)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(O&&n.principalId===O.id?o.principalId=O.id:O?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:O.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),C.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let g=createApiExtension({hocuspocus:C,sessionManager:w,contentDir:t,serverInstanceId:_,getFileIndex:()=>z?z.getFileIndex():new Map,getAliasMap:()=>z?z.getAliasMap():new Map,enableTestRoutes:l,shadowRef:x,flushGitCommit:()=>S.flushPendingGitCommit(),getCurrentBranch:()=>B?.getLastKnownBranch()??null,getDiskAckSVs:()=>T?.getLatestDiskAckSVsAsBase64()??{},contentRoot:d,backlinkIndex:b,signalChannel:k,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>V,localOpCliArgs:h,projectDir:n,getPrincipal:()=>O});C.configuration.extensions.push(g),C.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:x,contentRoot:d,getCurrentBranch:()=>B?.getLastKnownBranch()??null}))}catch(e){throw releaseServerLock(v),e}let A=null;function j(e,t){let n=resolve(e,`rescue`),r=resolve(n,`${t}${getDocExtension(t)}`);return r.startsWith(`${n}/`)?r:null}function M(e){let t=C.documents.get(e);if(!t)return null;let n=yXmlFragmentToProseMirrorRootNode(t.getXmlFragment(`default`),schema).toJSON(),r=mdManager.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return prependFrontmatter(typeof i==`string`?i:``,r)}let N=(e,t)=>applyExternalChange(C,e,t);function P(e){return e.kind===`rename`?e.newDocName:e.docName}async function F(e){try{switch(e.kind){case`create`:g.info({docName:e.docName},`[reconcile] create: ${e.docName}`),b.updateDocumentFromMarkdown(e.docName,e.content),b.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),k(`files`),k(`backlinks`),k(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=C.documents.get(t);if(!r){b.updateDocumentFromMarkdown(t,n),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),k(`backlinks`),k(`graph`);return}let i=getReconciledBase(t)??``,a=M(t)??i,o=reconcile({docName:t,base:i,ours:a,theirs:n}),s=contentHash(i).slice(0,6),c=contentHash(a).slice(0,6),l=contentHash(n).slice(0,6);switch(g.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:b.updateDocumentFromMarkdown(t,n),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),k(`backlinks`),k(`graph`);break;case`clean`:try{N(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),b.updateDocumentFromMarkdown(t,n),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`merged`:try{N(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),b.updateDocumentFromMarkdown(t,n),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`conflicts`:try{N(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),incrementConflict(),b.updateDocumentFromMarkdown(t,n),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`refused`:{incrementConflict();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=C.documents.get(t);if(!n){b.deleteDocument(t),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),k(`files`),k(`backlinks`),k(`graph`);return}let r=getReconciledBase(t)??``,i=M(t)??``,a=i!==r;if(a&&x.current){let e=x.current,n=B?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,d??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),g.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{g.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),b.deleteDocument(t),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),g.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),C.closeConnections(t),await C.unloadDocument(n),k(`files`),k(`backlinks`),k(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=C.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(n,r),b.renameDocument(t,n,r),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}g.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),k(`files`),k(`backlinks`),k(`graph`);break}case`conflict`:{let{docName:t}=e,n=C.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),g.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){g.error({err:t,kind:e.kind,docName:P(e)},`[reconcile] failed to handle ${e.kind} for ${P(e)}`)}}let I=[];async function L(e){if(isBatchInProgress()){I.push(e);return}await F(e)}async function R(){let e=I.splice(0,I.length);for(let t of e)await F(t)}let z=null,B=null,V=null,H=null;async function U(e){if(C.documents.size===0)return;let t=!1,n=new Promise(e=>{C.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(C.documents.keys());C.closeConnections(),C.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(C.documents.keys()),i=[],o=[];if(x.current){for(let e of n)if(!isSystemDoc(e))try{let t=M(e);if(t===null){g.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=j(x.current.gitDir,e);if(!n){g.warn({docName:e,gitDir:x.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),incrementRescueBuffer(),i.push(e),g.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),g.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else g.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function W(){return H||(H=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([q.then(()=>`completed`,e=>(g.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&g.warn({},`[server] init did not complete within 5s during shutdown`);let a=C.documents.size;try{try{try{B&&=(await B.unsubscribe(),null),z&&=(await z.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{T?.destroy(),D?.destroy(),A&&=(await A.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await w.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await U(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await S.flushPendingGitCommit(),await S.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{V&&=(await V.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(x.current){try{let e=(await esm_default({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(x.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(x.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?g.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):g.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(v)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),H)}let G=[];async function K(){try{O=await loadPrincipal(t),g.info({principalId:O.id},`[server] principal loaded`)}catch(e){g.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!x.current)try{x.current=await initShadowRepo(n),g.info({gitDir:x.current.gitDir},`[server] history repo initialized at ${x.current.gitDir}`)}catch(e){g.error({err:e},`[server] history repo init failed`),G.push(`shadow-repo`)}if(x.current)try{await shadowGit(x.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){g.warn({},`[server] history repo appears corrupted — reinitializing`);try{x.current=await initShadowRepo(n)}catch(e){g.error({err:e},`[server] history repo reinit failed`),x.current=void 0,G.includes(`shadow-repo`)||G.push(`shadow-repo`)}}else g.error({err:e},`[server] history repo check failed (transient?)`)}if(x.current)try{let e=resolve(x.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await esm_default({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await esm_default({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}g.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await commitUpstreamImport(x.current,d??``,t,r,e),incrementUpstreamImport()}catch(e){g.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else g.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{writeFileSync(e,r,`utf-8`)}catch(e){g.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){g.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);e.recovered&&e.journal&&g.warn({sourceDocName:e.journal.sourceDocName,destinationDocName:e.journal.destinationDocName,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${e.journal.sourceDocName} -> ${e.journal.destinationDocName}`)}catch(e){g.error({err:e},`[server] managed rename recovery failed`),G.push(`managed-rename-recovery`)}try{A=await C.openDirectConnection(SYSTEM_DOC_NAME),T?.emitServerInfo(_,getActiveBranch())}catch(e){g.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),G.push(`cc1-push`)}let e=resolveGitDir(n),r=e?readBranchFromHead(e)??`main`:`main`;switchReconciledBaseScope(r),b.switchBranch(r);try{z=await startWatcher(t,L,y),b.rebuildFromDisk(getActiveBranch()),b.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${getActiveBranch()}:`,e)})}catch(e){g.error({err:e},`[server] disk bridge watcher failed to start`),G.push(`file-watcher`)}try{B=await startHeadWatcher(n,async({trigger:e})=>{if(g.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),C.flushPendingStores(),await S.flushPendingGitCommit(),setBatchInProgress(!0),x.current){let e=getActiveBranch(),t=resolveGitDir(n),r=t?readBranchFromHead(t)??e:e,i=[];for(let[e,t]of C.documents){if(isSystemDoc(e))continue;let n=null;if(t.transact(()=>{n=M(e)},PARK_SNAPSHOT_ORIGIN),n===null)continue;let r=getReconciledBase(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await parkBranch(x.current,e,SERVICE_WRITER.id,i,r);t&&(incrementPark(),g.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){g.error({err:e},`[shadow] park failed`)}}},async e=>{let n=I.length,r=e.newBranch??`main`;if(setBatchInProgress(!1),g.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)await R();else{incrementBranchSwitch(),I.splice(0,I.length),switchReconciledBaseScope(r),b.switchBranch(r);for(let[e,n]of C.documents)if(!isSystemDoc(e))try{let i=safeContentPath(e,t);if(!existsSync(i)){let t=getReconciledBase(e)??``,i=M(e)??``;if(i!==t&&x.current){let t=x.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,d??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),g.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{g.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),g.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=readFileSync(i,`utf-8`);N(e,a),setReconciledBase(e,a),g.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){g.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(g.info({branch:r,docCount:C.documents.size},`[branch-switch] loaded branch ${r} (${C.documents.size} docs)`),b.rebuildFromDisk(r),b.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),x.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of C.documents)if(!isSystemDoc(t))try{let n=await readParkedState(x.current,r,SERVICE_WRITER.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=getReconciledBase(t);if(!i)continue;let a=reconcile({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:N(t,a.newContent),setReconciledBase(t,a.newContent),e++;break;case`conflicts`:N(t,a.newContent),setReconciledBase(t,a.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){g.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&g.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&x.current)try{let t=shadowGit(x.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
138
+ `))e&&await t.raw(`update-ref`,`-d`,e);g.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){g.error({err:e},`[branch-switch] detached cleanup failed`)}T?.emitBranchSwitched(r)}if(e.headMoved&&e.newHead&&x.current&&n>0){let t=d??`.`;try{let n=await commitUpstreamImport(x.current,t,e.oldHead,e.newHead,r);incrementUpstreamImport(),g.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){g.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){g.error({err:e},`[server] HEAD watcher failed to start`),G.push(`head-watcher`)}let i=h?.[0]??`open-knowledge`,a=[`-c`,`credential.helper=!${h&&h.length>1?h.join(` `):i} auth git-credential`];try{V=new SyncEngine({projectDir:n,contentDir:t,contentFilter:y,contentRoot:d,credentialArgs:a,cc1Broadcaster:T,setBatchInProgress,onStateChange:e=>{g.info({state:e},`[sync] state → ${e}`)}}),await V.start()}catch(e){g.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),V=null}}let q=K();return{hocuspocus:C,sessionManager:w,cc1Broadcaster:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,contentFilter:y,serverInstanceId:_,destroy:W,ready:q,degraded:G,lockDir:v,get syncEngine(){return V}}}const DEFAULT_PARENT_DEATH_POLL_MS=5e3,DEFAULT_IDLE_THRESHOLD_MS=1800*1e3;async function bootServer(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??getLogger(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=process.env.OK_PARENT_PID,s=typeof o==`string`&&/^[0-9]+$/.test(o)?Number.parseInt(o,10):void 0,c=e.lockKind??a??`interactive`,l=e.parentPid??s;initTelemetry();let{createServer:u}=await import(`node:http`),{WebSocketServer:d}=await import(`./wrapper-BTT6637Z.mjs`),{updateServerLockPort:f}=await import(`./server-lock-QiPvrcO9-CB330FUa.mjs`).then(e=>e.a),p=!1;!t&&e.ensureProjectGitFn&&(p=!!(await e.ensureProjectGitFn()).didInit);let m=!1;if(!t&&e.autoInitFn)try{m=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let h=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,includePatterns:e.includePatterns,excludePatterns:e.excludePatterns,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:c,parentPid:l}),{hocuspocus:g,destroy:_,ready:v,degraded:y,lockDir:b,agentPresenceBroadcaster:x}=h,S=u((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){g.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),C=new d({noServer:!0});C.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)});let w=e.keepaliveGraceMs??1e4,T=new Map,E=new Set,D=!1;S.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive socket error`)}),C.handleUpgrade(e,t,n,t=>{let n=parseKeepaliveConnectionId(e.url);if(n){let e=T.get(n);e!==void 0&&(clearTimeout(e),T.delete(n),i.info({connectionId:n},`[keepalive] reconnect during grace — timer cancelled`))}let r=setInterval(()=>{try{t.ping()}catch{}},3e4);r.unref?.();let a=n?setInterval(()=>{x?.bumpPresenceTs(toBroadcasterKey(n))},3e3):null;a?.unref?.(),t.on(`close`,()=>{if(clearInterval(r),a!==null&&clearInterval(a),!n)return;let e=setTimeout(()=>{if(T.delete(n),D)return;let e=(async()=>{i.info({connectionId:n},`[keepalive] grace expired — cleaning up sessions`);try{await h.sessionManager.closeAllForAgent(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] closeAllForAgent failed`)}try{h.agentFocusBroadcaster?.clearFocus(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearFocus failed`)}try{x?.clearPresence(toBroadcasterKey(n))}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearPresence failed`)}})();E.add(e),e.finally(()=>E.delete(e))},w);e.unref?.(),T.set(n,e),i.info({connectionId:n,graceMs:w},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`Upgrade socket error`)}),C.handleUpgrade(e,t,n,t=>{let n=g.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let O=null;r!==null&&(O=attachIdleShutdown({httpServer:S,thresholdMs:r??DEFAULT_IDLE_THRESHOLD_MS,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await _()})})),await new Promise((t,n)=>{let r=e=>n(e);S.once(`error`,r),S.listen(e.port,e.host,()=>{S.removeListener(`error`,r),t()})});let k=S.address(),A=typeof k==`object`&&k?k.port:e.port??0;if(f(b,A),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:b,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let j=!1,M=null,N=async()=>{if(!j){j=!0,D=!0,M!==null&&(clearInterval(M),M=null),O?.detach();for(let e of T.values())clearTimeout(e);T.clear(),E.size>0&&await Promise.allSettled([...E]),await new Promise(e=>{S.close(()=>e())}),await _(),await shutdownTelemetry()}};if(l!==void 0){let t=e.parentDeathPollMs??DEFAULT_PARENT_DEATH_POLL_MS,n=e.parentAliveCheck??isProcessAlive;M=setInterval(()=>{j||n(l)||(i.warn({parentPid:l,lockKind:c},`[boot] parent process gone — initiating graceful shutdown`),N().catch(e=>{i.error({err:e,parentPid:l},`[boot] parent-death shutdown failed`)}))},t),M.unref?.()}return{httpServer:S,destroy:N,lockDir:b,contentDir:e.contentDir,port:A,ready:v,degraded:y,didAutoInit:m,didGitInit:p,serverInstance:h}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_ZIP_BYTES=102400;function resolveBundledSkillDir(){let e=[`../assets/skills/open-knowledge`,`./assets/skills/open-knowledge`],t=[];for(let n of e){let e=fileURLToPath(new URL(n,import.meta.url));if(existsSync(e))return e;t.push(e)}throw Error(`Bundled skill asset directory not found. Tried: ${t.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function readCliVersion(){for(let e of[`../../cli/package.json`,`../package.json`]){let t=fileURLToPath(new URL(e,import.meta.url));if(!existsSync(t))continue;let n=await readFile(t,`utf-8`),r=JSON.parse(n);if(r.name===`@inkeep/open-knowledge`&&typeof r.version==`string`)return r.version}throw Error(`Could not resolve @inkeep/open-knowledge CLI version — no package.json with matching name found in candidate paths.`)}async function*walkFiles(e,t=e){let n=await readdir(e,{withFileTypes:!0});for(let r of n){let n=join(e,r.name);r.isDirectory()?yield*walkFiles(n,t):r.isFile()&&(yield relative(t,n))}}async function zipDirectory(e,t){let n=e.split(`/`).pop()??`open-knowledge`,r=new import_yazl.ZipFile;r.addEmptyDirectory(`${n}/`);let i=[];for await(let t of walkFiles(e))i.push(t);i.sort();for(let t of i){let i=join(e,t),a=`${n}/${t}`;r.addFile(i,a)}r.end(),await new Promise((e,n)=>{let i=createWriteStream(t);r.outputStream.pipe(i),i.on(`close`,()=>e()),i.on(`error`,n),r.outputStream.on(`error`,n)})}async function sha256OfFile(e){return new Promise((t,n)=>{let r=createHash(`sha256`),i=createReadStream(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>t(r.digest(`hex`))),i.on(`error`,n)})}function extractMetadataVersion(e){let t=e.indexOf(`
139
139
  ---`,4);if(!e.startsWith(`---
140
140
  `)||t<0)return;let n=e.slice(4,t),r=n.search(/^metadata:/m);if(r<0)return;let i=n.slice(r).split(`
141
141
  `).slice(1);for(let e of i){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,n={}){let r=statSync(e).size;if(r>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${r} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let i=await sha256OfFile(e),a=await readFile(join(resolveBundledSkillDir(),`SKILL.md`),`utf-8`);if(!/^name:\s+open-knowledge$/m.test(a.slice(0,1e3)))throw Error("SKILL.md frontmatter `name:` does not match 'open-knowledge'. Check packages/server/assets/skills/open-knowledge/SKILL.md frontmatter.");let o=extractMetadataVersion(a);if(!n.skipVersionCheck){if(!o)throw Error("SKILL.md metadata.version missing. Add it to packages/server/assets/skills/open-knowledge/SKILL.md or run `bash scripts/sync-skill-version.sh`.");if(o!==t)throw Error(`SKILL.md metadata.version (${o}) does not match CLI version (${t}). Run \`bash scripts/sync-skill-version.sh\` after bumping package versions.`)}return{size:r,sha256:i,skillVersion:o}}async function buildSkillZip(e={}){let t=e.sourceDir??resolveBundledSkillDir(),n=e.outputPath??join(process.cwd(),`openknowledge.skill`),r=await readCliVersion();await zipDirectory(t,n);let{size:i,sha256:a,skillVersion:o}=await validateSkillZip(n,r,{skipVersionCheck:e.skipVersionCheck});return{outputPath:n,size:i,sha256:a,cliVersion:r,skillVersion:o}}function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):n===`win32`?existsSync(join(r.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function ensureProjectGit(e){let t=resolve(e),n=resolve(t,`.git`);if(existsSync(n))return{didInit:!1};let r=``;try{r=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!existsSync(resolve(n,`HEAD`)))throw new ProjectGitInitError(`git init reported success but ${n}/HEAD is missing (partial init detected)`,r);return console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0}}const SIDECAR_FILENAME=`skill-installed-version`,SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS=6e4,VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/;async function readServerPackageVersion(){let e=await readFile(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}function sidecarPath(e){return join(e,`.open-knowledge`,SIDECAR_FILENAME)}async function readSidecarVersion(e){try{let t=(await readFile(sidecarPath(e),`utf-8`)).trim();return t.length===0||!VERSION_RE.test(t)?null:t}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function writeSidecarVersion(e,t){let n=sidecarPath(e);await mkdir(dirname(n),{recursive:!0}),await writeFile(n,`${t}\n`,`utf-8`)}function runSpawn(e,t,n,r,i){return new Promise(a=>{let o;try{o=e(t,n,{env:r,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){a({kind:`spawn-error`,stderr:``,error:e});return}let s=``,c=!1,l=e=>{c||(c=!0,clearTimeout(u),a(e))};o.stderr?.on(`data`,e=>{s+=typeof e==`string`?e:e.toString(`utf-8`)}),o.on(`error`,e=>{l({kind:`spawn-error`,stderr:s,error:e})}),o.on(`exit`,e=>{l(e===0?{kind:`ok`,exitCode:e,stderr:s}:{kind:`nonzero`,exitCode:e,stderr:s})});let u=setTimeout(()=>{try{o.kill(`SIGTERM`)}catch{}l({kind:`timeout`,stderr:s})},i)})}async function installUserSkill(e={}){let t=e.home??homedir(),n=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},r=e.spawn??spawn,i=e.timeoutMs??DEFAULT_TIMEOUT_MS,a;try{a=await readServerPackageVersion()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),`failed`}let o=await readSidecarVersion(t).catch(()=>null);if(o!==null&&o===a)return n.info?.({event:`skill-install.skip-current`,version:a},`Open Knowledge skill already installed at current version; skipping.`),`skip-current`;let s;try{s=resolveBundledSkillDir()}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),`failed`}let c=await runSpawn(r,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,s,`--agent`,`*`,`-g`,`-y`,`--copy`],{...process.env,HOME:t},i);if(c.kind===`ok`){try{await writeSidecarVersion(t,a)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),`failed`}return n.info?.({event:`skill-install.installed`,version:a},`Open Knowledge skill installed to detected agent hosts.`),`installed`}return c.kind===`timeout`?(n.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:i,stderr:c.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):c.kind===`spawn-error`?(n.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(c.error),stderr:c.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):(n.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:c.exitCode,stderr:c.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`)}export{getTracer as $,bootServer as A,saveInMemoryCheckpoint as At,createApiExtension as B,updateUiLockPort as Bt,SeedRootDirError as C,removeLastKnownHash as Ct,applyExternalChange as D,safeContentPath as Dt,applyAgentMarkdownWrite as E,rewriteWikiLinksForDocumentRename as Et,commitWip as F,splitMarkdownBlocks as Ft,createServerObserverExtension as G,writeTracker as Gt,createLiveDerivedIndexExtension as H,validateSkillZip as Ht,commitWipFromTree as I,startWatcher as It,evictStaleTrackerEntries as J,getWipRefPattern as Jt,detectClaudeDesktopPresence as K,require_picomatch as Kt,containsConflictMarkers as L,starterFolderRule as Lt,buildWipTree as M,setActiveSpanAttributes as Mt,classifyEvents as N,shadowGit as Nt,applySeed as O,safeSubdir as Ot,commitUpstreamImport as P,shutdownTelemetry as Pt,getMetrics as Q,contentHash as R,toBroadcasterKey as Rt,SeedPrerequisiteError as S,releaseUiLock as St,acquireUiLock as T,rewriteMarkdownLinksForDocumentRename as Tt,createPersistenceExtension as U,withSpan as Ut,createContentFilter as V,validateAgentId as Vt,createServer$1 as W,withSpanSync as Wt,getLogger as X,readContributors as Xt,extractWikiLinksFromMarkdown as Y,parseWriterId as Yt,getMeter as Z,ProjectGitInitError as _,readBranchFromHead as _t,BacklinkIndex as a,installUserSkill as at,SERVICE_WRITER as b,recordContributor as bt,FILE_SYSTEM_WRITER as c,isSystemDoc as ct,HocuspocusAuthRejection as d,loadPrincipal as dt,handleCollabSocketError as et,HocuspocusAuthTokenSchema as f,loggerFactory as ft,PinoLogger as g,planSeed as gt,OBSERVER_SYNC_ORIGIN as h,pathToDocName as ht,AgentSessionManager as i,initTelemetry as it,buildSkillZip as j,saveVersion as jt,attachIdleShutdown as k,safetyCheckpoint as kt,FILE_WATCHER_ORIGIN as l,lastKnownHash as lt,MANAGED_RENAME_ORIGIN as m,parseKeepaliveConnectionId as mt,AgentFocusBroadcaster as n,incrementServerObserverFire as nt,CC1Broadcaster as o,isPairedWriteOrigin as ot,LOG_MD_TEMPLATE as p,parseHocuspocusAuthToken as pt,ensureProjectGit as q,getShadowRepoPath as qt,AgentPresenceBroadcaster as r,initShadowRepo as rt,CONFLICT_MARKER_RE as s,isSelfWrite as st,AGENT_ID_RE as t,incrementCollabSocketFilteredError as tt,GIT_UPSTREAM_WRITER as u,listRescueCheckpoints as ut,ROLLBACK_ORIGIN as v,readUiLock as vt,UiLockCollisionError as w,resolveBundledSkillDir as wt,STARTER_FOLDERS as x,registerWrite as xt,SEED_CONFIG_FILENAME as y,reconcile as yt,contributorCount as z,updateLastKnownHash as zt};
142
- //# sourceMappingURL=dist-BVi1kLgS.mjs.map
142
+ //# sourceMappingURL=dist-DoVDgyml.mjs.map