omo-ai 5.1.72 → 5.1.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/bin/darwin/omo-keychain +0 -0
  2. package/bin/lib/child-process.js +15 -0
  3. package/bin/lib/reflection-lock.generated.js +1 -1
  4. package/bin/lib/service-auth.generated.js +48 -44
  5. package/bin/lib/thread-output.js +23 -7
  6. package/bin/lib/thread.js +1 -1
  7. package/package.json +1 -1
  8. package/plugin/CHANGELOG.md +95 -0
  9. package/plugin/extensions/assets.generated.json +3 -3
  10. package/plugin/extensions/gateway-store-worker.mjs +1 -1
  11. package/plugin/extensions/memory-run-supervisor.mjs +3 -3
  12. package/plugin/extensions/omo-claim-receipt.js +1 -1
  13. package/plugin/extensions/omo-computer-run-worker.mjs +1 -1
  14. package/plugin/extensions/omo-computer-use.js +2 -2
  15. package/plugin/extensions/omo-desktop-toolkit.js +1 -1
  16. package/plugin/extensions/omo-device-account.js +7 -12
  17. package/plugin/extensions/omo-device-service.js +6 -11
  18. package/plugin/extensions/omo-feedback.js +2 -2
  19. package/plugin/extensions/omo-init-deep-advisor.js +1 -1
  20. package/plugin/extensions/omo-member.js +1 -1
  21. package/plugin/extensions/omo-memory-commands.js +2 -2
  22. package/plugin/extensions/omo-memory-doctor.js +2 -2
  23. package/plugin/extensions/omo-memory-memfs.js +1 -1
  24. package/plugin/extensions/omo-memory-palace.js +1 -1
  25. package/plugin/extensions/omo-memory-sync.js +2 -2
  26. package/plugin/extensions/omo-onboarding-scan.js +2 -2
  27. package/plugin/extensions/omo-recall-store.js +1 -1
  28. package/plugin/extensions/omo-session-history.js +1 -1
  29. package/plugin/extensions/omo-side-panel.js +1 -1
  30. package/plugin/extensions/omo-task.js +2 -2
  31. package/plugin/extensions/omo-telemetry-otlp.js +1 -1
  32. package/plugin/extensions/omo-telemetry-posthog.js +1 -1
  33. package/plugin/extensions/omo-telemetry-recovery.js +1 -1
  34. package/plugin/extensions/omo-thread-client.js +4 -12
  35. package/plugin/extensions/omo-wake.js +6 -11
  36. package/plugin/extensions/omo.js +3 -3
  37. package/plugin/package.json +1 -1
  38. package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
  39. package/plugin/runtime/ast-grep-mcp/manifest.json +1 -1
  40. package/plugin/runtime/bunshin-ts/sdk.js +4 -4
  41. package/plugin/runtime/category-coverage/assets.generated.json +3 -3
  42. package/plugin/runtime/rollback-migrate.js +1 -1
  43. package/plugin/runtime/thread-sdk/sdk.js +4 -12
  44. package/plugin/skills/browser/runtime/omowright/manifest.json +1 -1
  45. package/plugin/skills/frontend/references/design/print-paged-media.md +1 -1
  46. package/plugin/skills/mass-ulw/SKILL.md +20 -22
  47. package/plugin/skills/mass-ulw/references/planning.md +61 -86
  48. package/plugin/skills/ulw-execute/SKILL.md +2 -2
  49. package/plugin/skills/ulw-loop/references/full-workflow.md +2 -2
  50. package/plugin/skills/ulw-plan/references/full-workflow.md +1 -1
  51. package/plugin/skills/ulw-plan/scripts/plan-templates.mjs +1 -1
  52. package/plugin/skills/ulw-research/references/research-collection.md +1 -1
Binary file
@@ -14,6 +14,10 @@ const HANDLED_SIGNALS = [
14
14
  ["SIGINT", false],
15
15
  ]
16
16
 
17
+ // Signals the launcher only relays: the engine uses them as wake-ups (senpi's supervisor wakes a draining host
18
+ // child with SIGUSR1), so a waiting launcher must neither die of one nor start a shutdown grace window.
19
+ const RELAYED_SIGNALS = ["SIGUSR1"]
20
+
17
21
  // The engine's own shutdown drains in ~1.5-2.5s. Ten seconds is the ceiling before the launcher
18
22
  // stops waiting on a child that is not going to leave and reports the death it was asked for.
19
23
  const DEFAULT_GRACE_MS = 10_000
@@ -123,6 +127,17 @@ export function runChild(command, args, options = {}) {
123
127
  listeners.push([signal, listener])
124
128
  process.on(signal, listener)
125
129
  }
130
+ for (const signal of RELAYED_SIGNALS) {
131
+ const listener = () => {
132
+ try {
133
+ child.kill(signal)
134
+ } catch {
135
+ // The child is already gone; its exit event carries the real answer.
136
+ }
137
+ }
138
+ listeners.push([signal, listener])
139
+ process.on(signal, listener)
140
+ }
126
141
  }
127
142
 
128
143
  child.on("error", (error) => settle(() => reject(error)))
@@ -1,7 +1,7 @@
1
1
  // Generated by bun script/build-reflection-lock.ts; do not edit.
