@inkeep/open-knowledge 0.0.0-dev-20260428211426 → 0.0.0-dev-20260429160105
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD_PARTY_NOTICES.md +15 -0
- package/dist/cli.mjs +284 -281
- package/dist/constants-DLhaxFjM.mjs +2 -0
- package/dist/{dist-CXdg7KnM.mjs → dist-CIeZOXfv.mjs} +22 -19
- package/dist/{dist-Ct-gJ7iD.mjs → dist-CNDKfHI8.mjs} +1 -1
- package/dist/{dist-0qFIeeXA.mjs → dist-DD_wEI4a.mjs} +15 -15
- package/dist/index.mjs +1 -1
- package/dist/{init-D0YdyLe_.mjs → init-2ZbpRqT6.mjs} +4 -4
- package/dist/init-Cy-4UOwQ.mjs +1 -0
- package/dist/{init-CMkePWjl.mjs → init-DWGTb8QS.mjs} +22 -7
- package/dist/init-DWvyb5i4.mjs +1 -0
- package/dist/{loader-BJU3jneI.mjs → loader-B73SzGQk.mjs} +2 -2
- package/dist/loader-Ce28eAYb.mjs +1 -0
- package/dist/paths-CcD8Nh_5.mjs +1 -0
- package/dist/paths-DqWCeGWM.mjs +2 -0
- package/dist/{preview-CXP9kBv6.mjs → preview-DRDic3pF.mjs} +2 -2
- package/dist/preview-DT0ltjSs.mjs +1 -0
- package/dist/public/assets/ActivityModeContent-spvhVGSd.js +2 -0
- package/dist/public/assets/DocumentContext-Xq_dn8Vf.js +33 -0
- package/dist/public/assets/GraphPanel-C36W-gM6.js +46 -0
- package/dist/public/assets/McpConsentDialogBody-CDOor7qb.js +1 -0
- package/dist/public/assets/SourceEditor-BeRKaESA.js +2 -0
- package/dist/public/assets/{agent-presence-BXsx4eTl.js → agent-presence-XtMgnv3n.js} +1 -1
- package/dist/public/assets/clipboard-0XbokP0-.js +5 -0
- package/dist/public/assets/{dialog-CtSN0d2b.js → dialog-B7UAZUVJ.js} +1 -1
- package/dist/public/assets/{dist-DeDgmJv2.js → dist-5Xm_mb8k.js} +1 -1
- package/dist/public/assets/{dist-GlH2KPqY.js → dist-BkmmA9Kx.js} +1 -1
- package/dist/public/assets/{dist-BqO6NfD-.js → dist-CBfh7n1S.js} +1 -1
- package/dist/public/assets/{dist-DR1MrLJC.js → dist-DUCdsXly.js} +1 -1
- package/dist/public/assets/{dist-DlS42TIP.js → dist-DxKDMu0r.js} +1 -1
- package/dist/public/assets/{dist-D2wwoXzm.js → dist-gwU6yV0l.js} +1 -1
- package/dist/public/assets/index-DmSa5KwJ.js +1843 -0
- package/dist/public/assets/index-ldPPE8aY.css +1 -0
- package/dist/public/assets/{panel-BCRdtBla.js → panel-DiSt1efw.js} +1 -1
- package/dist/public/assets/target-navigation-intent-DlP83APM.js +1 -0
- package/dist/public/assets/toggle-group-Cg6YuFV4.js +281 -0
- package/dist/public/assets/tooltip-BaQG219g.js +1 -0
- package/dist/public/index.html +14 -14
- package/dist/src-CCUnFptH.mjs +1 -0
- package/dist/start-BaIxHOku.mjs +1 -0
- package/dist/start-nj1M3dB_.mjs +2 -0
- package/package.json +1 -1
- package/dist/constants-DCJlLBSi.mjs +0 -2
- package/dist/init-D-5Gc0uq.mjs +0 -1
- package/dist/init-DUA_XKK1.mjs +0 -1
- package/dist/loader-1GTY76cQ.mjs +0 -1
- package/dist/paths-CNpYe27Q.mjs +0 -2
- package/dist/paths-fx16Ahvg.mjs +0 -1
- package/dist/preview-CHvLSbhb.mjs +0 -1
- package/dist/public/assets/ActivityModeContent-Ccu_n0bV.js +0 -2
- package/dist/public/assets/DocumentContext-C1msvcHp.js +0 -5
- package/dist/public/assets/GraphPanel-CJ_U3W3L.js +0 -46
- package/dist/public/assets/McpConsentDialogBody-Csjet19t.js +0 -1
- package/dist/public/assets/PageListContext-B5SWnlyE.js +0 -278
- package/dist/public/assets/SourceEditor-OFesfBB2.js +0 -3
- package/dist/public/assets/clipboard-DAcKCHl1.js +0 -32
- package/dist/public/assets/index-CwFTGDhe.js +0 -1843
- package/dist/public/assets/index-DjR45Lon.css +0 -1
- package/dist/public/assets/toggle-group-LDOO6zaV.js +0 -1
- package/dist/public/assets/tooltip-D0MnQ7ZX.js +0 -1
- package/dist/src-BIqAAP5m.mjs +0 -1
- package/dist/start-BOjBm-nL.mjs +0 -2
- package/dist/start-CZFHRjtT.mjs +0 -1
- /package/dist/public/assets/{button-BPXuMr5W.js → button-CXhPNzpp.js} +0 -0
- /package/dist/public/assets/{dist-CgLbXgrr.js → dist-Bgq0sPT8.js} +0 -0
|
@@ -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
|
|
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{$ as string,A as isOrphanMode,C as createCodeFenceTracker,D as getParseHealth,E as getHeadingSlug,F as sharedExtensions,I as stripFrontmatter,L as toWikiLinkSlug,M as normalizeBridge,N as prependFrontmatter,O as getWikiLinkText,P as resolveInternalHref,S as colorFromSeed,T as getFrontmatter,Y as object,_ as SYSTEM_DOC_NAME,_t as getSchema,a as ASSET_EXTENSIONS,b as classifyMarkdownHref,c as CC1DerivedViewPayloadSchema,d as CC1_CHANNEL_BRANCH_SWITCHED,f as CC1_CHANNEL_DISK_ACK,h as OK_DIR,i as ALLOWED_VIDEO_MIME_TYPES,j as mergeThreeWay,k as iconFromClientName,l as CC1DiskAckPayloadSchema,m as MarkdownManager,n as ALLOWED_AUDIO_MIME_TYPES,o as BridgeMergeContentLossError,p as CC1_CHANNEL_SERVER_INFO,r as ALLOWED_IMAGE_MIME_TYPES,s as CC1BranchSwitchedPayloadSchema,t as AGENT_ICON_COLORS,u as CC1ServerInfoPayloadSchema,v as applyFastDiff,vt as PluginKey,w as defaultScheduler,x as classifyWikiLinkTarget,y as applyIncrementalDiff,yt as Fragment}from"./dist-CIeZOXfv.mjs";import{a as acquireServerLock,c as readProcessLock,d as releaseServerLock,i as acquireProcessLock,l as readServerLock,n as RUNTIME_VERSION,o as isProcessAlive,p as updateProcessLockPort,t as ProcessLockCollisionError,u as releaseProcessLock}from"./server-lock-n3Y5JWNv-3o7br8XE.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
|
`:`
|
|
@@ -74,7 +74,7 @@ To resolve the conflict:`,(0,r.getConflictResolutionRecipe)(i,e))),a=o):n.diag.w
|
|
|
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(`
|
|
76
76
|
|
|
77
|
-
`)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function computeEditOps(e,t){let n=new Map,r=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function longestCommonSubsequence(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let a=1;a<=n;a++)for(let n=1;n<=r;n++)e[a-1]===t[n-1]?i[a][n]=i[a-1][n-1]+1:i[a][n]=Math.max(i[a-1][n],i[a][n-1]);let a=[],o=n,s=r;for(;o>0&&s>0;)e[o-1]===t[s-1]?(a.push([o-1,s-1]),o--,s--):i[o-1][s]>=i[o][s-1]?o--:s--;return a.reverse()}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let n=writeTracker.get(e)??[];n.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,n)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,n]of writeTracker){let r=n.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);r.length===0?writeTracker.delete(t):r.length!==n.length&&writeTracker.set(t,r)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function extractDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(isSupportedDocFile(r.path)){if(n){let e=relative(t,r.path);if(n.isExcluded(e))continue}switch(r.type){case`delete`:i.push(r);break;case`create`:lastKnownHash.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of o)try{c.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function l(e){let n=pathToDocName(e,t);if(!r)return n;let i=null;try{i=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=realpathSync(e)}catch(t){let i=t.code;return i!==`ENOENT`&&i!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),r.delete(n),n}if(!isWithinContentDir(a,t))return r.delete(n),n;let o=pathToDocName(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=removeLastKnownHash(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(r===void 0)continue;let i=contentHash(r);if(i===t){d.add(n.path),f.add(e.path),updateLastKnownHash(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||(removeLastKnownHash(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(t===void 0)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(t===void 0)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function isSelfWrite(e,t){let n=writeTracker.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,n,r,i,a){let o=a??new Set;try{let a=readdirSync(e,{withFileTypes:!0});for(let s of a){let a=join(e,s.name),c;try{c=lstatSync(a)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${a}, skipping:`,e);continue}if(c.isSymbolicLink()){let e;try{e=realpathSync(a)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${a}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${a}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${a} → ${e}, skipping`);continue}try{let c=statSync(e);if(o.has(c.ino)){if(c.isFile()&&isSupportedDocFile(s.name)){let n=pathToDocName(a,t),o=pathToDocName(e,t);i.set(n,o);let s=r.get(o);s&&!s.aliases.includes(n)&&s.aliases.push(n)}continue}if(o.add(c.ino),c.isDirectory()){if(n){let r=relative(t,e);if(n.isDirExcluded(r))continue}seedLastKnownHashes(e,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(n){let r=relative(t,e);if(n.isExcluded(r))continue}let o=pathToDocName(a,t),s=pathToDocName(e,t);i.set(o,s);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let n=extractDocExtension(e);if(n){let e=registerDocExtension(s,n);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(s,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:e,inode:c.ino,aliases:[o]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(c.isDirectory()){if(n){let e=relative(t,a);if(n.isDirExcluded(e))continue}seedLastKnownHashes(a,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(o.has(c.ino))continue;if(o.add(c.ino),n){let e=relative(t,a);if(n.isExcluded(e))continue}try{let e=readFileSync(a,`utf-8`);lastKnownHash.set(a,contentHash(e));let n=pathToDocName(a,t),i=extractDocExtension(a);if(i){let e=registerDocExtension(n,i);if(e.shadowed&&(console.warn(`[file-watcher] docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:a,inode:c.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${a}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${a}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(!isSystemDoc(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=extractDocExtension(e.path);i&®isterDocExtension(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let r=extractDocExtension(e.newPath);r&®isterDocExtension(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[]});break}}}async function handleRawEvents(e,t,n,r,i,a){let o=e.filter(e=>isSupportedDocFile(e.path));if(o.length===0)return;let s=await classifyEvents(o,t,n,a);for(let e of s){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=contentHash(e.content),r=e.path;try{r=realpathSync(e.path)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${n})`)}t=isSelfWrite(r,n)}else if(e.kind===`rename`){let n=contentHash(e.content),r=e.newPath;try{r=realpathSync(e.newPath)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=isSelfWrite(r,n)}if(updateFileIndex(e,r),n)switch(e.kind){case`create`:n.incrementMdDir(dirname(e.docName));break;case`delete`:n.decrementMdDir(dirname(e.docName));break;case`rename`:n.decrementMdDir(dirname(e.oldDocName)),n.incrementMdDir(dirname(e.newDocName));break}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let a=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(a),"disk.path.role":classifyFsPath(a)}},async()=>i(e))}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,n,r,i){let a;try{a=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let o=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await a.subscribe(e,async(a,o)=>{if(a){console.error(`[file-watcher]`,a);return}try{await handleRawEvents(o.map(e=>({type:e.type,path:e.path})),e,t,n,r,i)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},o)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,n,r,i){let{watch:a}=await import(`./chokidar-CblsKfnx.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let o=a(e,{ignoreInitial:!0,ignored:t?(n,r)=>{let i=relative(e,n);return i===``||i===`.`?!1:r?.isDirectory()?t.isDirExcluded(i):t.isExcluded(i)}:void 0});o.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let s=50,c=[],l=null;function u(a,o){c.push({type:a,path:o}),l||=setTimeout(()=>{let a=c;c=[],l=null,handleRawEvents(a,e,t,n,r,i).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return o.on(`add`,e=>u(`create`,e)),o.on(`change`,e=>u(`update`,e)),o.on(`unlink`,e=>u(`delete`,e)),{unsubscribe:()=>(l&&(clearTimeout(l),l=null,c=[]),o.close())}}async function startWatcher(e,t,n){let r;try{r=realpathSync(e)}catch{r=e}let i=new Map,a=new Map;seedLastKnownHashes(r,r,n,i,a);let o=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),s,c;try{let e=await startParcelWatcher(r,n,i,t,a);e?(s=e,c=`parcel`):(s=await startChokidarWatcher(r,n,i,t,a),c=`chokidar`)}catch(e){throw clearInterval(o),e}let l=s.unsubscribe.bind(s);return console.log(`[file-watcher] Watching ${r} for external .md changes (backend: ${c})`),{async unsubscribe(){return clearInterval(o),writeTracker.clear(),lastKnownHash.clear(),l()},getFileIndex(){return i},getAliasMap(){return a}}}const defaultGitConfigReader=(e,t,n)=>{let r=spawnSync(`git`,[`config`,n===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return r.status!==0||!r.stdout?null:r.stdout.trim()||null};async function resolveGitIdentity(e,t,n,r=defaultGitConfigReader){let i=r(e,`user.name`,`local`),a=r(e,`user.email`,`local`);if(i&&a)return{name:i,email:a};let o=r(e,`user.name`,`global`),s=r(e,`user.email`,`global`);if(o&&s)return{name:o,email:s};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function writeGitIdentity(e,t,n){let r=(t,n)=>{let r=spawnSync(`git`,[`config`,`--local`,t,n],{cwd:e,encoding:`utf-8`,timeout:5e3});if(r.status!==0){let e=r.stderr?.trim()??``;throw Error(`git config --local ${t} failed: ${e}`)}};r(`user.name`,t),r(`user.email`,n)}const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function isSafeLocalPath(e){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let t=homedir(),n=resolve(expandTilde(e));return n===t||n.startsWith(`${t}/`)}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,n){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(n(t,403,{ok:!1,error:`Forbidden: invalid origin for local-op endpoint`}),!1):(n(t,403,{ok:!1,error:`Forbidden: local-op endpoints require loopback connection`}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function isLoopbackAddress(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function isAllowedWorkspaceHostHeader(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}const MANAGED_RENAME_JOURNAL_VERSION=1,MANAGED_RENAME_JOURNAL_FILENAME=`managed-rename.json`;function journalDir(e){return resolve(e,`.open-knowledge`)}function managedRenameJournalPath(e){return resolve(journalDir(e),MANAGED_RENAME_JOURNAL_FILENAME)}function createManagedRenameRecoveryJournal(e){return{version:MANAGED_RENAME_JOURNAL_VERSION,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots}}function isManagedRenameSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function parseManagedRenameRecoveryJournal(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version!==MANAGED_RENAME_JOURNAL_VERSION)throw Error(`Unsupported managed rename journal version: ${String(t.version)}`);if(typeof t.sourceDocName!=`string`||t.sourceDocName.length===0)throw Error(`Managed rename journal is missing sourceDocName`);if(typeof t.destinationDocName!=`string`||t.destinationDocName.length===0)throw Error(`Managed rename journal is missing destinationDocName`);if(typeof t.createdAt!=`string`||t.createdAt.length===0)throw Error(`Managed rename journal is missing createdAt`);if(!Array.isArray(t.snapshots)||t.snapshots.length===0)throw Error(`Managed rename journal is missing snapshots`);if(!t.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal has invalid snapshots`);if(!t.snapshots.some(e=>e.docName===t.sourceDocName))throw Error(`Managed rename journal must include the source document snapshot`);return{version:t.version,sourceDocName:t.sourceDocName,destinationDocName:t.destinationDocName,createdAt:t.createdAt,snapshots:t.snapshots}}function readManagedRenameJournal(e){let t=managedRenameJournalPath(e);if(!existsSync(t))return null;let n=readFileSync(t,`utf-8`);try{return parseManagedRenameRecoveryJournal(JSON.parse(n))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function writeManagedRenameJournal(e,t){let n=managedRenameJournalPath(e);mkdirSync(dirname(n),{recursive:!0});let r=`${n}.tmp`;writeFileSync(r,JSON.stringify(t,null,2),`utf-8`),renameSync(r,n)}function clearManagedRenameJournal(e){rmSync(managedRenameJournalPath(e),{force:!0})}async function withManagedRenameRecovery(e,t,n){writeManagedRenameJournal(e,t);let r=await n();return clearManagedRenameJournal(e),r}function recoverPendingManagedRename(e){let t=readManagedRenameJournal(e);if(!t)return{recovered:!1,journal:null,restoredDocNames:[]};let n=new Set,r=[];for(let i of t.snapshots)try{let t=safeContentPath(i.docName,e);mkdirSync(dirname(t),{recursive:!0}),writeFileSync(t,i.content,`utf-8`),n.add(i.docName)}catch(e){r.push(i.docName),console.warn(`[managed-rename] Failed to restore ${i.docName}:`,e)}if(r.length>0)throw console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${r.join(`, `)})`),Error(`Managed rename recovery incomplete; failed to restore: ${r.join(`, `)}`);if(!n.has(t.destinationDocName)){let n=safeContentPath(t.destinationDocName,e);try{rmSync(n,{force:!0})}catch(e){throw existsSync(n)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t.destinationDocName}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t.destinationDocName}:`,e),Error(`Managed rename recovery incomplete; failed to clean destination: ${t.destinationDocName}`)}}return clearManagedRenameJournal(e),{recovered:!0,journal:t,restoredDocNames:[...n].sort((e,t)=>e.localeCompare(t))}}function matchFence$1(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$1(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$1(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$1(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n;for(;r<e.length;){if(e[r]!=="`"){r++;continue}let t=0;for(;e[r+t]==="`";)t++;if(t===n)return{nextIndex:r+n};r+=t}return null}function readWikiLink$1(e,t){let n=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function readMarkdownLink$1(e,t){let n=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!n)return null;let r=n[2]??``;return{text:n[1]??``,hrefRaw:r,href:r.startsWith(`<`)&&r.endsWith(`>`)?r.slice(1,-1):r,titleSuffix:n[3]??``,nextIndex:t+n[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),n=[];for(let e=0;e<t.length;e+=2)n.push({line:t[e]??``,ending:t[e+1]??``});return n}function rewriteWikiLinksInLine(e,t,n){let r=``,i=0,a=0,o=leadingMarkdownPrefixLength$1(e);for(o>0&&(r+=e.slice(0,o),a=o);a<e.length;){if(e[a]===`\\`&&a+1<e.length){r+=e.slice(a,a+2),a+=2;continue}if(e[a]==="`"){let t=readInlineCode$1(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let o=readWikiLink$1(e,a);if(o){o.target===t?(r+=`[[${n}${o.anchor?`#${o.anchor}`:``}${o.alias?`|${o.alias}`:``}]]`,i++):r+=e.slice(a,o.nextIndex),a=o.nextIndex;continue}}r+=e[a],a++}return{markdown:r,rewrites:i}}function buildRelativeMarkdownHref(e,t,n){let r=e.indexOf(`#`),i=r>=0?e.slice(r):``,a=r>=0?e.slice(0,r):e,o=a.indexOf(`?`),s=o>=0?a.slice(o):``,c=o>=0?a.slice(0,o):a,l=posix.dirname(t),u=posix.relative(l===`.`?``:l,n);return u||=posix.basename(n),c.endsWith(`.md`)&&(u+=`.md`),c.startsWith(`./`)&&!u.startsWith(`./`)&&!u.startsWith(`../`)&&(u=`./${u}`),`${u}${s}${i}`}function rewriteMarkdownLinksInLine(e,t,n,r){let i=``,a=0,o=0,s=leadingMarkdownPrefixLength$1(e);for(s>0&&(i+=e.slice(0,s),o=s);o<e.length;){if(e[o]===`\\`&&o+1<e.length){i+=e.slice(o,o+2),o+=2;continue}if(e[o]==="`"){let t=readInlineCode$1(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o+1]===`[`){let t=readWikiLink$1(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o-1]!==`!`){let s=readMarkdownLink$1(e,o);if(s){if(resolveInternalHref(s.href,t)?.docName===n){let e=buildRelativeMarkdownHref(s.href,t,r),n=s.hrefRaw.startsWith(`<`)&&s.hrefRaw.endsWith(`>`)?`<${e}>`:e;i+=`[${s.text}](${n}${s.titleSuffix})`,a++}else i+=e.slice(o,s.nextIndex);o=s.nextIndex;continue}}i+=e[o],o++}return{markdown:i,rewrites:a}}function rewriteWikiLinksForDocumentRename(e,t,n){let r=null,i=0;return{markdown:splitLines(e).map(({line:e,ending:a})=>{if(r)return isFenceClose$1(e,r)&&(r=null),`${e}${a}`;let o=matchFence$1(e);if(o)return r=o,`${e}${a}`;let s=rewriteWikiLinksInLine(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}function rewriteMarkdownLinksForDocumentRename(e,t,n,r){let i=null,a=0;return{markdown:splitLines(e).map(({line:e,ending:o})=>{if(i)return isFenceClose$1(e,i)&&(i=null),`${e}${o}`;let s=matchFence$1(e);if(s)return i=s,`${e}${o}`;let c=rewriteMarkdownLinksInLine(e,t,n,r);return a+=c.rewrites,`${c.markdown}${o}`}).join(``),rewrites:a}}const STARTER_FOLDERS=[{path:`external-sources`,match:`external-sources/**`,title:`External Sources`,description:"Raw sources SAVED verbatim — not just cited. The actual fetched text of URLs, extracted text of PDFs, and copies of any referenced files live as .md files here, each with frontmatter carrying the original URL, access date, and any publisher / author metadata. Produced by `ingest` — applies whether the user shared the URL OR the agent fetched it itself to ground a knowledge-base claim. The KB is closed-loop: downstream docs cite local paths in this folder, never bare web URLs. Immutable after capture (update only to refresh a stale fetch). No analysis in these files — that belongs in `research/`. Downstream articles cite specific docs here by path so every claim is traceable to preserved evidence rather than a dead link.",tags:[`source`,`immutable`,`layer-ingest`]},{path:`research`,match:`research/**`,title:`Research`,description:"Provisional analysis synthesizing external sources. Produced by the `research` tool. Every factual claim cites a specific doc in `external-sources/` (or an inline URL if ingest was skipped) — no unsourced assertions. Each article has `status: provisional` and a `sources:` frontmatter list of cited paths. Promoted to `articles/` via `consolidate` once the team decides the findings are stable.",tags:[`research`,`provisional`,`layer-research`]},{path:`articles`,match:`articles/**`,title:`Articles`,description:"Canonical knowledge committed after a team decision. Produced by `consolidate`. Carries `status: canonical` plus a `supersedes:` chain tying back to the `research/` docs it replaces, which in turn cite `external-sources/` — the full evidence chain is traceable without leaving the repo. Source-of-truth for the domain; update only when a new decision supersedes it.",tags:[`article`,`canonical`,`layer-consolidate`]}],LOG_MD_TEMPLATE=`---
|
|
77
|
+
`)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function computeEditOps(e,t){let n=new Map,r=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function longestCommonSubsequence(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let a=1;a<=n;a++)for(let n=1;n<=r;n++)e[a-1]===t[n-1]?i[a][n]=i[a-1][n-1]+1:i[a][n]=Math.max(i[a-1][n],i[a][n-1]);let a=[],o=n,s=r;for(;o>0&&s>0;)e[o-1]===t[s-1]?(a.push([o-1,s-1]),o--,s--):i[o-1][s]>=i[o][s-1]?o--:s--;return a.reverse()}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let n=writeTracker.get(e)??[];n.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,n)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,n]of writeTracker){let r=n.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);r.length===0?writeTracker.delete(t):r.length!==n.length&&writeTracker.set(t,r)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function extractDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(isSupportedDocFile(r.path)){if(n){let e=relative(t,r.path);if(n.isExcluded(e))continue}switch(r.type){case`delete`:i.push(r);break;case`create`:lastKnownHash.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of o)try{c.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function l(e){let n=pathToDocName(e,t);if(!r)return n;let i=null;try{i=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=realpathSync(e)}catch(t){let i=t.code;return i!==`ENOENT`&&i!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),r.delete(n),n}if(!isWithinContentDir(a,t))return r.delete(n),n;let o=pathToDocName(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=removeLastKnownHash(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(r===void 0)continue;let i=contentHash(r);if(i===t){d.add(n.path),f.add(e.path),updateLastKnownHash(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||(removeLastKnownHash(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(t===void 0)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(t===void 0)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function isSelfWrite(e,t){let n=writeTracker.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,n,r,i,a){let o=a??new Set;try{let a=readdirSync(e,{withFileTypes:!0});for(let s of a){let a=join(e,s.name),c;try{c=lstatSync(a)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${a}, skipping:`,e);continue}if(c.isSymbolicLink()){let e;try{e=realpathSync(a)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${a}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${a}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${a} → ${e}, skipping`);continue}try{let c=statSync(e);if(o.has(c.ino)){if(c.isFile()&&isSupportedDocFile(s.name)){let n=pathToDocName(a,t),o=pathToDocName(e,t);i.set(n,o);let s=r.get(o);s&&!s.aliases.includes(n)&&s.aliases.push(n)}continue}if(o.add(c.ino),c.isDirectory()){if(n){let r=relative(t,e);if(n.isDirExcluded(r))continue}seedLastKnownHashes(e,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(n){let r=relative(t,e);if(n.isExcluded(r))continue}let o=pathToDocName(a,t),s=pathToDocName(e,t);i.set(o,s);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let n=extractDocExtension(e);if(n){let e=registerDocExtension(s,n);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(s,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:e,inode:c.ino,aliases:[o]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(c.isDirectory()){if(n){let e=relative(t,a);if(n.isDirExcluded(e))continue}seedLastKnownHashes(a,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(o.has(c.ino))continue;if(o.add(c.ino),n){let e=relative(t,a);if(n.isExcluded(e))continue}try{let e=readFileSync(a,`utf-8`);lastKnownHash.set(a,contentHash(e));let n=pathToDocName(a,t),i=extractDocExtension(a);if(i){let e=registerDocExtension(n,i);if(e.shadowed&&(console.warn(`[file-watcher] docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:a,inode:c.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${a}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${a}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(!isSystemDoc(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=extractDocExtension(e.path);i&®isterDocExtension(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let r=extractDocExtension(e.newPath);r&®isterDocExtension(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[]});break}}}async function handleRawEvents(e,t,n,r,i,a){let o=e.filter(e=>isSupportedDocFile(e.path));if(o.length===0)return;let s=await classifyEvents(o,t,n,a);for(let e of s){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=contentHash(e.content),r=e.path;try{r=realpathSync(e.path)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${n})`)}t=isSelfWrite(r,n)}else if(e.kind===`rename`){let n=contentHash(e.content),r=e.newPath;try{r=realpathSync(e.newPath)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=isSelfWrite(r,n)}if(updateFileIndex(e,r),n)switch(e.kind){case`create`:n.incrementMdDir(dirname(e.docName));break;case`delete`:n.decrementMdDir(dirname(e.docName));break;case`rename`:n.decrementMdDir(dirname(e.oldDocName)),n.incrementMdDir(dirname(e.newDocName));break}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let a=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(a),"disk.path.role":classifyFsPath(a)}},async()=>i(e))}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,n,r,i){let a;try{a=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let o=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await a.subscribe(e,async(a,o)=>{if(a){console.error(`[file-watcher]`,a);return}try{await handleRawEvents(o.map(e=>({type:e.type,path:e.path})),e,t,n,r,i)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},o)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,n,r,i){let{watch:a}=await import(`./chokidar-CblsKfnx.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let o=a(e,{ignoreInitial:!0,ignored:t?(n,r)=>{let i=relative(e,n);return i===``||i===`.`?!1:r?.isDirectory()?t.isDirExcluded(i):t.isExcluded(i)}:void 0});o.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let s=50,c=[],l=null;function u(a,o){c.push({type:a,path:o}),l||=setTimeout(()=>{let a=c;c=[],l=null,handleRawEvents(a,e,t,n,r,i).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return o.on(`add`,e=>u(`create`,e)),o.on(`change`,e=>u(`update`,e)),o.on(`unlink`,e=>u(`delete`,e)),{unsubscribe:()=>(l&&(clearTimeout(l),l=null,c=[]),o.close())}}async function startWatcher(e,t,n){let r;try{r=realpathSync(e)}catch{r=e}let i=new Map,a=new Map;seedLastKnownHashes(r,r,n,i,a);let o=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),s,c;try{let e=await startParcelWatcher(r,n,i,t,a);e?(s=e,c=`parcel`):(s=await startChokidarWatcher(r,n,i,t,a),c=`chokidar`)}catch(e){throw clearInterval(o),e}let l=s.unsubscribe.bind(s);return console.log(`[file-watcher] Watching ${r} for external .md changes (backend: ${c})`),{async unsubscribe(){return clearInterval(o),writeTracker.clear(),lastKnownHash.clear(),l()},getFileIndex(){return i},getAliasMap(){return a}}}const defaultGitConfigReader=(e,t,n)=>{let r=spawnSync(`git`,[`config`,n===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return r.status!==0||!r.stdout?null:r.stdout.trim()||null};async function resolveGitIdentity(e,t,n,r=defaultGitConfigReader){let i=r(e,`user.name`,`local`),a=r(e,`user.email`,`local`);if(i&&a)return{name:i,email:a};let o=r(e,`user.name`,`global`),s=r(e,`user.email`,`global`);if(o&&s)return{name:o,email:s};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function writeGitIdentity(e,t,n){let r=(t,n)=>{let r=spawnSync(`git`,[`config`,`--local`,t,n],{cwd:e,encoding:`utf-8`,timeout:5e3});if(r.status!==0){let e=r.stderr?.trim()??``;throw Error(`git config --local ${t} failed: ${e}`)}};r(`user.name`,t),r(`user.email`,n)}const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function isSafeLocalPath(e){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let t=homedir(),n=resolve(expandTilde(e));return n===t||n.startsWith(`${t}/`)}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,n){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(n(t,403,{ok:!1,error:`Forbidden: invalid origin for local-op endpoint`}),!1):(n(t,403,{ok:!1,error:`Forbidden: local-op endpoints require loopback connection`}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function isLoopbackAddress(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function isAllowedWorkspaceHostHeader(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}const MANAGED_RENAME_JOURNAL_VERSION=1,MANAGED_RENAME_JOURNAL_FILENAME=`managed-rename.json`;function journalDir(e){return resolve(e,`.open-knowledge`)}function managedRenameJournalPath(e){return resolve(journalDir(e),MANAGED_RENAME_JOURNAL_FILENAME)}function createManagedRenameRecoveryJournal(e){return{version:MANAGED_RENAME_JOURNAL_VERSION,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots}}function isManagedRenameSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function parseManagedRenameRecoveryJournal(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version!==MANAGED_RENAME_JOURNAL_VERSION)throw Error(`Unsupported managed rename journal version: ${String(t.version)}`);if(typeof t.sourceDocName!=`string`||t.sourceDocName.length===0)throw Error(`Managed rename journal is missing sourceDocName`);if(typeof t.destinationDocName!=`string`||t.destinationDocName.length===0)throw Error(`Managed rename journal is missing destinationDocName`);if(typeof t.createdAt!=`string`||t.createdAt.length===0)throw Error(`Managed rename journal is missing createdAt`);if(!Array.isArray(t.snapshots)||t.snapshots.length===0)throw Error(`Managed rename journal is missing snapshots`);if(!t.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal has invalid snapshots`);if(!t.snapshots.some(e=>e.docName===t.sourceDocName))throw Error(`Managed rename journal must include the source document snapshot`);return{version:t.version,sourceDocName:t.sourceDocName,destinationDocName:t.destinationDocName,createdAt:t.createdAt,snapshots:t.snapshots}}function readManagedRenameJournal(e){let t=managedRenameJournalPath(e);if(!existsSync(t))return null;let n=readFileSync(t,`utf-8`);try{return parseManagedRenameRecoveryJournal(JSON.parse(n))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function writeManagedRenameJournal(e,t){let n=managedRenameJournalPath(e);mkdirSync(dirname(n),{recursive:!0});let r=`${n}.tmp`;writeFileSync(r,JSON.stringify(t,null,2),`utf-8`),renameSync(r,n)}function clearManagedRenameJournal(e){rmSync(managedRenameJournalPath(e),{force:!0})}async function withManagedRenameRecovery(e,t,n){writeManagedRenameJournal(e,t);let r=await n();return clearManagedRenameJournal(e),r}function recoverPendingManagedRename(e){let t=readManagedRenameJournal(e);if(!t)return{recovered:!1,journal:null,restoredDocNames:[]};let n=new Set,r=[];for(let i of t.snapshots)try{let t=safeContentPath(i.docName,e);mkdirSync(dirname(t),{recursive:!0}),writeFileSync(t,i.content,`utf-8`),n.add(i.docName)}catch(e){r.push(i.docName),console.warn(`[managed-rename] Failed to restore ${i.docName}:`,e)}if(r.length>0)throw console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${r.join(`, `)})`),Error(`Managed rename recovery incomplete; failed to restore: ${r.join(`, `)}`);if(!n.has(t.destinationDocName)){let n=safeContentPath(t.destinationDocName,e);try{rmSync(n,{force:!0})}catch(e){throw existsSync(n)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t.destinationDocName}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t.destinationDocName}:`,e),Error(`Managed rename recovery incomplete; failed to clean destination: ${t.destinationDocName}`)}}return clearManagedRenameJournal(e),{recovered:!0,journal:t,restoredDocNames:[...n].sort((e,t)=>e.localeCompare(t))}}function matchFence$1(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$1(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$1(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$1(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n;for(;r<e.length;){if(e[r]!=="`"){r++;continue}let t=0;for(;e[r+t]==="`";)t++;if(t===n)return{nextIndex:r+n};r+=t}return null}function readWikiLink$1(e,t){let n=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function readMarkdownLink$1(e,t){let n=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!n)return null;let r=n[2]??``;return{text:n[1]??``,hrefRaw:r,href:r.startsWith(`<`)&&r.endsWith(`>`)?r.slice(1,-1):r,titleSuffix:n[3]??``,nextIndex:t+n[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),n=[];for(let e=0;e<t.length;e+=2)n.push({line:t[e]??``,ending:t[e+1]??``});return n}function rewriteWikiLinksInLine(e,t,n){let r=``,i=0,a=0,o=leadingMarkdownPrefixLength$1(e);for(o>0&&(r+=e.slice(0,o),a=o);a<e.length;){if(e[a]===`\\`&&a+1<e.length){r+=e.slice(a,a+2),a+=2;continue}if(e[a]==="`"){let t=readInlineCode$1(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let o=readWikiLink$1(e,a);if(o){o.target===t?(r+=`[[${n}${o.anchor?`#${o.anchor}`:``}${o.alias?`|${o.alias}`:``}]]`,i++):r+=e.slice(a,o.nextIndex),a=o.nextIndex;continue}}r+=e[a],a++}return{markdown:r,rewrites:i}}function buildRelativeMarkdownHref(e,t,n){let r=e.indexOf(`#`),i=r>=0?e.slice(r):``,a=r>=0?e.slice(0,r):e,o=a.indexOf(`?`),s=o>=0?a.slice(o):``,c=o>=0?a.slice(0,o):a,l=posix.dirname(t),u=posix.relative(l===`.`?``:l,n);return u||=posix.basename(n),c.endsWith(`.mdx`)?u+=`.mdx`:c.endsWith(`.md`)&&(u+=`.md`),c.startsWith(`./`)&&!u.startsWith(`./`)&&!u.startsWith(`../`)&&(u=`./${u}`),`${u}${s}${i}`}function rewriteMarkdownLinksInLine(e,t,n,r){let i=``,a=0,o=0,s=leadingMarkdownPrefixLength$1(e);for(s>0&&(i+=e.slice(0,s),o=s);o<e.length;){if(e[o]===`\\`&&o+1<e.length){i+=e.slice(o,o+2),o+=2;continue}if(e[o]==="`"){let t=readInlineCode$1(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o+1]===`[`){let t=readWikiLink$1(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o-1]!==`!`){let s=readMarkdownLink$1(e,o);if(s){if(resolveInternalHref(s.href,t)?.docName===n){let e=buildRelativeMarkdownHref(s.href,t,r),n=s.hrefRaw.startsWith(`<`)&&s.hrefRaw.endsWith(`>`)?`<${e}>`:e;i+=`[${s.text}](${n}${s.titleSuffix})`,a++}else i+=e.slice(o,s.nextIndex);o=s.nextIndex;continue}}i+=e[o],o++}return{markdown:i,rewrites:a}}function rewriteWikiLinksForDocumentRename(e,t,n){let r=null,i=0;return{markdown:splitLines(e).map(({line:e,ending:a})=>{if(r)return isFenceClose$1(e,r)&&(r=null),`${e}${a}`;let o=matchFence$1(e);if(o)return r=o,`${e}${a}`;let s=rewriteWikiLinksInLine(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}function rewriteMarkdownLinksForDocumentRename(e,t,n,r){let i=null,a=0;return{markdown:splitLines(e).map(({line:e,ending:o})=>{if(i)return isFenceClose$1(e,i)&&(i=null),`${e}${o}`;let s=matchFence$1(e);if(s)return i=s,`${e}${o}`;let c=rewriteMarkdownLinksInLine(e,t,n,r);return a+=c.rewrites,`${c.markdown}${o}`}).join(``),rewrites:a}}const STARTER_FOLDERS=[{path:`external-sources`,match:`external-sources/**`,title:`External Sources`,description:"Raw sources SAVED verbatim — not just cited. The actual fetched text of URLs, extracted text of PDFs, and copies of any referenced files live as .md files here, each with frontmatter carrying the original URL, access date, and any publisher / author metadata. Produced by `ingest` — applies whether the user shared the URL OR the agent fetched it itself to ground a knowledge-base claim. The KB is closed-loop: downstream docs cite local paths in this folder, never bare web URLs. Immutable after capture (update only to refresh a stale fetch). No analysis in these files — that belongs in `research/`. Downstream articles cite specific docs here by path so every claim is traceable to preserved evidence rather than a dead link.",tags:[`source`,`immutable`,`layer-ingest`]},{path:`research`,match:`research/**`,title:`Research`,description:"Provisional analysis synthesizing external sources. Produced by the `research` tool. Every factual claim cites a specific doc in `external-sources/` (or an inline URL if ingest was skipped) — no unsourced assertions. Each article has `status: provisional` and a `sources:` frontmatter list of cited paths. Promoted to `articles/` via `consolidate` once the team decides the findings are stable.",tags:[`research`,`provisional`,`layer-research`]},{path:`articles`,match:`articles/**`,title:`Articles`,description:"Canonical knowledge committed after a team decision. Produced by `consolidate`. Carries `status: canonical` plus a `supersedes:` chain tying back to the `research/` docs it replaces, which in turn cite `external-sources/` — the full evidence chain is traceable without leaving the repo. Source-of-truth for the domain; update only when a new decision supersedes it.",tags:[`article`,`canonical`,`layer-consolidate`]}],LOG_MD_TEMPLATE=`---
|
|
78
78
|
title: Work Log
|
|
79
79
|
description: Append-only audit trail. After each turn that creates, edits, or restructures content in the knowledge base, append one dated entry here (one per turn, not per file). Silent edits break the audit trail.
|
|
80
80
|
---
|
|
@@ -113,30 +113,30 @@ What to log:
|
|
|
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;b=b.filter(e=>e.type!==`park`),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
|
|
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;b=b.filter(e=>e.type!==`park`),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),ALLOWED_VIDEO_MIME_TYPES_SET=new Set(ALLOWED_VIDEO_MIME_TYPES),ALLOWED_AUDIO_MIME_TYPES_SET=new Set(ALLOWED_AUDIO_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`?isSupportedDocFile(n)?n:`${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`&®isterWrite(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
|
|
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
|
|
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){
|
|
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()),
|
|
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{
|
|
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(`
|
|
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,forceUnloadDocument:C}=e,w=createConcurrencyGuard(),T=createInstalledAgentsProbe({probe:S??createOsProbe(process.platform)});function E(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 D(e){let t=E(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}let O={cluster:void 0,category:void 0,tags:void 0};function k(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=E(e);if(!t||!existsSync(t))return O;let{frontmatter:n}=stripFrontmatter(readFileSync(t,`utf-8`));return n?parseFrontmatterMetadata(n):O}catch{return O}}function A(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 j(e){return o?.().get(e)??e}function M(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function N(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function P(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 F(){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 I(){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 L=I();function R(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 z(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(C??t.unloadDocument.bind(t))(e))}return r}function B(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`&®isterWrite(e,contentHash(o))}}function V(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 H(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 U(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 W(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 G(e,n){return L(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=H(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:V([...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)?W(r,e,n):rewriteSupportedLinksForDocumentRename(l.get(r)??``,r,e,n);i.rewrites>0&&(U(r,i.markdown),h.push({docName:r,rewrites:i.rewrites})),p.updateDocumentFromMarkdown(r,i.markdown)}let r=rewriteSupportedLinksForDocumentRename((await z([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)),B(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 K=128;function q(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 J(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 Y(e){return{principalId:x?.()?.id,agentType:J(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function X(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 Z(e){return{value:e.value}}function Q(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}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=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=j(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}=q(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}=X(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,Y({clientName:u,clientVersion:d,label:f}),b),incrementAgentWriteCalls(),Q(p)}finally{g?.touchMode(s,`idle`)}P(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 te(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=j(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}=q(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}=X(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,Y({clientName:m,clientVersion:v,label:y}),S),incrementAgentWriteCalls(),Q(b)}finally{g?.touchMode(d,`idle`)}P(u,`agent-write-md`),h?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),_?.();let T=A(u),E=M(u),D=N();D===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":J(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 ne(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=j(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 re(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)continue;let i=getDocExtension(e);o.push({docName:e,docExt:i,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let a of t.aliases){if(n&&!a.startsWith(`${n}/`)&&a!==n)continue;let s=relative(r,t.canonicalPath);o.push({docName:a,docExt:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:s})}}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 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(`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:D(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),json(t,500,{ok:!1,error:`Failed to read backlinks`})}}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(`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 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`).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:D(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 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`),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=k(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:D(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 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(`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:D(e)}))})}catch(e){console.error(`[orphans]`,e),json(t,500,{ok:!1,error:`Failed to read orphan 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.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:D(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),json(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function ue(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=>j(e)))]:void 0;json(t,200,{ok:!0,deadLinks:p.getDeadLinks(F(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:D(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 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=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=j(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}=q(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}=X(S);recordContributor(f,p,m,v,void 0,Y({clientName:y,clientVersion:b,label:x}),e),incrementAgentWriteCalls(),Q(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}P(f,`agent-patch`),h?.setFocus(p,{agentName:m,currentDoc:f,writeKind:`edit`,ts:Date.now()}),_?.();let D=M(f),O=N();O===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":J(y)});let{response:k}=X(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 fe(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}=q(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=j(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,Y({clientName:c,clientVersion:l,label:u}))}finally{g?.touchMode(a,`idle`)}y&&P(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 pe(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 me(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=j(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 he(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=j(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(C??t.unloadDocument.bind(t))(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 ge(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 _e(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}=q(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 ve(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 ye(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 be(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 xe(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}=q(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=X(n);E=t||!r.response?r.response:Z(r.response),recordContributor(v,o,s,l,formatRollbackSubject(v,y),Y({clientName:u,clientVersion:d,label:p}),r.stored),incrementAgentWriteCalls(),Q(n,!t)}P(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 Se(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getMetrics())}async function Ce(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getParseHealth())}async function we(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 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=x?.()??null;if(!n){json(t,404,{error:`Principal not available`});return}json(t,200,n)}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`){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 De(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 Oe=1440*60*1e3;async function ke(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>Oe){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 Ae(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>Oe)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
|
+
`)[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 je(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}=q(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,Y({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 Me(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=E(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 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}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=q(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(_===v){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}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 G(d,f),b;if(h){let e=g.kind===`value`,t=e?g:normalizeSummary(`Renamed ${d} → ${f}`),n=X(t);b=e||!n.response?n.response:Z(n.response),recordContributor(f,a,o,s,formatRenameSubject(d,f),Y({clientName:c,clientVersion:l,label:u}),n.stored),incrementAgentWriteCalls(),Q(t,!e),P(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:R(e)})}}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}q(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 z(h.map(({fromDocName:e})=>e)),_=async()=>{await renameTrackedPathInGit(b,l,u)||(mkdirSync(dirname(u),{recursive:!0}),renameSync(l,u)),B(h,g)};if(o===`file`)await withManagedRenameRecovery(r,createManagedRenameRecoveryJournal({sourceDocName:s,destinationDocName:c,snapshots:V(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 Fe(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}q(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 z(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 Ie(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,a=getDocExtension(t);try{e=extractPageTitle(readFileSync(resolve(r,`${t}${a}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,docExt:a,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 Le(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 Re(e,t,n,i){let a;try{a=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:o,buffer:s,parentDocName:c}=a;if(!c){json(t,400,{ok:!1,error:`parentDocName is required`});return}if(c.includes(`\0`)||c.includes(`..`)||c.startsWith(`/`)){json(t,400,{ok:!1,error:`path-escape`});return}let l=resolve(r),u=resolve(l,dirname(c));if(!isWithinContentDir(u,l)){json(t,400,{ok:!1,error:`path-escape`});return}try{let e=realpathSync(u),n;try{n=realpathSync(l)}catch{n=l}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 d=await fileTypeFromBuffer(s),f=d?.mime,p=d?.ext;if(!f&&i.allowSvgFallback){let e=s.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(f=`image/svg+xml`,p=`svg`)}if(!f||!p||!n.has(f)){json(t,400,{ok:!1,error:`Unsupported file type${f?`: ${f}`:``}`});return}let m;m=!o||o===`upload`||GENERIC_PASTE_NAMES.test(o)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${p}`:sanitizeFilename(o),mkdirSync(u,{recursive:!0});try{let e=relative(r,resolve(u,writeUploadAtomic(u,m,s))),n=`/${e.split(sep).join(`/`)}`;console.log(`[upload] ok ${e} ${s.length}`),json(t,200,{ok:!0,src:n})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${m} ${s.length} ${n}`),json(t,500,{ok:!1,error:`Failed to save file`})}}async function ze(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}q(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),await Re(e,t,ALLOWED_MIME_TYPES,{allowSvgFallback:!0})}async function Be(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}q(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),await Re(e,t,ALLOWED_VIDEO_MIME_TYPES_SET,{allowSvgFallback:!1})}async function Ve(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}q(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),await Re(e,t,ALLOWED_AUDIO_MIME_TYPES_SET,{allowSvgFallback:!1})}let He=`/api/local-op/clone`,Ue=`/api/local-op/open`,We=600*1e3,Ge=45e3;async function Ke(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(!w.tryAcquire(He)){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`)},We);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){w.release(He);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 qe(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(),w.release(He)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),w.release(He)})}async function qe(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 Je(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(!w.tryAcquire(Ue)){json(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await qe(n);`port`in e?json(t,200,{port:e.port}):json(t,504,{ok:!1,error:e.error})}finally{w.release(Ue)}}let Ye=`/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`;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`;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(!w.tryAcquire(Ye)){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`)},We),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
|
+
`);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()),w.release(Ye)}),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())),w.release(Ye)})}async function tt(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(!w.tryAcquire(Xe)){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
|
+
`).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{w.release(Xe)}}async function nt(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(!w.tryAcquire(Ze)){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`)},We);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()),w.release(Ze)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),w.release(Ze)})}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=`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(!w.tryAcquire(Qe)){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{w.release(Qe)}}async function it(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(!w.tryAcquire($e)){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
|
+
`).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{w.release($e)}}async function at(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 ot=`/api/local-op/auth/set-identity`;async function st(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(!w.tryAcquire(ot)){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{w.release(ot)}}async function ct(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 lt(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 ut(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 dt(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 ft(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 pt(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 mt(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 ht(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 gt(e,t){if(checkLocalOpSecurity(e,t,json))return handleInstalledAgents(e,t,T.probeAll)}async function _t(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 vt={"/api/document":ne,"/api/documents":re,"/api/backlinks":ie,"/api/backlink-counts":ae,"/api/forward-links":oe,"/api/link-graph":se,"/api/dead-links":ue,"/api/orphans":ce,"/api/hubs":le,"/api/pages":Ie,"/api/suggest-links":Le,"/api/page-headings":Me,"/api/create-page":je,"/api/rename":Ne,"/api/rename-path":Pe,"/api/delete-path":Fe,"/api/upload-image":ze,"/api/upload-video":Be,"/api/upload-audio":Ve,"/api/agent-write":ee,"/api/agent-write-md":te,"/api/agent-patch":de,"/api/agent-undo":fe,"/api/agent-activity":pe,"/api/agent-burst-diff":me,"/api/save-version":_e,"/api/history":ve,"/api/diff":be,"/api/rollback":xe,"/api/metrics/reconciliation":Se,"/api/metrics/parse-health":Ce,"/api/metrics/agent-presence":Ee,"/api/server-info":we,"/api/principal":Te,"/api/rescue":ke,"/api/workspace":De,"/api/sync/status":ct,"/api/sync/trigger":lt,"/api/sync/set-enabled":ut,"/api/sync/conflicts":dt,"/api/sync/conflict-content":pt,"/api/sync/resolve-conflict":ft,"/api/sync/abort-merge":_t,"/api/local-op/clone":Ke,"/api/local-op/open":Je,"/api/local-op/auth/login":et,"/api/local-op/auth/status":tt,"/api/local-op/auth/repos":nt,"/api/local-op/auth/signout":rt,"/api/local-op/auth/pat":it,"/api/local-op/auth/identity":at,"/api/local-op/auth/set-identity":st,"/api/installed-agents":gt,"/api/seed/plan":mt,"/api/seed/apply":ht};return s&&(vt[`/api/test-reset`]=he,vt[`/api/test-rescan-backlinks`]=ge),{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=vt[n];if(i)await i(e,t);else if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await Ae(e,t,r)}else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await ye(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(`
|
|
128
128
|
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function loadNestedGitignores(e,t,n){let r;try{r=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let i of r){if(!i.isDirectory()||BUILTIN_SKIP_DIRS.has(i.name))continue;let r=join(e,i.name),a=relative(t,r);if(a.startsWith(`..`)||n.ignores(a)||n.ignores(`${a}/`))continue;let o=join(r,`.gitignore`);if(existsSync(o))try{let e=parseGitignorePatterns(readFileSync(o,`utf-8`)).map(e=>e.startsWith(`!`)?`!${a}/${e.slice(1)}`:`${a}/${e}`);n.add(e)}catch(e){console.warn(`[content-filter] Failed to read nested .gitignore at ${o}:`,e)}loadNestedGitignores(r,t,n)}}const FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function applyExternalChange(e,t,n){if(isSystemDoc(t))return;let r=e.documents.get(t);if(!r)return;let{frontmatter:i,body:a}=stripFrontmatter(n),o=mdManager.parseWithFallback(a),s=schema.nodeFromJSON(o),c=r.getXmlFragment(`default`);r.transact(()=>{updateYFragment(r,c,s,{mapping:new Map,isOMark:new Map}),r.getMap(`metadata`).set(`frontmatter`,i);let e=r.getText(`source`),t=e.toString();t!==n&&applyFastDiff(e,t,n)},FILE_WATCHER_ORIGIN),recordContributor(t,FILE_SYSTEM_WRITER.id,FILE_SYSTEM_WRITER.name,FILE_SYSTEM_WRITER.id,formatReconcileSubject(t)),setReconciledBase(t,n)}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function resolveGitDir(e){let t=resolve(e,`.git`);try{let n=statSync(t);if(n.isDirectory())return t;if(n.isFile()){let n=readFileSync(t,`utf-8`).trim().match(/^gitdir:\s*(.+)$/);if(n)return resolve(e,n[1])}}catch{}return null}function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let n=resolve(e,t.slice(5));try{return readFileSync(n,`utf-8`).trim()}catch{try{let n=readFileSync(resolve(e,`packed-refs`),`utf-8`),r=t.slice(5),i=n.split(`
|
|
129
129
|
`).find(e=>e.endsWith(` ${r}`));if(i)return i.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}async function startHeadWatcher(e,t,n){let r=resolveGitDir(e);if(!r)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let i=r,a=!1,o=null,s=null,c=null,l=null;async function u(e){if(f&&await f,!a)return;o&&=(clearTimeout(o),null),s&&=(clearTimeout(s),null);let t=readHeadSha(i),r=c!==t,u=readBranchFromHead(i),d;d=u?.startsWith(`detached-`)?`detached-head`:l===u?`within-branch`:`cross-branch`;let p=l;try{await n({headMoved:r,oldHead:c,newHead:t,timeout:e,batchKind:d,oldBranch:p,newBranch:u})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{a=!1,c=t,l=u}}function d(){o&&clearTimeout(o),o=setTimeout(()=>{o=null,u(!1)},QUIET_WINDOW_MS)}let f=null;async function p(e){if(!a){a=!0,c=readHeadSha(i);let n=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();f=n,await n,f=null,s=setTimeout(()=>{s=null,u(!0)},BATCH_TIMEOUT_MS)}d()}let m,h;try{h=await import(`@parcel/watcher`)}catch(e){throw Error(`@parcel/watcher unavailable for HEAD watching: ${e instanceof Error?e.message:e}`)}try{let e=await h.subscribe(i,(e,t)=>{if(e){console.error(`[head-watcher]`,e);return}for(let e of t){let t=e.path.split(`/`).pop()??``;if(WATCHED_FILES.has(t)){p(t);break}}});m=()=>e.unsubscribe()}catch(e){throw Error(`@parcel/watcher subscribe failed for HEAD watching: ${e instanceof Error?e.message:e}`)}return c=readHeadSha(i),l=readBranchFromHead(i),console.log(`[head-watcher] Watching ${i} for HEAD changes`),{unsubscribe:async()=>{a&&await u(!1),o&&clearTimeout(o),s&&clearTimeout(s),await m()},getLastKnownBranch:()=>l}}function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(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)}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,signalChannel:n,debounceMs:r=100}=e,i=new Map;function a(e){let t=i.get(e);t&&(clearTimeout(t),i.delete(e))}function o(e,o){a(e),i.set(e,setTimeout(()=>{i.delete(e);try{t.updateDocumentFromMarkdown(e,serializeLiveDocument(o)),n?.(`backlinks`),n?.(`graph`)}catch(t){console.error(`[live-derived-index] Failed to update backlinks for ${e}:`,t)}},r))}return{async onChange({documentName:e,document:t,transactionOrigin:n}){isSystemDoc(e)||isLocalOriginLike(n)&&n.context?.origin===`file-watcher`||o(e,t)},async beforeUnloadDocument({documentName:e}){a(e)},async onDestroy(){for(let e of i.values())clearTimeout(e);i.clear()}}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function loadPrincipal(e){let t=resolve(e,OK_DIR),n=resolve(t,PRINCIPAL_FILE),{name:r,email:i}=await readGitConfig(e);if(existsSync(n)){let e;try{e=JSON.parse(readFileSync(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?sanitizeGitIdentity(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?sanitizeGitIdentity(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return writeFileSync(n,JSON.stringify(s,null,2),`utf-8`),s}mkdirSync(t,{recursive:!0});let a=`principal-${randomUUID()}`,o=a.slice(10,18),s={id:a,display_name:r?sanitizeGitIdentity(r):`Local User`,display_email:i?sanitizeGitIdentity(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(n,JSON.stringify(s,null,2),`utf-8`),s}const OBSERVER_SYNC_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},isPairedWriteOrigin=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0;function shouldRethrowBridgeMergeLoss(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}function setupServerObservers(e){let{doc:t,xmlFragment:n,ytext:r,mdManager:i,schema:a}=e,o=(t,n)=>{let r=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:r}),docName:e.docName??null,timestamp:new Date().toISOString()})),incrementBridgeMergeContentLoss();let i=e.shadow?.();if(!i||!e.docName)return;let a=e.getBranch?.()??`main`,o=e.contentRoot??``;queueMicrotask(()=>{saveInMemoryCheckpoint(i,o,{kind:`bridge-merge-loss`,docName:e.docName,contents:n,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:a,metadata:{lostSubstrings:t.info.lostSubstrings}}).then(t=>{incrementBridgeMergeCheckpointCreated(),console.warn(JSON.stringify({event:`bridge-merge-checkpoint-created`,docName:e.docName,sha:t,kind:`bridge-merge-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{let t=e instanceof Error?e:Error(String(e));console.warn(`[Server Observer A] Silent checkpoint write failed:`,{name:t.name,message:t.message,stack:t.stack?.split(`
|
|
130
130
|
`).slice(0,4).join(`
|
|
131
|
-
`)})})})},s=``,c=!1,l=!1;try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),r=i.serialize(e);s=prependFrontmatter(getFrontmatter(t),r)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),s=``}let u=()=>{try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),c=i.serialize(e),l=prependFrontmatter(getFrontmatter(t),c);if(s===l)return;let u=r.toString();if(normalizeBridge(u)===normalizeBridge(l)){s=l;return}let d=s;t.transact(()=>{if(u===s)applyIncrementalDiff(r,u,l);else try{applyFastDiff(r,u,mergeThreeWay(s,l,u))}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(o(e,d),shouldRethrowBridgeMergeLoss()))throw e;applyFastDiff(r,u,e.info.result)}},OBSERVER_SYNC_ORIGIN),incrementServerObserverFire(`a`),s=r.toString()}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{s=r.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},d=(e,r)=>{if(r.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(r.origin)){try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),r=i.serialize(e);s=prependFrontmatter(getFrontmatter(t),r)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),c=!0}return}c=!0}};if(n.length>0&&r.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),o=i.serialize(e),c=prependFrontmatter(getFrontmatter(t),o);t.transact(()=>{r.insert(0,c)},OBSERVER_SYNC_ORIGIN),s=c}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),s=``}let f=()=>{try{let a=r.toString(),{frontmatter:o,body:c}=stripFrontmatter(a);if(normalizeBridge(s)===normalizeBridge(a)){let e=t.getMap(`metadata`);(e.get(`frontmatter`)??``)!==o&&t.transact(()=>{e.set(`frontmatter`,o)},OBSERVER_SYNC_ORIGIN);return}let l;try{l=i.parse(c)}catch(e){if(e instanceof SyntaxError||e instanceof VFileMessage||e instanceof RangeError&&e.message.includes(`Invalid content for node`)){console.debug(`[Server Observer B] Parse skipped (partial/invalid markdown):`,e),s=prependFrontmatter(o,c);return}throw e}let u=e.schema.nodeFromJSON(l);t.transact(()=>{updateYFragment(t,n,u,{mapping:new Map,isOMark:new Map}),t.getMap(`metadata`).set(`frontmatter`,o)},OBSERVER_SYNC_ORIGIN),incrementServerObserverFire(`b`);try{let e=i.serialize(l);if(e===c)s=prependFrontmatter(o,c);else{let n=prependFrontmatter(o,e),i=r.toString();i!==n&&t.transact(()=>{applyFastDiff(r,i,n)},OBSERVER_SYNC_ORIGIN),s=n}}catch(e){console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),s=prependFrontmatter(o,c)}}catch(e){incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),r=i.serialize(e);s=prependFrontmatter(getFrontmatter(t),r)}catch(e){console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},p=(e,r)=>{if(r.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(r.origin)){try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),r=i.serialize(e);s=prependFrontmatter(getFrontmatter(t),r)}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),l=!0}return}l=!0}},m=(t,n)=>{if(!c&&!l){e.onDispatch?.(`none`);return}if(n.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){c=!1,l=!1,e.onDispatch?.(`none`);return}c&&(c=!1,e.onDispatch?.(`a`),u()),l&&(l=!1,e.onDispatch?.(`b`),f())};return n.observeDeep(d),r.observe(p),t.on(`afterAllTransactions`,m),()=>{t.off(`afterAllTransactions`,m),n.unobserveDeep(d),r.unobserve(p)}}function createServerObserverExtension(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(isSystemDoc(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=setupServerObservers({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot});return t.set(r,n),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${r}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let n=t.createdBy;return!(typeof n.runtimeVersion!=`string`||typeof n.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let n;try{n=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let r;try{r=JSON.parse(n)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(r))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function writeStateManifest(e,t){let n=manifestPath(e);mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??RUNTIME_VERSION,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=manifestPath(e.lockDir),s=readStateManifest(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!isCompatibleSchema(c.stateSchemaVersion,n))throw new StateManifestError({kind:`incompatible`,path:o,message:`State manifest at ${o} declares stateSchemaVersion=${c.stateSchemaVersion} but this binary supports ${n}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${c.createdBy.runtimeVersion}, protocol ${c.createdBy.protocolVersion}.)`});try{let t={...c,lastWriteBy:{runtimeVersion:r,protocolVersion:i,at:a}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return writeStateManifest(e.lockDir,s),t.info({path:o,stateSchemaVersion:n},`[state-manifest] fresh project — wrote manifest`),s}let c={stateSchemaVersion:0,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i,adoptedAt:a}};return writeStateManifest(e.lockDir,c),t.warn({path:o,runtimeVersion:r},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),c}const log$1=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t,n=`main`){this.storePath=join(e,`.open-knowledge`,`conflicts.json`),this.projectDir=t,this.branch=n,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$1.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$1.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:i}=await import(`./git-handle-BhGnmvTB-Di8EsrYa.mjs`).then(e=>e.n),a=i(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(!n)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),r=resolve(t,e);if(r!==t&&!r.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),log$1.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=(await a.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
|
|
131
|
+
`)})})})},s=``,c=!1,l=!1;try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),r=i.serialize(e);s=prependFrontmatter(getFrontmatter(t),r)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),s=``}let u=()=>{try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),c=i.serialize(e),l=prependFrontmatter(getFrontmatter(t),c);if(s===l)return;let u=r.toString();if(normalizeBridge(u)===normalizeBridge(l)){s=l;return}let d=s;t.transact(()=>{if(u===s)applyIncrementalDiff(r,u,l);else try{applyFastDiff(r,u,mergeThreeWay(s,l,u))}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(o(e,d),shouldRethrowBridgeMergeLoss()))throw e;applyFastDiff(r,u,e.info.result)}},OBSERVER_SYNC_ORIGIN),incrementServerObserverFire(`a`),s=r.toString()}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{s=r.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},d=(e,r)=>{if(r.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(r.origin)){try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),r=i.serialize(e);s=prependFrontmatter(getFrontmatter(t),r)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),c=!0}return}c=!0}};if(n.length>0&&r.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),o=i.serialize(e),c=prependFrontmatter(getFrontmatter(t),o);t.transact(()=>{r.insert(0,c)},OBSERVER_SYNC_ORIGIN),s=c}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),s=``}let f=()=>{try{let a=r.toString(),{frontmatter:o,body:c}=stripFrontmatter(a);if(normalizeBridge(s)===normalizeBridge(a)){let e=t.getMap(`metadata`);(e.get(`frontmatter`)??``)!==o&&t.transact(()=>{e.set(`frontmatter`,o)},OBSERVER_SYNC_ORIGIN);return}let l=i.parseWithFallback(c),u=e.schema.nodeFromJSON(l);t.transact(()=>{updateYFragment(t,n,u,{mapping:new Map,isOMark:new Map}),t.getMap(`metadata`).set(`frontmatter`,o)},OBSERVER_SYNC_ORIGIN),incrementServerObserverFire(`b`);try{let e=i.serialize(l);if(e===c)s=prependFrontmatter(o,c);else{let n=prependFrontmatter(o,e),i=r.toString();i!==n&&t.transact(()=>{applyFastDiff(r,i,n)},OBSERVER_SYNC_ORIGIN),s=n}}catch(e){console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),s=prependFrontmatter(o,c)}}catch(e){incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),r=i.serialize(e);s=prependFrontmatter(getFrontmatter(t),r)}catch(e){console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},p=(e,r)=>{if(r.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(r.origin)){try{let e=yXmlFragmentToProseMirrorRootNode(n,a).toJSON(),r=i.serialize(e);s=prependFrontmatter(getFrontmatter(t),r)}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),l=!0}return}l=!0}},m=(t,n)=>{if(!c&&!l){e.onDispatch?.(`none`);return}if(n.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){c=!1,l=!1,e.onDispatch?.(`none`);return}c&&(c=!1,e.onDispatch?.(`a`),u()),l&&(l=!1,e.onDispatch?.(`b`),f())};return n.observeDeep(d),r.observe(p),t.on(`afterAllTransactions`,m),()=>{t.off(`afterAllTransactions`,m),n.unobserveDeep(d),r.unobserve(p)}}function createServerObserverExtension(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(isSystemDoc(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=setupServerObservers({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot});return t.set(r,n),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${r}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let n=t.createdBy;return!(typeof n.runtimeVersion!=`string`||typeof n.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let n;try{n=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let r;try{r=JSON.parse(n)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(r))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function writeStateManifest(e,t){let n=manifestPath(e);mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??RUNTIME_VERSION,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=manifestPath(e.lockDir),s=readStateManifest(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!isCompatibleSchema(c.stateSchemaVersion,n))throw new StateManifestError({kind:`incompatible`,path:o,message:`State manifest at ${o} declares stateSchemaVersion=${c.stateSchemaVersion} but this binary supports ${n}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${c.createdBy.runtimeVersion}, protocol ${c.createdBy.protocolVersion}.)`});try{let t={...c,lastWriteBy:{runtimeVersion:r,protocolVersion:i,at:a}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return writeStateManifest(e.lockDir,s),t.info({path:o,stateSchemaVersion:n},`[state-manifest] fresh project — wrote manifest`),s}let c={stateSchemaVersion:0,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i,adoptedAt:a}};return writeStateManifest(e.lockDir,c),t.warn({path:o,runtimeVersion:r},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),c}const log$1=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t,n=`main`){this.storePath=join(e,`.open-knowledge`,`conflicts.json`),this.projectDir=t,this.branch=n,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$1.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$1.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:i}=await import(`./git-handle-BhGnmvTB-Di8EsrYa.mjs`).then(e=>e.n),a=i(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(!n)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),r=resolve(t,e);if(r!==t&&!r.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),log$1.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=(await a.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
|
|
132
132
|
`).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){log$1.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),log$1.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`)}}};function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_PATTERNS=[/\b(401|403)\b/,/authentication failed/i,/authorization failed/i,/invalid credentials/i,/credential helper/i,/bad credentials/i,/token.*expired/i,/expired.*token/i,/permission denied.*\(publickey\)/i,/host key verification failed/i,/fatal:.*repository.*not found/i],SCOPE_MISMATCH_PATTERNS=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],NON_FAST_FORWARD_PATTERNS=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],PROTECTED_BRANCH_PATTERNS=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],MERGE_CONFLICT_PATTERNS=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],LFS_PATTERNS=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],LARGE_FILE_PATTERNS=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PRE_RECEIVE_PATTERNS=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],SECRET_DETECTED_PATTERNS=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],INDEX_LOCK_PATTERNS=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],DIRTY_TREE_PATTERNS=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],DISK_FULL_PATTERNS=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],NETWORK_PATTERNS=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],HTTP_5XX_PATTERNS=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],HTTP_429_PATTERNS=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function classifyGitError(e){let t=e instanceof Error?e:Error(String(e)),n=extractStderr(t),r=`${t.message}\n${n}`.toLowerCase();return matchesAny(r,INDEX_LOCK_PATTERNS)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n}:matchesAny(r,DIRTY_TREE_PATTERNS)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n}:matchesAny(r,DISK_FULL_PATTERNS)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n}:matchesAny(r,SCOPE_MISMATCH_PATTERNS)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:n}:matchesAny(r,AUTH_PATTERNS)?/\b401\b/.test(r)||/token.*expired/i.test(r)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:n}:/\b403\b/.test(r)?matchesAny(r,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:n}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:n}:matchesAny(r,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:matchesAny(r,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:matchesAny(r,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:matchesAny(r,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:matchesAny(r,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:matchesAny(r,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:matchesAny(r,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:matchesAny(r,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:matchesAny(r,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:matchesAny(r,NETWORK_PATTERNS)?/timed? out/i.test(r)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:n}:/refused/i.test(r)||/econnrefused/i.test(r)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:n}:/resolve.*host/i.test(r)||/enotfound/i.test(r)||/getaddrinfo/i.test(r)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:n}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:n}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:n}}function computeRemainingMs(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}const log=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i;function jitteredMs(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function isUnbornHead(e){try{let t=join(e,`.git`,`HEAD`);if(!existsSync(t))return!1;let n=readFileSync(t,`utf-8`).trim(),r=/^ref:\s+(refs\/.+)$/.exec(n);if(!r)return!1;let i=r[1];if(existsSync(join(e,`.git`,i)))return!1;let a=join(e,`.git`,`packed-refs`);if(existsSync(a)){let e=readFileSync(a,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${i}$`,`m`).test(e))return!1}return!0}catch{return!1}}function backoffMs(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var SyncEngine=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;setBatchInProgress;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;error;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.setBatchInProgress=e.setBatchInProgress,this.statePath=resolve(this.contentDir,`.open-knowledge`,`sync-state.json`),this.conflictStore=new ConflictStore(this.contentDir,this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){log.warn({err:e},`[sync] remote detection failed`)}if(this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=existsSync(join(this.projectDir,`.git`,`MERGE_HEAD`));if(this.conflictCount>0&&!t)log.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&t)try{let e=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
|
|
133
133
|
`).map(e=>e.trim()).filter(Boolean):[]),n=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&log.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(t&&this.conflictCount===0){log.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){this.transitionTo(`conflict`),log.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let n=computeRemainingMs(this.lastFetchUtc,this.pullIntervalSeconds),r=computeRemainingMs(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(n>0?n:void 0),this.schedulePush(r>0?r:void 0),log.info({branch:this.currentBranch,pullDelayMs:n,pushDelayMs:r},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=3e4,t=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-t>3e4){log.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await setTimeout$1(50)}this.pausedReason=void 0,this.error=void 0,this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}try{this.hasRemote=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){log.warn({err:e},`[sync] remote detection failed during enable`)}if(this.pausedReason=void 0,this.error=void 0,this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow()}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`)&&(this.pausedReason=void 0,this.error=void 0),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):log.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,error:this.error,pausedReason:this.pausedReason}}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}getConflicts(){return this.conflictStore.list()}async resolveConflict(e,t,n){await this.conflictStore.resolveConflict(e,t,n),this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`&&(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()),this.scheduleSaveState()}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{log.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??jitteredMs(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{log.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=backoffMs(e);return t>0?t:jitteredMs(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`)){if(this.state===`conflict`){this.schedulePull();return}if(isUnbornHead(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,log.warn({},`[sync] detached HEAD — pausing sync`);return}t=n,this.currentBranch=t}catch(e){this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))));return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.error=void 0}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));this.handleError(t);return}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{if(await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e))return;await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}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);return}finally{this.setBatchInProgress?.(!1)}}else this.transitionTo(`idle`);this.scheduleSaveState()}async runPushCycle(){if(!this.pushInFlight&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(isUnbornHead(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),n=join(tmpdir(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await withParentLock(async()=>{let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:n});if(isUnbornHead(this.projectDir)){log.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){log.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))));return}await e.git.raw([`read-tree`,i]);let a=new Set;try{let t=(await e.git.raw([`ls-tree`,`-r`,`--name-only`,i])).trim();for(let e of t?t.split(`
|
|
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,skipStateManifestCheck:g=!1}=e,_=getLogger(`server`);initTelemetry();let v=randomUUID(),y=resolve(t,`.open-knowledge`);if(acquireServerLock(y,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,...e.parentPid!==void 0&&{parentPid:e.parentPid},capabilities:[`http`,`ws`]}),!g)try{assertCompatibleStateManifest({lockDir:y,shadowRepoDir:resolveShadowDir(n)})}catch(e){throw releaseServerLock(y),e}let b,x,S,C,w,T,E=null,D=null,O=null,k=null;function A(e){E?.signal(e)}try{b=createContentFilter({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),x=new BacklinkIndex({projectDir:n,contentDir:t,contentFilter:b}),S={current:u},C=createPersistenceExtension({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:S,contentRoot:d,backlinkIndex:x,getCurrentBranch:()=>V?.getLastKnownBranch()??null,getPrincipal:()=>k,onAgentCommit:()=>E?.signal(`session-activity`),onDiskFlush:(e,t)=>E?.emitDiskAck(e,t)}),w=new Hocuspocus({quiet:r,debounce:i,maxDebounce:a,extensions:[C.extension]}),E=new CC1Broadcaster(w),D=new AgentFocusBroadcaster(w),O=new AgentPresenceBroadcaster(w),T=new AgentSessionManager(w);let m=createLiveDerivedIndexExtension({backlinkIndex:x,signalChannel:A});w.configuration.extensions.push(m),w.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!==v)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${v}`);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`&&(k&&n.principalId===k.id?o.principalId=k.id:k?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:k.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),w.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:w,sessionManager:T,contentDir:t,serverInstanceId:v,getFileIndex:()=>B?B.getFileIndex():new Map,getAliasMap:()=>B?B.getAliasMap():new Map,enableTestRoutes:l,shadowRef:S,flushGitCommit:()=>C.flushPendingGitCommit(),getCurrentBranch:()=>V?.getLastKnownBranch()??null,getDiskAckSVs:()=>E?.getLatestDiskAckSVsAsBase64()??{},contentRoot:d,backlinkIndex:x,signalChannel:A,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>H,localOpCliArgs:h,projectDir:n,getPrincipal:()=>k});w.configuration.extensions.push(g),w.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:S,contentRoot:d,getCurrentBranch:()=>V?.getLastKnownBranch()??null}))}catch(e){throw releaseServerLock(y),e}let j=null;function M(e,t){let n=resolve(e,`rescue`),r=resolve(n,`${t}${getDocExtension(t)}`);return r.startsWith(`${n}/`)?r:null}function N(e){let t=w.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 P=(e,t)=>applyExternalChange(w,e,t);function F(e){return e.kind===`rename`?e.newDocName:e.docName}async function I(e){try{switch(e.kind){case`create`:_.info({docName:e.docName},`[reconcile] create: ${e.docName}`),x.updateDocumentFromMarkdown(e.docName,e.content),x.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),A(`files`),A(`backlinks`),A(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=w.documents.get(t);if(!r){x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),A(`backlinks`),A(`graph`);return}let i=getReconciledBase(t)??``,a=N(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(_.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`:x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),A(`backlinks`),A(`graph`);break;case`clean`:try{P(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),A(`backlinks`),A(`graph`)}catch(e){_.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`merged`:try{P(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),A(`backlinks`),A(`graph`)}catch(e){_.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`conflicts`:try{P(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),incrementConflict(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),A(`backlinks`),A(`graph`)}catch(e){_.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=w.documents.get(t);if(!n){x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),A(`files`),A(`backlinks`),A(`graph`);return}let r=getReconciledBase(t)??``,i=N(t)??``,a=i!==r;if(a&&S.current){let e=S.current,n=V?.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(),_.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{_.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),_.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),w.closeConnections(t),await w.unloadDocument(n),A(`files`),A(`backlinks`),A(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=w.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(n,r),x.renameDocument(t,n,r),x.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)}_.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),A(`files`),A(`backlinks`),A(`graph`);break}case`conflict`:{let{docName:t}=e,n=w.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),_.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){_.error({err:t,kind:e.kind,docName:F(e)},`[reconcile] failed to handle ${e.kind} for ${F(e)}`)}}let L=[];async function R(e){if(isBatchInProgress()){L.push(e);return}await I(e)}async function z(){let e=L.splice(0,L.length);for(let t of e)await I(t)}let B=null,V=null,H=null,U=null;async function W(e){if(w.documents.size===0)return;let t=!1,n=new Promise(e=>{w.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(w.documents.keys());w.closeConnections(),w.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(w.documents.keys()),i=[],o=[];if(S.current){for(let e of n)if(!isSystemDoc(e))try{let t=N(e);if(t===null){_.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=M(S.current.gitDir,e);if(!n){_.warn({docName:e,gitDir:S.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),_.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),_.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else _.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 G(){return U||(U=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([J.then(()=>`completed`,e=>(_.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&_.warn({},`[server] init did not complete within 5s during shutdown`);let a=w.documents.size;try{try{try{V&&=(await V.unsubscribe(),null),B&&=(await B.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{E?.destroy(),O?.destroy(),j&&=(await j.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await T.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await W(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await C.flushPendingGitCommit(),await C.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)}),_.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{H&&=(await H.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(S.current){try{let e=(await esm_default({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(S.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(S.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?_.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):_.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(y)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),_.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)})}}})(),U)}let K=[];async function q(){try{k=await loadPrincipal(t),_.info({principalId:k.id},`[server] principal loaded`)}catch(e){_.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!S.current)try{S.current=await initShadowRepo(n),_.info({gitDir:S.current.gitDir},`[server] history repo initialized at ${S.current.gitDir}`)}catch(e){_.error({err:e},`[server] history repo init failed`),K.push(`shadow-repo`)}if(S.current)try{await shadowGit(S.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`)){_.warn({},`[server] history repo appears corrupted — reinitializing`);try{S.current=await initShadowRepo(n)}catch(e){_.error({err:e},`[server] history repo reinit failed`),S.current=void 0,K.includes(`shadow-repo`)||K.push(`shadow-repo`)}}else _.error({err:e},`[server] history repo check failed (transient?)`)}if(S.current)try{let e=resolve(S.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{}_.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await commitUpstreamImport(S.current,d??``,t,r,e),incrementUpstreamImport()}catch(e){_.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else _.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{writeFileSync(e,r,`utf-8`)}catch(e){_.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){_.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);e.recovered&&e.journal&&_.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){_.error({err:e},`[server] managed rename recovery failed`),K.push(`managed-rename-recovery`)}try{j=await w.openDirectConnection(SYSTEM_DOC_NAME),E?.emitServerInfo(v,getActiveBranch())}catch(e){_.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),K.push(`cc1-push`)}let e=resolveGitDir(n),r=e?readBranchFromHead(e)??`main`:`main`;switchReconciledBaseScope(r),x.switchBranch(r);try{B=await startWatcher(t,R,b),x.rebuildFromDisk(getActiveBranch()),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${getActiveBranch()}:`,e)})}catch(e){_.error({err:e},`[server] disk bridge watcher failed to start`),K.push(`file-watcher`)}try{V=await startHeadWatcher(n,async({trigger:e})=>{if(_.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),w.flushPendingStores(),await C.flushPendingGitCommit(),setBatchInProgress(!0),S.current){let e=getActiveBranch(),t=resolveGitDir(n),r=t?readBranchFromHead(t)??e:e,i=[];for(let[e,t]of w.documents){if(isSystemDoc(e))continue;let n=null;if(t.transact(()=>{n=N(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(S.current,e,SERVICE_WRITER.id,i,r);t&&(incrementPark(),_.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){_.error({err:e},`[shadow] park failed`)}}},async e=>{let n=L.length,r=e.newBranch??`main`;if(setBatchInProgress(!1),_.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 z();else{incrementBranchSwitch(),L.splice(0,L.length),switchReconciledBaseScope(r),x.switchBranch(r);for(let[e,n]of w.documents)if(!isSystemDoc(e))try{let i=safeContentPath(e,t);if(!existsSync(i)){let t=getReconciledBase(e)??``,i=N(e)??``;if(i!==t&&S.current){let t=S.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(),_.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{_.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),_.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=readFileSync(i,`utf-8`);P(e,a),setReconciledBase(e,a),_.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){_.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(_.info({branch:r,docCount:w.documents.size},`[branch-switch] loaded branch ${r} (${w.documents.size} docs)`),x.rebuildFromDisk(r),x.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),S.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of w.documents)if(!isSystemDoc(t))try{let n=await readParkedState(S.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`:P(t,a.newContent),setReconciledBase(t,a.newContent),e++;break;case`conflicts`:P(t,a.newContent),setReconciledBase(t,a.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){_.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&_.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&S.current)try{let t=shadowGit(S.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);_.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){_.error({err:e},`[branch-switch] detached cleanup failed`)}E?.emitBranchSwitched(r)}if(e.headMoved&&e.newHead&&S.current&&n>0){let t=d??`.`;try{let n=await commitUpstreamImport(S.current,t,e.oldHead,e.newHead,r);incrementUpstreamImport(),_.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){_.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){_.error({err:e},`[server] HEAD watcher failed to start`),
|
|
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,skipStateManifestCheck:g=!1}=e,_=getLogger(`server`);initTelemetry();let v=randomUUID(),y=resolve(t,`.open-knowledge`);if(acquireServerLock(y,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,...e.parentPid!==void 0&&{parentPid:e.parentPid},capabilities:[`http`,`ws`]}),!g)try{assertCompatibleStateManifest({lockDir:y,shadowRepoDir:resolveShadowDir(n)})}catch(e){throw releaseServerLock(y),e}let b,x,S,C,w,T,E=null,D=null,O=null,k=null,A=new Set,j=!1,M;function N(e){E?.signal(e)}try{b=createContentFilter({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),x=new BacklinkIndex({projectDir:n,contentDir:t,contentFilter:b}),S={current:u},C=createPersistenceExtension({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:S,contentRoot:d,backlinkIndex:x,getCurrentBranch:()=>W?.getLastKnownBranch()??null,getPrincipal:()=>k,onAgentCommit:()=>E?.signal(`session-activity`),onDiskFlush:(e,t)=>E?.emitDiskAck(e,t)}),w=new Hocuspocus({quiet:r,debounce:i,maxDebounce:a,extensions:[C.extension]});let m=w.shouldUnloadDocument.bind(w);w.shouldUnloadDocument=e=>(j||A.has(e))&&m(e),M=async e=>{A.add(e);try{await w.unloadDocument(e)}finally{A.delete(e)}},E=new CC1Broadcaster(w),D=new AgentFocusBroadcaster(w),O=new AgentPresenceBroadcaster(w),T=new AgentSessionManager(w);let g=createLiveDerivedIndexExtension({backlinkIndex:x,signalChannel:N});w.configuration.extensions.push(g),w.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!==v)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${v}`);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`&&(k&&n.principalId===k.id?o.principalId=k.id:k?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:k.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),w.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 _=createApiExtension({hocuspocus:w,sessionManager:T,contentDir:t,serverInstanceId:v,getFileIndex:()=>U?U.getFileIndex():new Map,getAliasMap:()=>U?U.getAliasMap():new Map,enableTestRoutes:l,shadowRef:S,flushGitCommit:()=>C.flushPendingGitCommit(),getCurrentBranch:()=>W?.getLastKnownBranch()??null,getDiskAckSVs:()=>E?.getLatestDiskAckSVsAsBase64()??{},contentRoot:d,backlinkIndex:x,signalChannel:N,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>G,localOpCliArgs:h,projectDir:n,getPrincipal:()=>k,forceUnloadDocument:M});w.configuration.extensions.push(_),w.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:S,contentRoot:d,getCurrentBranch:()=>W?.getLastKnownBranch()??null}))}catch(e){throw releaseServerLock(y),e}let P=null;function F(e,t){let n=resolve(e,`rescue`),r=resolve(n,`${t}${getDocExtension(t)}`);return r.startsWith(`${n}/`)?r:null}function I(e){let t=w.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 L=(e,t)=>applyExternalChange(w,e,t);function R(e){return e.kind===`rename`?e.newDocName:e.docName}async function z(e){try{switch(e.kind){case`create`:_.info({docName:e.docName},`[reconcile] create: ${e.docName}`),x.updateDocumentFromMarkdown(e.docName,e.content),x.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),N(`files`),N(`backlinks`),N(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=w.documents.get(t);if(!r){x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),N(`backlinks`),N(`graph`);return}let i=getReconciledBase(t)??``,a=I(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(_.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`:x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),N(`backlinks`),N(`graph`);break;case`clean`:try{L(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),N(`backlinks`),N(`graph`)}catch(e){_.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`merged`:try{L(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),N(`backlinks`),N(`graph`)}catch(e){_.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`conflicts`:try{L(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),incrementConflict(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),N(`backlinks`),N(`graph`)}catch(e){_.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=w.documents.get(t);if(!n){x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),N(`files`),N(`backlinks`),N(`graph`);return}let r=getReconciledBase(t)??``,i=I(t)??``,a=i!==r;if(a&&S.current){let e=S.current,n=W?.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(),_.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{_.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),_.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),w.closeConnections(t),await M(n),N(`files`),N(`backlinks`),N(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=w.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(n,r),x.renameDocument(t,n,r),x.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)}_.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),N(`files`),N(`backlinks`),N(`graph`);break}case`conflict`:{let{docName:t}=e,n=w.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),_.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){_.error({err:t,kind:e.kind,docName:R(e)},`[reconcile] failed to handle ${e.kind} for ${R(e)}`)}}let B=[];async function V(e){if(isBatchInProgress()){B.push(e);return}await z(e)}async function H(){let e=B.splice(0,B.length);for(let t of e)await z(t)}let U=null,W=null,G=null,K=null;async function q(e){if(w.documents.size===0)return;let t=!1,n=new Promise(e=>{w.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(w.documents.keys());w.closeConnections(),w.flushPendingStores();for(let e of w.documents.values())e.getConnectionsCount()===0&&w.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(w.documents.keys()),i=[],o=[];if(S.current){for(let e of n)if(!isSystemDoc(e))try{let t=I(e);if(t===null){_.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=F(S.current.gitDir,e);if(!n){_.warn({docName:e,gitDir:S.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),_.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),_.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else _.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 J(){return K||(K=(async()=>{let e=Date.now(),t=[];j=!0;let r,i=await Promise.race([Z.then(()=>`completed`,e=>(_.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&_.warn({},`[server] init did not complete within 5s during shutdown`);let a=w.documents.size;try{try{try{W&&=(await W.unsubscribe(),null),U&&=(await U.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{E?.destroy(),O?.destroy(),P&&=(await P.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await T.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await q(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await C.flushPendingGitCommit(),await C.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)}),_.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{G&&=(await G.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(S.current){try{let e=(await esm_default({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(S.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(S.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?_.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):_.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(y)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),_.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)})}}})(),K)}let Y=[];async function X(){try{k=await loadPrincipal(t),_.info({principalId:k.id},`[server] principal loaded`)}catch(e){_.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!S.current)try{S.current=await initShadowRepo(n),_.info({gitDir:S.current.gitDir},`[server] history repo initialized at ${S.current.gitDir}`)}catch(e){_.error({err:e},`[server] history repo init failed`),Y.push(`shadow-repo`)}if(S.current)try{await shadowGit(S.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`)){_.warn({},`[server] history repo appears corrupted — reinitializing`);try{S.current=await initShadowRepo(n)}catch(e){_.error({err:e},`[server] history repo reinit failed`),S.current=void 0,Y.includes(`shadow-repo`)||Y.push(`shadow-repo`)}}else _.error({err:e},`[server] history repo check failed (transient?)`)}if(S.current)try{let e=resolve(S.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{}_.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await commitUpstreamImport(S.current,d??``,t,r,e),incrementUpstreamImport()}catch(e){_.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else _.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{writeFileSync(e,r,`utf-8`)}catch(e){_.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){_.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);e.recovered&&e.journal&&_.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){_.error({err:e},`[server] managed rename recovery failed`),Y.push(`managed-rename-recovery`)}try{P=await w.openDirectConnection(SYSTEM_DOC_NAME),E?.emitServerInfo(v,getActiveBranch())}catch(e){_.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Y.push(`cc1-push`)}let e=resolveGitDir(n),r=e?readBranchFromHead(e)??`main`:`main`;switchReconciledBaseScope(r),x.switchBranch(r);try{U=await startWatcher(t,V,b),x.rebuildFromDisk(getActiveBranch()),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${getActiveBranch()}:`,e)})}catch(e){_.error({err:e},`[server] disk bridge watcher failed to start`),Y.push(`file-watcher`)}try{W=await startHeadWatcher(n,async({trigger:e})=>{if(_.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),w.flushPendingStores(),await C.flushPendingGitCommit(),setBatchInProgress(!0),S.current){let e=getActiveBranch(),t=resolveGitDir(n),r=t?readBranchFromHead(t)??e:e,i=[];for(let[e,t]of w.documents){if(isSystemDoc(e))continue;let n=null;if(t.transact(()=>{n=I(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(S.current,e,SERVICE_WRITER.id,i,r);t&&(incrementPark(),_.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){_.error({err:e},`[shadow] park failed`)}}},async e=>{let n=B.length,r=e.newBranch??`main`;if(setBatchInProgress(!1),_.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 H();else{incrementBranchSwitch(),B.splice(0,B.length),switchReconciledBaseScope(r),x.switchBranch(r);for(let[e,n]of w.documents)if(!isSystemDoc(e))try{let i=safeContentPath(e,t);if(!existsSync(i)){let t=getReconciledBase(e)??``,i=I(e)??``;if(i!==t&&S.current){let t=S.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(),_.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{_.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),_.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=readFileSync(i,`utf-8`);L(e,a),setReconciledBase(e,a),_.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){_.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(_.info({branch:r,docCount:w.documents.size},`[branch-switch] loaded branch ${r} (${w.documents.size} docs)`),x.rebuildFromDisk(r),x.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),S.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of w.documents)if(!isSystemDoc(t))try{let n=await readParkedState(S.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`:L(t,a.newContent),setReconciledBase(t,a.newContent),e++;break;case`conflicts`:L(t,a.newContent),setReconciledBase(t,a.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){_.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&_.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&S.current)try{let t=shadowGit(S.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);_.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){_.error({err:e},`[branch-switch] detached cleanup failed`)}E?.emitBranchSwitched(r)}if(e.headMoved&&e.newHead&&S.current&&n>0){let t=d??`.`;try{let n=await commitUpstreamImport(S.current,t,e.oldHead,e.newHead,r);incrementUpstreamImport(),_.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){_.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){_.error({err:e},`[server] HEAD watcher failed to start`),Y.push(`head-watcher`)}let i=h?.[0]??`open-knowledge`,a=[`-c`,`credential.helper=!${h&&h.length>1?h.join(` `):i} auth git-credential`];try{G=new SyncEngine({projectDir:n,contentDir:t,contentFilter:b,contentRoot:d,credentialArgs:a,cc1Broadcaster:E,setBatchInProgress,onStateChange:e=>{_.info({state:e},`[sync] state → ${e}`)}}),await G.start()}catch(e){_.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),G=null}}let Z=X();return{hocuspocus:w,sessionManager:T,cc1Broadcaster:E,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,contentFilter:b,serverInstanceId:v,destroy:J,ready:Z,degraded:Y,lockDir:y,get syncEngine(){return G}}}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-n3Y5JWNv-DXpg9_eU.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,skipStateManifestCheck:e.skipStateManifestCheck}),{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{extractWikiLinksFromMarkdown as $,getShadowRepoPath as $t,applySeed as A,rewriteMarkdownLinksForDocumentRename as At,containsConflictMarkers as B,splitMarkdownBlocks as Bt,SeedPrerequisiteError as C,readUiLock as Ct,acquireUiLock as D,releaseUiLock as Dt,UiLockCollisionError as E,registerWrite as Et,buildWipTree as F,saveInMemoryCheckpoint as Ft,createLiveDerivedIndexExtension as G,updateUiLockPort as Gt,contributorCount as H,starterFolderRule as Ht,classifyEvents as I,saveVersion as It,createServerObserverExtension as J,withSpan as Jt,createPersistenceExtension as K,validateAgentId as Kt,commitUpstreamImport as L,setActiveSpanAttributes as Lt,attachIdleShutdown as M,safeContentPath as Mt,bootServer as N,safeSubdir as Nt,applyAgentMarkdownWrite as O,removeLastKnownHash as Ot,buildSkillZip as P,safetyCheckpoint as Pt,evictStaleTrackerEntries as Q,require_picomatch as Qt,commitWip as R,shadowGit as Rt,STATE_MANIFEST_FILENAME as S,readStateManifest as St,StateManifestError as T,recordContributor as Tt,createApiExtension as U,toBroadcasterKey as Ut,contentHash as V,startWatcher as Vt,createContentFilter as W,updateLastKnownHash as Wt,detectProjectShape as X,writeStateManifest as Xt,detectClaudeDesktopPresence as Y,withSpanSync as Yt,ensureProjectGit as Z,writeTracker as Zt,ProjectGitInitError as _,parseHocuspocusAuthToken as _t,BacklinkIndex as a,incrementCollabSocketFilteredError as at,SERVICE_WRITER as b,planSeed as bt,FILE_SYSTEM_WRITER as c,initTelemetry as ct,HocuspocusAuthRejection as d,isSelfWrite as dt,getWipRefPattern as en,getLogger as et,HocuspocusAuthTokenSchema as f,isSystemDoc as ft,PinoLogger as g,loggerFactory as gt,OBSERVER_SYNC_ORIGIN as h,loadPrincipal as ht,AgentSessionManager as i,handleCollabSocketError as it,assertCompatibleStateManifest as j,rewriteWikiLinksForDocumentRename as jt,applyExternalChange as k,resolveBundledSkillDir as kt,FILE_WATCHER_ORIGIN as l,installUserSkill as lt,MANAGED_RENAME_ORIGIN as m,listRescueCheckpoints as mt,AgentFocusBroadcaster as n,readContributors as nn,getMetrics as nt,CC1Broadcaster as o,incrementServerObserverFire as ot,LOG_MD_TEMPLATE as p,lastKnownHash as pt,createServer$1 as q,validateSkillZip as qt,AgentPresenceBroadcaster as r,getTracer as rt,CONFLICT_MARKER_RE as s,initShadowRepo as st,AGENT_ID_RE as t,parseWriterId as tn,getMeter as tt,GIT_UPSTREAM_WRITER as u,isPairedWriteOrigin as ut,ROLLBACK_ORIGIN as v,parseKeepaliveConnectionId as vt,SeedRootDirError as w,reconcile as wt,STARTER_FOLDERS as x,readBranchFromHead as xt,SEED_CONFIG_FILENAME as y,pathToDocName as yt,commitWipFromTree as z,shutdownTelemetry as zt};
|
|
142
|
-
//# sourceMappingURL=dist-
|
|
142
|
+
//# sourceMappingURL=dist-DD_wEI4a.mjs.map
|