2
2
  var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};function fsErrorCode(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}async function retryOnEintr(operation){for(let attempt=0;;attempt+=1)try{return await operation()}catch(error){if(fsErrorCode(error)!=="EINTR"||attempt>=128)throw error}}function retryOnEintrSync(operation){for(let attempt=0;;attempt+=1)try{return operation()}catch(error){if(fsErrorCode(error)!=="EINTR"||attempt>=128)throw error}}var EINTR_RETRY_CAP=128;async function renameWithContentionRetry(from,to,deps){let delays=deps.platform==="win32"?deps.delaysMs??CONTENTION_DELAYS_MS:[],sleep=deps.sleep??sleepFor;for(let attempt=0;;attempt+=1)try{await retryOnEintr(()=>deps.admit===void 0?deps.rename(from,to):deps.admit(()=>deps.rename(from,to)));return}catch(error){let delay=delays[attempt],code=fsErrorCode(error);if(delay===void 0||code===void 0||!CONTENTION_CODES.has(code))throw error;await sleep(delay)}}var CONTENTION_CODES,CONTENTION_DELAYS_MS,sleepFor=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms));var init_rename_contention=__esm(()=>{CONTENTION_CODES=new Set(["EPERM","EBUSY","EACCES"]),CONTENTION_DELAYS_MS=[10,25,50,100,200,400]});import{Buffer as Buffer2}from"node:buffer";import{constants}from"node:fs";import*as fsp from"node:fs/promises";function openSyncWithExclusivePolicy(rawOpen,path,flags,mode){if(isExclusiveFlag(flags))return rawOpen(path,flags,mode);return retryOnEintrSync(()=>rawOpen(path,flags,mode))}function isExclusiveFlag(flag){if(typeof flag==="number")return(flag&constants.O_EXCL)!==0;return typeof flag==="string"&&flag.toLowerCase().includes("x")}async function writeHandleAll(handle,data,encoding,signal){let buffer=typeof data==="string"?Buffer2.from(data,encoding??"utf8"):data,offset=0;while(offset<buffer.length){signal?.throwIfAborted();let{bytesWritten}=await retryOnEintr(()=>handle.write(buffer,offset));if(bytesWritten<=0)throw Error(`fs write made no progress at offset ${offset}`);offset+=bytesWritten}}async function writePathAll(path,data,options,defaultFlag){let parsed=typeof options==="string"?{encoding:options}:options??{};parsed.signal?.throwIfAborted();let flag=parsed.flag??defaultFlag,openOnce=()=>fsp.open(path,flag,parsed.mode),handle=await(isExclusiveFlag(flag)?openOnce():retryOnEintr(openOnce));try{if(await writeHandleAll(handle,data,parsed.encoding??"utf8",parsed.signal),parsed.flush===!0)await retryOnEintr(()=>handle.sync())}finally{await handle.close().catch((error)=>{if(fsErrorCode(error)!=="EINTR")throw error})}}var init_write_all=()=>{};import{Buffer as Buffer3}from"node:buffer";import*as fsSync from"node:fs";import*as fsp2 from"node:fs/promises";function isFunction(value){return typeof value==="function"}function withAsyncRetry(operation){return(...args)=>retryOnEintr(async()=>operation(...args))}function withSyncRetry(operation){return(...args)=>retryOnEintrSync(()=>operation(...args))}function resilientNamespace(namespace,kind){let wrapFunction=kind==="async"?withAsyncRetry:withSyncRetry,cache=new Map;return new Proxy(namespace,{get(target,property){if(cache.has(property))return cache.get(property);let value=Reflect.get(target,property);if(!isFunction(value))return value;let wrapped=wrapFunction(value),native=Reflect.get(value,"native");if(isFunction(native))Object.assign(wrapped,{native:wrapFunction(native)});return cache.set(property,wrapped),wrapped}})}function wrapFileHandle(handle){return new Proxy(handle,{get(target,property){let value=Reflect.get(target,property);if(!isFunction(value))return value;let invoke=(args)=>Reflect.apply(value,target,[...args]);if(property==="close"||property===Symbol.asyncDispose)return(...args)=>{let result=invoke(args);if(!(result instanceof Promise))return result;return result.catch((error)=>{if(fsErrorCode(error)==="EINTR")return;throw error})};if(typeof property!=="string"||!IDEMPOTENT_HANDLE_METHODS.has(property))return(...args)=>invoke(args);return(...args)=>{let result=invoke(args);if(!(result instanceof Promise))return result;return result.catch((error)=>{if(fsErrorCode(error)!=="EINTR")throw error;return retryOnEintr(async()=>invoke(args))})}}})}function rename2(from,to,admit){return renameWithContentionRetry(from,to,{rename:(source,target)=>fsp2.rename(source,target),platform:process.platform,...admit===void 0?{}:{admit}})}function isHandleTarget(value){return typeof value==="object"&&!(value instanceof URL)&&!Buffer3.isBuffer(value)&&"fd"in value}function closeSync2(fd){try{fsSync.closeSync(fd)}catch(error){if(fsErrorCode(error)!=="EINTR")throw error}}function existsSync(path){try{return retryOnEintrSync(()=>fsSync.statSync(path)),!0}catch{return!1}}var IDEMPOTENT_HANDLE_METHODS,promises,sync,access,chmod,copyFile,cp,link,lstat,mkdir,mkdtemp,readFile,readdir,readlink,realpath,rm,rmdir,stat,statfs,unlink,accessSync,chmodSync,fsyncSync,linkSync,lstatSync,mkdirSync,readFileSync,readdirSync,realpathSync,statSync2,unlinkSync,writeFileSync,writeSync,constants2,watch,open3=async(...args)=>{let openOnce=()=>fsp2.open(...args),handle=await(isExclusiveFlag(args[1]??"r")?openOnce():retryOnEintr(openOnce));return wrapFileHandle(handle)},writeFile2=async(file,data,options)=>{if(typeof data!=="string"&&!(data instanceof Uint8Array))return fsp2.writeFile(file,data,options);if(isHandleTarget(file)){let parsed=typeof options==="string"?{encoding:options}:options??{};if(parsed.signal?.throwIfAborted(),await writeHandleAll(file,data,parsed.encoding??void 0,parsed.signal),parsed.flush===!0)await retryOnEintr(()=>file.sync());return}return writePathAll(file,data,options??void 0,"w")},appendFile2=async(path,data,options)=>{if(typeof data!=="string"&&!(data instanceof Uint8Array))return fsp2.appendFile(path,data,options);if(isHandleTarget(path)){let parsed=typeof options==="string"?{encoding:options}:options??{};if(await writeHandleAll(path,data,parsed.encoding??void 0),parsed.flush===!0)await retryOnEintr(()=>path.sync());return}return writePathAll(path,data,options??void 0,"a")},openSync2=(path,flags,mode)=>openSyncWithExclusivePolicy(fsSync.openSync,path,flags,mode??void 0);var init_resilient=__esm(()=>{init_rename_contention();init_write_all();init_write_all();IDEMPOTENT_HANDLE_METHODS=new Set(["stat","sync","datasync","chmod","chown","utimes","truncate"]);promises=resilientNamespace(fsp2,"async");sync=resilientNamespace(fsSync,"sync"),{access,chmod,copyFile,cp,link,lstat,mkdir,mkdtemp,readFile,readdir,readlink,realpath,rm,rmdir,stat,statfs,unlink}=promises,{accessSync,chmodSync,fsyncSync,linkSync,lstatSync,mkdirSync,readFileSync,readdirSync,realpathSync,statSync:statSync2,unlinkSync,writeFileSync,writeSync}=sync,{constants:constants2,watch}=fsSync});function normalizeForSecretScan(text,formatCharacters){let shadow="",map=[],seams=new Set,dropped=!1;for(let index=0;index<text.length;){let code=text.codePointAt(index)??0,width=code>65535?2:1,char=text.slice(index,index+width),control=code<32&&code!==10&&code!==9;if(code===160||formatCharacters==="separate"&&(control||FORMAT_CHARACTER.test(char)))shadow+=" ",map.push(index);else if(!control&&!FORMAT_CHARACTER.test(char)){if(dropped)seams.add(shadow.length);dropped=!1,shadow+=char;for(let unit=0;unit<width;unit+=1)map.push(index+unit)}else dropped=!0;index+=width}return{shadow,map,seams}}function originalSpan({map},start,end){let originalStart=map[start],originalLast=map[end-1];if(originalStart===void 0||originalLast===void 0)return;return{start:originalStart,end:originalLast+1}}function patternMatches(scan,patternClass,source,flags){let found=[],pattern=new RegExp(source,`${flags}g`),match;while((match=pattern.exec(scan.shadow))!==null){let span=originalSpan(scan,match.index,match.index+match[0].length);if(span!==void 0)found.push({class:patternClass,...span})}return found}function containmentIndex(matches){let sorted=[...matches].sort((a,b)=>a.start-b.start),maxEnd=[];for(let[index,match]of sorted.entries())maxEnd.push(Math.max(match.end,maxEnd[index-1]??-1));return(span)=>{let low=0,high=sorted.length;while(low<high){let middle=low+high>>1;if(sorted[middle].start<=span.start)low=middle+1;else high=middle}return low>0&&maxEnd[low-1]>=span.end}}function seamMatches(scan){if(scan.seams.size===0)return[];let seams=[...scan.seams].sort((a,b)=>a-b),found=[];for(let[patternClass,source,flags]of SECRET_PATTERN_SOURCES){if(!source.startsWith(LEADING_BOUNDARY))continue;let trailing=source.endsWith(LEADING_BOUNDARY),body=source.slice(LEADING_BOUNDARY.length,trailing?-LEADING_BOUNDARY.length:void 0),sticky=new RegExp(body,`${flags}y`),whole=new RegExp(`^(?:${body})$`,flags),starts=trailing?mergeSorted(seams,boundaryStarts(scan,`${LEADING_BOUNDARY}${body}`,flags)):seams,unboundedTail=body.endsWith("]+"),acceptedEnd=-1;for(let start of starts){if(unboundedTail&&start<acceptedEnd)continue;sticky.lastIndex=start;let match=sticky.exec(scan.shadow);if(match===null)continue;let end=start+match[0].length;if(trailing){while(end>start&&!boundaryOrSeam(scan,end))end-=1;if(end===start||!whole.test(scan.shadow.slice(start,end)))continue}if(!scan.seams.has(start)&&!scan.seams.has(end))continue;let span=originalSpan(scan,start,end);if(span===void 0)continue;found.push({class:patternClass,...span}),acceptedEnd=end}}return found}function boundaryStarts(scan,source,flags){let starts=[],pattern=new RegExp(source,`${flags}g`),match;while((match=pattern.exec(scan.shadow))!==null)starts.push(match.index);return starts}function mergeSorted(a,b){let merged=[],i=0,j=0;while(i<a.length||j<b.length){let next=j>=b.length||i<a.length&&a[i]<=b[j]?a[i++]:b[j++];if(merged[merged.length-1]!==next)merged.push(next)}return merged}function scanSecretLikeMaterial(value){if(!value)return[];let joined=normalizeForSecretScan(value,"drop"),separated=normalizeForSecretScan(value,"separate"),matches=[],pemOffset=0;while(!0){let block=findPemBlock(joined.shadow,pemOffset);if(block===void 0)break;let span=originalSpan(joined,block.start,block.end);if(span!==void 0)matches.push({class:"pem_block",...span});pemOffset=block.end}for(let[patternClass,source,flags]of SECRET_PATTERN_SOURCES)matches.push(...patternMatches(joined,patternClass,source,flags));return keepUncovered(matches,SECRET_PATTERN_SOURCES.flatMap(([patternClass,source,flags])=>patternMatches(separated,patternClass,source,flags))),keepUncovered(matches,seamMatches(joined)),keepUncovered(matches,patternMatches(joined,"split_credential_assignment",SPLIT_CREDENTIAL_ASSIGNMENT_SOURCE,"i")),matches.sort((a,b)=>a.start-b.start||a.end-b.end)}function redactSecretLikeMaterial(value){if(!value)return"";let matches=scanSecretLikeMaterial(value);if(matches.length===0)return value;let merged=[];for(let match of matches){let last=merged[merged.length-1];if(last!==void 0&&match.start<=last.end)last.end=Math.max(last.end,match.end);else merged.push({start:match.start,end:match.end})}let redacted="",cursor=0;for(let span of merged)redacted+=`${value.slice(cursor,span.start)}***`,cursor=span.end;return`${redacted}${value.slice(cursor)}`}function findPemBlock(value,from=0){let begin=value.indexOf("-----BEGIN ",from);if(begin<0)return;let labelEnd=value.indexOf("-----",begin+11);if(labelEnd<0||labelEnd-(begin+11)>64)return;let label=value.slice(begin+11,labelEnd);if(label.length===0||/[^A-Za-z0-9 ]/.test(label))return;let endMarker=value.indexOf("-----END ",labelEnd+5);while(endMarker>=0){let endLabelStart=endMarker+9,endLabelEnd=value.indexOf("-----",endLabelStart);if(endLabelEnd>=0&&value.slice(endLabelStart,endLabelEnd)===label)return{start:begin,end:endLabelEnd+5};endMarker=value.indexOf("-----END ",endLabelEnd>=0?endLabelEnd+5:endLabelStart)}return}var REFERENCE_TOKEN,REFERENCE_VALUE,SECRET_PATTERN_SOURCES,SPLIT_CREDENTIAL_ASSIGNMENT_SOURCE,FORMAT_CHARACTER,keepUncovered=(matches,candidates)=>{let covered=containmentIndex(matches);for(let candidate of candidates)if(!covered(candidate))matches.push(candidate)},WORD,LEADING_BOUNDARY="\\b",boundaryOrSeam=(scan,end)=>scan.seams.has(end)||WORD.test(scan.shadow[end-1]??"")!==WORD.test(scan.shadow[end]??"");var init_redact=__esm(()=>{REFERENCE_TOKEN=["process\\.env\\.[A-Za-z_][A-Za-z0-9_]*","os\\.environ(?:\\.get\\(|\\[)?","env\\.[A-Za-z_][A-Za-z0-9_]*","\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}","\\$[A-Za-z_][A-Za-z0-9_]*","\\{\\{[^}\\n]*\\}\\}","\\[(?:redacted|filtered)\\]","(?:redacted|filtered)","(?:bearer|changeme|placeholder|example|none|null|undefined|true|false)"].join("|"),REFERENCE_VALUE=`(?!(?:${REFERENCE_TOKEN})(?![^\\s"'<>,}\\])]))`,SECRET_PATTERN_SOURCES=[["aws_access_key","\\bAKIA[0-9A-Z]{16}\\b",""],["credential_assignment",`\\b(?:bearer|token|api[_-]?key|secret|password|passwd|pwd)\\s*[=:]\\s*${REFERENCE_VALUE}[^\\s"'<>,}\\])]{1,256}`,"i"],["authorization_header",`\\bAuthorization\\s*:\\s*Bearer\\s+${REFERENCE_VALUE}[^\\s"'<>,}\\])]{1,256}`,"i"],["openai_key","\\bsk-(?:proj-)?[-_A-Za-z0-9]+\\b",""],["vendor_token","\\b(?:ghp|github_pat|glpat|xox[baprs])[-_][-_A-Za-z0-9]+\\b",""]],SPLIT_CREDENTIAL_ASSIGNMENT_SOURCE=`(?:a\\s*u\\s*t\\s*h\\s*o\\s*r\\s*i\\s*z\\s*a\\s*t\\s*i\\s*o\\s*n|p\\s*a\\s*s\\s*s\\s*w\\s*(?:o\\s*r\\s*)?d|s\\s*e\\s*c\\s*r\\s*e\\s*t|t\\s*o\\s*k\\s*e\\s*n|a\\s*p\\s*i\\s*[_-]?\\s*k\\s*e\\s*y)\\s*[:=]\\s*${REFERENCE_VALUE}[^\\s"'<>,}\\])]{6,256}`,FORMAT_CHARACTER=/\p{Cf}/u;WORD=/[A-Za-z0-9_]/});var STABLE_LOG_OUTPUT;var init_stable_log_output=__esm(()=>{STABLE_LOG_OUTPUT=["-c","log.showSignature=false","-c","log.follow=false"]});var init_frontmatter_scalar=()=>{};var init_frontmatter_validation=__esm(()=>{init_frontmatter_scalar()});var init_paths=__esm(()=>{init_resilient()});var init_completion_repair=__esm(()=>{init_stable_log_output();init_redact()});var CONFUSABLES,CONFUSABLE;var init_lookalike_text=__esm(()=>{CONFUSABLES={"а":"a","е":"e","о":"o","р":"p","с":"c","у":"y","х":"x","і":"i","ј":"j","ѕ":"s","ԁ":"d","ԛ":"q","ԝ":"w","ӏ":"l","А":"a","Е":"e","О":"o","Р":"p","С":"c","Х":"x","І":"i","Ј":"j","Ѕ":"s","К":"k","М":"m","Н":"h","Т":"t","В":"b","α":"a","ε":"e","ο":"o","ρ":"p","τ":"t","υ":"u","ν":"v","κ":"k","ι":"i","Ο":"o","Α":"a","Β":"b","Ε":"e","Η":"h","Ι":"i","Κ":"k","Μ":"m","Ν":"n","Ρ":"p","Τ":"t","Υ":"y","Χ":"x","ı":"i","İ":"i"},CONFUSABLE=new RegExp(`[${Object.keys(CONFUSABLES).join("")}]`,"gu")});var init_frontmatter_entries=__esm(()=>{init_frontmatter_scalar();init_lookalike_text()});var init_frontmatter=__esm(()=>{init_frontmatter_entries();init_frontmatter_scalar();init_frontmatter_validation()});init_resilient();import{hostname as readHostname}from"node:os";import{join}from"node:path";init_resilient();import{execFile}from"node:child_process";var procPidInfoLookup=null;async function openProcPidInfo(){if(process.platform!=="darwin")return null;try{let{dlopen,FFIType}=await import("bun:ffi"),library=dlopen("/usr/lib/libSystem.B.dylib",{proc_pidinfo:{args:[FFIType.i32,FFIType.i32,FFIType.u64,FFIType.ptr,FFIType.i32],returns:FFIType.i32}});return(pid,flavor,arg,buffer,size)=>Number(library.symbols.proc_pidinfo(pid,flavor,arg,buffer,size))}catch{return null}}function loadProcPidInfo(){return procPidInfoLookup??=openProcPidInfo(),procPidInfoLookup}async function readDarwinProcessStartSeconds(pid){if(process.platform!=="darwin")return null;if(!Number.isSafeInteger(pid)||pid<=0)return null;let procPidInfo=await loadProcPidInfo();if(procPidInfo===null)return null;let buffer=new Uint8Array(136),written=0;try{written=procPidInfo(pid,3,0n,buffer,136)}catch{return null}if(written!==136)return null;let view=new DataView(buffer.buffer,buffer.byteOffset,buffer.byteLength),startSeconds=Number(view.getBigUint64(120,!0));return startSeconds>0?startSeconds:null}var PROCESS_QUERY_LIMITED_INFORMATION=4096,kernel32Lookup=null;async function openKernel32(){if(process.platform!=="win32")return null;try{let{dlopen,FFIType}=await import("bun:ffi");return dlopen("kernel32.dll",{OpenProcess:{args:[FFIType.u32,FFIType.i32,FFIType.u32],returns:FFIType.ptr},GetProcessTimes:{args:[FFIType.ptr,FFIType.ptr,FFIType.ptr,FFIType.ptr,FFIType.ptr],returns:FFIType.i32},CloseHandle:{args:[FFIType.ptr],returns:FFIType.i32}}).symbols}catch{return null}}async function readWin32ProcessCreationFiletime(pid){if(process.platform!=="win32")return null;if(!Number.isSafeInteger(pid)||pid<=0)return null;kernel32Lookup??=openKernel32();let kernel32=await kernel32Lookup;if(kernel32===null)return null;let handle=kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,0,pid);if(handle===null||handle===0||handle===0n)return null;try{let creation=new BigUint64Array(1),ok=kernel32.GetProcessTimes(handle,creation,new BigUint64Array(1),new BigUint64Array(1),new BigUint64Array(1)),filetime=creation[0]??0n;return ok===0||filetime===0n?null:filetime}finally{kernel32.CloseHandle(handle)}}function errorCode(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}async function execFileText(command,args){return await new Promise((resolve)=>{execFile(command,args,{encoding:"utf8",timeout:2000,windowsHide:!0},(error,stdout)=>{if(error!==null){resolve(null);return}let value=stdout.trim();resolve(value.length>0?value:null)})})}async function readLinuxStartIdentity(pid){try{let stat=await readFile(`/proc/${pid}/stat`,"utf8"),commandEnd=stat.lastIndexOf(")");if(commandEnd<0)return null;let startTicks=stat.slice(commandEnd+2).trim().split(/\s+/)[19];return startTicks===void 0?null:`linux-proc-start-ticks:${startTicks}`}catch{return null}}async function readWin32StartIdentity(pid){if(getPidLiveness(pid)==="dead")return null;let creationFiletime=await readWin32ProcessCreationFiletime(pid);if(creationFiletime!==null)return`win32-creation-filetime:${creationFiletime}`;let value=await execFileText("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${pid} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToString('o')`]);return value===null?null:`win32-creation-date:${value}`}function createProcessStartIdentityReader(read,ownPid){let ownIdentity;return(pid)=>{if(pid!==ownPid)return read(pid);return ownIdentity??=read(pid).then((identity)=>{if(identity===null)ownIdentity=void 0;return identity},(error)=>{throw ownIdentity=void 0,error}),ownIdentity}}var getProcessStartIdentity=createProcessStartIdentityReader(readProcessStartIdentity,process.pid);async function readProcessStartIdentity(pid){if(process.platform==="linux")return await readLinuxStartIdentity(pid);if(process.platform==="darwin"||process.platform==="freebsd"){if(getPidLiveness(pid)==="dead")return null;let startSeconds=await readDarwinProcessStartSeconds(pid);if(startSeconds!==null)return`proc-start-epoch:${startSeconds}`;let value=await execFileText("/bin/ps",["-o","lstart=","-p",String(pid)]);return value===null?null:`ps-lstart:${value.replace(/\s+/g," ")}`}if(process.platform==="win32")return await readWin32StartIdentity(pid);return null}function identityScheme(identity){let separator=identity.indexOf(":");return separator<=0?null:identity.slice(0,separator)}function startIdentitiesConflict(recorded,actual){let recordedScheme=identityScheme(recorded);if(recordedScheme===null||recordedScheme!==identityScheme(actual))return!1;return recorded!==actual}function startIdentitiesComparable(recorded,actual){return identityScheme(recorded)===identityScheme(actual)}function getPidLiveness(pid){try{return process.kill(pid,0),"alive"}catch(error){let code=errorCode(error);if(code==="ESRCH")return"dead";if(code==="EPERM")return"alive";return"unknown"}}function errorCode2(error){return error instanceof Error&&"code"in error&&typeof error.code==="string"?error.code:"unknown error"}async function readJson(path,readText){let text;try{text=await readText(path)}catch(error){let code=errorCode2(error);return code==="ENOENT"?{kind:"missing"}:{kind:"unreadable",code}}try{return{kind:"ok",value:JSON.parse(text)}}catch{return{kind:"invalid"}}}function fieldsOf(value){return typeof value==="object"&&value!==null?value:{}}function isRunOutcome(value,runId){let fields=fieldsOf(value),childExit=fieldsOf(fields.childExit);return fields.version===1&&fields.runId===runId&&typeof fields.finishedAt==="string"&&(fields.attempt===void 0||typeof fields.attempt==="number"&&Number.isInteger(fields.attempt)&&fields.attempt>0)&&typeof fields.childExit==="object"&&fields.childExit!==null&&(childExit.code===null||typeof childExit.code==="number")&&(childExit.signal===null||typeof childExit.signal==="string")&&typeof fields.timedOut==="boolean"}function stuck(runId,reason){return{state:"stuck",runId,reason}}async function reflectionLauncherLiveness(pid,recordedStart,probe){let liveness=(probe.getPidLiveness??getPidLiveness)(pid);if(liveness!=="alive"||typeof recordedStart!=="string")return liveness;let actualStart=await(probe.getProcessStartIdentity??getProcessStartIdentity)(pid).catch(()=>null);if(actualStart!==null&&startIdentitiesComparable(recordedStart,actualStart)&&recordedStart!==actualStart)return"dead";return"alive"}async function classifyReflectionLockHolder(reflectionDir,probe={}){let readText=probe.readText??((path)=>readFile(path,"utf8")),active=await readJson(join(reflectionDir,"active.lock"),readText);if(active.kind==="missing")return{state:"none"};if(active.kind==="unreadable")return stuck("unknown",`active.lock could not be read (${active.code})`);if(active.kind==="invalid")return stuck("unknown","active.lock is not valid JSON");let fields=fieldsOf(active.value),runId=typeof fields.runId==="string"?fields.runId:"unknown",launcherPid=typeof fields.launcherPid==="number"?fields.launcherPid:void 0,launcherHostname=typeof fields.launcherHostname==="string"?fields.launcherHostname:void 0;if(launcherPid===void 0||launcherHostname===void 0)return stuck(runId,"its launcher identity is missing");if(launcherHostname!==(probe.hostname??readHostname)())return stuck(runId,`it is owned by host ${launcherHostname}, which cannot be checked from here`);let launcher=await reflectionLauncherLiveness(launcherPid,fields.launcherProcessStart,probe);if(launcher==="alive")return{state:"live",runId};if(launcher==="unknown")return stuck(runId,`launcher pid ${launcherPid} could not be checked`);let runDir=join(reflectionDir,"runs",runId),outcome=await readJson(join(runDir,"outcome.json"),readText);if(outcome.kind==="missing")return stuck(runId,`launcher pid ${launcherPid} is gone and the run recorded no outcome`);if(outcome.kind==="unreadable")return stuck(runId,`its outcome could not be read (${outcome.code})`);if(outcome.kind==="invalid")return stuck(runId,"its outcome is not valid JSON");if(!isRunOutcome(outcome.value,runId))return stuck(runId,"its outcome is not a recorded run outcome");let claim=await readJson(join(runDir,"terminal-claim.json"),readText);if(claim.kind==="unreadable")return stuck(runId,`its terminal claim could not be read (${claim.code})`);if(claim.kind==="invalid")return stuck(runId,"its terminal claim is not valid JSON");if(claim.kind==="ok"){let claimantPid=fieldsOf(claim.value).claimantPid;if(typeof claimantPid!=="number")return stuck(runId,"its terminal claim names no claimant");let claimant=(probe.getPidLiveness??getPidLiveness)(claimantPid);if(claimant==="alive")return{state:"live",runId};if(claimant==="unknown")return stuck(runId,`publish claimant pid ${claimantPid} could not be checked`)}return{state:"dead",runId}}init_resilient();import{hostname as readHostname2}from"node:os";import{basename as basename5,join as join29}from"node:path";init_resilient();import{join as join2}from"node:path";var RETRYABLE_ON_WIN32=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),PERMISSION_CODES=new Set(["EPERM","EACCES","ENOTEMPTY"]),WIN32_BUSY_RETRIES=5;function errorCode3(error){return error instanceof Error&&"code"in error&&typeof error.code==="string"?error.code:void 0}async function removeTree(path,platform=process.platform){try{await rm(path,{recursive:!0,force:!0});return}catch(error){let code=errorCode3(error);if(!(platform==="win32"?RETRYABLE_ON_WIN32.has(code??""):PERMISSION_CODES.has(code??"")))throw error}await makeWritable(path);let attempts=platform==="win32"?WIN32_BUSY_RETRIES:1;for(let attempt=1;;attempt+=1)try{await rm(path,{recursive:!0,force:!0});return}catch(error){if(attempt>=attempts||errorCode3(error)!=="EBUSY")throw error}}async function makeWritable(path){let stats=await lstat(path).catch((error)=>{if(errorCode3(error)==="ENOENT")return;throw error});if(stats===void 0||stats.isSymbolicLink())return;if(!stats.isDirectory()){await chmod(path,384);return}await chmod(path,448);for(let name of await readdir(path))await makeWritable(join2(path,name))}init_resilient();import path5 from"node:path";init_resilient();import path from"node:path";import{randomUUID}from"node:crypto";import{hostname}from"node:os";import{constants as osConstants}from"node:os";var LOCK_SH=1,LOCK_EX=2,LOCK_NB=4,LIBC={darwin:{names:["/usr/lib/libSystem.B.dylib"],errnoSymbol:"__error"},linux:{names:["libc.so.6","libc.musl-x86_64.so.1","libc.musl-aarch64.so.1","libc.so"],errnoSymbol:"__errno_location"}},flockLookup=null;async function openFlock(){let libc=LIBC[process.platform];if(libc===void 0)return null;let ffi;try{ffi=await import("bun:ffi")}catch{return null}for(let name of libc.names)try{let library=ffi.dlopen(name,{flock:{args:[ffi.FFIType.i32,ffi.FFIType.i32],returns:ffi.FFIType.i32},[libc.errnoSymbol]:{args:[],returns:ffi.FFIType.ptr}}),errnoAt=library.symbols[libc.errnoSymbol];if(errnoAt===void 0)continue;return(fd,operation)=>{let rc=Number(library.symbols.flock(fd,operation));if(rc===0)return{rc,errno:0};let pointer=errnoAt();return{rc,errno:pointer===null?-1:ffi.read.i32(pointer,0)}}}catch{continue}return null}function loadFlock(){return flockLookup??=openFlock(),flockLookup}async function osFileLockAvailable(){return await loadFlock()!==null}var errnos=osConstants.errno;function classifyFlockFailure(errno){if(errno===errnos.EWOULDBLOCK||errno===errnos.EAGAIN||errno===errnos.EINTR)return{kind:"busy"};if(errno===errnos.ENOLCK||errno===errnos.EOPNOTSUPP||errno===errnos.ENOTSUP||errno===errnos.ENOSYS)return{kind:"unavailable",errno};return{kind:"failed",errno}}async function attempt(fd,mode){let flock=await loadFlock();if(flock===null)return{kind:"unavailable"};let{rc,errno}=flock(fd,mode|LOCK_NB);return rc===0?{kind:"acquired"}:classifyFlockFailure(errno)}function tryLockShared(fd){return attempt(fd,LOCK_SH)}function tryLockExclusive(fd){return attempt(fd,LOCK_EX)}function isNonEmptyString(value){return typeof value==="string"&&value.length>0}function parseLockRecord(content){let value;try{value=JSON.parse(content)}catch{return null}if(typeof value!=="object"||value===null||Array.isArray(value))return null;let candidate=value;if(!Number.isInteger(candidate.pid)||Number(candidate.pid)<=0)return null;if(!isNonEmptyString(candidate.process_start))return null;if(!isNonEmptyString(candidate.hostname))return null;if(!isNonEmptyString(candidate.nonce))return null;if(!isNonEmptyString(candidate.created_at)||Number.isNaN(Date.parse(candidate.created_at)))return null;if(!isNonEmptyString(candidate.purpose))return null;if(candidate.run_id!==void 0&&!isNonEmptyString(candidate.run_id))return null;return{pid:Number(candidate.pid),process_start:candidate.process_start,hostname:candidate.hostname,nonce:candidate.nonce,created_at:candidate.created_at,purpose:candidate.purpose,...candidate.run_id===void 0?{}:{run_id:candidate.run_id},...candidate.git_activity_lock===!0?{git_activity_lock:!0}:{}}}async function createLockRecord(purpose,options={}){if(purpose.length===0)throw Error("lock purpose must not be empty");let processStart=await getProcessStartIdentity(process.pid);return{pid:process.pid,process_start:processStart??"unavailable",hostname:hostname(),nonce:randomUUID(),created_at:new Date().toISOString(),purpose,...options.runId===void 0?{}:{run_id:options.runId},...await osFileLockAvailable()?{git_activity_lock:!0}:{}}}var provenDeadTakeovers=new Map;function recordProvenDeadTakeover(lockPath,previousOwner,takeoverNonce){provenDeadTakeovers.set(lockPath,{previous:previousOwner,takeoverNonce})}function provenDeadTakeoverFor(lockPath,acquisitionNonce){let entry=provenDeadTakeovers.get(lockPath);return entry?.takeoverNonce===acquisitionNonce?entry.previous:void 0}function forgetProvenDeadTakeover(lockPath,acquisitionNonce){if(provenDeadTakeovers.get(lockPath)?.takeoverNonce===acquisitionNonce)provenDeadTakeovers.delete(lockPath)}function errorCode4(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}async function readOwner(lockPath){try{let raw=await readFile(lockPath,"utf8"),identity=await stat(lockPath,{bigint:!0});return{raw,record:parseLockRecord(raw),dev:identity.dev,ino:identity.ino,mtimeMs:Number(identity.mtimeMs)}}catch(error){let code=errorCode4(error);if(code==="ENOENT")return null;if(path.sep==="\\"&&code==="EPERM")return{raw:"",record:null,dev:0,ino:0,mtimeMs:Date.now()};throw error}}function isSameOwner(left,right){return left.dev===right.dev&&left.ino===right.ino&&left.mtimeMs===right.mtimeMs&&left.raw===right.raw}async function releaseLock(lockPath,record){forgetProvenDeadTakeover(lockPath,record.nonce);let owner=await readOwner(lockPath);if(owner===null||owner.record?.nonce!==record.nonce)return!1;try{return await unlink(lockPath),!0}catch(error){if(errorCode4(error)==="ENOENT")return!1;throw error}}init_resilient();import{randomUUID as randomUUID2}from"node:crypto";import path3 from"node:path";init_resilient();import path2 from"node:path";var CANDIDATE_STALE_AGE_MS=3600000,CANDIDATE_UNLINK_ATTEMPTS=3,knownLeakedCandidates=new Set;function trackLeakedCandidate(candidatePath){knownLeakedCandidates.add(candidatePath)}function forgetLeakedCandidate(candidatePath){knownLeakedCandidates.delete(candidatePath)}var LEAKED_CANDIDATE_NAME=/\.candidate-(?:(\d+)-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function isCreatorDead(name){let pid=LEAKED_CANDIDATE_NAME.exec(name)?.[1];return pid!==void 0&&getPidLiveness(Number(pid))==="dead"}function errorCode5(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}function notifyFailure(options,candidatePath){try{options.onFailure?.(candidatePath)}catch{}}function isSharingError(error){if(process.platform!=="win32")return!1;let code=errorCode5(error);return code==="EBUSY"||code==="EPERM"||code==="EACCES"}async function sweepStaleLockCandidates(lockDirectory,now=Date.now,options={}){let names;try{names=await readdir(lockDirectory)}catch(error){if(errorCode5(error)==="ENOENT"){for(let candidatePath of knownLeakedCandidates)if(path2.dirname(candidatePath)===lockDirectory)forgetLeakedCandidate(candidatePath);return 0}throw error}let swept=0;for(let name of names){if(!LEAKED_CANDIDATE_NAME.test(name))continue;let candidatePath=path2.join(lockDirectory,name);try{let status=await stat(candidatePath);if(!(knownLeakedCandidates.has(candidatePath)||isCreatorDead(name)||now()-status.mtimeMs>CANDIDATE_STALE_AGE_MS))continue;let removed=!1;for(let attempt=0;attempt<CANDIDATE_UNLINK_ATTEMPTS;attempt+=1)try{await(options.unlink??unlink)(candidatePath),forgetLeakedCandidate(candidatePath),removed=!0;break}catch(error){if(errorCode5(error)==="ENOENT"){forgetLeakedCandidate(candidatePath),removed=!0;break}if(!(options.isSharingError?.(error)??isSharingError(error)))throw error;if(attempt+1===CANDIDATE_UNLINK_ATTEMPTS)notifyFailure(options,candidatePath)}if(removed)swept+=1}catch(error){if(errorCode5(error)==="ENOENT")forgetLeakedCandidate(candidatePath);notifyFailure(options,candidatePath)}}return swept}var sweptLockDirectories=new Map;function claimDirectorySweep(lockDirectory,at){let lastSwept=sweptLockDirectories.get(lockDirectory);if(lastSwept!==void 0&&at-lastSwept<600000)return!1;return sweptLockDirectories.set(lockDirectory,at),!0}function rearmCandidateSweep(lockDirectory){sweptLockDirectories.delete(lockDirectory)}var LINK_FALLBACK_ERRORS=new Set(["EACCES","EPERM","ENOTSUP"]);function errorCode6(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}function isUnlinkSharingError(error,override){if(override!==void 0)return override(error);if(process.platform!=="win32")return!1;let code=errorCode6(error);return code==="EBUSY"||code==="EPERM"||code==="EACCES"}var candidateFs={};function currentCandidateFs(){return candidateFs}async function unlinkCandidate(candidatePath){for(let attempt=0;attempt<CANDIDATE_UNLINK_ATTEMPTS;attempt+=1)try{return await(candidateFs.unlink??unlink)(candidatePath),forgetLeakedCandidate(candidatePath),!0}catch(error){if(errorCode6(error)==="ENOENT")return forgetLeakedCandidate(candidatePath),!0;if(!isUnlinkSharingError(error,candidateFs.isSharingError))throw trackLeakedCandidate(candidatePath),rearmCandidateSweep(path3.dirname(candidatePath)),error;if(attempt+1===CANDIDATE_UNLINK_ATTEMPTS)return trackLeakedCandidate(candidatePath),rearmCandidateSweep(path3.dirname(candidatePath)),!1}return!1}async function openFreshCandidate(lockPath){for(let attempt=0;;attempt+=1){let candidatePath=`${lockPath}.candidate-${process.pid}-${randomUUID2()}`;try{return{candidatePath,handle:await open3(candidatePath,"wx",384)}}catch(error){if(!await unlinkCandidate(candidatePath))rearmCandidateSweep(path3.dirname(lockPath));if(errorCode6(error)!=="EINTR"||attempt>=EINTR_RETRY_CAP)throw error}}}async function publishFallback(lockPath,record){let handle;try{handle=await open3(lockPath,"wx",384)}catch(error){if(errorCode6(error)==="EEXIST")return!1;throw error}try{return await(candidateFs.writeFallback??writeHandleAll)(handle,`${JSON.stringify(record)}
3
3
  `,"utf8"),await handle.sync(),!0}finally{await handle.close()}}async function publishExclusive(lockPath,record){await mkdir(path3.dirname(lockPath),{recursive:!0,mode:448});let{candidatePath,handle}=await openFreshCandidate(lockPath);try{try{await writeHandleAll(handle,`${JSON.stringify(record)}
4
- `,"utf8"),await handle.sync()}finally{await handle.close()}try{return await(candidateFs.link??link)(candidatePath,lockPath),!0}catch(error){if(isCandidatePublishRace(error))return!1;if(LINK_FALLBACK_ERRORS.has(errorCode6(error)??""))return await publishFallback(lockPath,record);throw error}}finally{if(!await unlinkCandidate(candidatePath))rearmCandidateSweep(path3.dirname(lockPath))}}function isCandidatePublishRace(error){let code=errorCode6(error);return code==="EEXIST"||code==="ENOENT"}function lockRetryDelayMs(attempt,baseMs,random=Math.random){let ceiling=Math.min(250,baseMs*2**Math.min(attempt,30));return Math.max(1,Math.round(ceiling/2+random()*ceiling/2))}function delay(milliseconds,signal){return signal?.throwIfAborted(),new Promise((resolve,reject)=>{let timer=setTimeout(finish,milliseconds),onAbort=()=>finish(signal?.reason??new DOMException("The operation was aborted","AbortError"));signal?.addEventListener("abort",onAbort,{once:!0});function finish(error){clearTimeout(timer),signal?.removeEventListener("abort",onAbort),error===void 0?resolve():reject(error)}})}init_resilient();import{randomUUID as randomUUID3}from"node:crypto";import{hostname as hostname2}from"node:os";function errorCode7(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}async function isLockOwnerProvenDead(owner){if(owner.hostname!==hostname2())return!1;let liveness=getPidLiveness(owner.pid);if(liveness==="dead")return!0;if(liveness==="unknown")return!1;let actualStart=await getProcessStartIdentity(owner.pid);if(actualStart===null||owner.process_start==="unavailable")return!1;return startIdentitiesConflict(owner.process_start,actualStart)}async function isRecoverableOwner(owner,now,incompleteLockGraceMs){if(owner.record!==null)return isLockOwnerProvenDead(owner.record);return now-owner.mtimeMs>incompleteLockGraceMs}async function reclaimStaleRecoveryLock(recoveryPath,now,incompleteLockGraceMs){let stale=await readOwner(recoveryPath);if(stale===null||!await isRecoverableOwner(stale,now,incompleteLockGraceMs))return!1;let tombstonePath=`${recoveryPath}.reaping-${randomUUID3()}`;try{await rename2(recoveryPath,tombstonePath)}catch(error){if(errorCode7(error)==="ENOENT")return!1;if(isUnlinkSharingError(error))return!1;throw error}let moved=await readOwner(tombstonePath);if(moved!==null&&isSameOwner(moved,stale))return await unlink(tombstonePath),!0;try{await link(tombstonePath,recoveryPath)}catch(error){if(errorCode7(error)!=="EEXIST")throw error}return await unlink(tombstonePath),!1}async function recoverStaleOwner(lockPath,snapshot,contender,now,incompleteLockGraceMs){if(!await isRecoverableOwner(snapshot,now,incompleteLockGraceMs))return!1;let recoveryPath=`${lockPath}.recovery`,recoveryRecord={...contender,nonce:randomUUID3(),created_at:new Date().toISOString(),purpose:`${contender.purpose}:recovery`};for(let attempt=0;;attempt+=1){if(await readOwner(recoveryPath)===null&&await publishExclusive(recoveryPath,recoveryRecord))break;if(attempt>0||!await reclaimStaleRecoveryLock(recoveryPath,now,incompleteLockGraceMs))return!1}try{let current=await readOwner(lockPath);if(current===null)return!0;if(!isSameOwner(current,snapshot))return!1;if(!await isRecoverableOwner(current,now,incompleteLockGraceMs))return!1;let fence=await readOwner(recoveryPath);if(fence===null||fence.record?.nonce!==recoveryRecord.nonce)return!1;if(await unlink(lockPath),current.record!==null)recordProvenDeadTakeover(lockPath,current.record,contender.nonce);return!0}finally{await releaseLock(recoveryPath,recoveryRecord)}}var INCOMPLETE_LOCK_GRACE_MS=5000;class LockContentionError extends Error{lockPath;owner;retriable=!0;constructor(lockPath,owner){super(`Lock is held: ${lockPath}`);this.lockPath=lockPath;this.owner=owner;this.name="LockContentionError"}}async function acquireWithoutDirectorySweep(lockPath,record,options={}){let waitTimeoutMs=options.waitTimeoutMs??0,retryDelayMs=options.retryDelayMs??25,incompleteLockGraceMs=options.incompleteLockGraceMs??INCOMPLETE_LOCK_GRACE_MS,now=options.now??Date.now;if(waitTimeoutMs<0||retryDelayMs<=0||incompleteLockGraceMs<0)throw Error("lock wait options must be positive");let deadline=now()+waitTimeoutMs;try{return await acquireLoop(lockPath,record,options,{retryDelayMs,incompleteLockGraceMs,now,deadline})}catch(error){throw forgetProvenDeadTakeover(lockPath,record.nonce),error}}function forfeitDeadOwnerProof(lockPath,record,recoveredDeadOwner){if(recoveredDeadOwner)forgetProvenDeadTakeover(lockPath,record.nonce);return!1}async function acquireLoop(lockPath,record,options,timing){let{retryDelayMs,incompleteLockGraceMs,now,deadline}=timing,sawOtherOwner=!1,recoveredDeadOwner=!1;for(let attempt=0;;attempt+=1){options.signal?.throwIfAborted();let owner=await readOwner(lockPath);if(owner===null){if(await publishExclusive(lockPath,record))return{sawOtherOwner};if(options.signal?.throwIfAborted(),sawOtherOwner=!0,recoveredDeadOwner=forfeitDeadOwnerProof(lockPath,record,recoveredDeadOwner),owner=await readOwner(lockPath),owner===null)continue}if(sawOtherOwner=!0,recoveredDeadOwner=forfeitDeadOwnerProof(lockPath,record,recoveredDeadOwner),await recoverStaleOwner(lockPath,owner,record,now(),incompleteLockGraceMs)){recoveredDeadOwner=!0;continue}if(options.signal?.throwIfAborted(),now()>=deadline)throw new LockContentionError(lockPath,owner.record);await delay(Math.min(lockRetryDelayMs(attempt,retryDelayMs),Math.max(1,deadline-now())),options.signal)}}init_resilient();import{hostname as hostname3}from"node:os";import path4 from"node:path";var LOCK_FILE_SUFFIX=".lock";function errorCode8(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}async function provenDeadOwner(lockPath){let raw;try{raw=await readFile(lockPath,"utf8")}catch(error){if(errorCode8(error)==="ENOENT")return null;throw error}let owner=parseLockRecord(raw);if(owner===null||owner.hostname!==hostname3()||getPidLiveness(owner.pid)!=="dead")return null;return await isLockOwnerProvenDead(owner)?owner:null}async function reclaimIfDeadOwner(lockPath,options){let previousOwner=(await lstat(lockPath).catch(()=>{return}))?.isFile()===!0?await provenDeadOwner(lockPath):null;if(previousOwner===null)return!1;let sweeper=await createLockRecord("dead-owner-sweep");try{await acquireWithoutDirectorySweep(lockPath,sweeper,{waitTimeoutMs:0})}catch(error){if(error instanceof LockContentionError)return!1;throw error}return await releaseLock(lockPath,sweeper),options.onReclaimed?.(lockPath,previousOwner),!0}async function sweepDeadOwnerLocks(lockDirectory,options={}){let names;try{names=await readdir(lockDirectory)}catch(error){if(errorCode8(error)!=="ENOENT")options.onFailure?.(lockDirectory,error);return 0}let reclaimed=0;for(let name of names){if(!name.endsWith(LOCK_FILE_SUFFIX))continue;let lockPath=path4.join(lockDirectory,name);try{if(await reclaimIfDeadOwner(lockPath,options))reclaimed+=1}catch(error){options.onFailure?.(lockPath,error)}}return reclaimed}async function acquireLock(lockPath,record,options={}){let lockDirectory=path5.dirname(lockPath),reclaimedForThisAcquisition;if(claimDirectorySweep(lockDirectory,(options.now??Date.now)())){let candidateFs=currentCandidateFs();await sweepStaleLockCandidates(lockDirectory,Date.now,{...candidateFs.unlink===void 0?{}:{unlink:candidateFs.unlink},...candidateFs.isSharingError===void 0?{}:{isSharingError:candidateFs.isSharingError},onFailure:()=>rearmCandidateSweep(lockDirectory)}).catch(()=>{rearmCandidateSweep(lockDirectory)}),await sweepDeadOwnerLocks(lockDirectory,{onReclaimed:(reclaimedPath,previousOwner)=>{if(path5.resolve(reclaimedPath)===path5.resolve(lockPath))reclaimedForThisAcquisition=previousOwner}})}let outcome=await acquireWithoutDirectorySweep(lockPath,record,options);if(reclaimedForThisAcquisition!==void 0&&!outcome.sawOtherOwner&&provenDeadTakeoverFor(lockPath,record.nonce)===void 0)recordProvenDeadTakeover(lockPath,reclaimedForThisAcquisition,record.nonce)}async function withLock(lockPath,record,fn,options){await acquireLock(lockPath,record,options);try{return await fn()}finally{await releaseLock(lockPath,record)}}import{createHash}from"node:crypto";import path6 from"node:path";function memoryWriterLockPath(locksDirectory){return path6.join(locksDirectory,"memory-write.lock")}function reflectionSchedulerLockPath(locksDirectory){return path6.join(locksDirectory,"reflection-scheduler.lock")}function runFinalizationLockPath(locksDirectory,runId){let trimmed=runId.trim();if(!trimmed||trimmed==="."||trimmed==="..")throw Error("run id must contain a safe identifier");if(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/.test(trimmed))return path6.join(locksDirectory,`finalize-${trimmed}.lock`);let slug=trimmed.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").slice(0,48)||"run",digest=createHash("sha256").update(trimmed).digest("hex").slice(0,16);return path6.join(locksDirectory,`finalize-${slug}-${digest}.lock`)}function receiptsLockPath(locksDirectory){return path6.join(locksDirectory,"receipts.lock")}init_resilient();import{hostname as hostname4}from"node:os";import{join as join3}from"node:path";init_resilient();var publishing=Promise.resolve();init_redact();var RECEIPTS_FILE="receipts.jsonl",DETAIL_LIMIT=400,LOCK_WAIT_MS=30000;function receiptsPath(runtimeDir){return join3(runtimeDir,RECEIPTS_FILE)}function receiptIdentity(receipt){return receipt.kind==="facts"?JSON.stringify([receipt.kind,receipt.batchId,receipt.event]):JSON.stringify([receipt.kind,receipt.runId,receipt.event,receipt.generation])}function appendMemoryReceiptOnce(runtimeDir,input){return underReceiptsLock(runtimeDir,async()=>{let identity=receiptIdentity(input),{receipts}=parseReceipts(await readText(runtimeDir));if(receipts.some((receipt)=>receiptIdentity(receipt)===identity))return!1;return await writeLine(runtimeDir,toReceipt(input)),!0})}async function underReceiptsLock(runtimeDir,operation){let locks=join3(runtimeDir,"locks");return await mkdir(locks,{recursive:!0}),withLock(receiptsLockPath(locks),await createLockRecord("receipts"),operation,{waitTimeoutMs:LOCK_WAIT_MS})}function toReceipt(input){let detail=input.detail===void 0?void 0:boundDetail(input.detail),reason=input.reason===void 0?void 0:boundDetail(input.reason);return{v:1,at:new Date().toISOString(),...input,...reason===void 0?{}:{reason},...detail===void 0?{}:{detail},host:hostname4(),pid:process.pid}}function boundDetail(detail){let masked=redactSecretLikeMaterial(detail);return masked.length<=DETAIL_LIMIT?masked:`${masked.slice(0,DETAIL_LIMIT-3)}...`}async function writeLine(runtimeDir,receipt){let path=receiptsPath(runtimeDir);if(await appendFile2(path,`${JSON.stringify(receipt)}
4
+ `,"utf8"),await handle.sync()}finally{await handle.close()}try{return await(candidateFs.link??link)(candidatePath,lockPath),!0}catch(error){if(isCandidatePublishRace(error))return!1;if(LINK_FALLBACK_ERRORS.has(errorCode6(error)??""))return await publishFallback(lockPath,record);throw error}}finally{if(!await unlinkCandidate(candidatePath))rearmCandidateSweep(path3.dirname(lockPath))}}function isCandidatePublishRace(error){let code=errorCode6(error);return code==="EEXIST"||code==="ENOENT"}function lockRetryDelayMs(attempt,baseMs,random=Math.random){let ceiling=Math.min(250,baseMs*2**Math.min(attempt,30));return Math.max(1,Math.round(ceiling/2+random()*ceiling/2))}function delay(milliseconds,signal){return signal?.throwIfAborted(),new Promise((resolve,reject)=>{let timer=setTimeout(finish,milliseconds),onAbort=()=>finish(signal?.reason??new DOMException("The operation was aborted","AbortError"));signal?.addEventListener("abort",onAbort,{once:!0});function finish(error){clearTimeout(timer),signal?.removeEventListener("abort",onAbort),error===void 0?resolve():reject(error)}})}init_resilient();import{randomUUID as randomUUID3}from"node:crypto";import{hostname as hostname2}from"node:os";function errorCode7(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}async function isLockOwnerProvenDead(owner){if(owner.hostname!==hostname2())return!1;let liveness=getPidLiveness(owner.pid);if(liveness==="dead")return!0;if(liveness==="unknown")return!1;let actualStart=await getProcessStartIdentity(owner.pid);if(actualStart===null||owner.process_start==="unavailable")return!1;return startIdentitiesConflict(owner.process_start,actualStart)}async function isRecoverableOwner(owner,now,incompleteLockGraceMs){if(owner.record!==null)return isLockOwnerProvenDead(owner.record);return now-owner.mtimeMs>incompleteLockGraceMs}async function reclaimStaleRecoveryLock(recoveryPath,now,incompleteLockGraceMs){let stale=await readOwner(recoveryPath);if(stale===null||!await isRecoverableOwner(stale,now,incompleteLockGraceMs))return!1;let tombstonePath=`${recoveryPath}.reaping-${randomUUID3()}`;try{await rename2(recoveryPath,tombstonePath)}catch(error){if(errorCode7(error)==="ENOENT")return!1;if(isUnlinkSharingError(error))return!1;throw error}let moved=await readOwner(tombstonePath);if(moved!==null&&isSameOwner(moved,stale))return await unlink(tombstonePath),!0;try{await link(tombstonePath,recoveryPath)}catch(error){if(errorCode7(error)!=="EEXIST")throw error}return await unlink(tombstonePath),!1}async function recoverStaleOwner(lockPath,snapshot,contender,now,incompleteLockGraceMs){if(!await isRecoverableOwner(snapshot,now,incompleteLockGraceMs))return!1;let recoveryPath=`${lockPath}.recovery`,recoveryRecord={...contender,nonce:randomUUID3(),created_at:new Date().toISOString(),purpose:`${contender.purpose}:recovery`};for(let attempt=0;;attempt+=1){if(await readOwner(recoveryPath)===null&&await publishExclusive(recoveryPath,recoveryRecord))break;if(attempt>0||!await reclaimStaleRecoveryLock(recoveryPath,now,incompleteLockGraceMs))return!1}try{let current=await readOwner(lockPath);if(current===null)return!0;if(!isSameOwner(current,snapshot))return!1;if(!await isRecoverableOwner(current,now,incompleteLockGraceMs))return!1;let fence=await readOwner(recoveryPath);if(fence===null||fence.record?.nonce!==recoveryRecord.nonce)return!1;try{await unlink(lockPath)}catch(error){if(errorCode7(error)!=="ENOENT")throw error}if(current.record!==null)recordProvenDeadTakeover(lockPath,current.record,contender.nonce);return!0}finally{await releaseLock(recoveryPath,recoveryRecord)}}var INCOMPLETE_LOCK_GRACE_MS=5000;class LockContentionError extends Error{lockPath;owner;retriable=!0;constructor(lockPath,owner){super(`Lock is held: ${lockPath}`);this.lockPath=lockPath;this.owner=owner;this.name="LockContentionError"}}async function acquireWithoutDirectorySweep(lockPath,record,options={}){let waitTimeoutMs=options.waitTimeoutMs??0,retryDelayMs=options.retryDelayMs??25,incompleteLockGraceMs=options.incompleteLockGraceMs??INCOMPLETE_LOCK_GRACE_MS,now=options.now??Date.now;if(waitTimeoutMs<0||retryDelayMs<=0||incompleteLockGraceMs<0)throw Error("lock wait options must be positive");let deadline=now()+waitTimeoutMs;try{return await acquireLoop(lockPath,record,options,{retryDelayMs,incompleteLockGraceMs,now,deadline})}catch(error){throw forgetProvenDeadTakeover(lockPath,record.nonce),error}}function forfeitDeadOwnerProof(lockPath,record,recoveredDeadOwner){if(recoveredDeadOwner)forgetProvenDeadTakeover(lockPath,record.nonce);return!1}async function acquireLoop(lockPath,record,options,timing){let{retryDelayMs,incompleteLockGraceMs,now,deadline}=timing,sawOtherOwner=!1,recoveredDeadOwner=!1;for(let attempt=0;;attempt+=1){options.signal?.throwIfAborted();let owner=await readOwner(lockPath);if(owner===null){if(await publishExclusive(lockPath,record))return{sawOtherOwner};if(options.signal?.throwIfAborted(),sawOtherOwner=!0,recoveredDeadOwner=forfeitDeadOwnerProof(lockPath,record,recoveredDeadOwner),owner=await readOwner(lockPath),owner===null)continue}if(sawOtherOwner=!0,recoveredDeadOwner=forfeitDeadOwnerProof(lockPath,record,recoveredDeadOwner),await recoverStaleOwner(lockPath,owner,record,now(),incompleteLockGraceMs)){recoveredDeadOwner=!0;continue}if(options.signal?.throwIfAborted(),now()>=deadline)throw new LockContentionError(lockPath,owner.record);await delay(Math.min(lockRetryDelayMs(attempt,retryDelayMs),Math.max(1,deadline-now())),options.signal)}}init_resilient();import{hostname as hostname3}from"node:os";import path4 from"node:path";var LOCK_FILE_SUFFIX=".lock";function errorCode8(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}async function provenDeadOwner(lockPath){let raw;try{raw=await readFile(lockPath,"utf8")}catch(error){if(errorCode8(error)==="ENOENT")return null;throw error}let owner=parseLockRecord(raw);if(owner===null||owner.hostname!==hostname3()||getPidLiveness(owner.pid)!=="dead")return null;return await isLockOwnerProvenDead(owner)?owner:null}async function reclaimIfDeadOwner(lockPath,options){let previousOwner=(await lstat(lockPath).catch(()=>{return}))?.isFile()===!0?await provenDeadOwner(lockPath):null;if(previousOwner===null)return!1;let sweeper=await createLockRecord("dead-owner-sweep");try{await acquireWithoutDirectorySweep(lockPath,sweeper,{waitTimeoutMs:0})}catch(error){if(error instanceof LockContentionError)return!1;throw error}return await releaseLock(lockPath,sweeper),options.onReclaimed?.(lockPath,previousOwner),!0}async function sweepDeadOwnerLocks(lockDirectory,options={}){let names;try{names=await readdir(lockDirectory)}catch(error){if(errorCode8(error)!=="ENOENT")options.onFailure?.(lockDirectory,error);return 0}let reclaimed=0;for(let name of names){if(!name.endsWith(LOCK_FILE_SUFFIX))continue;let lockPath=path4.join(lockDirectory,name);try{if(await reclaimIfDeadOwner(lockPath,options))reclaimed+=1}catch(error){options.onFailure?.(lockPath,error)}}return reclaimed}async function acquireLock(lockPath,record,options={}){let lockDirectory=path5.dirname(lockPath),reclaimedForThisAcquisition;if(claimDirectorySweep(lockDirectory,(options.now??Date.now)())){let candidateFs=currentCandidateFs();await sweepStaleLockCandidates(lockDirectory,Date.now,{...candidateFs.unlink===void 0?{}:{unlink:candidateFs.unlink},...candidateFs.isSharingError===void 0?{}:{isSharingError:candidateFs.isSharingError},onFailure:()=>rearmCandidateSweep(lockDirectory)}).catch(()=>{rearmCandidateSweep(lockDirectory)}),await sweepDeadOwnerLocks(lockDirectory,{onReclaimed:(reclaimedPath,previousOwner)=>{if(path5.resolve(reclaimedPath)===path5.resolve(lockPath))reclaimedForThisAcquisition=previousOwner}})}let outcome=await acquireWithoutDirectorySweep(lockPath,record,options);if(reclaimedForThisAcquisition!==void 0&&!outcome.sawOtherOwner&&provenDeadTakeoverFor(lockPath,record.nonce)===void 0)recordProvenDeadTakeover(lockPath,reclaimedForThisAcquisition,record.nonce)}async function withLock(lockPath,record,fn,options){await acquireLock(lockPath,record,options);try{return await fn()}finally{await releaseLock(lockPath,record)}}import{createHash}from"node:crypto";import path6 from"node:path";function memoryWriterLockPath(locksDirectory){return path6.join(locksDirectory,"memory-write.lock")}function reflectionSchedulerLockPath(locksDirectory){return path6.join(locksDirectory,"reflection-scheduler.lock")}function runFinalizationLockPath(locksDirectory,runId){let trimmed=runId.trim();if(!trimmed||trimmed==="."||trimmed==="..")throw Error("run id must contain a safe identifier");if(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/.test(trimmed))return path6.join(locksDirectory,`finalize-${trimmed}.lock`);let slug=trimmed.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").slice(0,48)||"run",digest=createHash("sha256").update(trimmed).digest("hex").slice(0,16);return path6.join(locksDirectory,`finalize-${slug}-${digest}.lock`)}function receiptsLockPath(locksDirectory){return path6.join(locksDirectory,"receipts.lock")}init_resilient();import{hostname as hostname4}from"node:os";import{join as join3}from"node:path";init_resilient();var publishing=Promise.resolve();init_redact();var RECEIPTS_FILE="receipts.jsonl",DETAIL_LIMIT=400,LOCK_WAIT_MS=30000;function receiptsPath(runtimeDir){return join3(runtimeDir,RECEIPTS_FILE)}function receiptIdentity(receipt){return receipt.kind==="facts"?JSON.stringify([receipt.kind,receipt.batchId,receipt.event]):JSON.stringify([receipt.kind,receipt.runId,receipt.event,receipt.generation])}function appendMemoryReceiptOnce(runtimeDir,input){return underReceiptsLock(runtimeDir,async()=>{let identity=receiptIdentity(input),{receipts}=parseReceipts(await readText(runtimeDir));if(receipts.some((receipt)=>receiptIdentity(receipt)===identity))return!1;return await writeLine(runtimeDir,toReceipt(input)),!0})}async function underReceiptsLock(runtimeDir,operation){let locks=join3(runtimeDir,"locks");return await mkdir(locks,{recursive:!0}),withLock(receiptsLockPath(locks),await createLockRecord("receipts"),operation,{waitTimeoutMs:LOCK_WAIT_MS})}function toReceipt(input){let detail=input.detail===void 0?void 0:boundDetail(input.detail),reason=input.reason===void 0?void 0:boundDetail(input.reason);return{v:1,at:new Date().toISOString(),...input,...reason===void 0?{}:{reason},...detail===void 0?{}:{detail},host:hostname4(),pid:process.pid}}function boundDetail(detail){let masked=redactSecretLikeMaterial(detail);return masked.length<=DETAIL_LIMIT?masked:`${masked.slice(0,DETAIL_LIMIT-3)}...`}async function writeLine(runtimeDir,receipt){let path=receiptsPath(runtimeDir);if(await appendFile2(path,`${JSON.stringify(receipt)}
5
5
  `,{encoding:"utf8",mode:384,flush:!0}),process.platform!=="win32")await chmod(path,384)}async function readText(runtimeDir){try{return await readFile(receiptsPath(runtimeDir),"utf8")}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return"";throw error}}function parseReceipts(text){let receipts=[],skippedPartialLines=0;for(let line of text.split(`
6
6
  `)){if(line.length===0)continue;let receipt=parseReceipt(line);if(receipt===null)skippedPartialLines++;else receipts.push(receipt)}return{receipts,skippedPartialLines}}function parseReceipt(line){let value;try{value=JSON.parse(line)}catch{return null}if(typeof value!=="object"||value===null)return null;let candidate=value;if(candidate.v!==1||typeof candidate.event!=="string"||typeof candidate.at!=="string")return null;if(candidate.kind==="facts")return typeof candidate.batchId==="string"?candidate:null;if(candidate.kind!=="reflection"&&candidate.kind!=="dream")return null;return typeof candidate.runId==="string"&&typeof candidate.generation==="string"?candidate:null}import{join as join5}from"node:path";import{randomUUID as randomUUID4}from"node:crypto";init_resilient();import{dirname,join as join4}from"node:path";async function readRun(path){let parsed=await readJsonOptional(path);if(parsed===null)return null;if(!isReservedRun(parsed))throw Error(`Invalid reflection reservation: ${path}`);return parsed}async function readJsonOptional(path){let raw;try{raw=await readFile(path,"utf8")}catch(error){if(errorCode9(error)==="ENOENT")return null;throw error}return JSON.parse(raw)}async function writeJsonAtomic(path,value){await mkdir(dirname(path),{recursive:!0,mode:448});let temporaryPath=`${path}.tmp-${randomUUID4()}`,renamed=!1;try{await writeFile2(temporaryPath,`${JSON.stringify(value,null,2)}
7
7
  `,{encoding:"utf8",mode:384}),await rename2(temporaryPath,path),renamed=!0}finally{if(!renamed)await unlinkIfPresent(temporaryPath)}}async function unlinkIfPresent(path){await unlink(path).catch((error)=>{if(errorCode9(error)!=="ENOENT")throw error})}async function moveTornReservationAside(reflectionDir,expected,at){let activePath=join4(reflectionDir,"active.lock"),current;try{current=await readFile(activePath,"utf8")}catch(error){if(errorCode9(error)==="ENOENT")return;throw error}if(current!==expected)return;let name=`active.lock.torn-${at.toISOString().replace(/[:.]/g,"-")}`;return await rename2(activePath,join4(reflectionDir,name)),name}function isReservedRun(value){if(!value||typeof value!=="object")return!1;let run=value;return typeof run.runId==="string"&&run.runId.length>0&&isReflectionRequest(run.request)}function isReflectionRequest(value){if(!value||typeof value!=="object")return!1;let request=value;return(request.trigger==="manual"||request.trigger==="compaction"||request.trigger==="step-count"||request.trigger==="dream")&&(request.trigger==="dream"?request.origin==="manual"||request.origin==="idle"||request.origin==="shutdown"||request.origin==="pressure":request.origin===void 0)&&Array.isArray(request.conversationIds)&&request.conversationIds.every((id)=>typeof id==="string")&&Array.isArray(request.snapshots)&&(request.targetDoc===void 0||request.trigger==="dream"&&typeof request.targetDoc==="string")}function errorCode9(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}var ABANDONED_FILENAME="abandoned.json";async function writeAbandoned(runDir,record){await writeJsonAtomic(join5(runDir,ABANDONED_FILENAME),record)}init_resilient();import{basename as basename4,isAbsolute as isAbsolute4,join as join22,relative,resolve as resolve10}from"node:path";import{resolve}from"node:path";var CONFIG_LOCK_ERROR=/(could not lock config file|unable to create '[^']*config\.lock')/i,LOCK_CONTENTION_ERROR=/(could not lock config file|unable to create '[^']*\.lock'|cannot lock ref|another git process seems to be running)/i,ATTEMPTS=5,BASE_DELAY_MS=25,mutationQueues=new Map;function isGitConfigLockError(error){return CONFIG_LOCK_ERROR.test(errorText(error))}function isGitLockError(error){return LOCK_CONTENTION_ERROR.test(errorText(error))}function errorText(error){return error instanceof Error?error.message:String(error)}async function withSerializedGitConfigMutation(dir,mutate){let key=resolve(dir),task=(mutationQueues.get(key)??Promise.resolve()).catch(()=>{return}).then(()=>retryConfigMutation(mutate));mutationQueues.set(key,task);try{await task}finally{if(mutationQueues.get(key)===task)mutationQueues.delete(key)}}async function withGitLockRetry(operation){for(let attempt=1;attempt<=ATTEMPTS;attempt+=1)try{return await operation()}catch(error){if(!isGitLockError(error)||attempt===ATTEMPTS)throw error;await delay2(BASE_DELAY_MS*2**(attempt-1))}throw Error("unreachable: git lock retry exhausted without result")}async function retryConfigMutation(mutate){for(let attempt=1;attempt<=ATTEMPTS;attempt+=1)try{await mutate();return}catch(error){if(!isGitConfigLockError(error)||attempt===ATTEMPTS)throw error;await delay2(BASE_DELAY_MS*2**(attempt-1))}}function delay2(durationMs){return new Promise((resolveDelay)=>setTimeout(resolveDelay,durationMs))}class GitError extends Error{constructor(message,options){super(message,options);this.name=new.target.name}}class GitCommandError extends GitError{argv;code;stdout;stderr;termination;constructor(argv,code,stdout,stderr,termination){let detail=stderr.trim()||stdout.trim()||silentExitDetail(code,termination);super(`git ${argv.join(" ")} failed: ${detail}`);this.argv=argv;this.code=code;this.stdout=stdout;this.stderr=stderr;this.termination=termination}}function silentExitDetail(code,termination){if(termination===void 0)return`exit code ${code}`;let signal=termination.signal===null?"no signal":`signal ${termination.signal}`;return`exit code ${code} with no output (${signal}, after ${termination.elapsedMs}ms)`}class GitTimeoutError extends GitError{argv;timeoutMs;constructor(argv,timeoutMs){super(`git ${argv.join(" ")} timed out after ${timeoutMs}ms`);this.argv=argv;this.timeoutMs=timeoutMs}}class GitAbortedError extends GitError{argv;constructor(argv){super(`git ${argv.join(" ")} was cancelled`);this.argv=argv}}class GitNotFoundError extends GitError{constructor(options){super("Git is required for memory storage but was not found on PATH.",options)}}class DirtyRepoError extends GitError{porcelain;encodingDiagnostics;constructor(porcelain,encodingDiagnostics){let encoding=encodingDiagnostics.length>0?` Dirty markdown encoding issue(s): ${encodingDiagnostics.join("; ")}.`:"";super(`Memory repo has uncommitted changes. Commit, discard, or sync them before using memory tools.