omo-ai 5.1.64 → 5.1.65
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/bin/darwin/omo-keychain +0 -0
- package/bin/lib/doctor-memory-runtime.js +167 -0
- package/bin/lib/doctor-reflection-lock.js +102 -6
- package/bin/lib/doctor.js +4 -2
- package/bin/lib/launcher.js +21 -3
- package/bin/lib/provider-map.json +1 -1
- package/bin/lib/reflection-lock.generated.js +39 -1
- package/bin/lib/service-auth.generated.js +37 -18
- package/bin/lib/thread.js +28 -2
- package/package.json +2 -2
- package/plugin/CHANGELOG.md +54 -0
- package/plugin/extensions/dream-persona.md +1 -1
- package/plugin/extensions/gateway-store-worker.mjs +1 -1
- package/plugin/extensions/memory-run-supervisor.mjs +3 -3
- package/plugin/extensions/omo-claim-receipt.js +1 -1
- package/plugin/extensions/omo-computer-use.js +1 -1
- package/plugin/extensions/omo-desktop-toolkit.js +1 -1
- package/plugin/extensions/omo-device-account.js +66 -2
- package/plugin/extensions/omo-device-service.js +5 -5
- package/plugin/extensions/omo-feedback.js +2 -2
- package/plugin/extensions/omo-init-deep-advisor.js +1 -1
- package/plugin/extensions/omo-member.js +2 -2
- package/plugin/extensions/omo-memory-commands.js +3 -3
- package/plugin/extensions/omo-memory-doctor.js +3 -3
- package/plugin/extensions/omo-memory-memfs.js +1 -1
- package/plugin/extensions/omo-memory-palace.js +2 -2
- package/plugin/extensions/omo-memory-sync.js +1 -1
- package/plugin/extensions/omo-onboarding-scan.js +3 -3
- package/plugin/extensions/omo-recall-store.js +1 -1
- package/plugin/extensions/omo-session-history.js +1 -1
- package/plugin/extensions/omo-side-panel.js +2 -2
- package/plugin/extensions/omo-task.js +2 -2
- package/plugin/extensions/omo-telemetry-otlp.js +2 -2
- package/plugin/extensions/omo-telemetry-posthog.js +1 -1
- package/plugin/extensions/omo-telemetry-recovery.js +1 -1
- package/plugin/extensions/omo-thread-client.js +5 -5
- package/plugin/extensions/omo.js +3 -3
- package/plugin/package.json +2 -1
- package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
- package/plugin/runtime/ast-grep-mcp/manifest.json +1 -1
- package/plugin/runtime/bunshin-ts/sdk.js +2 -2
- package/plugin/runtime/category-coverage/index.js +2 -2
- package/plugin/runtime/rollback-migrate.js +1 -1
- package/plugin/runtime/task-config/index.js +3 -3
- package/plugin/runtime/thread-sdk/sdk.js +5 -5
- package/plugin/skills/browser/SKILL.md +3 -1
- package/plugin/skills/browser/runtime/omowright/index.js +232 -341
- package/plugin/skills/browser/runtime/omowright/manifest.json +5 -5
- package/plugin/skills/browser/runtime/omowright/page-bundle.js +1586 -1394
- package/plugin/skills/browser/scripts/browser-doctor-report.mjs +68 -0
- package/plugin/skills/browser/scripts/browser-doctor.mjs +8 -43
- package/plugin/skills/browser/scripts/omowright.mjs +7 -1
|
@@ -1,2 +1,40 @@
|
|
|
1
1
|
// Generated by bun script/build-reflection-lock.ts; do not edit.
|
|
2
|
-
import{hostname as readHostname}from"node:os";import{join}from"node:path";import*as fsSync from"node:fs";import*as fsp from"node:fs/promises";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}}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}})}var promises=resilientNamespace(fsp,"async");var 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;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 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 launcherLiveness(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 launcherLiveness(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}}export{classifyReflectionLockHolder};
|
|
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
|
+
`,"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)}
|
|
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
|
+
`)){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
|
+
`,{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.
|
|
8
|
+
${porcelain.trimEnd()}${encoding}`);this.porcelain=porcelain;this.encodingDiagnostics=encodingDiagnostics}}class NoEffectiveChangesError extends GitError{paths;constructor(paths){super(`Memory write produced no effective changes for: ${paths.join(", ")}`);this.paths=paths}}class InvalidGitPathError extends GitError{}init_resilient();import{spawn}from"node:child_process";import{win32}from"node:path";var REPOSITORY_LOCAL_GIT_ENV=new Set(["GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_CONFIG","GIT_OBJECT_DIRECTORY","GIT_DIR","GIT_WORK_TREE","GIT_IMPLICIT_WORK_TREE","GIT_GRAFT_FILE","GIT_NO_REPLACE_OBJECTS","GIT_REPLACE_REF_BASE","GIT_PREFIX","GIT_SHALLOW_FILE","GIT_COMMON_DIR","GIT_NAMESPACE"]);var NUMBERED_CONFIG_PAIR=/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/;function defeatsMemoryHooks(key){let name=key.trim(),firstDot=name.indexOf("."),lastDot=name.lastIndexOf(".");if(firstDot<=0||lastDot===name.length-1)return!1;let section=name.slice(0,firstDot).toLowerCase(),variable=name.slice(lastDot+1).toLowerCase();if(section==="core")return firstDot===lastDot&&(variable==="hookspath"||variable==="fsmonitor");return variable==="path"&&(section==="include"||section==="includeif")}function configCountPairs(environment){let raw=environment.get("GIT_CONFIG_COUNT");if(raw===void 0)return[];if(raw.trim()!==""&&!/^\s*\+?\d+$/.test(raw))return;let count=Number(raw.trim()||"0"),pairs=[];for(let index=0;index<count;index+=1){let key=environment.get(`GIT_CONFIG_KEY_${index}`),value=environment.get(`GIT_CONFIG_VALUE_${index}`);if(key===void 0||value===void 0)return;pairs.push([key,value])}return pairs}function dequoteStep(text,start){if(text[start]!=="'")return;let value="",at=start+1;for(;;){let quote=text.indexOf("'",at);if(quote<0)return;value+=text.slice(at,quote);let escaped=text[quote+2];if(text[quote+1]==="\\"&&(escaped==="'"||escaped==="!")&&text[quote+3]==="'"){value+=escaped,at=quote+4;continue}return{value,end:quote+1}}}function configParameterEntries(text){let entries=[],at=0;while(at<text.length){let key=dequoteStep(text,at);if(!key)return;let{end,value:name}=key;if(text[end]==="="){if(end+=1,text[end]==="'"){let value=dequoteStep(text,end);if(!value)return;end=value.end}}else{let equals=name.indexOf("=");if(equals>=0)name=name.slice(0,equals)}if(end<text.length&&!/\s/.test(text[end]??""))return;entries.push({source:text.slice(at,end),key:name});while(end<text.length&&/\s/.test(text[end]??""))end+=1;at=end}return entries}function memoryGitEnvironment(environment,platform=process.platform){let kept={},gitName=platform==="win32"?(name)=>name.toUpperCase():(name)=>name,byGitName=new Map;for(let[name,value]of Object.entries(environment)){let key=gitName(name);if(!byGitName.has(key))byGitName.set(key,value);if(REPOSITORY_LOCAL_GIT_ENV.has(key)||NUMBERED_CONFIG_PAIR.test(key))continue;if(key==="GIT_CONFIG_COUNT"||key==="GIT_CONFIG_PARAMETERS")continue;kept[name]=value}let pairs=configCountPairs(byGitName)?.filter(([key])=>!defeatsMemoryHooks(key))??[];if(pairs.length>0)kept.GIT_CONFIG_COUNT=String(pairs.length);pairs.forEach(([key,value],index)=>{kept[`GIT_CONFIG_KEY_${index}`]=key,kept[`GIT_CONFIG_VALUE_${index}`]=value});let parameters=byGitName.get("GIT_CONFIG_PARAMETERS"),entries=parameters===void 0?[]:configParameterEntries(parameters)?.filter((entry)=>!defeatsMemoryHooks(entry.key))??[];if(entries.length>0)kept.GIT_CONFIG_PARAMETERS=entries.map((entry)=>entry.source).join(" ");return kept}import{basename,dirname as dirname2,join as join7,resolve as resolve4}from"node:path";import{join as join6,resolve as resolve2}from"node:path";var AGENTS_DIRNAME="agents",REPO_DIRNAME="repo",RUNTIME_DIRNAME="runtime";function buildIdentityPaths(memoryRoot,id){let root=join6(memoryRoot,AGENTS_DIRNAME,id),runtime=join6(root,RUNTIME_DIRNAME);return{root,repo:join6(root,REPO_DIRNAME),runtime,locks:join6(runtime,"locks"),transcripts:join6(runtime,"transcripts"),reflection:join6(runtime,"reflection"),reflectionSessions:join6(runtime,"reflection-sessions"),worktrees:join6(runtime,"worktrees"),viewers:join6(runtime,"viewers"),pushQueue:join6(runtime,"push-queue"),factsQueue:join6(runtime,"facts-queue"),facts:join6(runtime,"facts"),notices:join6(runtime,"notices"),recall:join6(runtime,"recall"),recallLedger:join6(runtime,"recall","ledger"),recallPending:join6(runtime,"recall","pending")}}init_resilient();init_resilient();init_resilient();init_resilient();init_resilient();var LINUX_LOCAL_FILESYSTEMS=new Set([61267,1481003842,2435016766,16914836,4076150800,801189825,2035054128,3393526350]);function isLocalFilesystemType(platform,type,rootType){if(platform==="linux")return LINUX_LOCAL_FILESYSTEMS.has(type);if(platform==="darwin")return rootType!==void 0&&type===rootType;return!1}async function isOnLocalFilesystem(path){try{let{type}=await statfs(path),rootType=process.platform==="darwin"?(await statfs("/")).type:void 0;return isLocalFilesystemType(process.platform,type,rootType)}catch{return!1}}var GIT_ACTIVITY_LOCK_NAME="git-activity.flock",GIT_ACTIVITY_SHARED_WAIT_MS=1e4,SHARED_RETRY_MS=5;function identityLocksDirForRepo(repoDir){let resolved=resolve4(repoDir);if(basename(resolved)!==REPO_DIRNAME||basename(dirname2(dirname2(resolved)))!==AGENTS_DIRNAME)return null;return join7(dirname2(resolved),RUNTIME_DIRNAME,"locks")}class GitActivityLockError extends GitError{}function errorCode10(error){return error instanceof Error&&"code"in error&&typeof error.code==="string"?error.code:void 0}async function mkdirIfMissing(dir){try{await mkdir(dir)}catch(error){if(errorCode10(error)!=="EEXIST")throw error}}async function openActivityLock(repoDir){let locksDir=identityLocksDirForRepo(repoDir);if(locksDir===null)return null;try{return await mkdirIfMissing(dirname2(locksDir)),await mkdirIfMissing(locksDir),await open3(join7(locksDir,GIT_ACTIVITY_LOCK_NAME),constants2.O_RDWR|constants2.O_CREAT,384)}catch(error){if(errorCode10(error)==="ENOENT")return null;throw error}}function cannotWriteMemoryHome(error){let code=errorCode10(error);return code==="EROFS"||code==="EACCES"||code==="EPERM"}async function holdGitActivityShared(repoDir){let handle;try{handle=await openActivityLock(repoDir)}catch(error){if(cannotWriteMemoryHome(error))return null;throw error}if(handle===null)return null;let deadline=Date.now()+GIT_ACTIVITY_SHARED_WAIT_MS;for(;;){let outcome=await tryLockShared(handle.fd);if(outcome.kind==="acquired"){let held=handle;return{fd:held.fd,release:()=>held.close()}}if(outcome.kind==="unavailable")return await handle.close(),null;if(outcome.kind==="failed")throw await handle.close(),new GitActivityLockError(`The memory repository's git-activity lock failed with errno ${outcome.errno}: ${repoDir}`);if(Date.now()>=deadline)throw await handle.close(),new GitActivityLockError(`The memory repository's git-activity lock stayed exclusively held for ${GIT_ACTIVITY_SHARED_WAIT_MS} ms: ${repoDir}`);await new Promise((resolveRetry)=>setTimeout(resolveRetry,SHARED_RETRY_MS))}}async function probeGitActivityIdle(repoDir){let handle=await openActivityLock(repoDir).catch(()=>null);if(handle===null)return{kind:"unavailable"};let outcome=await tryLockExclusive(handle.fd);if(outcome.kind==="acquired"){let locksDir=identityLocksDirForRepo(repoDir);return{kind:"idle",vouches:locksDir!==null&&await isOnLocalFilesystem(locksDir),release:()=>handle.close()}}return await handle.close(),outcome.kind==="busy"?{kind:"busy"}:{kind:"unavailable"}}init_resilient();import{spawnSync}from"node:child_process";import{join as join8}from"node:path";var GIT_TIMEOUT_DIAGNOSTICS_ENV="OMO_GIT_TIMEOUT_DIAGNOSTICS_DIR",SNAPSHOT_TIMEOUT_MS=15000;function processSnapshot(pid){let command=process.platform==="win32"?spawnSync("powershell",["-NoProfile","-Command",["Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CreationDate,CommandLine | Format-Table -AutoSize -Wrap | Out-String -Width 400",`@(${pid}) + @(Get-CimInstance Win32_Process -Filter "ParentProcessId=${pid}" | ForEach-Object { $_.ProcessId }) | ForEach-Object { "threads of $_"; (Get-Process -Id $_ -ErrorAction SilentlyContinue).Threads | Group-Object ThreadState,WaitReason -NoElement | Format-Table -AutoSize | Out-String }`].join("; ")],{encoding:"utf8",timeout:SNAPSHOT_TIMEOUT_MS,windowsHide:!0}):spawnSync("ps",["-axo","pid,ppid,stat,wchan,etime,command"],{encoding:"utf8",timeout:SNAPSHOT_TIMEOUT_MS,windowsHide:!0});if(command.error)return`process snapshot failed: ${command.error.message}`;return`${command.stdout}${command.stderr}`}function recordGitTimeout(environment,pid,argv,cwd,timeoutMs,snapshot=processSnapshot){let directory=environment[GIT_TIMEOUT_DIAGNOSTICS_ENV];if(!directory||pid===void 0)return;try{mkdirSync(directory,{recursive:!0}),writeFileSync(join8(directory,`git-timeout-${pid}-${Date.now()}.json`),`${JSON.stringify({at:new Date().toISOString(),pid,cwd,timeoutMs,argv:argv.slice(0,12),argCount:argv.length,processes:snapshot(pid)},null,2)}
|
|
9
|
+
`)}catch(error){process.stderr.write(`git timeout diagnostics could not be written to ${directory}: ${String(error)}
|
|
10
|
+
`)}}var GIT_KILL_GRACE_MS=1e4,GIT_EXIT_DRAIN_MS=2000,WINDOWS_GIT_CANDIDATES=[["ProgramFiles",["Git","cmd","git.exe"]],["ProgramW6432",["Git","cmd","git.exe"]],["ProgramFiles(x86)",["Git","cmd","git.exe"]],["LOCALAPPDATA",["Programs","Git","cmd","git.exe"]]];function environmentValue(environment,name){for(let[key,value]of Object.entries(environment)){if(key.toLowerCase()!==name.toLowerCase()||value===void 0)continue;let trimmed=value.trim();if(trimmed.length>0)return trimmed}return}function windowsGitExecutables(environment){let seen=new Set,candidates=[];for(let[environmentName,pathParts]of WINDOWS_GIT_CANDIDATES){let root=environmentValue(environment,environmentName);if(root===void 0||!/^[A-Za-z]:[\\/]/.test(root))continue;let candidate=win32.join(root,...pathParts),normalizedCandidate=win32.normalize(candidate).toLowerCase();if(seen.has(normalizedCandidate))continue;seen.add(normalizedCandidate),candidates.push(candidate)}return candidates}function isGitNotFoundFromEnoent(error){if(!(error instanceof GitNotFoundError)||!(error.cause instanceof Error))return!1;return error.cause.code==="ENOENT"}async function runGitCommand(executable,argv,options,environment){let activity=await holdGitActivityShared(options.cwd);try{return await spawnGitCommand(executable,argv,options,environment,activity?.fd)}finally{await activity?.release()}}function spawnGitCommand(executable,argv,options,environment,activityFd){return new Promise((resolve,reject)=>{let startedAt=Date.now(),hasStdin=options.stdin!==void 0,child=spawn(executable,[...argv],{cwd:options.cwd,env:environment,shell:!1,stdio:[hasStdin?"pipe":"ignore","pipe","pipe",...activityFd===void 0?[]:[activityFd]],windowsHide:!0}),stdout=[],stderr=[],settled=!1,timedOut=!1,exitDrain,killTimer,timer=setTimeout(()=>{timedOut=!0,recordGitTimeout(environment,child.pid,argv,options.cwd,options.timeoutMs),child.kill("SIGTERM"),killTimer=setTimeout(()=>child.kill("SIGKILL"),options.killGraceMs??GIT_KILL_GRACE_MS)},options.timeoutMs),aborted=!1,onAbort=()=>{aborted=!0,child.kill("SIGTERM")};if(options.signal?.aborted===!0)onAbort();else options.signal?.addEventListener("abort",onAbort,{once:!0});child.stdout.on("data",(chunk)=>stdout.push(chunk)),child.stderr.on("data",(chunk)=>stderr.push(chunk));let stdinError,stdin=hasStdin?child.stdin:null;if(stdin)stdin.on("error",(error)=>{if(error.code!=="EPIPE")stdinError=error}),stdin.end(options.stdin);child.on("error",(error)=>{if(settled)return;if(settled=!0,clearTimeout(timer),clearTimeout(killTimer),clearTimeout(exitDrain),options.signal?.removeEventListener("abort",onAbort),error.code==="ENOENT"){if(!existsSync(options.cwd)){resolve({code:128,stdout:"",stderr:`fatal: cannot change to '${options.cwd}': No such file or directory`});return}reject(new GitNotFoundError({cause:error}))}else reject(error)});let settleWithResult=(code,signal)=>{if(settled)return;if(settled=!0,clearTimeout(timer),clearTimeout(killTimer),clearTimeout(exitDrain),options.signal?.removeEventListener("abort",onAbort),aborted){reject(new GitAbortedError(argv));return}if(timedOut){reject(new GitTimeoutError(argv,options.timeoutMs));return}let stdoutBytes=Buffer.concat(stdout);resolve({code:code??1,stdout:stdoutBytes.toString("utf8"),stderr:Buffer.concat(stderr).toString("utf8")+describeStdinError(stdinError),stdoutBytes,termination:{signal,elapsedMs:Date.now()-startedAt}})};child.on("exit",(code,signal)=>{if(settled)return;if(timedOut||aborted){settled=!0,clearTimeout(timer),clearTimeout(killTimer),options.signal?.removeEventListener("abort",onAbort),reject(aborted?new GitAbortedError(argv):new GitTimeoutError(argv,options.timeoutMs));return}clearTimeout(timer),exitDrain=setTimeout(()=>{child.stdout.destroy(),child.stderr.destroy(),settleWithResult(code,signal)},options.exitDrainMs??GIT_EXIT_DRAIN_MS)}),child.on("close",(code,signal)=>settleWithResult(code,signal))})}var NO_FSMONITOR=["-c","core.fsmonitor=false"];function createNodeGitExec(runtime={}){let platform=runtime.platform??process.platform,runCommand=runtime.runCommand??runGitCommand;return{async run(callerArgv,options){let argv=[...NO_FSMONITOR,...callerArgv],environment=memoryGitEnvironment(options.env??process.env,platform);try{return await runCommand("git",argv,options,environment)}catch(error){if(platform!=="win32"||!isGitNotFoundFromEnoent(error))throw error;for(let fallback of windowsGitExecutables(environment))try{return await runCommand(fallback,argv,options,environment)}catch(fallbackError){if(isGitNotFoundFromEnoent(fallbackError))continue;throw fallbackError}throw error}}}}function describeStdinError(error){return error===void 0?"":`
|
|
11
|
+
omo: git stdin was not fully delivered (${error.code??error.message})
|
|
12
|
+
`}init_resilient();import{join as join10}from"node:path";function authorFlags(author){let name=author.authorName.trim()||author.agentId,email=author.authorEmail??`${author.agentId}@omo.local`;return["-c",`user.name=${name}`,"-c",`user.email=${email}`]}function normalizePathspecs(paths){return[...new Set(paths.map((path)=>path.replace(/\\/g,"/")).filter((path)=>path.trim()))]}function normalizeSeedPath(path){let normalized=path.replace(/\\/g,"/"),segments=normalized.split("/").filter(Boolean);if(!normalized||normalized.startsWith("/")||segments.some((segment)=>segment==="."||segment===".."))throw new InvalidGitPathError(`Invalid memory seed path: ${path}`);return segments.join("/")}function commandError(argv,result){return new GitCommandError(argv,result.code,result.stdout,result.stderr,result.termination)}init_resilient();import{randomUUID as randomUUID6}from"node:crypto";import{isAbsolute,resolve as resolve5}from"node:path";init_resilient();import{randomUUID as randomUUID5}from"node:crypto";import{basename as basename2,dirname as dirname3,join as join9}from"node:path";async function writeWorktreeFile(root,path,content,mode,exclusive){let target=join9(root,path);if(await assertSafeParents(root,path),!exclusive)await assertReplaceableTarget(target);await mkdir(dirname3(target),{recursive:!0}),await assertSafeParents(root,path);let temporary=join9(dirname3(target),`.${basename2(target)}.omo-${process.pid}-${randomUUID5()}`),file=await open3(temporary,"wx",mode);try{await writeHandleAll(file,content,"utf8"),await chmod(temporary,mode),await file.sync()}catch(error){throw await file.close(),await rm(temporary,{force:!0}),error}if(await file.close(),exclusive){try{await link(temporary,target)}catch(error){if(await rm(temporary,{force:!0}),errorCode11(error)==="EEXIST")return!1;throw error}await rm(temporary)}else await rename2(temporary,target);return await syncDirectory(dirname3(target)),!0}async function moveWorktreeFile(root,path){let target=join9(root,path);await assertSafeParents(root,path);try{let stat=await lstat(target);if(!stat.isFile())throw unsupportedWorktree(path,stat.isSymbolicLink()?"symlink":"non-file");let moved=join9(dirname3(target),`.${basename2(target)}.omo-moved-${process.pid}-${randomUUID5()}`);return await rename2(target,moved),moved}catch(error){if(errorCode11(error)==="ENOENT")return;throw error}}async function restoreMovedWorktreeFile(root,path,moved){let target=join9(root,path);try{await link(moved,target)}catch(error){if(errorCode11(error)==="EEXIST")return!1;throw error}return await rm(moved),await syncDirectory(dirname3(target)),!0}async function reserveMovedWorktreeDeletion(root,path,moved,restoreClaimed){let target=join9(root,path),marker=randomUUID5();try{await mkdir(target,{mode:448}),await writeFile2(join9(target,".omo-reservation"),marker,"utf8")}catch(error){if(errorCode11(error)==="EEXIST")return;throw error}let reserved=await lstat(target);return{verify:async()=>{let current;try{current=await lstat(target)}catch(error){if(errorCode11(error)==="ENOENT")return;throw error}if(!current.isDirectory()||current.dev!==reserved.dev||current.ino!==reserved.ino)return;try{if(await readFile(join9(target,".omo-reservation"),"utf8")!==marker)return}catch(error){if(errorCode11(error)==="ENOENT")return;throw error}return{finish:async()=>{let claimed=join9(dirname3(target),`.${basename2(target)}.omo-reserved-${process.pid}-${randomUUID5()}`);try{await rename2(target,claimed)}catch(error){if(errorCode11(error)==="ENOENT")return!1;throw error}let owned=await lstat(claimed),ownedMarker;if(owned.isDirectory())try{ownedMarker=await readFile(join9(claimed,".omo-reservation"),"utf8")}catch(error){if(errorCode11(error)!=="ENOENT")throw error}if(!owned.isDirectory()||owned.dev!==reserved.dev||owned.ino!==reserved.ino||ownedMarker!==marker){let restored=await restoreClaimed(claimed);return restored===!0?!1:restored}await rm(moved),await rm(claimed,{recursive:!0}),await syncDirectory(dirname3(target));try{return await lstat(target),!1}catch(error){if(errorCode11(error)==="ENOENT")return!0;throw error}}}}}}async function restoreClaimedWorktreeFile(root,path,claimed){if(!(await lstat(claimed)).isFile())return claimed;try{await link(claimed,join9(root,path))}catch(error){if(errorCode11(error)==="EEXIST")return claimed;throw error}return await rm(claimed),!0}async function discardMovedWorktreeFile(moved){await rm(moved,{force:!0})}async function removeWorktreeFile(root,path){let target=join9(root,path);await assertSafeParents(root,path);let stat;try{stat=await lstat(target)}catch(error){if(errorCode11(error)==="ENOENT")return;throw error}if(!stat.isFile())throw unsupportedWorktree(path,stat.isSymbolicLink()?"symlink":"non-file");await rm(target),await syncDirectory(dirname3(target))}async function assertSafeParents(root,path){let parts=path.split("/").slice(0,-1),current=root;for(let part of parts){current=join9(current,part);try{let stat=await lstat(current);if(stat.isSymbolicLink()||!stat.isDirectory())throw unsupportedWorktree(path,"unsafe parent")}catch(error){if(errorCode11(error)==="ENOENT")return;throw error}}}function unsupportedWorktree(path,kind){return new GitPathStateError(`Unsupported worktree ${kind} at path: ${path}`)}function errorCode11(error){return error instanceof Error&&"code"in error&&typeof error.code==="string"?error.code:void 0}async function assertReplaceableTarget(path){try{let stat=await lstat(path);if(!stat.isFile())throw unsupportedWorktree(path,stat.isSymbolicLink()?"symlink":"non-file")}catch(error){if(errorCode11(error)!=="ENOENT")throw error}}async function syncDirectory(path){try{let directory=await open3(path,"r");try{await directory.sync()}finally{await directory.close()}}catch(error){if(process.platform!=="win32"||!["EISDIR","EPERM","EACCES","EINVAL"].includes(errorCode11(error)??""))throw error}}var GIT_TIMEOUT_MS=30000;async function writeIndexIfIdentity(options){let rawIndexPath=(await git(options,["rev-parse","--git-path","index"])).stdout.trim(),indexPath=isAbsolute(rawIndexPath)?rawIndexPath:resolve5(options.dir,rawIndexPath),lockPath=`${indexPath}.lock`,temporary=`${indexPath}.omo-${process.pid}-${randomUUID6()}`,lock;try{lock=await open3(lockPath,"wx")}catch(error){if(errorCode11(error)==="EEXIST")return!1;throw error}let published=!1;try{if(!sameIdentity(await options.capture(),options.expected))return!1;await copyFile(indexPath,temporary);let argv=options.next===null?["update-index","--force-remove","--",options.path]:["update-index","--add","--cacheinfo",options.next.mode,options.next.oid,options.path];return await git(options,argv,{GIT_INDEX_FILE:temporary}),await writeHandleAll(lock,await readFile(temporary)),await lock.sync(),await lock.close(),await rename2(lockPath,indexPath),published=!0,!0}finally{if(!published)await lock.close().catch(()=>{return});if(await rm(temporary,{force:!0}),!published)await rm(lockPath,{force:!0})}}async function git(options,argv,env={}){let result=await options.exec.run(argv,{cwd:options.dir,timeoutMs:GIT_TIMEOUT_MS,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...env}});if(result.code!==0)throw commandError(argv,result);return result}function sameIdentity(left,right){return JSON.stringify(left)===JSON.stringify(right)}var GIT_TIMEOUT_MS2=30000,INDEX_MODES=new Set(["100644","100755"]);class GitPathStateError extends Error{constructor(message,options){super(message,options);this.name="GitPathStateError"}}class GitPathStateStore{dir;exec;ownershipLossRecoveryPath;constructor(dir,exec){this.dir=dir;this.exec=exec}async capture(path){let normalized=normalizeGitPath(path);return{index:await this.captureIndex(normalized),worktree:await this.captureWorktree(normalized)}}async captureAll(paths){let normalized=[...new Set(paths.map(normalizeGitPath))],states=await Promise.all(normalized.map(async(path)=>[path,await this.capture(path)]));return new Map(states)}async hashWorktreeBlob(content,write=!1){return this.hashBlob([...write?["-w"]:[],"--no-filters","--stdin"],content)}async hashIndexBlob(path,content,write=!1){let normalized=normalizeGitPath(path);return this.hashBlob([...write?["-w"]:[],`--path=${normalized}`,"--stdin"],content)}async readBlob(oid){return assertOid(oid),(await this.git(["cat-file","blob",oid])).stdout}async setIndex(path,identity){let normalized=normalizeGitPath(path);assertIndexIdentity(identity),await this.git(["update-index","--add","--cacheinfo",identity.mode,identity.oid,normalized])}async writeIndexIfIdentity(path,expected,next){let normalized=normalizeGitPath(path);if(next!==null)assertIndexIdentity(next);return writeIndexIfIdentity({dir:this.dir,exec:this.exec,path:normalized,expected,next,capture:()=>this.captureIndex(normalized)})}async removeIndex(path){let normalized=normalizeGitPath(path);await this.git(["update-index","--force-remove","--",normalized])}async writeWorktree(path,identity){let normalized=normalizeGitPath(path);assertWorktreeIdentity(identity),await writeWorktreeFile(this.dir,normalized,await this.readBlob(identity.oid),identity.mode,!1)}async writeWorktreeIfIdentity(path,expected,next){this.ownershipLossRecoveryPath=void 0;let normalized=normalizeGitPath(path);if(expected.kind==="missing"){if((await this.captureWorktree(normalized)).kind!=="missing")return!1;if(next.kind==="missing")return!0;return assertWorktreeIdentity(next),writeWorktreeFile(this.dir,normalized,await this.readBlob(next.oid),next.mode,!0)}let moved=await moveWorktreeFile(this.dir,normalized);if(moved===void 0)return!1;try{let current=await this.captureMovedWorktree(moved);if(!sameIdentity2(current,expected)){if(!await restoreMovedWorktreeFile(this.dir,normalized,moved))await discardMovedWorktreeFile(moved);return!1}if(next.kind==="missing"){let reservation=await this.reserveWorktreeDeletion(normalized,moved);if(reservation===void 0)return await discardMovedWorktreeFile(moved),!1;let finalizer=await reservation.verify();if(finalizer===void 0)return await discardMovedWorktreeFile(moved),!1;let removed=await finalizer.finish();if(removed!==!0)await discardMovedWorktreeFile(moved);if(typeof removed==="string")this.ownershipLossRecoveryPath=removed;return removed===!0}assertWorktreeIdentity(next);let published=await writeWorktreeFile(this.dir,normalized,await this.readBlob(next.oid),next.mode,!0);return await discardMovedWorktreeFile(moved),published}catch(error){if(!await restoreMovedWorktreeFile(this.dir,normalized,moved))await discardMovedWorktreeFile(moved);throw error}}consumeOwnershipLossRecoveryPath(){let path=this.ownershipLossRecoveryPath;return this.ownershipLossRecoveryPath=void 0,path}async reserveWorktreeDeletion(path,moved){return reserveMovedWorktreeDeletion(this.dir,path,moved,(claimed)=>this.restoreWorktreeClaim(path,claimed))}async restoreWorktreeClaim(path,claimed){return restoreClaimedWorktreeFile(this.dir,path,claimed)}async removeWorktree(path){await removeWorktreeFile(this.dir,normalizeGitPath(path))}async captureIndex(path){let records=(await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",path])).stdout.split("\x00").filter(Boolean);if(records.length===0)return null;let parsed=records.map(parseIndexRecord);if(parsed.some((record)=>record.stage!=="0"))throw new GitPathStateError(`Git path is unmerged and cannot be recovered safely: ${path}`);if(parsed.length!==1||parsed[0]?.path!==path)throw new GitPathStateError(`Git path did not resolve to one stage-zero index entry: ${path}`);let record=parsed[0];if(!INDEX_MODES.has(record.mode))throw new GitPathStateError(`Unsupported Git index mode ${record.mode} for path: ${path}`);return{mode:record.mode,oid:record.oid}}async captureWorktree(path){await assertSafeParents(this.dir,path);let fullPath=join10(this.dir,path),stat;try{stat=await lstat(fullPath)}catch(error){if(errorCode11(error)==="ENOENT")return{kind:"missing"};throw error}if(!stat.isFile())throw unsupportedWorktree(path,stat.isSymbolicLink()?"symlink":"non-file");let oid=await this.hashWorktreeBlob(await readFile(fullPath),!0);return{kind:"file",mode:worktreeMode(stat.mode),oid}}async captureMovedWorktree(path){let stat=await lstat(path);if(!stat.isFile())throw unsupportedWorktree(path,stat.isSymbolicLink()?"symlink":"non-file");return{kind:"file",mode:worktreeMode(stat.mode),oid:await this.hashWorktreeBlob(await readFile(path),!0)}}async hashBlob(argv,content){let oid=(await this.git(["hash-object",...argv],content)).stdout.trim();return assertOid(oid),oid}async git(argv,stdin){let result=await this.exec.run(argv,{cwd:this.dir,timeoutMs:GIT_TIMEOUT_MS2,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_GLOB_PATHSPECS:"0",GIT_ICASE_PATHSPECS:"0"},...stdin===void 0?{}:{stdin}});if(result.code!==0)throw commandError(argv,result);return result}}function normalizeGitPath(path){let normalized=path.replace(/\\/g,"/"),segments=normalized.split("/");if(!normalized||normalized.includes("\x00")||normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||segments.some((part)=>!part||part==="."||part===".."||part.toLowerCase()===".git"))throw new GitPathStateError(`Invalid repository-relative Git path: ${path}`);return normalized}function parseIndexRecord(record){let match=/^(\d{6}) ([0-9a-f]+) ([0-3])\t([\s\S]+)$/.exec(record);if(match===null)throw new GitPathStateError("Git returned a malformed index entry");return{mode:match[1],oid:match[2],stage:match[3],path:match[4]}}function assertOid(oid){if(!/^[0-9a-f]+$/.test(oid))throw new GitPathStateError(`Invalid Git object ID: ${oid}`)}function assertIndexIdentity(identity){if(!INDEX_MODES.has(identity.mode))throw new GitPathStateError(`Unsupported Git index mode: ${identity.mode}`);assertOid(identity.oid)}function assertWorktreeIdentity(identity){if(identity.kind!=="file"||!Number.isInteger(identity.mode)||identity.mode<0||identity.mode>511)throw new GitPathStateError("Invalid worktree file identity");assertOid(identity.oid)}function worktreeMode(statMode){return process.platform==="win32"?420:statMode&511}function sameIdentity2(left,right){return JSON.stringify(left)===JSON.stringify(right)}init_resilient();import{join as join11}from"node:path";function describeDirtyMarkdownEncodingIssues(root,porcelain){return porcelain.split(/\r?\n/).map((line)=>line.trimEnd()).filter(Boolean).map(parsePorcelainPath).filter((path)=>path?.endsWith(".md")??!1).map((path)=>describeMarkdownEncodingIssue(root,path)).filter((issue)=>issue!==null)}function parsePorcelainPath(line){if(line.length<4)return null;let status=line.slice(0,2);if(status===" D"||status==="D "||status==="DD")return null;let rawPath=line.slice(3);return(rawPath.includes(" -> ")?rawPath.split(" -> ").pop()??rawPath:rawPath).replace(/^"|"$/g,"")}function describeMarkdownEncodingIssue(root,relativePath){let path=join11(root,relativePath);if(!existsSync(path))return null;let bytes=readFileSync(path);if(bytes.length>=2&&bytes[0]===255&&bytes[1]===254)return`${relativePath} has UTF-16 LE BOM`;if(bytes.length>=2&&bytes[0]===254&&bytes[1]===255)return`${relativePath} has UTF-16 BE BOM`;if(bytes.includes(0))return`${relativePath} contains NUL bytes, possibly UTF-16`;return null}init_resilient();init_resilient();import{dirname as dirname4,join as join20}from"node:path";var NO_AUTO_MAINTENANCE=["-c","maintenance.auto=false","-c","gc.auto=0"];init_resilient();import{hostname as hostname5}from"node:os";import{join as join15}from"node:path";init_resilient();import{execFile as execFile2}from"node:child_process";import{join as join13}from"node:path";init_resilient();import{join as join12}from"node:path";function liveProcView(selfUid){return{root:"/proc",selfPid:process.pid,selfUid}}function errnoCode(error){if(!(error instanceof Error)||!("code"in error))return;let code=error.code;return typeof code==="string"?code:void 0}function unreadableFdDirMeansHeld(ownerUid,selfUid){return ownerUid===selfUid}async function listProcPids(view){let entries=await readdir(view.root).catch(()=>{return});if(entries===void 0||!entries.includes(String(view.selfPid)))return null;return entries.filter((entry)=>/^\d+$/.test(entry)).map((entry)=>Number.parseInt(entry,10))}async function classifyEntryError(view,pid,error){let code=errnoCode(error);if(code==="ENOENT"||code==="ENOTDIR"||code==="ESRCH")return"gone";if(code==="EACCES"||code==="EPERM"){let owner=await stat(join12(view.root,String(pid))).catch(()=>{return});if(owner===void 0)return"gone";return unreadableFdDirMeansHeld(owner.uid,view.selfUid)?"indeterminate":"gone"}return"indeterminate"}async function scanEveryProcess(view,inspect){let pids=await listProcPids(view);if(pids===null)return{kind:"unavailable"};let verdicts=await Promise.all(pids.map(async(pid)=>({pid,verdict:await inspect(pid)})));if(verdicts.some(({verdict})=>verdict==="indeterminate"))return{kind:"indeterminate"};return{kind:"holders",pids:verdicts.filter(({verdict})=>verdict==="match").map(({pid})=>pid).sort((a,b)=>a-b)}}async function fdVerdict(view,pid,fdPath,lock){let target;try{target=await readlink(fdPath)}catch(error){return errnoCode(error)==="ENOENT"?"no-match":classifyEntryError(view,pid,error)}if(lock.real!==void 0&&target===lock.real)return"match";try{let opened=await stat(fdPath);return opened.dev===lock.dev&&opened.ino===lock.ino?"match":"no-match"}catch(error){return errnoCode(error)==="ENOENT"?"no-match":classifyEntryError(view,pid,error)}}async function processHoldsLock(view,pid,lock){let fdDir=join13(view.root,String(pid),"fd"),fds;try{fds=await readdir(fdDir)}catch(error){return classifyEntryError(view,pid,error)}let sawIndeterminate=!1;for(let fd of fds){let verdict=await fdVerdict(view,pid,join13(fdDir,fd),lock);if(verdict==="match")return"match";if(verdict==="indeterminate")sawIndeterminate=!0}return sawIndeterminate?"indeterminate":"no-match"}async function scanProcFdHolders(lockPath,view){let identity=await stat(lockPath).catch(()=>{return});if(identity===void 0)return{kind:"holders",pids:[]};let lock={real:await realpath(lockPath).catch(()=>{return}),dev:identity.dev,ino:identity.ino};return scanEveryProcess(view,(pid)=>processHoldsLock(view,pid,lock))}var LSOF_ANSWER_BOUND_MS=60000;function runLsofBounded(argv,boundMs){return new Promise((resolveRun)=>{let settled=!1,child=execFile2("lsof",[...argv],{windowsHide:!0,maxBuffer:33554432},(error,stdout)=>{if(settled)return;settled=!0,clearTimeout(bound),resolveRun({error,stdout})}),bound=setTimeout(()=>{if(settled)return;settled=!0,child.kill("SIGKILL"),resolveRun(null)},boundMs)})}async function scanLsofHolders(path,boundMs){let run=await runLsofBounded(["-t","--",path],boundMs);if(run===null)return null;let listed=run.stdout.trim();if(listed.length>0){let lines=listed.split(/\r?\n/);return lines.every((line)=>/^\d+$/.test(line))?lines.map((line)=>Number.parseInt(line,10)):null}if(run.error===null)return[];return run.error.code===1?[]:null}function boundedScan(scan,boundMs){return new Promise((resolveScan)=>{let bound=setTimeout(()=>resolveScan({kind:"indeterminate"}),boundMs);scan.then((answer)=>{clearTimeout(bound),resolveScan(answer)},()=>{clearTimeout(bound),resolveScan({kind:"indeterminate"})})})}async function answerFromProcOrLsof(procScan,lsofScan,boundMs=LSOF_ANSWER_BOUND_MS){if(process.platform==="win32")return null;let geteuid=process.geteuid;if(process.platform==="linux"&&geteuid!==void 0){let scan=await boundedScan(procScan(liveProcView(geteuid.call(process))),boundMs);switch(scan.kind){case"holders":return scan.pids;case"indeterminate":return null;case"unavailable":break;default:throw new GitError(`Unhandled /proc scan outcome: ${JSON.stringify(scan)}`)}}return lsofScan()}function findOpenFileHolderPids(path,options={}){let boundMs=options.lsofBoundMs??LSOF_ANSWER_BOUND_MS;return answerFromProcOrLsof((view)=>scanProcFdHolders(path,view),()=>scanLsofHolders(path,boundMs),boundMs)}init_resilient();import{join as join14,resolve as resolve6,sep}from"node:path";function inside(path,roots){return roots.some((root)=>path===root||path.startsWith(root.endsWith(sep)?root:`${root}${sep}`))}async function repoTree(dir){let identity=await stat(dir).catch(()=>{return});if(identity===void 0)return null;let real=await realpath(dir).catch(()=>{return});return{roots:[...new Set([resolve6(dir),...real===void 0?[]:[real]])],dev:identity.dev,ino:identity.ino}}async function cwdVerdict(view,pid,tree){if(pid===view.selfPid)return"no-match";let cwdLink=join14(view.root,String(pid),"cwd"),target;try{target=await readlink(cwdLink)}catch(error){return classifyEntryError(view,pid,error)}if(inside(target,tree.roots))return"match";try{let cwd=await stat(cwdLink);return cwd.dev===tree.dev&&cwd.ino===tree.ino?"match":"no-match"}catch(error){return errnoCode(error)==="ENOENT"?"no-match":classifyEntryError(view,pid,error)}}async function scanProcCwdUsers(dir,view){let tree=await repoTree(dir);if(tree===null)return{kind:"indeterminate"};return scanEveryProcess(view,(pid)=>cwdVerdict(view,pid,tree))}async function scanLsofCwdUsers(dir,boundMs){let tree=await repoTree(dir),uid=process.getuid?.();if(tree===null||uid===void 0)return null;let run=await runLsofBounded(["-w","-a","-d","cwd","-u",String(uid),"-Fpn"],boundMs);if(run===null||run.error!==null)return null;let pid,sawSelf=!1,users=new Set;for(let line of run.stdout.split(`
|
|
13
|
+
`))if(line.startsWith("p")){if(!/^p\d+$/.test(line))return null;if(pid=Number.parseInt(line.slice(1),10),pid===process.pid)sawSelf=!0}else if(line.startsWith("n")&&pid!==void 0&&pid!==process.pid&&inside(line.slice(1),tree.roots))users.add(pid);return sawSelf?[...users].sort((a,b)=>a-b):null}function findProcessesWorkingIn(dir,options={}){let boundMs=options.lsofBoundMs??LSOF_ANSWER_BOUND_MS;return answerFromProcOrLsof((view)=>scanProcCwdUsers(dir,view),()=>scanLsofCwdUsers(dir,boundMs),boundMs)}var PRODUCTION_LOCK_SCANS={findHolders:(lockPath)=>findOpenFileHolderPids(lockPath),findRepoUsers:(repoDir)=>findProcessesWorkingIn(repoDir)};function envSettleOverride(){let raw=process.env.OMO_TEST_GIT_LOCK_SETTLE_MS;if(raw===void 0)return;let parsed=Number.parseInt(raw,10);return Number.isInteger(parsed)&&parsed>=0?parsed:void 0}var GIT_LOCK_SETTLE_MS=envSettleOverride()??300,KEPT_REASON_TEXT={"owner-not-proven-dead":"the process that last held the memory-write lock cannot be proven dead","repo-in-use":"a live process is still working in the repository, or that could not be ruled out","changed-during-settle":"it changed while it was being checked, so a git process is still using it","open-holder":"a process holds it open, or open holders could not be determined","unlink-failed":"it could not be removed"};class StrandedGitLockError extends GitError{kept;paths;constructor(kept){super(["Stranded git lock file(s) block the memory write:",...kept.map(({path,reason})=>`- ${path}: ${KEPT_REASON_TEXT[reason]}`),"They were kept because a git command or another session may still be using them, and removing a lock that is in use can corrupt the memory repository.","If no git command or other session is working on this memory, re-check and remove each one after confirming:",...kept.map(({path})=>` /memory unlock ${path}`)].join(`
|
|
14
|
+
`));this.kept=kept;this.paths=kept.map(({path})=>path)}}async function collectRefLockPaths(gitDir){let found=[],walk=async(dir)=>{for(let name of await readdir(dir).catch(()=>[])){let full=join15(dir,name),status=await lstat(full).catch(()=>{return});if(status===void 0)continue;if(status.isDirectory())await walk(full);else if(name.endsWith(".lock"))found.push(full)}};return await walk(join15(gitDir,"refs")),found}async function presentLockFiles(gitDir){let candidates=[join15(gitDir,"index.lock"),join15(gitDir,"HEAD.lock"),join15(gitDir,"packed-refs.lock"),join15(gitDir,"config.lock"),...await collectRefLockPaths(gitDir)],present=new Map;for(let candidate of candidates){let status=await lstat(candidate).catch(()=>{return});if(status?.isFile())present.set(candidate,{ino:status.ino,mtimeMs:status.mtimeMs})}return present}async function settledVerdict(candidate,before,holders,kernelVouches){let status=await lstat(candidate).catch(()=>{return});if(status===void 0||status.ino!==before.ino||status.mtimeMs!==before.mtimeMs)return"changed-during-settle";if(holders===null)return kernelVouches?"removable":"open-holder";return holders.length>0?"open-holder":"removable"}function writerLockPathForRepo(repoDir){let locksDir=identityLocksDirForRepo(repoDir);return locksDir===null?null:memoryWriterLockPath(locksDir)}async function authorizedPreviousOwner(repoDir){let writerLockPath=writerLockPathForRepo(repoDir);if(writerLockPath===null)return null;let raw=await readFile(writerLockPath,"utf8").catch(()=>{return}),current=raw===void 0?null:parseLockRecord(raw);if(current===null||current.pid!==process.pid||current.hostname!==hostname5())return null;let previous=provenDeadTakeoverFor(writerLockPath,current.nonce);return previous!==void 0&&await isLockOwnerProvenDead(previous)?previous:null}function keepAll(present,reason){return{removed:[],kept:[...present.keys()].map((path)=>({path,reason}))}}async function sweepStrandedGitLockFiles(dir,settleMs=GIT_LOCK_SETTLE_MS,scans=PRODUCTION_LOCK_SCANS){let present=await presentLockFiles(join15(dir,".git"));if(present.size===0)return{removed:[],kept:[]};let previous=await authorizedPreviousOwner(dir);if(previous===null)return keepAll(present,"owner-not-proven-dead");await new Promise((resolveSleep)=>setTimeout(resolveSleep,settleMs));let users=await scans.findRepoUsers(dir);if(users!==null&&users.length>0)return keepAll(present,"repo-in-use");let holders=new Map;for(let candidate of present.keys())holders.set(candidate,await scans.findHolders(candidate));let activity=await probeGitActivityIdle(dir);if(activity.kind==="busy")return keepAll(present,"repo-in-use");try{let kernelVouches=activity.kind==="idle"&&activity.vouches&&previous.git_activity_lock===!0;if(users===null&&!kernelVouches)return keepAll(present,"repo-in-use");let removed=[],kept=[];for(let[candidate,before]of present){let verdict=await settledVerdict(candidate,before,holders.get(candidate)??null,kernelVouches);if(verdict!=="removable"){kept.push({path:candidate,reason:verdict});continue}try{await unlink(candidate),removed.push(candidate)}catch{kept.push({path:candidate,reason:"unlink-failed"})}}return{removed,kept}}finally{if(activity.kind==="idle")await activity.release()}}async function withStrandedGitLockRecovery(dir,run,scans=PRODUCTION_LOCK_SCANS){try{return await withGitLockRetry(run)}catch(error){if(!isGitLockError(error))throw error;let report=await sweepStrandedGitLockFiles(dir,GIT_LOCK_SETTLE_MS,scans);if(report.removed.length===0){if(report.kept.length>0)throw new StrandedGitLockError(report.kept);throw error}return run()}}init_stable_log_output();async function landedAfterTimeout(reads,headBefore,message){let head=await reads.head();if(head===null||head===headBefore)return null;let parent=await reads.result(["rev-parse","--verify","--quiet",`${head}^`]);if((parent.code===0?parent.stdout.trim():null)!==headBefore)return null;let subject=await reads.result([...STABLE_LOG_OUTPUT,"log","-1","--format=%s",head]);return subject.code===0&&subject.stdout.trim()===(message.split(`
|
|
15
|
+
`)[0]??"").trim()?head:null}async function commitJudgedByOutcome(commit,reads,message){let headBefore=await reads.head();try{await commit();return}catch(error){if(!(error instanceof GitTimeoutError))throw error;let landed=await landedAfterTimeout(reads,headBefore,message);if(landed===null)throw error;return landed}}async function runMemoryRepoMaintenance(git,options){let looseObjectsBefore=await countLooseObjects(git);if(looseObjectsBefore<options.minLooseObjects)return{status:"skipped",looseObjects:looseObjectsBefore};return await git(["maintenance","run","--task=loose-objects","--quiet"],options.timeoutMs,options.signal),options.signal?.throwIfAborted(),await git(["prune-packed","--quiet"],options.timeoutMs,options.signal),{status:"packed",looseObjectsBefore,looseObjectsAfter:await countLooseObjects(git)}}async function countLooseObjects(git){let{stdout}=await git(["count-objects","-v"]),count=/^count: (\d+)$/m.exec(stdout)?.[1];return count===void 0?0:Number(count)}init_resilient();import{join as join16}from"node:path";async function ensureRepoConfigDefaults(port,run,authorName){let local=await readLocalConfig(run),configGet=(key)=>local===null?port.configGet(key):Promise.resolve(local.get(key.toLowerCase())??null);if(await configGet("omo.agentId")!==port.agentId)await port.configSet("omo.agentId",port.agentId);if(!await configGet("user.email"))await port.configSet("user.email",`${port.agentId}@omo.local`);if(!await configGet("user.name"))await port.configSet("user.name",authorName);if(await configGet("commit.gpgsign")===null)await port.configSet("commit.gpgsign","false");if(await configGet("gc.auto")===null)await port.configSet("gc.auto","0");if(await configGet("core.autocrlf")!=="false"&&await restoreConvertedCheckouts(port.dir,run).catch(()=>!1))await port.configSet("core.autocrlf","false")}async function readLocalConfig(run){let listing=await run.result(["config","--local","--list","-z"]);if(listing.code!==0)return null;let values=new Map;for(let entry of listing.stdout.split("\x00")){if(entry.length===0)continue;let newline=entry.indexOf(`
|
|
16
|
+
`),key=(newline<0?entry:entry.slice(0,newline)).toLowerCase(),value=newline<0?"":entry.slice(newline+1).trim();if(value.length>0)values.set(key,value);else values.delete(key)}return values}async function restoreConvertedCheckouts(dir,run){let listing=await run.result(["ls-files","--eol","-z"]);if(listing.code!==0)return!1;if(listing.stdout.length===0)return!0;try{for(let record of listing.stdout.split("\x00")){let tab=record.indexOf("\t");if(tab<0)continue;let[index,worktree]=record.slice(0,tab).trim().split(/\s+/);if(index!=="i/lf"||worktree!=="w/crlf"&&worktree!=="w/mixed")continue;let path=record.slice(tab+1),target=join16(dir,path),copy=await readFile(target).catch(()=>{return}),bytes=copy===void 0?void 0:dropCarriageReturnsBeforeLineFeeds(copy);if(bytes===void 0||!await matchesIndexBlob(run,path,bytes))continue;let{mode}=await stat(target);await writeFile2(`${target}.omo-eol.tmp`,bytes,{mode}),await rename2(`${target}.omo-eol.tmp`,target).catch(async(error)=>{throw await rm(`${target}.omo-eol.tmp`,{force:!0}),error})}}catch{return!1}return reindexUnchangedCopies(dir,run)}async function reindexUnchangedCopies(dir,run){let changed=await run.result(["diff-files","--name-only","-z"]);if(changed.code!==0)return!1;let unchanged=[];for(let path of new Set(changed.stdout.split("\x00").filter(Boolean))){let copy=await readFile(join16(dir,path)).catch(()=>{return});if(copy!==void 0&&await matchesIndexBlob(run,path,copy))unchanged.push(path)}if(unchanged.length===0)return!0;let input=unchanged.map((path)=>`${path}\x00`).join("");return(await run.result(["-c","core.autocrlf=false","update-index","-q","-z","--stdin"],input)).code===0}async function matchesIndexBlob(run,path,bytes){let blob=await run.result(["cat-file","blob",`:${path}`]);return blob.code===0&&Buffer.from(blob.stdout,"utf8").equals(bytes)}function dropCarriageReturnsBeforeLineFeeds(bytes){let out=Buffer.allocUnsafe(bytes.length),length=0;for(let index=0;index<bytes.length;index+=1){if(bytes[index]===13&&bytes[index+1]===10)continue;out[length]=bytes[index]??0,length+=1}return out.subarray(0,length)}init_resilient();init_stable_log_output();import{randomUUID as randomUUID7}from"node:crypto";import{isAbsolute as isAbsolute2,join as join17}from"node:path";var CACHE_SIZE=4,FULL_OBJECT_ID=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/,COMMIT_MARK="\x01",STORE_NAME="omo-path-commit-times.json",STORE_VERSION=2,FULL_WALK_TIMEOUT_MS=300000;class PathCommitTimes{dir;git;lsTree;computed=new Map;constructor(dir,git,lsTree){this.dir=dir;this.git=git;this.lsTree=lsTree}async at(revision){let oid=FULL_OBJECT_ID.test(revision)?revision:await this.resolve(revision),cached=this.computed.get(oid);if(cached!==void 0)return this.computed.delete(oid),this.computed.set(oid,cached),(await cached).live;let bases=[...this.computed.entries()].reverse(),pending=this.compute(oid,bases);this.computed.set(oid,pending),pending.catch(()=>{if(this.computed.get(oid)===pending)this.computed.delete(oid)});let oldest=this.computed.keys().next().value;if(this.computed.size>CACHE_SIZE&&oldest!==void 0)this.computed.delete(oldest);return(await pending).live}async resolve(revision){return(await this.git.run(["rev-parse","--verify",`${revision}^{commit}`])).stdout.trim()}async compute(oid,bases){let present=await this.lsTree(oid),all=await this.reachableTimes(oid,bases);return{all,live:liveTimes(present,all)}}async reachableTimes(oid,bases){let stored=await this.readStore(),candidates=[...bases.map(([base,computed])=>[base,()=>computed.then((value)=>value.all,()=>null)]),...stored===null?[]:[[stored.revision,async()=>stored.times]]];for(let[base,load]of candidates){if(base===oid){let times=await load();if(times!==null)return times;continue}if(!await this.isAncestor(base,oid))continue;let times=await load();if(times===null)continue;let result=maxTimes(times,parseLogTimes((await this.log([`${base}..${oid}`])).stdout));if(base===stored?.revision)await this.writeStore(oid,result);return result}let result=parseLogTimes((await this.log([oid],FULL_WALK_TIMEOUT_MS)).stdout);if(stored===null||await this.isAncestor(stored.revision,oid))await this.writeStore(oid,result);return result}log(range,timeoutMs){return this.git.run([...STABLE_LOG_OUTPUT,"log","--format=%x01%ct","--name-only","-z","--no-renames","--diff-merges=first-parent","--diff-filter=d",...range,"--"],timeoutMs)}async isAncestor(ancestor,descendant){return(await this.git.result(["merge-base","--is-ancestor",ancestor,descendant])).code===0}async storePath(){let common=(await this.git.run(["rev-parse","--git-common-dir"])).stdout.trim();return join17(isAbsolute2(common)?common:join17(this.dir,common),STORE_NAME)}async readStore(){let parsed;try{parsed=JSON.parse(await readFile(await this.storePath(),"utf8"))}catch{return null}if(typeof parsed!=="object"||parsed===null)return null;let{version,revision,times}=parsed;if(version!==STORE_VERSION||typeof revision!=="string"||!FULL_OBJECT_ID.test(revision))return null;if(typeof times!=="object"||times===null||Array.isArray(times))return null;let entries=Object.entries(times);if(!entries.every((entry)=>Number.isSafeInteger(entry[1])))return null;return{revision,times:new Map(entries)}}async writeStore(revision,times){let temp;try{let path=await this.storePath();temp=`${path}.${process.pid}.${randomUUID7()}.tmp`,await writeFile2(temp,`${JSON.stringify({version:STORE_VERSION,revision,times:Object.fromEntries(times)})}
|
|
17
|
+
`,"utf8"),await rename2(temp,path)}catch{if(temp!==void 0)await rm(temp,{force:!0}).catch(()=>{return})}}}function parseLogTimes(stdout){let times=new Map,committedAt=Number.NaN;for(let token of stdout.split("\x00")){if(token.startsWith(COMMIT_MARK)){committedAt=Number.parseInt(token.slice(1),10);continue}let path=token.replace(/^\n/,"");if(path.length===0||!Number.isSafeInteger(committedAt))continue;times.set(path,Math.max(times.get(path)??committedAt,committedAt))}return times}function maxTimes(base,added){let merged=new Map(base);for(let[path,time]of added)merged.set(path,Math.max(merged.get(path)??time,time));return merged}function liveTimes(present,all){let times=new Map;for(let path of present){let time=all.get(path);if(time!==void 0)times.set(path,time)}return times}init_resilient();import{join as join18,resolve as resolve7}from"node:path";var files=new Map,FILE_CACHE_SIZE=256,OBJECT_ID=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/,REPO_ENV=["GIT_DIR","GIT_COMMON_DIR","GIT_WORK_TREE","GIT_NAMESPACE","GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"];function readHeadFromFiles(repoDir){if(REPO_ENV.some((key)=>process.env[key]!==void 0))return;try{let marker=resolve7(repoDir,".git"),markerStat=lstatSync(marker,{bigint:!0,throwIfNoEntry:!1}),gitDir=marker;if(markerStat?.isFile()){let pointer=readText2(marker),target=typeof pointer==="string"?/^gitdir: ([^\r\n]+)\r?\n?$/.exec(pointer)?.[1]:void 0;if(target===void 0)return;gitDir=resolve7(repoDir,target)}else if(!markerStat?.isDirectory())return;let common=readText2(join18(gitDir,"commondir"));if(common===null||common===""||common!==void 0&&!/^[^\r\n]+\r?\n?$/.test(common))return;let commonDir=common===void 0?gitDir:resolve7(gitDir,common.trim()),config=readText2(join18(commonDir,"config"));if(typeof config!=="string"||/^\s*(?:\[include(?:if)?\b|(?:refstorage|worktreeconfig)\s*(?:=|$))/im.test(config))return;if([gitDir,commonDir].some((dir)=>lstatSync(join18(dir,"config.worktree"),{throwIfNoEntry:!1})!==void 0))return;if(lstatSync(join18(commonDir,"reftable"),{throwIfNoEntry:!1})!==void 0)return;if(!lstatSync(join18(commonDir,"objects"),{throwIfNoEntry:!1})?.isDirectory())return;let head=readText2(join18(gitDir,"HEAD"));if(typeof head!=="string")return;let detached=objectId(head);if(detached!==void 0)return detached;let ref=/^ref: (refs\/heads\/[A-Za-z0-9_./-]+)\r?\n?$/.exec(head)?.[1];if(ref===void 0||ref.includes("..")||ref.split("/").some((part)=>!part||part.startsWith(".")||part.endsWith(".")||part.endsWith(".lock")))return;let loose=readText2(join18(commonDir,ref));if(loose!==void 0)return typeof loose==="string"?objectId(loose):void 0;let packed=readText2(join18(commonDir,"packed-refs"));if(typeof packed!=="string")return;let found;for(let line of packed.split(/\r?\n/)){if(line===""||line.startsWith("#"))continue;if(line.startsWith("^")&&OBJECT_ID.test(line.slice(1)))continue;let entry=/^([0-9a-f]{40}|[0-9a-f]{64}) (refs\/\S+)$/.exec(line);if(entry===null)return;if(entry[2]===ref){if(found!==void 0)return;found=entry[1]}}return found}catch(error){if(error instanceof Error&&"code"in error)return;throw error}}function objectId(text){let value=text.replace(/\r?\n$/,"");return OBJECT_ID.test(value)?value:void 0}function stamp(stats){return`${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`}function readText2(path){let stats=lstatSync(path,{bigint:!0,throwIfNoEntry:!1});if(stats===void 0){files.delete(path);return}if(!stats.isFile())return null;let current=stamp(stats),cached=files.get(path);if(cached?.stamp===current)return files.delete(path),files.set(path,cached),cached.text;let text=readFileSync(path,"utf8"),after=lstatSync(path,{bigint:!0,throwIfNoEntry:!1});if(after===void 0||stamp(after)!==current)return null;files.set(path,{stamp:current,text});let oldest=files.keys().next().value;if(files.size>FILE_CACHE_SIZE&&oldest!==void 0)files.delete(oldest);return text}function parseLogOutput(output){return output.split("\x1E").slice(1).map((record)=>parseRecord(record.split("\x1F")))}function parseLogOutputWithPaths(output){return output.split("\x1E").slice(1).map((record)=>{let fields=record.split("\x1F"),[committedAt="",...paths]=(fields.pop()??"").split("\x00");return{...parseRecord([...fields,committedAt]),paths:paths.map((path)=>path.replace(/^\n/,"")).filter(Boolean)}})}function parseRecord(fields){let[sha="",subject="",body="",authorName="",authorEmail="",committedAt=""]=fields,normalizedBody=body.replace(/\r?\n$/,"");return{sha,subject,body:normalizedBody,authorName,authorEmail,committedAt:committedAt.trim(),trailers:parseTrailers(normalizedBody)}}function parseTrailers(body){let trailers={};for(let line of body.split(/\r?\n/)){let match=/^([^:\s][^:]*):\s*(.*)$/.exec(line);if(match===null)continue;let key=match[1]?.trim();if(key!==void 0&&key.length>0)trailers[key]=match[2]??""}return trailers}function parseLsTreeSized(stdout){let entries=[];for(let record of stdout.split("\x00")){if(record.length===0)continue;let tab=record.indexOf("\t");if(tab===-1)continue;let meta=record.slice(0,tab).trim().split(/\s+/),path=record.slice(tab+1);if(meta.length<4||path.length===0)continue;let size=meta[3];if(size===void 0||size==="-")continue;let bytes=Number.parseInt(size,10);if(!Number.isSafeInteger(bytes)||bytes<0)continue;entries.push({path,bytes})}return entries}function parseLsTreeBlobs(stdout){let entries=[];for(let record of stdout.split("\x00")){let tab=record.indexOf("\t");if(tab===-1)continue;let[,type,oid]=record.slice(0,tab).trim().split(/\s+/),path=record.slice(tab+1);if(type!=="blob"||oid===void 0||path.length===0)continue;entries.push({path,oid})}return entries}function parseCatFileBatch(output){let blobs=new Map,offset=0;while(offset<output.length){let newline=output.indexOf(10,offset);if(newline===-1)throw Error("git cat-file --batch output ended inside a record header");let header=output.toString("utf8",offset,newline);offset=newline+1;let[oid,type,sizeText]=header.split(" ");if(sizeText===void 0)continue;let size=Number.parseInt(sizeText,10);if(oid===void 0||!Number.isSafeInteger(size)||size<0||offset+size>output.length)throw Error(`git cat-file --batch output is malformed at "${header}"`);if(type==="blob")blobs.set(oid,output.toString("utf8",offset,offset+size));offset+=size+1}return blobs}init_stable_log_output();class GitRevisionReads{git;constructor(git){this.git=git}async head(){let cached=this.git.dir===void 0?void 0:readHeadFromFiles(this.git.dir);if(cached!==void 0)return cached;let result=await this.git.result(["rev-parse","--verify","HEAD"]);if(result.code!==0)return null;return result.stdout.trim()||null}async headCommitTimestamp(){let result=await this.git.result([...STABLE_LOG_OUTPUT,"show","-s","--format=%ct","HEAD"]);if(result.code!==0)return null;let timestamp=Number.parseInt(result.stdout.trim(),10);return Number.isSafeInteger(timestamp)&×tamp>=0?timestamp:null}async lsTree(revision="HEAD",path){let suffix=path?["--",path]:[];return(await this.git.run(["ls-tree","-r","--name-only","-z",revision,...suffix])).stdout.split("\x00").filter(Boolean)}async lsTreeSized(revision="HEAD"){return parseLsTreeSized((await this.git.run(["ls-tree","-r","-l","-z",revision])).stdout)}async lsTreeBlobs(revision="HEAD"){return parseLsTreeBlobs((await this.git.run(["ls-tree","-r","-z",revision])).stdout)}async show(revision,path){return(await this.git.run(["show",`${revision}:${path}`])).stdout}async readBlobs(oids){let unique=[...new Set(oids)];if(unique.length===0)return new Map;let argv=["cat-file","--batch"],result=await this.git.result(argv,`${unique.join(`
|
|
18
|
+
`)}
|
|
19
|
+
`);if(result.code!==0)throw commandError(argv,result);return parseCatFileBatch(result.stdoutBytes??Buffer.from(result.stdout,"utf8"))}async log(options={}){let includePaths=options.includePaths===!0,argv=includePaths?[...STABLE_LOG_OUTPUT,"-c","log.showRoot=false","log","--format=%x1e%H%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%cI","--name-only","-z","--no-renames","--full-diff"]:[...STABLE_LOG_OUTPUT,"log","--format=%x1e%H%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%cI"];if(options.grep!==void 0&&options.grep.length>0)argv.push("--fixed-strings","--all-match",...options.grep.map((pattern)=>`--grep=${pattern}`));if(options.limit!==void 0)argv.push("-n",String(options.limit));if(options.since!==void 0)argv.push(`--since=${options.since.toISOString()}`);if(options.range!==void 0)argv.push(options.range);if(options.paths!==void 0&&options.paths.length>0)argv.push("--",...options.paths);let{stdout}=await this.git.run(argv,options.timeoutMs);return includePaths?parseLogOutputWithPaths(stdout):parseLogOutput(stdout)}}async function assertNoUnrelatedChanges(dir,paths,status){let unrelated=(await status()).split(/\r?\n/).filter(Boolean).filter((line)=>{let path=parsePorcelainPath(line);return path!==null&&!paths.some((allowed)=>path===allowed||path.startsWith(`${allowed}/`)||allowed.startsWith(path.endsWith("/")?path:`${path}/`))});if(unrelated.length===0)return;let listing=`${unrelated.join(`
|
|
20
|
+
`)}
|
|
21
|
+
`;throw new DirtyRepoError(listing,describeDirtyMarkdownEncodingIssues(dir,listing))}init_resilient();import{join as join19}from"node:path";var PENDING_ROLLBACK="omo-pending-rollback.json";class PendingRollbackEditsKeptError extends Error{paths;constructor(paths){super(`An earlier memory write that failed behind a git lock was unstaged, but ${paths.join(", ")} changed after that failure, so the current file contents were kept as they are. Commit or discard those edits, then retry the memory write.`);this.paths=paths;this.name="PendingRollbackEditsKeptError"}}function markerPath(dir){return join19(dir,".git",PENDING_ROLLBACK)}function parsePending(raw){try{let value=JSON.parse(raw);if(typeof value!=="object"||value===null)return null;let{head,paths}=value;if(typeof head!=="string"||!Array.isArray(paths)||!paths.every((path)=>typeof path==="string"))return null;return{head,paths}}catch{return null}}async function settlePendingRollback(repo){let raw=await readFile(markerPath(repo.dir),"utf8").catch(()=>{return});if(raw===void 0||existsSync(join19(repo.dir,".git","index.lock")))return;let pending=parsePending(raw);if(pending===null||await repo.head()!==pending.head||pending.paths.length===0){await rm(markerPath(repo.dir),{force:!0});return}let atHead=new Set(await repo.lsTree("HEAD"));if(await repo.unstage(pending.paths.filter((path)=>atHead.has(path)),pending.paths.filter((path)=>!atHead.has(path))),await rm(markerPath(repo.dir),{force:!0}),(await repo.status(pending.paths)).trim().length>0)throw new PendingRollbackEditsKeptError(pending.paths)}init_redact();class MemorySecretError extends Error{name="MemorySecretError";path;patternClass;where;constructor(options){super(options.where==="path"?`refused: ${redactSecretLikeMaterial(options.path)} is a secret-like file name (${options.patternClass})`:`refused: ${options.path} contains secret-like content (${options.patternClass}); remove it and retry`);this.path=options.path,this.patternClass=options.patternClass,this.where=options.where}}function secretPatternClassOf(text){return scanSecretLikeMaterial(text)[0]?.class}async function assertNoSecretLikeStaging(paths,gitResult){for(let path of paths){let patternClass=secretPatternClassOf(path);if(patternClass!==void 0)throw new MemorySecretError({path,patternClass,where:"path"})}for(let path of paths){let result=await gitResult(["show",`:${path}`]);if(result.code!==0)continue;let patternClass=secretPatternClassOf(result.stdout);if(patternClass!==void 0)throw new MemorySecretError({path,patternClass,where:"content"})}}import{resolve as resolve8}from"node:path";var worktreeMutationQueues=new Map;async function withSerializedGitWorktreeMutation(dir,mutate){let key=resolve8(dir),task=(worktreeMutationQueues.get(key)?.then(()=>{return},()=>{return})??Promise.resolve()).then(mutate),settled=task.then(()=>{return},()=>{return});worktreeMutationQueues.set(key,settled);try{return await task}finally{if(worktreeMutationQueues.get(key)===settled)worktreeMutationQueues.delete(key)}}var GIT_TIMEOUT_MS3=30000,COMMIT_TIMEOUT_MS=120000,INITIAL_COMMIT="chore: initialize local memory",EMPTY_INITIAL_COMMIT="chore: initialize empty local memory";class GitMemoryRepo{dir;agentId;pathState;exec;hookInstaller;reads;commitTimes;commitTimeoutMs;constructor(options){this.dir=options.dir,this.agentId=options.agentId,this.exec=options.exec??createNodeGitExec(),this.pathState=new GitPathStateStore(this.dir,this.exec),this.hookInstaller=options.installHooks??(()=>{return}),this.commitTimeoutMs=options.commitTimeoutMs??COMMIT_TIMEOUT_MS,this.reads=new GitRevisionReads({dir:this.dir,run:(argv,timeoutMs)=>this.git(argv,timeoutMs),result:(argv,stdin)=>this.gitResult(argv,stdin)}),this.commitTimes=new PathCommitTimes(this.dir,{run:(argv,timeoutMs)=>this.git(argv,timeoutMs),result:(argv,stdin)=>this.gitResult(argv,stdin)},(revision)=>this.reads.lsTree(revision))}async init(options={}){if(await mkdir(this.dir,{recursive:!0}),!existsSync(join20(this.dir,".git")))await withGitLockRetry(()=>this.git(["init","--template="])),await withGitLockRetry(()=>this.git(["symbolic-ref","HEAD","refs/heads/main"]));await(options.installHooks??this.hookInstaller)(this.dir),await this.ensureIdentity(options.authorName?.trim()||"OmO Agent");let currentHead=await this.head();if(currentHead)return currentHead;let paths=[];for(let seed of options.seedFiles??[]){let relativePath=normalizeSeedPath(seed.relativePath),fullPath=join20(this.dir,relativePath);await mkdir(dirname4(fullPath),{recursive:!0}),await writeFile2(fullPath,seed.content,"utf8"),paths.push(relativePath)}let author={agentId:this.agentId,authorName:options.authorName?.trim()||"OmO Agent"};if(paths.length>0){if(await this.stage(paths),await this.hasPathChanges(paths))return(await this.commitStaged(INITIAL_COMMIT,author)).sha}return await withStrandedGitLockRecovery(this.dir,()=>this.git([...NO_AUTO_MAINTENANCE,...authorFlags(author),"commit","--allow-empty","-m",EMPTY_INITIAL_COMMIT])),this.requireHead()}async cleanCheck(){await this.hookInstaller(this.dir),await settlePendingRollback(this);let porcelain=await this.status();if(!porcelain.trim())return;throw new DirtyRepoError(porcelain,describeDirtyMarkdownEncodingIssues(this.dir,porcelain))}async commitWrite(paths,reason,author){await this.hookInstaller(this.dir);let normalized=normalizePathspecs(paths);if(normalized.length===0)throw new NoEffectiveChangesError(normalized);return await settlePendingRollback(this),await assertNoUnrelatedChanges(this.dir,normalized,()=>this.status()),await this.stage(normalized),this.commitPrepared(normalized,reason,author)}async commitPrepared(paths,reason,author){await this.hookInstaller(this.dir);let normalized=normalizePathspecs(paths);if(normalized.length===0)throw new NoEffectiveChangesError(normalized);if(await settlePendingRollback(this),await assertNoUnrelatedChanges(this.dir,normalized,()=>this.status()),!await this.hasPathChanges(normalized))throw new NoEffectiveChangesError(normalized);return await assertNoSecretLikeStaging(normalized,(argv)=>this.gitResult(argv)),this.commitStaged(reason,author)}async status(paths=[]){let normalized=normalizePathspecs(paths),suffix=normalized.length>0?["--",...normalized]:[];return(await this.git(["-c","core.quotePath=false","status","--porcelain","--untracked-files=all",...suffix])).stdout}head(){return this.reads.head()}headCommitTimestamp(){return this.reads.headCommitTimestamp()}lsTree(revision="HEAD",path){return this.reads.lsTree(revision,path)}lsTreeSized(revision="HEAD"){return this.reads.lsTreeSized(revision)}lsTreeBlobs(revision="HEAD"){return this.reads.lsTreeBlobs(revision)}show(revision,path){return this.reads.show(revision,path)}pathCommitTimes(revision){return this.commitTimes.at(revision)}readBlobs(oids){return this.reads.readBlobs(oids)}log(options={}){return this.reads.log(options)}async restorePaths(paths){let normalized=normalizePathspecs(paths);if(normalized.length===0)return;let atHead=new Set(await this.lsTree("HEAD")),tracked=normalized.filter((path)=>atHead.has(path)),untracked=normalized.filter((path)=>!atHead.has(path));if(tracked.length>0)await withStrandedGitLockRecovery(this.dir,()=>this.git(["restore","--source=HEAD","--staged","--worktree","--",...tracked]));for(let path of untracked)await withStrandedGitLockRecovery(this.dir,()=>this.git(["rm","-q","--cached","--ignore-unmatch","--",path])),await rm(join20(this.dir,path),{force:!0})}async unstage(tracked,untracked){if(tracked.length>0)await withStrandedGitLockRecovery(this.dir,()=>this.git(["restore","--source=HEAD","--staged","--",...tracked]));if(untracked.length>0)await withStrandedGitLockRecovery(this.dir,()=>this.git(["rm","-q","--cached","-f","--ignore-unmatch","--",...untracked]))}maintain(options){return runMemoryRepoMaintenance((argv,timeoutMs,signal)=>this.git(argv,timeoutMs,signal),options)}async worktreeAdd(path,branch,startPoint="HEAD"){await withSerializedGitWorktreeMutation(this.dir,()=>withGitLockRetry(()=>this.git(["worktree","add","-b",branch,path,startPoint])))}async worktreeRemove(path,force=!0){await withSerializedGitWorktreeMutation(this.dir,()=>withGitLockRetry(()=>this.git(["worktree","remove",...force?["--force"]:[],path])))}async merge(ref,options={}){let argv=[...NO_AUTO_MAINTENANCE,"merge"];if(options.noFF??!0)argv.push("--no-ff");if(options.message)argv.push("-m",options.message);return argv.push(ref),await withStrandedGitLockRecovery(this.dir,()=>this.git(argv)),this.requireHead()}async configGet(key){let result=await this.gitResult(["config","--local","--get",key]);if(result.code===1)return null;if(result.code!==0)throw commandError(["config","--local","--get",key],result);return result.stdout.trim()||null}async configSet(key,value){await withSerializedGitConfigMutation(this.dir,async()=>{await this.git(["config","--local",key,value])})}ensureIdentity(authorName){return ensureRepoConfigDefaults(this,{result:(argv,stdin)=>this.gitResult(argv,stdin)},authorName)}async stage(paths){await withStrandedGitLockRecovery(this.dir,()=>this.git(["add","-A","--",...paths]))}async hasPathChanges(paths){return(await this.status(paths)).trim().length>0}async commitStaged(reason,author){return{committed:!0,sha:await commitJudgedByOutcome(()=>withStrandedGitLockRecovery(this.dir,()=>this.git([...NO_AUTO_MAINTENANCE,...authorFlags(author),"commit","-m",reason],this.commitTimeoutMs)),{head:()=>this.head(),result:(argv)=>this.gitResult(argv)},reason)??await this.requireHead()}}async requireHead(){let head=await this.head();if(!head)throw Error("Memory repository has no HEAD commit");return head}async git(argv,timeoutMs,signal){let result=await this.gitResult(argv,void 0,timeoutMs,signal);if(result.code!==0)throw commandError(argv,result);return result}gitResult(argv,stdin,timeoutMs=GIT_TIMEOUT_MS3,signal){return this.exec.run(argv,{cwd:this.dir,timeoutMs,...signal===void 0?{}:{signal},env:{...process.env,GIT_TERMINAL_PROMPT:"0"},...stdin===void 0?{}:{stdin}})}}init_resilient();init_resilient();init_resilient();import{basename as basename3,isAbsolute as isAbsolute3,join as join21,resolve as resolve9}from"node:path";init_resilient();init_frontmatter_scalar();init_frontmatter_validation();init_paths();init_redact();init_completion_repair();init_stable_log_output();init_redact();init_completion_repair();init_resilient();init_stable_log_output();init_frontmatter();init_frontmatter_scalar();init_frontmatter_validation();init_paths();init_redact();init_resilient();init_resilient();init_stable_log_output();var GIT_TIMEOUT_MS4=30000;async function discardReflectionWorktree(repo,dir,branch,exec=createNodeGitExec()){return removeWorktreeAndBranch(repo,dir,branch,exec)}async function removeWorktreeAndBranch(repo,dir,branch,exec){await repo.worktreeRemove(dir,!0).catch(()=>{return}),await rm(dir,{recursive:!0,force:!0}).catch(()=>{return}),await run(exec,repo.dir,["worktree","prune"]),await run(exec,repo.dir,["branch","-D",branch]);let listed=await run(exec,repo.dir,["worktree","list","--porcelain"]),branchRef=await run(exec,repo.dir,["show-ref","--verify",`refs/heads/${branch}`]);return{worktreeRemoved:!existsSync(dir)&&!listed.stdout.split(/\r?\n/).includes(`worktree ${resolve9(dir)}`),branchRemoved:branchRef.code!==0}}function run(exec,cwd,argv){return exec.run(argv,{cwd,timeoutMs:GIT_TIMEOUT_MS4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}var GIT_TIMEOUT_MS5=30000,REFLECTION_BRANCH_PREFIX="memory/reflection-",LEGACY_BRANCH_PREFIX="reflection/run-",REFLECTION_ORPHAN_GRACE_MS=900000;async function listReflectionLeftovers(repo,worktreesDir,exec=createNodeGitExec()){let root=resolve10(worktreesDir),listed=await git2(exec,repo.dir,["worktree","list","--porcelain"]),registeredWorktrees=parseRegisteredWorktrees(listed.stdout).filter((worktree)=>isInside(root,worktree.dir)),registered=new Set(registeredWorktrees.map((worktree)=>worktree.dir)),strayDirs=(await directoryNames(root)).filter((name)=>/^\d+-/.test(name)).map((name)=>join22(root,name)).filter((dir)=>!registered.has(dir)),branches=(await git2(exec,repo.dir,["for-each-ref","--format=%(refname:short)",`refs/heads/${REFLECTION_BRANCH_PREFIX}*`,`refs/heads/${LEGACY_BRANCH_PREFIX}*`])).stdout.split(/\r?\n/).map((line)=>line.trim()).filter(isReflectionBranch);return{registeredWorktrees,strayDirs,branches}}function selectReflectionOrphans(leftovers,selection){let graceMs=selection.graceMs??REFLECTION_ORPHAN_GRACE_MS,isOrphan=(name,present)=>{let owner=parseReflectionOwner(name);if(owner===void 0||isLive(selection.liveRunIds,owner.runId))return!1;if(!present)return!0;return owner.epoch===void 0||owner.epoch<=selection.now-graceMs};return{registeredWorktrees:leftovers.registeredWorktrees.filter((worktree)=>isOrphan(basename4(worktree.dir),worktree.present)),strayDirs:leftovers.strayDirs.filter((dir)=>isOrphan(basename4(dir),!0)),branches:leftovers.branches.filter((branch)=>isOrphan(branch,!0))}}async function sweepReflectionOrphans(repo,worktreesDir,options){let exec=options.exec??createNodeGitExec(),root=resolve10(worktreesDir),orphans=selectReflectionOrphans(await listReflectionLeftovers(repo,root,exec),options),receipts=[],discarded=new Set;for(let worktree of orphans.registeredWorktrees){let branch=worktree.branch??`${REFLECTION_BRANCH_PREFIX}${basename4(worktree.dir)}`;discarded.add(branch),receipts.push(await attempt2("worktree",worktree.dir,async()=>{let cleanup=await discardReflectionWorktree(repo,worktree.dir,branch,exec);return cleanup.worktreeRemoved&&cleanup.branchRemoved}))}for(let dir of orphans.strayDirs)receipts.push(await attempt2("directory",dir,async()=>{if(!isInside(root,resolve10(dir)))throw Error(`Refusing to remove ${dir} outside ${root}`);return await rm(dir,{recursive:!0,force:!0}),!existsSync(dir)}));if(orphans.strayDirs.length>0)await run2(exec,repo.dir,["worktree","prune"]);for(let branch of orphans.branches){if(discarded.has(branch))continue;receipts.push(await attempt2("branch",branch,async()=>(await run2(exec,repo.dir,["branch","-D",branch]),(await run2(exec,repo.dir,["show-ref","--verify",`refs/heads/${branch}`])).code!==0)))}return receipts}function parseReflectionOwner(name){if(name.startsWith(LEGACY_BRANCH_PREFIX))return{runId:name.slice(11)};let suffix=name.startsWith(REFLECTION_BRANCH_PREFIX)?name.slice(REFLECTION_BRANCH_PREFIX.length):name,parsed=/^(\d+)-(.+)$/.exec(suffix);return parsed===null?void 0:{runId:parsed[2],epoch:Number(parsed[1])}}function isLive(liveRunIds,runId){return liveRunIds.has(runId)||liveRunIds.has(`reflection-${runId}`)}function isReflectionBranch(branch){return branch.startsWith(REFLECTION_BRANCH_PREFIX)||branch.startsWith(LEGACY_BRANCH_PREFIX)}function parseRegisteredWorktrees(porcelain){let worktrees=[],dir,branch,flush=()=>{if(dir!==void 0)worktrees.push({dir,...branch===void 0?{}:{branch},present:existsSync(dir)});dir=void 0,branch=void 0};for(let line of porcelain.split(/\r?\n/))if(line.startsWith("worktree "))flush(),dir=resolve10(line.slice(9).trim());else if(line.startsWith("branch refs/heads/"))branch=line.slice(18).trim();return flush(),worktrees}function isInside(root,path){let offset=relative(root,path);return offset!==""&&!offset.startsWith("..")&&!isAbsolute4(offset)}async function attempt2(kind,target,operation){try{return{kind,target,removed:await operation()}}catch(error){return{kind,target,removed:!1,detail:error instanceof Error?error.message:String(error)}}}async function directoryNames(path){try{return(await readdir(path,{withFileTypes:!0})).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort()}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return[];throw error}}async function git2(exec,cwd,argv){let result=await run2(exec,cwd,argv);if(result.code!==0)throw Error(result.stderr.trim()||`git ${argv.join(" ")} failed`);return result}function run2(exec,cwd,argv){return exec.run(argv,{cwd,timeoutMs:GIT_TIMEOUT_MS5,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}import{join as join23}from"node:path";var QUARANTINE_FILENAME="quarantined.json",RESERVATION_EVIDENCE_FILENAME="reservation.quarantined.json";async function writeQuarantine(runDir,record,reservation){if(reservation!==void 0)await writeJsonAtomic(join23(runDir,RESERVATION_EVIDENCE_FILENAME),reservation);await writeJsonAtomic(join23(runDir,QUARANTINE_FILENAME),record)}init_resilient();import{randomUUID as randomUUID8}from"node:crypto";import{dirname as dirname5,join as join24}from"node:path";class RunTerminalClaimUnrecoverableError extends Error{runDir;constructor(runDir,options){super(`Run terminal claim cannot be recovered in ${runDir}`,options);this.runDir=runDir;this.name="RunTerminalClaimUnrecoverableError"}}function runTerminalClaimPath(runDir){return join24(runDir,"terminal-claim.json")}async function claimRunTerminal(runDir,identity,kind,seams={},claimantPid=process.pid){let path=runTerminalClaimPath(runDir),requested={version:1,kind,runId:identity.runId,attempt:identity.attempt,claimantPid},discarded=0;for(;;){if(createExclusiveClaim(path,requested))return requested;let snapshot;try{snapshot=readClaimSnapshot(path)}catch(error){throw new RunTerminalClaimUnrecoverableError(runDir,{cause:error})}if(snapshot===void 0)continue;let existing=snapshot.claim;if(existing===void 0){if(discarded>0)throw new RunTerminalClaimUnrecoverableError(runDir);discarded+=1,await seams.beforeRecovery?.("invalid");let replacement=await recoverClaim(runDir,path,snapshot,"invalid",identity,seams);if(replacement!==void 0)return replacement;continue}if(runTerminalClaimMatches(existing,identity,kind))return existing;if(existing.kind!=="publish"||!claimantIsConfirmedDead(existing,seams))return existing;await seams.beforeRecovery?.("dead-publish");let replacement=await recoverClaim(runDir,path,snapshot,"dead-publish",identity,seams);if(replacement!==void 0)return replacement}}function runTerminalClaimMatches(claim,identity,kind){return claim.runId===identity.runId&&claim.attempt===identity.attempt&&(kind===void 0||claim.kind===kind)}function createExclusiveClaim(path,claim){let candidate=`${path}.${process.pid}.${randomUUID8()}.candidate`;writeDurableClaim(candidate,claim);try{linkSync(candidate,path)}catch(error){if(errorCode12(error)==="EEXIST")return!1;throw error}finally{removeClaim(candidate)}return syncDirectory2(dirname5(path)),!0}function writeDurableClaim(path,claim){let file=openSync2(path,"wx",384);try{writeFileSync(file,`${JSON.stringify(claim,null,2)}
|
|
22
|
+
`,"utf8"),fsyncSync(file)}finally{closeSync2(file)}}function readClaimSnapshot(path){let raw;try{raw=readFileSync(path,"utf8")}catch(error){if(errorCode12(error)==="ENOENT")return;throw error}try{return{raw,claim:parseRunTerminalClaim(JSON.parse(raw))}}catch{return{raw,claim:void 0}}}async function recoverClaim(runDir,claimPath,inspected,reason,identity,seams){let record=await createLockRecord("reflection-finalize",{runId:identity.runId});return withLock(join24(runDir,"terminal-claim-recovery.lock"),record,async()=>{let current=readClaimSnapshot(claimPath);if(current===void 0)return;if(current.raw!==inspected.raw)return current.claim;if(reason==="invalid"){if(current.claim!==void 0)return current.claim}else{if(current.claim===void 0)return;if(current.claim.kind!=="publish"||!claimantIsConfirmedDead(current.claim,seams))return current.claim}removeClaim(claimPath);return},{waitTimeoutMs:Number.POSITIVE_INFINITY})}function removeClaim(path){try{unlinkSync(path)}catch(error){if(errorCode12(error)!=="ENOENT")throw error}}function claimantIsConfirmedDead(claim,seams){return(seams.getPidLiveness??getPidLiveness)(claim.claimantPid)==="dead"}function parseRunTerminalClaim(value){if(!isRecord(value)||value.version!==1||value.kind!=="publish"&&value.kind!=="abandon"||typeof value.runId!=="string"||!Number.isInteger(value.attempt)||!Number.isInteger(value.claimantPid)||Number(value.claimantPid)<=0)throw TypeError("Invalid run terminal claim");return{version:1,kind:value.kind,runId:value.runId,attempt:Number(value.attempt),claimantPid:Number(value.claimantPid)}}function syncDirectory2(path){let directory;try{directory=openSync2(path,"r")}catch(error){if(process.platform==="win32"&&["EISDIR","EPERM"].includes(errorCode12(error)??""))return;throw error}try{fsyncSync(directory)}catch(error){if(process.platform!=="win32"||!["EPERM","EACCES","EINVAL"].includes(errorCode12(error)??""))throw error}finally{closeSync2(directory)}}function errorCode12(error){return error instanceof Error&&"code"in error?String(error.code):void 0}function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function readRunTerminalPublication(runDir,attempt){for(let name of["final.json","abandoned.json","quarantined.json"])if(fileExists(join24(runDir,name)))return"settled";let outcome=readJsonFile(join24(runDir,"outcome.json"));if(outcome!==void 0&&outcome.attempt===attempt)return"finalize";let publishing=readJsonFile(join24(runDir,"publishing.json"));if(publishing!==void 0&&publishing.version===1&&publishing.attempt===attempt)return"veto";return}function fileExists(path){try{return readFileSync(path),!0}catch(error){if(errorCode12(error)==="ENOENT")return!1;throw error}}function readJsonFile(path){let raw;try{raw=readFileSync(path,"utf8")}catch(error){if(errorCode12(error)==="ENOENT")return;throw error}try{let value=JSON.parse(raw);return isRecord(value)?value:{}}catch{return{}}}init_resilient();import{join as join27}from"node:path";init_resilient();import{randomUUID as randomUUID9}from"node:crypto";import{join as join25}from"node:path";import{Buffer as Buffer4}from"node:buffer";var REFLECTION_STATE_SCHEMA_VERSION="v3_assistant_steps",REFLECTION_SNAPSHOT_MAX_BYTES=131072;function entryBytes(entry){return Buffer4.byteLength(`${JSON.stringify(entry)}
|
|
23
|
+
`,"utf8")}function anchorRowIndex(entries,reflectedThroughMessageId){if(reflectedThroughMessageId===void 0)return-1;let anchor=-1;for(let[index,entry]of entries.entries())if(entry.source_message_id===reflectedThroughMessageId)anchor=index;return anchor}function isCanonicalEntry(entry){return(entry.kind==="user"||entry.kind==="assistant")&&entry.source_message_id.length>0&&entry.text.trim().length>0}function countCompletedSteps(entries){return entries.filter((entry)=>entry.kind==="assistant"&&entry.source_message_id.length>0&&entry.text.trim().length>0).length}function deriveState(state,entries){let totalCompletedSteps=countCompletedSteps(entries),reflectedCompletedSteps=Math.min(Math.max(0,Math.trunc(state.reflected_completed_steps)),totalCompletedSteps),anchorIndex=anchorRowIndex(entries,state.reflected_through_message_id);return{...state,schema_version:REFLECTION_STATE_SCHEMA_VERSION,total_completed_steps:totalCompletedSteps,reflected_completed_steps:reflectedCompletedSteps,steps_since_last_successful_reflection:Math.max(0,totalCompletedSteps-reflectedCompletedSteps),unreflected_bytes:entries.slice(anchorIndex+1).reduce((total,entry)=>total+entryBytes(entry),0)}}function captureCursorSnapshot(entries,state,options={}){let anchorIndex=anchorRowIndex(entries,state.reflected_through_message_id),startIndex=entries.findIndex((entry,index)=>index>anchorIndex&&isCanonicalEntry(entry));if(startIndex<0)return null;let start=entries[startIndex];if(!start||!isCanonicalEntry(start))return null;let maxBytes=options.maxBytes??REFLECTION_SNAPSHOT_MAX_BYTES,windowStart=anchorIndex+1,bytes=entries.slice(windowStart,startIndex).reduce((total,entry)=>total+entryBytes(entry),0),endMessageId,endLine=-1,budgetExhausted=!1;for(let index=startIndex;index<entries.length;index+=1){let entry=entries[index];if(!entry)break;if(bytes+=entryBytes(entry),!isCanonicalEntry(entry))continue;let groupEnd=index,groupBytes=bytes;for(let next=index+1;next<entries.length;next+=1){let trailing=entries[next];if(!trailing||trailing.source_message_id!==entry.source_message_id)break;groupEnd=next,groupBytes+=entryBytes(trailing)}if(groupBytes>maxBytes&&endMessageId!==void 0){budgetExhausted=!0;break}if(endMessageId=entry.source_message_id,endLine=groupEnd+1,bytes=groupBytes,index=groupEnd,groupBytes>=maxBytes){budgetExhausted=!0;break}}if(endMessageId===void 0||endLine<0)return null;if(!budgetExhausted&&bytes<=maxBytes)endLine=entries.length;let backlogRemaining=entries.length-endLine;return{start_message_id:start.source_message_id,end_message_id:endMessageId,start_line:windowStart,end_snapshot_line:endLine,entries:entries.slice(windowStart,endLine),...backlogRemaining>0?{backlog_remaining:backlogRemaining}:{}}}function finalizeCursor(state,entries,snapshot,success,succeededAt){if(!success)return deriveState(state,entries);let snapshotEntries=entries.slice(0,Math.max(0,snapshot.end_snapshot_line));return deriveState({...state,reflected_through_message_id:snapshot.end_message_id,reflected_through_byte_offset:reflectedThroughByteOffset(entries,snapshot.end_message_id),reflected_completed_steps:countCompletedSteps(snapshotEntries),last_reflection_succeeded_at:succeededAt,consecutive_failures:0,next_eligible_at:void 0},entries)}function reflectedThroughByteOffset(entries,messageId){let offset=0,reflectedOffset=0;for(let entry of entries)if(offset+=Buffer4.byteLength(`${JSON.stringify(entry)}
|
|
24
|
+
`,"utf8"),entry.source_message_id===messageId)reflectedOffset=offset;return reflectedOffset}function initialReflectionState(){return{schema_version:REFLECTION_STATE_SCHEMA_VERSION,total_completed_steps:0,reflected_completed_steps:0,steps_since_last_successful_reflection:0}}function textRow(kind,text,capturedAt,sourceLineId,sourceMessageId){return{kind,text,captured_at:capturedAt,source_line_id:sourceLineId,source_message_id:sourceMessageId}}function truncateToolResult(text,limit=4096){if(text.length<=limit)return text;let headLength=Math.ceil(limit*3/4),tailLength=limit-headLength,dropped=text.length-limit,tail=tailLength>0?text.slice(text.length-tailLength):"";return`${text.slice(0,headLength)}
|
|
25
|
+
…[truncated ${dropped} chars]…
|
|
26
|
+
${tail}`}function projectTranscriptEntries(message,capturedAt){if(message.kind==="user"||message.kind==="error"){if(message.kind==="error"&&message.text.trim().length===0)return[];return[textRow(message.kind,message.text,capturedAt,`${message.messageId}:${message.kind}`,message.messageId)]}let entries=[],assistantText=(message.textBlocks??[]).filter((text)=>text.trim().length>0).join(`
|
|
27
|
+
`);if(assistantText.length>0)entries.push(textRow("assistant",assistantText,capturedAt,`${message.messageId}:assistant`,message.messageId));for(let[index,reasoning]of(message.reasoningBlocks??[]).entries()){let text=typeof reasoning==="string"?reasoning:"[REDACTED REASONING]";if(text.trim().length===0)continue;entries.push(textRow("reasoning",text,capturedAt,`${message.messageId}:reasoning:${index}`,message.messageId))}for(let toolCall of message.toolCalls??[])entries.push({kind:"tool_call",name:toolCall.name,argsText:toolCall.argsText?.slice(0,300),resultText:toolCall.resultText===void 0?void 0:truncateToolResult(toolCall.resultText),resultOk:toolCall.resultOk,captured_at:capturedAt,source_line_id:`${message.messageId}:tool:${toolCall.callId}`,source_message_id:message.messageId});return entries}init_resilient();class JournalLockTimeoutError extends Error{lockPath;retriable=!0;constructor(lockPath){super(`Timed out acquiring transcript journal lock: ${lockPath}`);this.lockPath=lockPath;this.name="JournalLockTimeoutError"}}function errorCode13(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}function delay3(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){if(clearTimeout(timer),signal?.removeEventListener("abort",onAbort),error===void 0)resolve();else reject(error)}})}var ACQUISITION_WAIT_MS=5000,RETRY_DELAY_MS=10;function parseOwner(raw){let[pidText,startIdentity]=raw.trimEnd().split(`
|
|
28
|
+
`),pid=Number.parseInt(pidText??"",10);if(!Number.isSafeInteger(pid)||pid<=0)return null;return{pid,startIdentity:startIdentity??""}}async function isOwnerDead(owner){if(getPidLiveness(owner.pid)==="dead")return!0;if(owner.startIdentity.length===0)return!1;let actual=await getProcessStartIdentity(owner.pid);return actual!==null&&actual!==owner.startIdentity}async function tryReclaimStaleLock(lockPath){let readRaw=()=>readFile(lockPath,"utf8").catch((error)=>{if(errorCode13(error)==="ENOENT")return null;throw error}),snapshot=await readRaw();if(snapshot===null)return;let owner=parseOwner(snapshot);if(owner!==null){if(!await isOwnerDead(owner))return}else{let stats=await stat(lockPath).catch((error)=>{if(errorCode13(error)==="ENOENT")return null;throw error});if(stats===null||Date.now()-stats.mtimeMs<=ACQUISITION_WAIT_MS)return}if(await readRaw()!==snapshot)return;await unlink(lockPath).catch((error)=>{if(errorCode13(error)!=="ENOENT")throw error})}async function acquireAndRun(lockPath,task,signal){let deadline=Date.now()+ACQUISITION_WAIT_MS,handle;for(;;){signal?.throwIfAborted();try{handle=await open3(lockPath,"wx",384);break}catch(error){if(errorCode13(error)!=="EEXIST"||Date.now()>=deadline)throw new JournalLockTimeoutError(lockPath);signal?.throwIfAborted(),await tryReclaimStaleLock(lockPath),await delay3(RETRY_DELAY_MS,signal)}}try{let startIdentity=await getProcessStartIdentity(process.pid)??"";return await writeHandleAll(handle,`${process.pid}
|
|
29
|
+
${startIdentity}
|
|
30
|
+
`,"utf8"),signal?.throwIfAborted(),await task()}finally{await handle.close(),await unlink(lockPath).catch((error)=>{if(errorCode13(error)!=="ENOENT")throw error})}}var queueTails=new Map,withLocalJournalLock=(lockPath,task,signal)=>{let previous=queueTails.get(lockPath)??Promise.resolve(),queued=!0,run=previous.catch(()=>{return}).then(()=>(queued=!1,signal?.throwIfAborted(),acquireAndRun(lockPath,task,signal))),tail=run.then(()=>{return},()=>{return});if(queueTails.set(lockPath,tail),tail.then(()=>{if(queueTails.get(lockPath)===tail)queueTails.delete(lockPath)}),signal===void 0)return run;return new Promise((resolve,reject)=>{let onAbort=()=>{if(queued)reject(signal.reason)};if(signal.aborted)onAbort();else signal.addEventListener("abort",onAbort,{once:!0});run.then(resolve,reject).finally(()=>signal.removeEventListener("abort",onAbort))})};init_resilient();function errorCode14(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}var SKIPPABLE_SYNC_CODES=new Set(["ENOENT","EISDIR","EPERM","EACCES","EINVAL"]);async function syncHandle(path){let handle;try{handle=await open3(path,"r")}catch(error){if(SKIPPABLE_SYNC_CODES.has(errorCode14(error)??""))return;throw error}try{await handle.sync()}catch(error){if(!SKIPPABLE_SYNC_CODES.has(errorCode14(error)??""))throw error}finally{await handle.close()}}async function syncJournalFile(path){await syncHandle(path)}async function syncJournalDirectory(dir){await syncHandle(dir)}function errorCode15(error){if(!(error instanceof Error)||!("code"in error))return;return typeof error.code==="string"?error.code:void 0}function isTranscriptEntry(value){if(!value||typeof value!=="object")return!1;let row=value;if(typeof row.kind!=="string"||typeof row.captured_at!=="string"||typeof row.source_line_id!=="string"||typeof row.source_message_id!=="string")return!1;if(row.kind==="tool_call")return!0;return(row.kind==="user"||row.kind==="assistant"||row.kind==="reasoning"||row.kind==="error")&&typeof row.text==="string"}function optionalString(value){return typeof value==="string"&&value.length>0?value:void 0}function nonNegativeInteger(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0?value:0}function optionalNonNegativeInteger(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0?value:void 0}function parseState(raw){if(raw===null)return initialReflectionState();try{let parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object")return initialReflectionState();let state=parsed,reflectedThroughByteOffset=optionalNonNegativeInteger(state.reflected_through_byte_offset),unreflectedBytes=optionalNonNegativeInteger(state.unreflected_bytes),consecutiveFailures=optionalNonNegativeInteger(state.consecutive_failures),nextEligibleAt=optionalString(state.next_eligible_at),transcriptPrunedAt=optionalString(state.transcript_pruned_at);return{...transcriptPrunedAt===void 0?{}:{transcript_pruned_at:transcriptPrunedAt},...unreflectedBytes===void 0?{}:{unreflected_bytes:unreflectedBytes},...consecutiveFailures===void 0?{}:{consecutive_failures:consecutiveFailures},...nextEligibleAt===void 0?{}:{next_eligible_at:nextEligibleAt},schema_version:"v3_assistant_steps",reflected_through_message_id:optionalString(state.reflected_through_message_id),...reflectedThroughByteOffset===void 0?{}:{reflected_through_byte_offset:reflectedThroughByteOffset},total_completed_steps:nonNegativeInteger(state.total_completed_steps),reflected_completed_steps:nonNegativeInteger(state.reflected_completed_steps),steps_since_last_successful_reflection:nonNegativeInteger(state.steps_since_last_successful_reflection),last_reflection_started_at:optionalString(state.last_reflection_started_at),last_reflection_succeeded_at:optionalString(state.last_reflection_succeeded_at),pending_compaction:typeof state.pending_compaction==="boolean"?state.pending_compaction:void 0}}catch{return initialReflectionState()}}class TranscriptJournal{options;transcriptPath;statePath;lockPath;now;lock;snapshotMaxBytes;constructor(options){this.options=options;this.snapshotMaxBytes=options.snapshotMaxBytes??REFLECTION_SNAPSHOT_MAX_BYTES,this.transcriptPath=join25(options.journalDir,"transcript.jsonl"),this.statePath=join25(options.journalDir,"state.json"),this.lockPath=join25(options.journalDir,"state.lock"),this.now=options.now??(()=>new Date),this.lock=options.lock??withLocalJournalLock}async reconcile(messages,signal){let capturedAt=this.now().toISOString();return this.append(messages.flatMap((message)=>projectTranscriptEntries(message,capturedAt)),signal)}async append(entries,signal){if(signal?.throwIfAborted(),entries.length===0&&!await this.exists())return{appended:0,skipped:0};return this.locked(()=>this.appendUnlocked(entries),signal)}async readEntries(){if(!await this.exists())return[];return this.locked(()=>this.readEntriesUnlocked())}async getState(){if(!await this.exists())return deriveState(initialReflectionState(),[]);return this.locked(async()=>{let entries=await this.readEntriesUnlocked(),state=deriveState(await this.readStateUnlocked(),entries);return await this.writeStateUnlocked(state,entries),state})}async setPendingCompaction(pending){await this.locked(async()=>{let entries=await this.readEntriesUnlocked(),state={...await this.readStateUnlocked(),pending_compaction:pending};await this.writeStateUnlocked(state,entries)})}async captureReflectionSnapshot(signal,options={}){if(signal?.throwIfAborted(),!await this.exists())return null;return this.locked(async()=>{let entries=await this.readEntriesUnlocked(),state=deriveState(await this.readStateUnlocked(),entries),snapshot=captureCursorSnapshot(entries,state,{maxBytes:options.maxBytes??this.snapshotMaxBytes});if(snapshot===null)return null;return signal?.throwIfAborted(),await this.writeStateUnlocked({...state,last_reflection_started_at:this.now().toISOString()},entries),snapshot},signal)}async flush(signal){signal?.throwIfAborted();let aborted=()=>signal?.aborted??!1;if(await syncJournalFile(this.transcriptPath),aborted())return;if(await syncJournalFile(this.statePath),aborted())return;await syncJournalDirectory(this.options.journalDir)}async readEntriesSnapshot(){let raw;try{raw=await readFile(this.transcriptPath,"utf8")}catch(error){if(errorCode15(error)!=="ENOENT")throw error;return[]}let entries=[];for(let line of raw.split(`
|
|
31
|
+
`)){if(line.trim().length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch(error){if(error instanceof SyntaxError)continue;throw error}if(isTranscriptEntry(parsed))entries.push(parsed)}return entries}async backfillReflectionByteOffset(entries){let state=await this.readStateUnlocked();return await this.writeStateUnlocked({...state,reflected_through_byte_offset:state.reflected_through_byte_offset??(state.reflected_through_message_id===void 0?0:reflectedThroughByteOffset(entries,state.reflected_through_message_id))},entries),this.readStateUnlocked()}async recordReflectionFailure(){await this.locked(async()=>{let entries=await this.readEntriesUnlocked(),state=await this.readStateUnlocked(),failures=(state.consecutive_failures??0)+1,delay=Math.min(300000,5000*2**(failures-1));await this.writeStateUnlocked({...state,consecutive_failures:failures,next_eligible_at:new Date(this.now().getTime()+delay).toISOString()},entries)})}async finalizeReflection(snapshot,success){await this.locked(async()=>{let entries=await this.readEntriesUnlocked(),state=deriveState(await this.readStateUnlocked(),entries);await this.writeStateUnlocked(finalizeCursor(state,entries,snapshot,success,this.now().toISOString()),entries)})}async exists(){try{return(await stat(this.options.journalDir)).isDirectory()}catch(error){if(errorCode15(error)==="ENOENT")return!1;throw error}}async locked(task,signal){return signal?.throwIfAborted(),await mkdir(this.options.journalDir,{recursive:!0,mode:448}),this.lock(this.lockPath,task,signal)}async appendUnlocked(entries){let existing=await this.readEntriesUnlocked(),sourceIds=new Set(existing.map((entry)=>entry.source_line_id)),fresh=[],skipped=0;for(let entry of entries)if(sourceIds.has(entry.source_line_id))skipped+=1;else sourceIds.add(entry.source_line_id),fresh.push(entry);if(fresh.length>0)await appendFile2(this.transcriptPath,`${fresh.map((entry)=>JSON.stringify(entry)).join(`
|
|
32
|
+
`)}
|
|
33
|
+
`,"utf8");let allEntries=[...existing,...fresh],state=await this.readStateUnlocked(),rebuilt=existing.length===0&&fresh.length>0&&state.transcript_pruned_at!==void 0;return await this.writeStateUnlocked(rebuilt?this.reanchorAfterPrune(state,allEntries):state,allEntries),{appended:fresh.length,skipped}}reanchorAfterPrune(state,entries){let{transcript_pruned_at:_prunedAt,reflected_through_byte_offset:_offset,...rest}=state,anchor=state.reflected_through_message_id;if(anchor===void 0)return rest;let anchorIndex=-1;for(let[index,entry]of entries.entries())if(entry.source_message_id===anchor)anchorIndex=index;if(anchorIndex>=0)return{...rest,reflected_completed_steps:countCompletedSteps(entries.slice(0,anchorIndex+1))};this.options.warn?.("journal anchor lost after prune",{journalDir:this.options.journalDir,reflectedThroughMessageId:anchor});let{reflected_through_message_id:_anchor,...unanchored}=rest;return{...unanchored,reflected_completed_steps:0}}async readEntriesUnlocked(){let raw;try{raw=await readFile(this.transcriptPath,"utf8")}catch(error){if(errorCode15(error)!=="ENOENT")throw error;return[]}return raw.split(`
|
|
34
|
+
`).filter((line)=>line.trim().length>0).map((line)=>{let parsed=JSON.parse(line);if(!isTranscriptEntry(parsed))throw Error("Invalid transcript journal row");return parsed})}async readStateUnlocked(){try{return parseState(await readFile(this.statePath,"utf8"))}catch(error){if(errorCode15(error)==="ENOENT")return initialReflectionState();throw error}}async writeStateUnlocked(state,entries){let derived=deriveState({...state,...state.reflected_through_message_id!==void 0&&state.reflected_through_byte_offset===void 0?{reflected_through_byte_offset:reflectedThroughByteOffset(entries,state.reflected_through_message_id)}:{}},entries),temporaryPath=`${this.statePath}.tmp-${randomUUID9()}`;await writeFile2(temporaryPath,`${JSON.stringify(derived,null,2)}
|
|
35
|
+
`,"utf8");try{await(this.options.renameFile??rename2)(temporaryPath,this.statePath)}catch(error){try{await rm(temporaryPath,{force:!0})}catch(cleanupError){throw AggregateError([error,cleanupError],"state rename failed and its temporary file could not be removed")}throw error}}}import{join as join26}from"node:path";function emptyReflectionParkState(){return{version:1,streak:0}}function isReflectionParked(state){return state.parkedAt!==void 0}function isAutomaticReflectionRequest(request){if(request.trigger==="manual")return!1;if(request.trigger==="dream")return request.origin!=="manual";return!0}function applyReflectionParkFailure(state,failure){let streak=state.streak+1,threshold=failure.definitive===!0?1:failure.retryable?6:3,parkedAt=state.parkedAt??(streak>=threshold?failure.at:void 0),detail=failure.detail?.slice(0,512);return{version:1,streak,firstFailureAt:state.firstFailureAt??failure.at,lastFailure:{runId:failure.runId,at:failure.at,fingerprint:failure.fingerprint,retryable:failure.retryable,...failure.reason===void 0?{}:{reason:failure.reason},...detail===void 0?{}:{detail}},...parkedAt===void 0?{}:{parkedAt},...state.lastProbeAt===void 0?{}:{lastProbeAt:state.lastProbeAt}}}function clearReflectionPark(){return emptyReflectionParkState()}class ReflectionParkStateError extends Error{name="ReflectionParkStateError"}function isUnreadableReflectionParkState(error){return error instanceof ReflectionParkStateError||error instanceof SyntaxError}function parseReflectionParkState(value){if(!isRecord2(value)||value.version!==1)throw new ReflectionParkStateError("Invalid reflection park state");let streak=value.streak;if(typeof streak!=="number"||!Number.isInteger(streak)||streak<0)throw new ReflectionParkStateError("Invalid reflection park streak");let firstFailureAt=optionalTimestamp(value.firstFailureAt,"firstFailureAt"),parkedAt=optionalTimestamp(value.parkedAt,"parkedAt"),lastProbeAt=optionalTimestamp(value.lastProbeAt,"lastProbeAt"),lastFailure=value.lastFailure===void 0?void 0:parseParkFailure(value.lastFailure);return{version:1,streak,...firstFailureAt===void 0?{}:{firstFailureAt},...lastFailure===void 0?{}:{lastFailure},...parkedAt===void 0?{}:{parkedAt},...lastProbeAt===void 0?{}:{lastProbeAt}}}function parseParkFailure(value){if(!isRecord2(value))throw new ReflectionParkStateError("Invalid reflection park failure");let{runId,at,fingerprint,retryable,reason,detail}=value;if(typeof runId!=="string"||typeof fingerprint!=="string"||typeof retryable!=="boolean")throw new ReflectionParkStateError("Invalid reflection park failure");let timestamp=optionalTimestamp(at,"at");if(timestamp===void 0)throw new ReflectionParkStateError("Invalid reflection park failure timestamp");if(reason!==void 0&&typeof reason!=="string")throw new ReflectionParkStateError("Invalid reflection park failure reason");if(detail!==void 0&&typeof detail!=="string")throw new ReflectionParkStateError("Invalid reflection park failure detail");return{runId,at:timestamp,fingerprint,retryable,...reason===void 0?{}:{reason},...detail===void 0?{}:{detail}}}function optionalTimestamp(value,field){if(value===void 0)return;if(typeof value!=="string"||Number.isNaN(Date.parse(value)))throw new ReflectionParkStateError(`Invalid reflection park ${field}`);return value}function isRecord2(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}var PARK_FILENAME="park.json";async function readReflectionParkFile(reflectionDir){let parsed=await readJsonOptional(join26(reflectionDir,PARK_FILENAME));return parsed===null?emptyReflectionParkState():parseReflectionParkState(parsed)}class ReflectionParkFile{reflectionDir;now;path;constructor(reflectionDir,now){this.reflectionDir=reflectionDir;this.now=now;this.path=join26(reflectionDir,PARK_FILENAME)}async read(){try{return await readReflectionParkFile(this.reflectionDir)}catch(error){if(isUnreadableReflectionParkState(error))return emptyReflectionParkState();throw error}}async write(state){if(!isReflectionParked(state)&&state.streak===0){await unlinkIfPresent(this.path);return}await writeJsonAtomic(this.path,state)}async transition(active,runId,outcome,failure){let before=await this.read();if(outcome==="merged"||outcome==="no_changes"){let cleared=clearReflectionPark();if(isReflectionParked(before)||before.streak>0)await this.write(cleared);return{state:cleared,parked:!1,justParked:!1}}if(active===void 0||!isAutomaticReflectionRequest(active.request))return{state:before,parked:isReflectionParked(before),justParked:!1};let after=applyReflectionParkFailure(before,{runId,at:this.now().toISOString(),...failure??{fingerprint:`${outcome}:`,retryable:!0}});return await this.write(after),{state:after,parked:isReflectionParked(after),justParked:isReflectionParked(after)&&!isReflectionParked(before)}}}function errorCode16(error){return error instanceof Error&&"code"in error&&typeof error.code==="string"?error.code:void 0}async function readPendingRunId(reflectionDir){try{let parsed=JSON.parse(await readFile(join27(reflectionDir,"pending.json"),"utf8")),runId=typeof parsed==="object"&&parsed!==null?parsed.runId:void 0;return typeof runId==="string"?runId:void 0}catch(error){if(errorCode16(error)==="ENOENT"||error instanceof SyntaxError)return;throw error}}async function releaseReservationWithoutPromotion(options){let now=options.now??(()=>new Date),record=await createLockRecord("reflection-scheduler",{runId:options.runId});return withLock(reflectionSchedulerLockPath(options.locksDir),record,async()=>{let activePath=join27(options.reflectionDir,"active.lock"),active=await readRun(activePath);if(active?.runId!==options.runId)return{released:!1};if(active.request.trigger!=="manual"&&active.request.trigger!=="dream")for(let conversationId of active.request.conversationIds){let journalDir=join27(options.transcriptsDir,conversationId);if(!await stat(journalDir).then((status)=>status.isDirectory(),()=>!1))continue;await new TranscriptJournal({journalDir,now}).recordReflectionFailure()}await new ReflectionParkFile(options.reflectionDir,now).transition(active,options.runId,"failed",void 0);let pendingRunId=await readPendingRunId(options.reflectionDir);return await unlink(activePath),{released:!0,...pendingRunId===void 0?{}:{pendingRunId}}},{waitTimeoutMs:0})}init_resilient();import{randomUUID as randomUUID10}from"node:crypto";import{join as join28}from"node:path";var RUN_ID_NAME=/^(?:\d+-)?reflection-run-(\d+)(?:\.json)?$/,RESERVATION_STATE_FILES=["active.lock","pending.json"],RUN_ID_MARK_FILE="run-id.json";function reflectionRunNumber(name){let digits=RUN_ID_NAME.exec(name)?.[1];if(digits===void 0)return 0;let parsed=Number.parseInt(digits,10);return Number.isSafeInteger(parsed)?parsed:0}async function scanReflectionRunHighWater(paths){let scanned=await Promise.all([highestNamedRun(join28(paths.reflection,"completions")),highestNamedRun(join28(paths.reflection,"runs")),highestNamedRun(paths.reflectionSessions),highestNamedRun(paths.worktrees),...RESERVATION_STATE_FILES.map((name)=>reservedRun(join28(paths.reflection,name)))]);return Math.max(0,...scanned)}async function highestNamedRun(directory){return(await readdir(directory).catch(()=>[])).reduce((highest,name)=>Math.max(highest,reflectionRunNumber(name)),0)}async function reservedRun(path){let runId=await readFile(path,"utf8").then((raw)=>JSON.parse(raw).runId).catch(()=>{return});return typeof runId==="string"?reflectionRunNumber(runId):0}function reflectionRunIdMarkPath(reflectionDir){return join28(reflectionDir,RUN_ID_MARK_FILE)}async function readReflectionRunIdMark(reflectionDir){try{let parsed=JSON.parse(await readFile(reflectionRunIdMarkPath(reflectionDir),"utf8"));if(!parsed||typeof parsed!=="object")return;let highWater=parsed.highWater;return typeof highWater==="number"&&Number.isSafeInteger(highWater)&&highWater>=0?highWater:void 0}catch{return}}async function recordReflectionRunIdMark(reflectionDir,highWater){let current=await readReflectionRunIdMark(reflectionDir),next=Math.max(current??0,highWater);if(current===next)return next;await mkdir(reflectionDir,{recursive:!0,mode:448});let target=reflectionRunIdMarkPath(reflectionDir),temporary=`${target}.tmp-${randomUUID10()}`;try{await writeFile2(temporary,`${JSON.stringify({version:1,highWater:next})}
|
|
36
|
+
`,{encoding:"utf8",mode:384}),await rename2(temporary,target)}catch(error){throw await rm(temporary,{force:!0}),error}return next}function parseReservationRunLedger(value){if(!isRecord3(value))throw Error("Invalid reservation run ledger");let{trigger,kind}=value;if(value.version!==1||typeof value.runId!=="string")throw Error("Invalid reservation run ledger identity");if(kind!=="reflection"&&kind!=="dream")throw Error("Invalid reservation run kind");if(trigger!=="step-count"&&trigger!=="compaction"&&trigger!=="manual"&&trigger!=="dream")throw Error("Invalid reservation run trigger");if(kind==="dream"!==(trigger==="dream"))throw Error("Reservation run kind and trigger disagree");if(trigger==="dream"&&value.origin!=="manual"&&value.origin!=="idle"&&value.origin!=="shutdown"&&value.origin!=="pressure")throw Error("Dream run origin is required");if(["startedAt","worktreeDir","worktreeBranch","baseSha","gitFilePath","gitFileSnapshot","commonConfigPath"].some((field)=>typeof value[field]!=="string"))throw Error("Invalid reservation run paths");if(["hardDeadlineAt","terminationGraceMs","deadlineAt"].some((field)=>typeof value[field]!=="number"||!Number.isFinite(value[field])))throw Error("Invalid reservation run deadline");let hardDeadlineAt=Number(value.hardDeadlineAt),terminationGraceMs=Number(value.terminationGraceMs);if(Number(value.deadlineAt)!==hardDeadlineAt+terminationGraceMs)throw Error("Reservation run deadline mismatch");if(value.mergePolicy!=="auto"&&value.mergePolicy!=="integration")throw Error("Invalid reservation merge policy");if(value.targetDoc!==void 0&&(kind!=="dream"||typeof value.targetDoc!=="string"))throw Error("Invalid dream target document");for(let field of["systemTokenBudget","systemTokenTarget"])if(value[field]!==void 0&&(kind!=="dream"||!Number.isInteger(value[field])||Number(value[field])<=0))throw Error(`Invalid dream ${field}`);if(value.systemTokenBudget===void 0!==(value.systemTokenTarget===void 0))throw Error("Dream token budget metadata is incomplete");if(!optionalPid(value.pid)||!optionalIdentity(value.processStart)||!optionalPid(value.childPid)||!optionalIdentity(value.childProcessStart))throw Error("Invalid reservation process identity");if(value.attempt!==void 0&&(!Number.isInteger(value.attempt)||Number(value.attempt)<=0))throw Error("Invalid reservation run attempt");if(value.model!==void 0&&typeof value.model!=="string")throw Error("Invalid reservation run model");if(value.thinking!==void 0&&typeof value.thinking!=="string")throw Error("Invalid reservation run thinking");if(value.category!==void 0&&typeof value.category!=="string")throw Error("Invalid reservation run category");if(value.conversationIds!==void 0&&(!Array.isArray(value.conversationIds)||!value.conversationIds.every((id)=>typeof id==="string")))throw Error("Invalid reservation run conversations");if(value.launching!==void 0&&typeof value.launching!=="boolean")throw Error("Invalid reservation run launching state");if(value.queued!==void 0&&typeof value.queued!=="boolean")throw Error("Invalid reservation run queued state");if(value.cleanupIncomplete!==void 0&&typeof value.cleanupIncomplete!=="boolean")throw Error("Invalid reservation run cleanup state");if(value.commonConfigSnapshot!==null&&typeof value.commonConfigSnapshot!=="string")throw Error("Invalid common config snapshot");if(value.finalizePhase!==void 0&&value.finalizePhase!=="validated"&&value.finalizePhase!=="integrated"&&value.finalizePhase!=="settled")throw Error("Invalid finalization phase");for(let field of["validatedTipSha","integrationSha","finalizeReason","finalizeDetail","finalizedAt"])if(value[field]!==void 0&&typeof value[field]!=="string")throw Error(`Invalid ${field}`);if(value.validatedChangedPaths!==void 0&&(!Array.isArray(value.validatedChangedPaths)||!value.validatedChangedPaths.every((path)=>typeof path==="string")))throw Error("Invalid validated changed paths");if(value.finalizeOutcome!==void 0&&!isReflectionOutcome(value.finalizeOutcome))throw Error("Invalid finalization outcome");return value}function optionalPid(value){return value===void 0||Number.isInteger(value)&&Number(value)>0}function optionalIdentity(value){return value===void 0||value===null||typeof value==="string"}function isRecord3(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function isReflectionOutcome(value){return value==="merged"||value==="no_changes"||value==="parent_dirty"||value==="dirty_uncommitted"||value==="merge_conflict"||value==="admin_tamper"||value==="timed_out"||value==="failed"}async function startVerdict(pid,recordedStart,seams){let actualStart=await(seams.getProcessStartIdentity??getProcessStartIdentity)(pid).catch(()=>null);if(recordedStart===null||actualStart===null)return"unknown";return startIdentitiesComparable(recordedStart,actualStart)&&recordedStart!==actualStart?"dead":"alive"}async function classifyRecordedProcess(pid,recordedStart,seams={}){if(pid===void 0)return"absent";if(recordedStart===void 0)return"unknown";let liveness=(seams.getPidLiveness??getPidLiveness)(pid);if(liveness==="dead")return"dead";if(liveness==="unknown")return"unknown";return startVerdict(pid,recordedStart,seams)}async function classifyRecordedProcessLenient(pid,recordedStart,seams={}){if(pid===void 0)return"absent";let liveness=(seams.getPidLiveness??getPidLiveness)(pid);if(liveness==="dead")return"dead";if(liveness==="unknown"||recordedStart===void 0)return"unknown";return startVerdict(pid,recordedStart,seams)}var REFLECTION_LAUNCH_WINDOW_MS=60000,STRANDED_RUN_GRACE_MS=REFLECTION_LAUNCH_WINDOW_MS+REFLECTION_ORPHAN_GRACE_MS,TERMINAL_SENTINELS=["final.json","abandoned.json","quarantined.json"],TOMBSTONE_PREFIX=".prune-",TORN_RUN_ID=/reflection-run-(\d+)"/g;function errorCode17(error){return error instanceof Error&&"code"in error&&typeof error.code==="string"?error.code:void 0}async function readText3(path,probe){try{return{kind:"text",text:await(probe.readText??((target)=>readFile(target,"utf8")))(path)}}catch(error){return errorCode17(error)==="ENOENT"?{kind:"missing"}:{kind:"unreadable"}}}function parseJson(text){try{return{ok:!0,value:JSON.parse(text)}}catch{return{ok:!1}}}function fieldsOf2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)?value:{}}async function listDirectory(path,probe){if(probe.listDirectory!==void 0)return probe.listDirectory(path);try{return(await readdir(path,{withFileTypes:!0})).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort()}catch{return[]}}async function modifiedAt(path,probe){if(probe.modifiedAt!==void 0)return probe.modifiedAt(path);return stat(path).then((status)=>status.mtimeMs,()=>{return})}async function exists(path,probe){return(await readText3(path,probe)).kind!=="missing"}async function hasTerminalSentinel(runDir,probe){for(let name of TERMINAL_SENTINELS)if(await exists(join29(runDir,name),probe))return!0;return!1}async function readFinalOutcome(runDir,probe){let read=await readText3(join29(runDir,"final.json"),probe);if(read.kind==="missing")return;let parsed=read.kind==="text"?parseJson(read.text):{ok:!1},outcome=parsed.ok?fieldsOf2(parsed.value).outcome:void 0;return typeof outcome==="string"?outcome:"unknown"}async function settledSentinel(runDir,runId,active,probe){for(let name of["abandoned.json","quarantined.json"]){let read=await readText3(join29(runDir,name),probe);if(read.kind==="missing")continue;let parsed=read.kind==="text"?parseJson(read.text):{ok:!1},sentinel=parsed.ok?fieldsOf2(parsed.value):{};if(sentinel.runId!==runId||typeof sentinel.generation!=="string")return"other-generation";let generation=Date.parse(sentinel.generation),reservedAt=typeof active.reservedAt==="string"?Date.parse(active.reservedAt):Number.NaN,ledger=await readLedger(runDir,probe),startedAt=ledger.present?ledger.fields.startedAt:void 0;if(Number.isFinite(generation)&&Number.isFinite(reservedAt)&&generation>=reservedAt||startedAt===sentinel.generation)return"match";return"other-generation"}return}async function recordedProcesses(ledger,probe,classify){for(let[role,pidKey,startKey]of[["supervisor","pid","processStart"],["child","childPid","childProcessStart"]]){let pid=typeof ledger[pidKey]==="number"?ledger[pidKey]:void 0,start=typeof ledger[startKey]==="string"||ledger[startKey]===null?ledger[startKey]:void 0,verdict=await classify(pid,start,probe);if(verdict==="alive")return{live:!0,reason:`its ${role} pid ${pid} is still running`};if(verdict==="unknown")return{live:!0,reason:`its ${role} pid ${pid} could not be checked`}}return{live:!1}}function stillLaunching(ledger,now){let hardDeadlineAt=ledger.fields.hardDeadlineAt;return ledger.valid&&ledger.fields.launching===!0&&typeof hardDeadlineAt==="number"&&now<=hardDeadlineAt}var STILL_LAUNCHING="its supervisor is still launching and its hard deadline has not passed";function validLedger(value,runId){try{return parseReservationRunLedger(value).runId===runId}catch{return!1}}async function readLedger(runDir,probe){let read=await readText3(join29(runDir,"ledger.json"),probe);if(read.kind==="missing")return{present:!1};let parsed=read.kind==="text"?parseJson(read.text):{ok:!1};return parsed.ok?{present:!0,fields:fieldsOf2(parsed.value),valid:validLedger(parsed.value,basename5(runDir))}:{present:!0,fields:{},valid:!1}}var TORN_LOCK_MIN_AGE_MS=3600000,TORN_LAUNCHER_PID=/"launcherPid"\s*:\s*(\d+)/,TORN_LAUNCHER_HOST=/"launcherHostname"\s*:\s*"([^"]*)"/,TORN_LAUNCHER_START=/"launcherProcessStart"\s*:\s*"([^"]*)"/;async function tornLockBlocker(reflectionDir,bytes,probe){let now=(probe.now??Date.now)(),lockAt=await modifiedAt(join29(reflectionDir,"active.lock"),probe);if(lockAt===void 0||now-lockAt<=TORN_LOCK_MIN_AGE_MS)return"it is recent";let host=TORN_LAUNCHER_HOST.exec(bytes)?.[1];if(host!==void 0&&host!==(probe.hostname??readHostname2)())return`its launcher is on host ${host}`;let pid=TORN_LAUNCHER_PID.exec(bytes)?.[1];if(pid!==void 0&&host===void 0)return"its launcher host is unknown";if(pid!==void 0&&await reflectionLauncherLiveness(Number.parseInt(pid,10),TORN_LAUNCHER_START.exec(bytes)?.[1],probe)!=="dead")return`its launcher pid ${pid} may still be alive`;let runsDir=join29(reflectionDir,"runs");for(let name of await listDirectory(runsDir,probe)){if(name.startsWith("."))continue;let runDir=join29(runsDir,name);if(await hasTerminalSentinel(runDir,probe))continue;let at=await modifiedAt(runDir,probe);if(at===void 0||now-at<=REFLECTION_ORPHAN_GRACE_MS)return`run ${name} is a young run dir`;let ledger=await readLedger(runDir,probe);if(ledger.present&&stillLaunching(ledger,now))return`run ${name} is still launching`;if(ledger.present&&(await recordedProcesses(ledger.fields,probe,classifyRecordedProcess)).live)return`run ${name} may still be live`}return}async function tornLock(reflectionDir,bytes,reason,probe){let blocker=await tornLockBlocker(reflectionDir,bytes,probe);if(blocker!==void 0)return{kind:"stuck",runId:"unknown",reason:`${reason} and ${blocker}`};return{kind:"reap",action:"lock-torn",runId:"unknown",reason}}async function decideStuck(reflectionDir,verdict,probe){let passThrough={kind:"stuck",runId:verdict.runId,reason:verdict.reason},lock=await readText3(join29(reflectionDir,"active.lock"),probe);if(lock.kind!=="text")return passThrough;let parsed=parseJson(lock.text);if(!parsed.ok)return tornLock(reflectionDir,lock.text,"active.lock is not valid JSON",probe);let fields=fieldsOf2(parsed.value),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){if(!isReservedRun(parsed.value))return tornLock(reflectionDir,lock.text,"active.lock is not a reservation",probe);return{kind:"stuck",runId:verdict.runId,reason:"its launcher identity is missing; a session reconciles it"}}if(launcherHostname!==(probe.hostname??readHostname2)())return passThrough;if(await reflectionLauncherLiveness(launcherPid,fields.launcherProcessStart,probe)!=="dead")return passThrough;let runId=verdict.runId,runDir=join29(reflectionDir,"runs",runId);if(await exists(join29(runDir,"outcome.json"),probe))return passThrough;if(!isReservedRun(parsed.value))return tornLock(reflectionDir,lock.text,"active.lock is not a reservation",probe);let finalOutcome=await readFinalOutcome(runDir,probe);if(finalOutcome==="merged"||finalOutcome==="no_changes")return{kind:"stuck",runId,reason:"it finished with a folded outcome that only a session can settle; open a session"};if(finalOutcome!==void 0)return{kind:"reap",action:"terminal-recorded",runId,reason:"the run already recorded its terminal state"};let settled=await settledSentinel(runDir,runId,fields,probe);if(settled==="match")return{kind:"reap",action:"release-settled",runId,reason:"it was already settled and only the release is missing"};if(settled==="other-generation")return{kind:"stuck",runId,reason:"its run dir holds a terminal record from another generation"};let ledger=await readLedger(runDir,probe);if(!ledger.present){let reservedAt=typeof fields.reservedAt==="string"?Date.parse(fields.reservedAt):Number.NaN;if(Number.isFinite(reservedAt)&&(probe.now??Date.now)()-reservedAt<=REFLECTION_LAUNCH_WINDOW_MS)return{kind:"stuck",runId,reason:"its launcher is gone but the launch window has not closed"};return{kind:"reap",action:"launch-interrupted",runId,reason:`launcher pid ${launcherPid} is gone and the run never started`}}if(stillLaunching(ledger,(probe.now??Date.now)()))return{kind:"stuck",runId,reason:STILL_LAUNCHING};let processes=await recordedProcesses(ledger.fields,probe,ledger.valid?classifyRecordedProcess:classifyRecordedProcessLenient);if(processes.live)return{kind:"stuck",runId,reason:processes.reason};if(ledger.valid)return{kind:"reap",action:"processes-dead",runId,reason:"its launcher, supervisor and child are all gone and it recorded no outcome"};return{kind:"reap",action:"ledger-unreadable",runId,reason:"its ledger cannot be read and its recorded processes are gone"}}async function decideStaleReflectionLock(reflectionDir,probe={}){let verdict=await classifyReflectionLockHolder(reflectionDir,probe);if(verdict.state==="none"||verdict.state==="live")return{verdict,decision:{kind:"none"}};if(verdict.state==="dead")return{verdict,decision:{kind:"finalize",runId:verdict.runId}};return{verdict,decision:await decideStuck(reflectionDir,verdict,probe)}}async function strandedSince(runDir,probe={}){let prelaunch=join29(runDir,"prelaunch.json");return await exists(prelaunch,probe)?await modifiedAt(prelaunch,probe):await modifiedAt(runDir,probe)}async function decideStrandedRun(runDir,probe={}){let ledger=await readLedger(runDir,probe);if(!ledger.present){let prelaunch=await readText3(join29(runDir,"prelaunch.json"),probe);if(prelaunch.kind==="text"){let parsed=parseJson(prelaunch.text),named=parsed.ok?fieldsOf2(parsed.value).runId:void 0;if(typeof named!=="string")return{kind:"keep",reason:"its prelaunch.json cannot be read"};if(named!==basename5(runDir))return{kind:"keep",reason:"its prelaunch.json names another run"}}let since=await strandedSince(runDir,probe);if(since===void 0||(probe.now??Date.now)()-since<=STRANDED_RUN_GRACE_MS)return{kind:"keep",reason:"it is inside the launch grace window"};return{kind:"reap",action:"no-ledger",reason:"it never got a ledger"}}if(stillLaunching(ledger,(probe.now??Date.now)()))return{kind:"keep",reason:STILL_LAUNCHING};let processes=await recordedProcesses(ledger.fields,probe,ledger.valid?classifyRecordedProcess:classifyRecordedProcessLenient);if(processes.live)return{kind:"keep",reason:processes.reason};if(ledger.valid)return{kind:"reap",action:"processes-dead",reason:"its supervisor and child are gone and it recorded no outcome"};return{kind:"reap",action:"ledger-unreadable",reason:"its ledger cannot be read and its recorded processes are gone"}}async function emitReceipt(context,input){try{await context.appendReceipt(context.runtimeDir,input)}catch(error){context.warnings.push(`receipt for ${"runId"in input?input.runId:input.batchId} not written: ${error instanceof Error?error.message:String(error)}`)}}async function underLock(lockPath,purpose,task){try{return await withLock(lockPath,await createLockRecord(purpose),task,{waitTimeoutMs:0})}catch(error){if(error instanceof LockContentionError)return"busy";throw error}}function isoOr(value,fallback){return typeof value==="string"&&Number.isFinite(Date.parse(value))?value:fallback}function identityFromLedger(fields,fallback){let kind=fields.kind==="dream"||fields.kind==="reflection"?fields.kind:fallback.kind,trigger=typeof fields.trigger==="string"?fields.trigger:fallback.trigger,origin=typeof fields.origin==="string"?fields.origin:fallback.origin;return{kind,trigger,...origin===void 0?{}:{origin}}}function identityFromReservation(active){let request=fieldsOf2(active.request),trigger=typeof request.trigger==="string"?request.trigger:"unknown",origin=typeof request.origin==="string"?request.origin:void 0;return{kind:trigger==="dream"?"dream":"reflection",trigger,...origin===void 0?{}:{origin}}}async function abandonRun(context,runDir,runId,reason,generation,identity,launcher){await mkdir(runDir,{recursive:!0,mode:448}),await writeAbandoned(runDir,{version:1,runId,abandonedAt:new Date(context.now()).toISOString(),reason,generation,...identity,...launcher===void 0?{}:{launcher:{pid:typeof launcher.launcherPid==="number"?launcher.launcherPid:void 0,hostname:typeof launcher.launcherHostname==="string"?launcher.launcherHostname:void 0,processStart:typeof launcher.launcherProcessStart==="string"?launcher.launcherProcessStart:null}}}),await emitReceipt(context,{kind:identity.kind,runId,trigger:identity.origin??identity.trigger,event:"abandoned",generation,reason})}async function quarantineRun(context,runDir,runId,generation,identity,reservation,reason="ledger_unreadable"){let evidence=[...(await readdir(runDir).catch(()=>[])).sort(),...reservation===void 0?[]:[RESERVATION_EVIDENCE_FILENAME]];await writeQuarantine(runDir,{version:1,runId,kind:identity.kind,trigger:identity.trigger,...identity.origin===void 0?{}:{origin:identity.origin},generation,reason,quarantinedAt:new Date(context.now()).toISOString(),evidence},reservation),await emitReceipt(context,{kind:identity.kind,runId,trigger:identity.origin??identity.trigger,event:"quarantined",generation,reason})}async function reservedRunId(path){let raw=await readFile(path,"utf8").catch(()=>{return}),parsed=raw===void 0?void 0:parseJson(raw),runId=parsed?.ok===!0?fieldsOf2(parsed.value).runId:void 0;return typeof runId==="string"?runId:void 0}async function readActiveFields(reflectionDir){let raw=await readFile(join29(reflectionDir,"active.lock"),"utf8").catch(()=>{return});if(raw===void 0)return;let parsed=parseJson(raw);return parsed.ok?fieldsOf2(parsed.value):void 0}async function releaseReservation(context,runId){try{return await releaseReservationWithoutPromotion({reflectionDir:context.reflectionDir,transcriptsDir:context.transcriptsDir,locksDir:context.locksDir,runId,now:()=>new Date(context.now())})}catch(error){if(error instanceof LockContentionError)return{released:!1};throw error}}async function settleActiveMinimally(context,decision){let runId=decision.runId,runDir=join29(context.reflectionDir,"runs",runId),written=await underLock(runFinalizationLockPath(context.locksDir,runId),"reflection-finalize",async()=>{let again=(await decideStaleReflectionLock(context.reflectionDir,context.probe)).decision;if(again.kind!=="reap"||again.action!==decision.action||again.runId!==runId)return{settled:!1,reason:"the decision changed"};let active=await readActiveFields(context.reflectionDir)??{},identity=identityFromReservation(active),reservedAt=isoOr(active.reservedAt,new Date(context.now()).toISOString());if(decision.action==="launch-interrupted")return await abandonRun(context,runDir,runId,"launch_interrupted",reservedAt,identity,active),{settled:!0};if(decision.action==="terminal-recorded"||decision.action==="release-settled"){let released=await releaseReservation(context,runId);return released.released?{settled:!0,alreadyReleased:!0,...released.pendingRunId===void 0?{}:{pendingRunId:released.pendingRunId}}:{settled:!1,reason:"the reservation changed before it could be released"}}if(decision.action!=="processes-dead"&&decision.action!=="ledger-unreadable")return{settled:!1,reason:`${decision.action} is not settled from here`};let ledger=await readLedger(runDir,{}),fields=ledger.present?ledger.fields:{},attempt=typeof fields.attempt==="number"?fields.attempt:void 0,published=readRunTerminalPublication(runDir,attempt);if(published!==void 0)return{settled:!1,reason:`the run is already ${published==="settled"?"settled":"publishing its outcome"}`};let claim=await claimRunTerminal(runDir,{runId,attempt:attempt??1},"abandon",context.probe);if(!runTerminalClaimMatches(claim,{runId,attempt:attempt??1},"abandon"))return{settled:!1,reason:"another process claimed the run"};let generation=isoOr(fields.startedAt,reservedAt);if(decision.action==="processes-dead")await abandonRun(context,runDir,runId,"processes_dead",generation,identityFromLedger(fields,identity));else await quarantineRun(context,runDir,runId,generation,identityFromLedger(fields,identity),isReservedRun(active)?active:void 0);return{settled:!0}});if(written==="busy")return{settled:!1,reason:"a session is finalizing it"};if(!written.settled)return written;if(written.alreadyReleased===!0)return written;let released=await releaseReservation(context,runId);if(!released.released)return{settled:!1,reason:"the reservation changed before it could be released"};return{settled:!0,...released.pendingRunId===void 0?{}:{pendingRunId:released.pendingRunId}}}async function reapTornLock(context,paths){return await underLock(reflectionSchedulerLockPath(context.locksDir),"reflection-scheduler",async()=>{let again=(await decideStaleReflectionLock(context.reflectionDir,context.probe)).decision;if(again.kind!=="reap"||again.action!=="lock-torn")return!1;let bytes=await readFile(join29(context.reflectionDir,"active.lock"),"utf8"),named=[...bytes.matchAll(TORN_RUN_ID)].map((match)=>Number.parseInt(match[1]??"0",10)).filter(Number.isSafeInteger),scanned=await scanReflectionRunHighWater({reflection:context.reflectionDir,...paths}),highWater=Math.max(scanned,...named);if(highWater>0)await recordReflectionRunIdMark(context.reflectionDir,highWater);let at=new Date(context.now());if(await moveTornReservationAside(context.reflectionDir,bytes,at)===void 0)return!1;let tornRun=named.length===0?"unknown":`reflection-run-${Math.max(...named)}`;return await emitReceipt(context,{kind:"reflection",runId:tornRun,trigger:"unknown",event:"abandoned",generation:at.toISOString(),reason:"lock_torn"}),!0})===!0}async function settleStrandedRunUnderLock(context,runDir,runId,decision){let since=await strandedSince(runDir,{});return await underLock(runFinalizationLockPath(context.locksDir,runId),"reflection-finalize",async()=>{if(await hasTerminalSentinel(runDir,{}))return!1;let ledger=await readLedger(runDir,{}),fields=ledger.present?ledger.fields:{},unknown={kind:"reflection",trigger:"unknown"},fallback=new Date(since??context.now()).toISOString();if(decision.action==="no-ledger")return await quarantineRun(context,runDir,runId,fallback,unknown,void 0,"stranded_no_ledger"),!0;let generation=isoOr(fields.startedAt,fallback);if(decision.action==="processes-dead")await abandonRun(context,runDir,runId,"processes_dead",generation,identityFromLedger(fields,unknown));else await quarantineRun(context,runDir,runId,generation,identityFromLedger(fields,unknown));return!0})===!0}async function strandedRuns(context,apply){let runsDir=join29(context.reflectionDir,"runs"),reserved=new Set;for(let name of["active.lock","pending.json"]){let raw=await readFile(join29(context.reflectionDir,name),"utf8").catch(()=>{return}),parsed=raw===void 0?void 0:parseJson(raw);if(parsed?.ok===!0&&typeof fieldsOf2(parsed.value).runId==="string")reserved.add(fieldsOf2(parsed.value).runId)}let reports=[];for(let runId of await listDirectory(runsDir,{})){if(runId.startsWith(".")||reserved.has(runId))continue;let runDir=join29(runsDir,runId);if(await hasTerminalSentinel(runDir,{}))continue;let decision=await decideStrandedRun(runDir,context.probe);if(decision.kind==="keep"||!apply){reports.push({runId,decision,applied:!1});continue}let applied=await settleStrandedRunUnderLock(context,runDir,runId,decision);reports.push({runId,decision,applied:applied===!0})}return reports}async function removeTombstones(context,apply){let runsDir=join29(context.reflectionDir,"runs"),names=(await readdir(runsDir).catch(()=>[])).filter((name)=>name.startsWith(TOMBSTONE_PREFIX)).sort(),reports=[];for(let name of names){if(!apply){reports.push({name,removed:!1});continue}try{await removeTree(join29(runsDir,name)),reports.push({name,removed:!0})}catch(error){reports.push({name,removed:!1,error:error instanceof Error?error.message:String(error)})}}return reports}async function runStaleLockReaper(options){let probe=options.probe??{},context={runtimeDir:options.runtimeDir,reflectionDir:join29(options.runtimeDir,"reflection"),transcriptsDir:join29(options.runtimeDir,"transcripts"),locksDir:join29(options.runtimeDir,"locks"),probe,now:probe.now??Date.now,appendReceipt:options.appendReceipt??appendMemoryReceiptOnce,warnings:[]},paths={reflectionSessions:join29(options.runtimeDir,"reflection-sessions"),worktrees:join29(options.runtimeDir,"worktrees")},{verdict:before,decision}=await decideStaleReflectionLock(context.reflectionDir,probe),minimal=options.settle===void 0,action,pendingKept,keptReason;if(options.dryRun===!0){if(action=decision.kind==="reap"?"would-reap":decision.kind==="none"?"none":"kept",decision.kind==="reap")pendingKept=await reservedRunId(join29(context.reflectionDir,"pending.json"))}else if(decision.kind==="reap"&&decision.action==="lock-torn")action=await reapTornLock(context,paths)?"reaped":"kept";else if(decision.kind==="reap"||decision.kind==="finalize")if(options.settle===void 0){let settled=decision.kind==="reap"?await settleActiveMinimally(context,decision):{settled:!1,reason:"it recorded its outcome; open a session to finalize it"};if(action=settled.settled?"reaped":"kept",settled.settled&&settled.pendingRunId!==void 0)pendingKept=settled.pendingRunId;if(!settled.settled)keptReason=settled.reason}else if(options.shouldSettle?.(decision.runId)===!1)action="settle-declined";else await options.settle(),action="settled";else action=decision.kind==="none"?"none":"kept";if(options.settle!==void 0&&options.settleAlways===!0&&options.dryRun!==!0&&action!=="settled")await options.settle();let stranded=minimal?await strandedRuns(context,options.dryRun!==!0):[],tombstones=minimal?await removeTombstones(context,options.dryRun!==!0):[],after=options.dryRun===!0?before:await classifyReflectionLockHolder(context.reflectionDir,probe);return{before,decision,action,after,stranded,tombstones,warnings:context.warnings,dryRun:options.dryRun===!0,...pendingKept===void 0?{}:{pendingKept},...keptReason===void 0?{}:{keptReason}}}async function reclaimDeadOwnerLocks(locksDir){let names=(await readdir(locksDir).catch(()=>[])).filter((name)=>name.endsWith(".lock")).sort(),reclaimed=[],failures=new Map;await sweepDeadOwnerLocks(locksDir,{onReclaimed:(lockPath)=>{reclaimed.push(basename5(lockPath))},onFailure:(lockPath,error)=>{failures.set(basename5(lockPath),error instanceof Error?error.message:String(error))}});let kept=names.filter((name)=>!reclaimed.includes(name)).map((name)=>({name,reason:failures.get(name)??"owner is alive or not provably dead"}));return{reclaimed,kept}}function formatStaleLockFixLines(identity,report,locks){let lines=[],{decision}=report;if(decision.kind==="reap"||decision.kind==="finalize"){let label=decision.kind==="reap"?decision.action:"finalize";if(report.action==="would-reap"){if(lines.push(`WOULD FIX ${identity} active.lock run ${decision.runId} (${label})`),report.pendingKept!==void 0)lines.push(`INFO ${identity} pending ${report.pendingKept} stays queued for the next session`)}else if(report.action==="reaped"||report.action==="settled"&&(report.after.state==="none"||("runId"in report.after)&&report.after.runId!==decision.runId)){if(lines.push(`FIXED ${identity} active.lock run ${decision.runId} (${label})`),report.pendingKept!==void 0)lines.push(`INFO ${identity} pending ${report.pendingKept} kept for the next session`)}else if(decision.kind==="finalize"&&report.action==="kept")lines.push(`KEPT ${identity} active.lock run ${decision.runId} (it recorded its outcome; open a session to finalize it)`);else lines.push(`KEPT ${identity} active.lock run ${decision.runId} (${report.keptReason??`${label} did not release the lock`})`)}else if(decision.kind==="stuck")lines.push(`KEPT ${identity} active.lock run ${decision.runId} (${decision.reason})`);for(let entry of report.stranded){if(entry.decision.kind!=="reap")continue;lines.push(`${entry.applied?"FIXED":report.dryRun?"WOULD FIX":"KEPT"} ${identity} run ${entry.runId} (${entry.decision.action})`)}for(let tombstone of report.tombstones)if(tombstone.removed)lines.push(`FIXED ${identity} removed tombstone ${tombstone.name}`);else if(tombstone.error!==void 0)lines.push(`KEPT ${identity} tombstone ${tombstone.name} (${tombstone.error})`);for(let warning of report.warnings)lines.push(`WARN ${identity} ${warning}`);if(locks!==void 0){let failed=locks.kept.filter((entry)=>entry.reason!=="owner is alive or not provably dead");lines.push(`INFO ${identity} locks reclaimed ${locks.reclaimed.length}, kept ${locks.kept.length}${failed.length===0?"":` (${failed.map((entry)=>`${entry.name}: ${entry.reason}`).join("; ")})`}`)}return lines}init_resilient();import{randomUUID as randomUUID11}from"node:crypto";import{join as join30}from"node:path";var HOST_SWEEP_STATE_FILE="runtime-sweep.json",HOST_SWEEP_LOCK_FILE="runtime-sweep.lock";function errorCode18(error){return error instanceof Error&&"code"in error&&typeof error.code==="string"?error.code:void 0}async function isDirectory(path){return stat(path).then((status)=>status.isDirectory(),()=>!1)}async function listRuntimeIdentities(memoryRoot){let agentsRoot=join30(memoryRoot,"agents"),names;try{names=(await readdir(agentsRoot)).filter((name)=>!name.startsWith(".")).sort()}catch(error){if(errorCode18(error)==="ENOENT")return[];throw error}let identities=[];for(let name of names){let root=join30(agentsRoot,name),runtimeDir=join30(root,"runtime");if(!await isDirectory(runtimeDir))continue;identities.push({name,root,runtimeDir,hasRepo:await isDirectory(join30(root,"repo"))})}return identities}async function readHostSweepState(memoryRoot){try{let parsed=JSON.parse(await readFile(join30(memoryRoot,HOST_SWEEP_STATE_FILE),"utf8")),fields=typeof parsed==="object"&&parsed!==null?parsed:{};return{version:1,...typeof fields.cursor==="string"?{cursor:fields.cursor}:{},...typeof fields.completedAt==="string"?{completedAt:fields.completedAt}:{}}}catch{return{version:1}}}async function writeHostSweepState(memoryRoot,state){await mkdir(memoryRoot,{recursive:!0,mode:448});let target=join30(memoryRoot,HOST_SWEEP_STATE_FILE),temporary=`${target}.tmp-${randomUUID11()}`;try{await writeFile2(temporary,`${JSON.stringify(state)}
|
|
37
|
+
`,{encoding:"utf8",mode:384}),await rename2(temporary,target)}catch(error){throw await rm(temporary,{force:!0}),error}}function resumeOrder(identities,cursor,unbounded){if(cursor===void 0)return{rest:identities,wrap:[]};return{rest:identities.filter((identity)=>identity.name>cursor),wrap:unbounded?identities.filter((identity)=>identity.name<=cursor):[]}}async function sweepHostIdentities(options){let now=options.now??Date.now,startedAt=now(),record=await createLockRecord("runtime-sweep");try{return await withLock(join30(options.memoryRoot,HOST_SWEEP_LOCK_FILE),record,async()=>{let state=await readHostSweepState(options.memoryRoot),unbounded=options.maxIdentities===void 0&&options.budgetMs===void 0,{rest,wrap}=resumeOrder(await listRuntimeIdentities(options.memoryRoot),state.cursor,unbounded),visited=[],lines=[],visit=async(identity)=>{if(options.signal?.aborted===!0)return!1;if(options.maxIdentities!==void 0&&visited.length>=options.maxIdentities)return!1;if(options.budgetMs!==void 0&&visited.length>0&&now()-startedAt>=options.budgetMs)return!1;for(let step of options.steps)lines.push(...await step(identity));return visited.push(identity.name),!0},reachedEnd=!0;for(let identity of rest){if(!await visit(identity)){reachedEnd=!1;break}if(options.dryRun!==!0)await writeHostSweepState(options.memoryRoot,{version:1,cursor:identity.name})}if(reachedEnd&&options.dryRun!==!0)await writeHostSweepState(options.memoryRoot,{version:1,completedAt:new Date(now()).toISOString()});if(reachedEnd){for(let identity of wrap)if(!await visit(identity))break}return{status:"swept",visited,completed:reachedEnd,lines}},{waitTimeoutMs:0})}catch(error){if(error instanceof LockContentionError)return{status:"busy"};throw error}}import{dirname as dirname7}from"node:path";var RETENTION_STORES=["runs","completions","reflection-sessions","journals","sidecars","ledgers","recall-runs"];class PassBudget{now;budgetMs;signal;resume;startedAt;last;stopped;aborted=!1;admittedAny=!1;constructor(now,budgetMs,signal,resume){this.now=now;this.budgetMs=budgetMs;this.signal=signal;this.resume=resume;this.startedAt=now()}skip(store,name){if(this.resume===void 0)return!1;let resumeAt=RETENTION_STORES.indexOf(this.resume.store),here=RETENTION_STORES.indexOf(store);if(resumeAt<0||here>resumeAt)return!1;if(here<resumeAt)return!0;return this.resume.lastName!==void 0&&name<=this.resume.lastName}admit(store){if(!this.proceed(store))return!1;if(this.admittedAny&&this.now()-this.startedAt>=this.budgetMs)return this.stop(store),!1;return this.admittedAny=!0,!0}proceed(store){if(this.stopped!==void 0)return!1;if(this.signal?.aborted!==!0)return!0;return this.aborted=!0,this.stop(store),!1}stop(store){if(this.last!==void 0)this.stopped=this.last;else if(this.resume!==void 0&&RETENTION_STORES.indexOf(this.resume.store)>=RETENTION_STORES.indexOf(store))this.stopped=this.resume;else this.stopped={store}}remainingMs(){return Math.max(0,this.budgetMs-(this.now()-this.startedAt))}done(store,name){this.last={store,lastName:name}}}init_resilient();import{join as join38}from"node:path";init_resilient();import{join as join31}from"node:path";async function readReflectionRetentionGuard(context){await mkdir(context.paths.locks,{recursive:!0,mode:448});let record=await createLockRecord("reflection-scheduler",{runId:"runtime-retention"});try{return await withLock(reflectionSchedulerLockPath(context.paths.locks),record,async()=>{let highWater=await scanReflectionRunHighWater(context.paths);if(highWater>0)await recordReflectionRunIdMark(context.paths.reflection,highWater);let reservations=await readReservations(context.paths.reflection);return{highWater,reserved:reservations.runIds,reservedConversationIds:reservations.conversationIds}},{waitTimeoutMs:0})}catch(error){if(error instanceof LockContentionError)return;throw error}}async function reservedRunIds(reflectionDir){return(await readReservations(reflectionDir)).runIds}async function readReservations(reflectionDir){let runIds=new Set,conversationIds=new Set;for(let name of["active.lock","pending.json"]){let record=await readFile(join31(reflectionDir,name),"utf8").then((raw)=>JSON.parse(raw)).catch(()=>{return});if(typeof record?.runId==="string")runIds.add(record.runId);let ids=record?.request?.conversationIds;if(Array.isArray(ids)){for(let id of ids)if(typeof id==="string")conversationIds.add(id)}}return{runIds,conversationIds}}class LazyRetentionGuard{context;pending;value;busy=!1;constructor(context){this.context=context}async get(){return this.pending??=readReflectionRetentionGuard(this.context).then((guard)=>(this.value=guard,this.busy=guard===void 0,guard)),this.pending}}init_resilient();import{join as join33}from"node:path";init_resilient();import{join as join32}from"node:path";var DAY_MS=86400000,DEFAULT_RUNTIME_RETENTION={retentionDays:7,abandonedJournalDays:14,discardUnreflectedJournals:!1,completionsDays:30,passBudgetMs:60000};class StoreTally{removed=[];kept={};keep(name,reason){this.kept[name]=reason}result(){return{removed:[...this.removed].sort(),kept:{...this.kept}}}}function errorCode19(error){return error instanceof Error&&"code"in error&&typeof error.code==="string"?error.code:void 0}function describeError(error){return error instanceof Error?error.message:String(error)}async function listNames(directory){try{return(await readdir(directory)).sort()}catch(error){if(errorCode19(error)==="ENOENT"||errorCode19(error)==="ENOTDIR")return[];throw error}}async function newestMtime(path){let stats=await lstat(path).catch(()=>{return});if(stats===void 0)return;let newest=stats.mtimeMs;if(!stats.isDirectory())return newest;for(let name of await listNames(path)){let inner=await newestMtime(join32(path,name));if(inner!==void 0&&inner>newest)newest=inner}return newest}async function idleSince(path,cutoffMs){let newest=await newestMtime(path);return newest!==void 0&&newest<=cutoffMs}var SUCCESS_OUTCOMES=new Set(["merged","no_changes"]);async function readUnreflectedRetentionGate(reflectionDir,reflectionEnabled,admit=()=>!0){if(!reflectionEnabled)return{open:!0};let parkedAt=await readJson2(join33(reflectionDir,"park.json")).then((park)=>stringField(park,"parkedAt"));if(parkedAt!==void 0)return{open:!1,newest:{kind:"parked",at:parkedAt}};let lastSuccess,lastFailure,failure=(kind,at)=>{if(lastFailure===void 0||at>lastFailure.at)lastFailure={kind,at}},completions=join33(reflectionDir,"completions");for(let name of await listNames(completions)){if(!name.endsWith(".json"))continue;if(!admit())return;let record=await readJson2(join33(completions,name)),outcome=stringField(record,"outcome"),at=parse(stringField(record,"finishedAt"));if(outcome===void 0||at===void 0)continue;if(SUCCESS_OUTCOMES.has(outcome))lastSuccess=Math.max(lastSuccess??at,at);else failure("failed",at)}let runs=join33(reflectionDir,"runs");for(let name of await listNames(runs)){if(!admit())return;let abandoned=parse(stringField(await readJson2(join33(runs,name,"abandoned.json")),"generation"));if(abandoned!==void 0)failure("abandoned",abandoned);let quarantined=parse(stringField(await readJson2(join33(runs,name,"quarantined.json")),"generation"));if(quarantined!==void 0)failure("quarantined",quarantined)}if(lastFailure===void 0||lastSuccess!==void 0&&lastSuccess>=lastFailure.at)return{open:!0};return{open:!1,newest:{kind:lastFailure.kind,at:new Date(lastFailure.at).toISOString()}}}async function readJson2(path){try{return JSON.parse(await readFile(path,"utf8"))}catch{return}}function stringField(value,key){if(!value||typeof value!=="object"||Array.isArray(value))return;let field=value[key];return typeof field==="string"&&field.length>0?field:void 0}function parse(value){if(value===void 0)return;let at=Date.parse(value);return Number.isNaN(at)?void 0:at}init_resilient();import{Buffer as Buffer5}from"node:buffer";import{randomUUID as randomUUID12}from"node:crypto";import{join as join34}from"node:path";var TRANSCRIPT="transcript.jsonl",STATE="state.json",LOCK="state.lock";async function pruneTranscriptJournals(context,lazyGuard,gate,lock=withLocalJournalLock){let tally=new StoreTally;for(let sessionId of await listNames(context.paths.transcripts)){if(context.budget?.skip("journals",sessionId)===!0)continue;if(context.budget?.admit("journals")===!1)break;let outcome=await visitJournal(context,lazyGuard,gate,lock,sessionId).catch((error)=>{if(context.signal?.aborted===!0)throw error;return"state-unreadable"});if(outcome==="removed")tally.removed.push(sessionId);else if(outcome!==void 0)tally.keep(sessionId,outcome);context.budget?.done("journals",sessionId)}return tally.result()}async function visitJournal(context,lazyGuard,gate,lock,sessionId){let dir=join34(context.paths.transcripts,sessionId),stats=await lstat(dir).catch(()=>{return});if(stats===void 0||!stats.isDirectory())return;if(context.isLiveSession?.(sessionId)===!0)return"live";if(existsSync(join34(dir,LOCK)))return"locked";let first=await judge(context,dir,!1,gate);if(typeof first==="string")return first;let guard=await lazyGuard.get();if(guard===void 0)return"scheduler-busy";if(guard.reservedConversationIds.has(sessionId))return"reserved";return await context.beforeJournalClaim?.(sessionId),removeUnderLock(context,dir,lock,gate)}async function judge(context,dir,holdingLock,gate){let state=await readState(join34(dir,STATE));if(state==="unreadable")return"state-unreadable";let kind=classify(state);if(typeof kind==="string")return kind;if(kind.kind!=="never"&&!existsSync(join34(dir,TRANSCRIPT)))return"pruned";if(kind.kind!=="fully"&&!context.policy.discardUnreflectedJournals)return"unreflected-retention-off";if(kind.kind!=="fully"&&gate?.open!==!0)return"reflection-unhealthy";let days=kind.kind==="fully"?context.policy.retentionDays:context.policy.abandonedJournalDays,cutoff=context.now()-days*DAY_MS,newest=await newestFileMtime(dir,holdingLock);if(newest===void 0||newest>cutoff)return"recent";let startedAt=typeof state?.last_reflection_started_at==="string"?Date.parse(state.last_reflection_started_at):Number.NaN;if(!Number.isNaN(startedAt)&&startedAt>cutoff)return"recent";if(state!==void 0&&!await transcriptMatchesState(dir,state))return"state-behind-transcript";return kind}async function transcriptMatchesState(dir,state){let size=(await lstat(join34(dir,TRANSCRIPT)).catch(()=>{return}))?.size;if(size===void 0)return!0;let entries=await new TranscriptJournal({journalDir:dir}).readEntriesSnapshot();if(entries.reduce((total,entry)=>total+Buffer5.byteLength(`${JSON.stringify(entry)}
|
|
38
|
+
`,"utf8"),0)!==size)return!1;let anchor=typeof state.reflected_through_message_id==="string"?state.reflected_through_message_id:void 0,derived=deriveState({...initialReflectionState(),...anchor===void 0?{}:{reflected_through_message_id:anchor},reflected_completed_steps:count(state.reflected_completed_steps)??0},entries);if(derived.total_completed_steps!==count(state.total_completed_steps))return!1;return state.unreflected_bytes===void 0||derived.unreflected_bytes===state.unreflected_bytes}function classify(state){if(state===void 0)return{kind:"never"};let total=count(state.total_completed_steps),reflected=count(state.reflected_completed_steps),since=count(state.steps_since_last_successful_reflection);if(total===void 0||reflected===void 0||since===void 0)return"unclassified";let anchor=typeof state.reflected_through_message_id==="string"&&state.reflected_through_message_id.length>0;if(reflected===0&&!anchor)return{kind:"never"};if(total>0&&since===0&&anchor)return state.pending_compaction===!0?"pending-compaction":{kind:"fully"};if(reflected>0&&since>0&&anchor)return{kind:"partly"};return"unclassified"}function count(value){if(value===void 0)return 0;return typeof value==="number"&&Number.isInteger(value)&&value>=0?value:void 0}async function readState(path){let raw;try{raw=await readFile(path,"utf8")}catch(error){if(errorCode19(error)==="ENOENT")return;throw error}try{let parsed=JSON.parse(raw);return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:"unreadable"}catch{return"unreadable"}}async function newestFileMtime(dir,holdingLock){let newest=holdingLock?0:(await lstat(dir).catch(()=>{return}))?.mtimeMs;if(newest===void 0)return;for(let name of await listNames(dir)){if(holdingLock&&name===LOCK)continue;let stamp=(await lstat(join34(dir,name)).catch(()=>{return}))?.mtimeMs;if(stamp!==void 0&&stamp>newest)newest=stamp}return newest}async function removeUnderLock(context,dir,lock,gate){let verdict;try{verdict=await lock(join34(dir,LOCK),async()=>{let current=await judge(context,dir,!0,gate);if(typeof current==="string")return current;if(current.kind==="never")await unlinkIfPresent2(join34(dir,STATE)),await unlinkIfPresent2(join34(dir,TRANSCRIPT));else await stampPruned(join34(dir,STATE),context.now()),await unlinkIfPresent2(join34(dir,TRANSCRIPT));return current})}catch(error){if(error instanceof JournalLockTimeoutError)return"locked";throw error}if(typeof verdict==="string")return verdict;if(verdict.kind!=="never")return"removed";try{return await rmdir(dir),"removed"}catch(error){let code=errorCode19(error);if(code==="ENOENT")return"removed";if(code==="ENOTEMPTY"||code==="EEXIST")return"changed-during-removal";throw error}}async function unlinkIfPresent2(path){await unlink(path).catch((error)=>{if(errorCode19(error)!=="ENOENT")throw error})}async function stampPruned(statePath,now){let state=await readState(statePath);if(state==="unreadable"||state===void 0)throw Error(`journal state vanished under its lock: ${statePath}`);let temporary=`${statePath}.tmp-${randomUUID12()}`;try{let{reflected_through_byte_offset:_offset,...kept}=state;await writeFile2(temporary,`${JSON.stringify({...kept,transcript_pruned_at:new Date(now).toISOString()},null,2)}
|
|
39
|
+
`,"utf8"),await rename2(temporary,statePath)}catch(error){throw await rm(temporary,{force:!0}),error}}async function classifyJournalEntry(context,dir,gate={open:!0}){context.signal?.throwIfAborted();let stats=await lstat(dir).catch(()=>{return});if(stats===void 0||!stats.isDirectory())return;return judge(context,dir,!1,gate).catch((error)=>{if(context.signal?.aborted===!0)throw error;return"state-unreadable"})}init_resilient();import{randomUUID as randomUUID13}from"node:crypto";import{join as join35}from"node:path";var RETENTION_TOMBSTONE_PREFIX=".prune-",FOLDED_OUTCOMES=new Set(["merged","no_changes"]),TERMINAL_SENTINELS2=["abandoned.json","quarantined.json"];async function pruneReflectionRuns(context,lazyGuard){let runsDir=join35(context.paths.reflection,"runs"),tally=new StoreTally,folded=[],crashTombstones=[];for(let name of await listNames(runsDir)){if(context.budget?.proceed("runs")===!1)return tally.result();let runDir=join35(runsDir,name);if(name.startsWith(RETENTION_TOMBSTONE_PREFIX)){crashTombstones.push(runDir);continue}let classified=await classify2(runDir,name);if(typeof classified==="string")tally.keep(name,classified);else folded.push(classified)}for(let runDir of crashTombstones){if(context.budget?.admit("runs")===!1)return tally.result();await removeTombstone(runDir,context)}let newest=folded.reduce((best,run)=>best===void 0||run.finishedAt>best.finishedAt||run.finishedAt===best.finishedAt&&run.name>best.name?run:best,void 0),cutoff=context.now()-context.policy.retentionDays*DAY_MS;for(let run of folded){if(context.budget?.skip("runs",run.name)===!0)continue;if(context.budget?.admit("runs")===!1)break;let guard=run.name===newest?.name||run.finishedAt>cutoff||!await idleSince(join35(runsDir,run.name),cutoff)?void 0:await lazyGuard.get();if(run.name===newest?.name)tally.keep(run.name,"anchor");else if(run.finishedAt>cutoff||!await idleSince(join35(runsDir,run.name),cutoff))tally.keep(run.name,"recent");else if(guard===void 0)tally.keep(run.name,"scheduler-busy");else if(guard.reserved.has(run.name))tally.keep(run.name,"reserved");else if(reflectionRunNumber(run.name)===guard.highWater)tally.keep(run.name,"anchor");else{let outcome=await claimAndRemove(context,runsDir,run.name,cutoff);if(outcome==="removed")tally.removed.push(run.name);else tally.keep(run.name,outcome)}context.budget?.done("runs",run.name)}return tally.result()}async function classify2(runDir,name){let raw;try{raw=await readFile(join35(runDir,"final.json"),"utf8")}catch(error){if(errorCode19(error)!=="ENOENT"&&errorCode19(error)!=="ENOTDIR")return"malformed";return TERMINAL_SENTINELS2.some((file)=>existsSync(join35(runDir,file)))?"unfolded-terminal":"no-terminal"}let final;try{let parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return"malformed";final=parsed}catch{return"malformed"}let finishedAt=typeof final.finishedAt==="string"?Date.parse(final.finishedAt):Number.NaN;if(final.runId!==name||Number.isNaN(finishedAt)||typeof final.outcome!=="string")return"malformed";return FOLDED_OUTCOMES.has(final.outcome)?{name,finishedAt}:"unfolded-terminal"}async function claimAndRemove(context,runsDir,name,cutoff){let lockPath=runFinalizationLockPath(context.paths.locks,name),record=await createLockRecord("runtime-retention",{runId:name});try{await acquireLock(lockPath,record,{waitTimeoutMs:0})}catch(error){if(error instanceof LockContentionError)return"locked";throw error}let tombstone;try{if((await reservedRunIds(context.paths.reflection)).has(name))return"reserved";if(!await idleSince(join35(runsDir,name),cutoff))return"recent";tombstone=join35(runsDir,`${RETENTION_TOMBSTONE_PREFIX}${name}-${randomUUID13()}`);try{await context.beforeClaimRename?.(join35(runsDir,name),tombstone),await rename2(join35(runsDir,name),tombstone)}catch(error){return context.warn?.("memory runtime retention could not claim a run directory",{runId:name,error:describeError(error)}),"claim-failed"}}finally{await releaseLock(lockPath,record)}return await context.beforeTombstoneDelete?.(tombstone),await removeTombstone(tombstone,context),"removed"}async function removeTombstone(path,context){try{return await removeTree(path),!0}catch(error){return context.warn?.("memory runtime retention could not delete a tombstone",{path,error:describeError(error)}),!1}}init_resilient();import{randomUUID as randomUUID14}from"node:crypto";import{basename as basename6,dirname as dirname6,join as join36}from"node:path";var KIBITZER_SIDECAR_OWNER_LOCK_PURPOSE="recall-sidecar",KIBITZER_SIDECAR_TOMBSTONE_PREFIX=".prune-",KIBITZER_ENCODED_SESSION_PATTERN=/^[A-Za-z0-9_-]+$/,SIDECARS_DIRNAME="sidecars",OWNER_LOCK_PREFIX="recall-sidecar.",OWNER_LOCK_SUFFIX=".lock",KIBITZER_SIDECAR_RETENTION_MS=604800000;function kibitzerSidecarsRoot(recallDir){return join36(recallDir,SIDECARS_DIRNAME)}function kibitzerSidecarOwnerLockPathFor(locksDir,encodedSession){return join36(locksDir,`${OWNER_LOCK_PREFIX}${encodedSession}${OWNER_LOCK_SUFFIX}`)}async function pruneKibitzerSidecars(options){let now=options.now??Date.now,maxAgeMs=options.maxAgeMs??KIBITZER_SIDECAR_RETENTION_MS,owned=options.owned??new Set,root=kibitzerSidecarsRoot(options.recallDir),names=await readdir(root).catch((error)=>{if(errorCode20(error)!=="ENOENT")options.warn?.("kibitzer sidecar sweep listing failed",{path:root,error:describe(error)});return[]}),pruned=[],keptReasons={};for(let name of[...names].sort()){let path=join36(root,name);if(!name.startsWith(KIBITZER_SIDECAR_TOMBSTONE_PREFIX)){if(options.skip?.(name)===!0)continue;if(options.admit?.()===!1)break}let outcome=await visitSidecar(options,name,path,now,maxAgeMs,owned);if(outcome==="removed")pruned.push(name);else if(outcome!==void 0)keptReasons[name]=outcome;if(!name.startsWith(KIBITZER_SIDECAR_TOMBSTONE_PREFIX))options.done?.(name)}return{pruned,kept:Object.keys(keptReasons),keptReasons}}async function visitSidecar(options,name,path,now,maxAgeMs,owned){if(name.startsWith(KIBITZER_SIDECAR_TOMBSTONE_PREFIX)){await remove(path,options.warn);return}if(owned.has(name))return"owned";if(!KIBITZER_ENCODED_SESSION_PATTERN.test(name))return;let stats=await lstat(path).catch(()=>{return});if(stats===void 0||!stats.isDirectory())return;if(!await idleFor(path,now(),maxAgeMs))return"recent";return claimAndRemove2(path,kibitzerSidecarOwnerLockPathFor(options.locksDir,name),now(),maxAgeMs,options)}async function idleFor(dir,at,maxAgeMs){let newest=await newestMtime2(dir);return newest!==void 0&&at-newest>=maxAgeMs}async function newestMtime2(dir){let own=await lstat(dir).then((stats)=>stats.mtimeMs,()=>{return});if(own===void 0)return;let newest=own;for(let name of await readdir(dir).catch(()=>[])){let stamp=await lstat(join36(dir,name)).then((stats)=>stats.mtimeMs,()=>{return});if(stamp!==void 0&&stamp>newest)newest=stamp}return newest}async function claimAndRemove2(dir,lockPath,at,maxAgeMs,options){let warn=options.warn,record;try{record=await createLockRecord(KIBITZER_SIDECAR_OWNER_LOCK_PURPOSE),await acquireLock(lockPath,record,{waitTimeoutMs:0})}catch(error){if(!(error instanceof LockContentionError))warn?.("kibitzer sidecar sweep lock failed",{lockPath,error:describe(error)});return"locked"}let tombstone;try{if(!await idleFor(dir,at,maxAgeMs))return"recent";tombstone=join36(dirname6(dir),`${KIBITZER_SIDECAR_TOMBSTONE_PREFIX}${basename6(dir)}-${randomUUID14()}`);try{await options.beforeClaimRename?.(dir,tombstone),await rename2(dir,tombstone)}catch(error){if(errorCode20(error)==="ENOENT")return"changed-during-removal";return warn?.("kibitzer sidecar sweep claim failed",{path:dir,error:describe(error)}),"claim-failed"}}finally{await releaseLock(lockPath,record).catch((error)=>{warn?.("kibitzer sidecar sweep lock release failed",{lockPath,error:describe(error)})})}return await options.beforeTombstoneDelete?.(tombstone),await remove(tombstone,warn),"removed"}async function remove(path,warn){try{return await removeTree(path),!0}catch(error){return warn?.("kibitzer sidecar sweep removal failed",{path,error:describe(error)}),!1}}function errorCode20(error){return error instanceof Error&&"code"in error&&typeof error.code==="string"?error.code:void 0}function describe(error){return error instanceof Error?error.message:String(error)}init_resilient();import{join as join37}from"node:path";var DEFAULT_RUNTIME_MAX_BYTES=2147483648,RUNTIME_SIZE_WARN_RATIO=0.8;function runtimeSizeStanding(bytes,maxBytes){if(maxBytes<=0)return{level:"ok"};let percent=Math.floor(bytes/maxBytes*100);return{level:bytes>=maxBytes*RUNTIME_SIZE_WARN_RATIO?"warn":"ok",percent}}function formatRuntimeBytes(bytes){let units=["KiB","MiB","GiB","TiB"];if(bytes<1024)return`${bytes} B`;let value=bytes/1024,unit=0;while(value>=1024&&unit<units.length-1)value/=1024,unit+=1;return`${value.toFixed(value>=100?0:1)} ${units[unit]}`}var SPLIT_STORES=new Set(["reflection","recall"]);function chargedBytes(stats){let blocks=stats.blocks;if(typeof blocks==="number"&&Number.isFinite(blocks)&&(blocks>0||stats.size===0))return blocks*512;return stats.size}function isGone(error){let code=error instanceof Error&&"code"in error?error.code:void 0;return code==="ENOENT"||code==="ENOTDIR"}async function lstatOrUndefined(path){try{return await lstat(path)}catch(error){if(isGone(error))return;throw error}}async function namesOf(path){try{return await readdir(path)}catch(error){if(isGone(error))return[];throw error}}async function measureTreeBytes(path,signal){signal?.throwIfAborted();let stats=await lstatOrUndefined(path);if(stats===void 0)return 0;let bytes=chargedBytes(stats);if(!stats.isDirectory())return bytes;for(let name of await namesOf(path))bytes+=await measureTreeBytes(join37(path,name),signal);return bytes}async function measureRuntimeSizeWithinBudget(runtimeDir,input){let signal=input.signal??(input.budgetMs===void 0?void 0:AbortSignal.timeout(input.budgetMs));try{return{size:await measureRuntimeSize(runtimeDir,signal===void 0?{}:{signal})}}catch(error){if(signal?.aborted!==!0)throw error;return{sizeUnknown:{budgetMs:input.budgetMs??0,at:new Date(input.now).toISOString()}}}}async function measureRuntimeSize(runtimeDir,options={}){let signal=options.signal;signal?.throwIfAborted();let root=await lstatOrUndefined(runtimeDir);if(root===void 0)return{bytes:0,stores:[]};let bytes=chargedBytes(root),stores=[];if(root.isDirectory())for(let name of await namesOf(runtimeDir)){let path=join37(runtimeDir,name),stats=await lstatOrUndefined(path);if(stats===void 0)continue;if(stats.isDirectory()&&SPLIT_STORES.has(name)){bytes+=chargedBytes(stats);for(let child of await namesOf(path)){let childBytes=await measureTreeBytes(join37(path,child),signal);bytes+=childBytes,stores.push({store:`${name}/${child}`,bytes:childBytes})}continue}let storeBytes=await measureTreeBytes(path,signal);bytes+=storeBytes,stores.push({store:name,bytes:storeBytes})}return stores.sort((left,right)=>right.bytes-left.bytes||left.store.localeCompare(right.store)),{bytes,stores}}var RUNTIME_CAP_SIDECAR_FLOOR_MS=3600000,RUNTIME_CAP_JOURNAL_FLOOR_MS=86400000,RUNTIME_CAP_KEPT_UNFOLDED_RUNS=10,CAP_KEEP_REASONS=new Set(["reserved","reflection-unhealthy","unreflected-retention-off","high-water","newest","newest-unfolded","reserved","locked","recent","live","owned","changed-during-removal","state-unreadable"]);function capOutcome(outcome){if(outcome==="removed")return"removed";return CAP_KEEP_REASONS.has(outcome)?outcome:"recent"}async function runRuntimeSizeCap(options){options.signal?.throwIfAborted();let clock=options.clock??(()=>performance.now()),kept={},evicted=[],skipped=[],gate={suspendedSince:void 0,heldBytes:0};await clearTombstones(options);let measureStart=clock(),budgetSignal=options.measureSignal,keptResume=options.resume===void 0?{}:{cursor:options.resume},beforeBytes;try{beforeBytes=(await measureRuntimeSize(options.paths.runtime,budgetSignal===void 0?{}:{signal:budgetSignal})).bytes}catch(error){if(options.signal?.throwIfAborted(),budgetSignal?.aborted!==!0)throw error;return skipped.push("measure-over-budget"),{maxBytes:options.maxBytes,beforeBytes:0,afterBytes:0,exceededBytes:0,evicted,kept,skipped,measureMs:clock()-measureStart,unreflectedHeldBytes:0,...keptResume}}let measureEnd=clock(),measureMs=measureEnd-measureStart,base={maxBytes:options.maxBytes,beforeBytes,evicted,kept,skipped,measureMs,unreflectedHeldBytes:0},unchanged=()=>({...base,afterBytes:beforeBytes,exceededBytes:options.maxBytes>0?Math.max(0,beforeBytes-options.maxBytes):0});if(options.budgetMs!==void 0&&measureMs>options.budgetMs)return skipped.push("measure-over-budget"),{...unchanged(),...keptResume};if(options.maxBytes<=0||beforeBytes<=options.maxBytes)return unchanged();let guard=await readReflectionRetentionGuard({...options});if(guard===void 0)skipped.push("reflection-scheduler-busy");let deadline=options.budgetMs===void 0?Number.POSITIVE_INFINITY:measureEnd+options.budgetMs,bytes=beforeBytes,last,cursor;walk:for(let tier of await tiers(options,guard,kept,gate))for(let candidate of await tier()){if(bytes<=options.maxBytes)break walk;if(isBeforeCursor(candidate,options.resume))continue;if(options.signal?.throwIfAborted(),clock()>=deadline){cursor=last===void 0?options.resume:{store:"cap",tier:last.tier,clock:last.at,lastName:last.name};break walk}let size=await measureTreeBytes(candidate.measuredPath),outcome=await candidate.evict();if(last=candidate,outcome==="removed")bytes-=size,evicted.push({tier:candidate.tier,name:candidate.name,bytes:size});else kept[candidate.name]=outcome}let afterBytes=evicted.length===0?beforeBytes:(await measureRuntimeSize(options.paths.runtime)).bytes;return{...base,unreflectedHeldBytes:gate.heldBytes,afterBytes,exceededBytes:Math.max(0,afterBytes-options.maxBytes),...gate.suspendedSince===void 0?{}:{suspendedSince:gate.suspendedSince},...cursor===void 0?{}:{cursor}}}async function measureRuntimeCapEvictableBytes(options){let reservations=await readReservations(options.paths.reflection),guard={highWater:await scanReflectionRunHighWater(options.paths),reserved:reservations.runIds,reservedConversationIds:reservations.conversationIds},bytes=0;for(let tier of await tiers({...options,maxBytes:0},guard,{},{suspendedSince:void 0,heldBytes:0}))for(let candidate of await tier())options.signal?.throwIfAborted(),bytes+=await measureTreeBytes(candidate.measuredPath);return bytes}function describeRuntimeCapExcess(input){if(input.overCapBytes<=0)return;let over=`cap exceeded by ${formatRuntimeBytes(input.overCapBytes)}`,held=!input.discardUnreflectedJournals&&input.unreflectedBytes>0?`held by unreflected journals: ${formatRuntimeBytes(input.unreflectedBytes)} (discard_unreflected_journals off)`:void 0;if(input.evictableBytes>=input.overCapBytes)return`${over}; the next maintenance pass evicts it (${formatRuntimeBytes(input.evictableBytes)} evictable)`;if(input.evictableBytes>0)return`${over}; the next maintenance pass evicts up to ${formatRuntimeBytes(input.evictableBytes)} of it${held===void 0?"":`; ${held}`}`;if(held!==void 0&&input.overCapBytes<=input.unreflectedBytes)return`${over}, nothing evictable; ${held}`;return`${over}, nothing evictable: live sessions, reserved runs and the newest runs are never evicted${held===void 0?"":`; ${held}`}`}function isBeforeCursor(candidate,cursor){if(cursor===void 0||candidate.tier!==cursor.tier)return!1;return candidate.at<cursor.clock||candidate.at===cursor.clock&&candidate.name.localeCompare(cursor.lastName)<=0}async function clearTombstones(options){let runsDir=join38(options.paths.reflection,"runs");for(let name of await listNames(runsDir))if(name.startsWith(RETENTION_TOMBSTONE_PREFIX))await removeTombstone(join38(runsDir,name),options);let sidecarsDir=kibitzerSidecarsRoot(options.paths.recall);for(let name of await listNames(sidecarsDir))if(name.startsWith(KIBITZER_SIDECAR_TOMBSTONE_PREFIX))await removeTombstone(join38(sidecarsDir,name),options)}async function tiers(options,guard,kept,gate){let runGuard=guard??{highWater:await scanReflectionRunHighWater(options.paths),reserved:await reservedRunIds(options.paths.reflection),reservedConversationIds:new Set},runs=await runCandidates(options,runGuard,kept),journalScan,journals=async()=>guard===void 0?void 0:await(journalScan??=journalCandidates(options,guard.reservedConversationIds,kept)),unfolded=async(entries)=>{if(entries.length===0)return entries;let hold=async(reason)=>{for(let entry of entries)kept[entry.name]=reason,gate.heldBytes+=await measureTreeBytes(entry.measuredPath);return[]};if(options.policy.discardUnreflectedJournals!==!0)return hold("unreflected-retention-off");let health=await readUnreflectedRetentionGate(options.paths.reflection,options.reflectionEnabled??!0);if(health===void 0)return hold("reflection-unhealthy");if(health.open)return entries;if(health.newest!==void 0)gate.suspendedSince=health.newest.at;return hold("reflection-unhealthy")};return[async()=>runs.folded,async()=>(await journals())?.fully??[],()=>sidecarCandidates(options,kept),async()=>unfolded((await journals())?.never??[]),async()=>unfolded((await journals())?.partly??[]),async()=>runs.unfolded]}async function runCandidates(options,guard,kept){let runsDir=join38(options.paths.reflection,"runs"),context={...options},folded=[],unfolded=[];for(let name of await listNames(runsDir)){if(name.startsWith(RETENTION_TOMBSTONE_PREFIX))continue;let classified=await classify2(join38(runsDir,name),name);if(typeof classified!=="string")folded.push({name,at:classified.finishedAt});else if(classified==="unfolded-terminal")unfolded.push({name,at:await newestMtime(join38(runsDir,name))??0})}let byAge=(left,right)=>left.at-right.at||left.name.localeCompare(right.name);folded.sort(byAge),unfolded.sort(byAge);let exempt=(name)=>{if(reflectionRunNumber(name)===guard.highWater)return"high-water";if(guard.reserved.has(name))return"reserved";return},newestFolded=folded.at(-1)?.name,foldedCandidates=[];for(let run of folded){let reason=exempt(run.name)??(run.name===newestFolded?"newest":void 0);if(reason!==void 0){kept[run.name]=reason;continue}foldedCandidates.push({tier:"folded-run",name:run.name,at:run.at,measuredPath:join38(runsDir,run.name),evict:async()=>capOutcome(await claimAndRemove(context,runsDir,run.name,Number.POSITIVE_INFINITY))})}let retentionCutoff=options.now()-options.policy.retentionDays*DAY_MS,keptUnfolded=new Set(unfolded.slice(-RUNTIME_CAP_KEPT_UNFOLDED_RUNS).map((run)=>run.name)),unfoldedCandidates=[];for(let run of unfolded){let reason=exempt(run.name)??(keptUnfolded.has(run.name)?"newest-unfolded":void 0)??(run.at>retentionCutoff?"recent":void 0);if(reason!==void 0){kept[run.name]=reason;continue}unfoldedCandidates.push({tier:"unfolded-run",name:run.name,at:run.at,measuredPath:join38(runsDir,run.name),evict:async()=>capOutcome(await claimAndRemove(context,runsDir,run.name,retentionCutoff))})}return{folded:foldedCandidates,unfolded:unfoldedCandidates}}async function journalCandidates(options,reserved,kept){let floorDays=(options.journalFloorMs??RUNTIME_CAP_JOURNAL_FLOOR_MS)/DAY_MS,context={...options,policy:{...options.policy,retentionDays:options.journalFloorMs===void 0?0:floorDays,abandonedJournalDays:floorDays}},lock=options.journalLock??withLocalJournalLock,classifyContext={...context,policy:{...context.policy,discardUnreflectedJournals:!0}},realGate=await readUnreflectedRetentionGate(options.paths.reflection,options.reflectionEnabled??!0),found={fully:[],never:[],partly:[]};for(let sessionId of await listNames(options.paths.transcripts)){let dir=join38(options.paths.transcripts,sessionId);if(options.isLiveSession?.(sessionId)===!0){kept[sessionId]="live";continue}if(reserved.has(sessionId)){kept[sessionId]="reserved";continue}let verdict=await classifyJournalEntry(classifyContext,dir);if(verdict==="state-unreadable")kept[sessionId]="state-unreadable";if(verdict===void 0||typeof verdict==="string")continue;found[verdict.kind].push({name:sessionId,at:await newestMtime(dir)??0})}let toCandidates=(entries,tier,transcriptOnly)=>entries.sort((left,right)=>left.at-right.at||left.name.localeCompare(right.name)).map((entry)=>{let dir=join38(options.paths.transcripts,entry.name);return{tier,name:entry.name,at:entry.at,measuredPath:transcriptOnly?join38(dir,"transcript.jsonl"):dir,evict:async()=>capOutcome(await removeUnderLock(context,dir,lock,realGate).catch((error)=>{if(options.signal?.aborted===!0)throw error;return"state-unreadable"}))}});return{fully:toCandidates(found.fully,"fully-reflected-transcript",!0),never:toCandidates(found.never,"never-reflected-journal",!1),partly:toCandidates(found.partly,"partly-reflected-transcript",!0)}}async function sidecarCandidates(options,kept){let root=kibitzerSidecarsRoot(options.paths.recall),entries=[];for(let name of await listNames(root)){if(name.startsWith(KIBITZER_SIDECAR_TOMBSTONE_PREFIX)||!KIBITZER_ENCODED_SESSION_PATTERN.test(name))continue;if(options.ownedSidecars?.has(name)===!0){kept[name]="owned";continue}let path=join38(root,name),stats=await lstat(path).catch(()=>{return});if(stats===void 0||!stats.isDirectory())continue;let at=await newestMtime(path)??0;if(options.now()-at<RUNTIME_CAP_SIDECAR_FLOOR_MS){kept[name]="recent";continue}entries.push({name,at})}return entries.sort((left,right)=>left.at-right.at||left.name.localeCompare(right.name)),entries.map((entry)=>({tier:"sidecar",name:entry.name,at:entry.at,measuredPath:join38(root,entry.name),evict:async()=>capOutcome(await claimAndRemove2(join38(root,entry.name),kibitzerSidecarOwnerLockPathFor(options.paths.locks,entry.name),options.now(),RUNTIME_CAP_SIDECAR_FLOOR_MS,{recallDir:options.paths.recall,locksDir:options.paths.locks,...options.warn===void 0?{}:{warn:options.warn}}))}))}init_resilient();import{join as join39}from"node:path";var COMPLETIONS_KEEP_NEWEST=50;async function pruneCompletions(context,lazyGuard){let dir=join39(context.paths.reflection,"completions"),tally=new StoreTally,records=[];for(let name of await listNames(dir)){if(!name.endsWith(".json"))continue;if(context.budget?.proceed("completions")===!1)return tally.result();let runId=name.slice(0,-5),record=await readCompletion(join39(dir,name),runId);if(record===void 0)tally.keep(runId,"malformed");else records.push(record)}let newestFirst=[...records].sort((left,right)=>right.finishedAt-left.finishedAt||(left.runId<right.runId?1:-1)),newest=new Set(newestFirst.slice(0,COMPLETIONS_KEEP_NEWEST).map((record)=>record.runId));records.sort((left,right)=>left.runId<right.runId?-1:left.runId>right.runId?1:0);let cutoff=context.now()-context.policy.completionsDays*DAY_MS;for(let record of records){if(context.budget?.skip("completions",record.runId)===!0)continue;if(context.budget?.admit("completions")===!1)break;let number=reflectionRunNumber(record.runId);if(newest.has(record.runId))tally.keep(record.runId,"newest");else if(!record.consumed)tally.keep(record.runId,"pending-delivery");else if(record.finishedAt>cutoff)tally.keep(record.runId,"recent");else if(existsSync(join39(context.paths.reflection,"runs",record.runId)))tally.keep(record.runId,"run-present");else{let guarded=await keepByGuard(context,lazyGuard,number);if(guarded!==void 0)tally.keep(record.runId,guarded);else await rm(join39(dir,`${record.runId}.json`),{force:!0}),tally.removed.push(record.runId)}context.budget?.done("completions",record.runId)}return tally.result()}async function keepByGuard(context,lazyGuard,number){let guard=await lazyGuard.get();if(guard===void 0)return"scheduler-busy";let mark=await readReflectionRunIdMark(context.paths.reflection);if(mark===void 0||number===0||number>mark)return"no-mark";if(number===guard.highWater)return"anchor";return}async function readCompletion(path,runId){try{let parsed=JSON.parse(await readFile(path,"utf8"));if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return;let record=parsed,delivery=record.delivery,finishedAt=typeof record.finishedAt==="string"?Date.parse(record.finishedAt):Number.NaN;if(record.schemaVersion!==1||record.runId!==runId||Number.isNaN(finishedAt))return;if(delivery?.status!=="pending"&&delivery?.status!=="consumed")return;return{runId,finishedAt,consumed:delivery.status==="consumed"}}catch{return}}init_resilient();import{join as join40}from"node:path";async function pruneLegacyRecallRuns(context){let dir=join40(context.paths.recall,"runs");if(!existsSync(dir))return"absent";if(context.budget?.skip("recall-runs","runs")===!0)return"kept";if(context.budget?.admit("recall-runs")===!1)return"kept";if(!await idleSince(dir,context.now()-context.policy.retentionDays*DAY_MS))return"kept";return await removeTree(dir),context.budget?.done("recall-runs","runs"),"removed"}async function pruneLegacyReflectionSessions(context,lazyGuard){let tally=new StoreTally,cutoff=context.now()-context.policy.retentionDays*DAY_MS;for(let name of await listNames(context.paths.reflectionSessions)){if(context.budget?.skip("reflection-sessions",name)===!0)continue;if(context.budget?.admit("reflection-sessions")===!1)break;let path=join40(context.paths.reflectionSessions,name),guard=await idleSince(path,cutoff)?await lazyGuard.get():void 0;if(!await idleSince(path,cutoff))tally.keep(name,"recent");else if(guard===void 0)tally.keep(name,"scheduler-busy");else if(reflectionRunNumber(name)===guard.highWater)tally.keep(name,"anchor");else try{await removeTree(path),tally.removed.push(name)}catch(error){context.warn?.("memory runtime retention could not remove a legacy reflection session",{path,error:describeError(error)}),tally.keep(name,"changed-during-removal")}context.budget?.done("reflection-sessions",name)}return tally.result()}init_resilient();import{join as join41}from"node:path";async function pruneRecallLedgers(context){let tally=new StoreTally,cutoff=context.now()-context.policy.completionsDays*DAY_MS;for(let name of await listNames(context.paths.recallLedger)){if(!name.endsWith(".json"))continue;if(context.budget?.skip("ledgers",name)===!0)continue;if(context.budget?.admit("ledgers")===!1)break;let sessionId=name.slice(0,-5),path=join41(context.paths.recallLedger,name),stats=await lstat(path).catch(()=>{return});if(stats===void 0||!stats.isFile())continue;if(context.isLiveSession?.(sessionId)===!0)tally.keep(sessionId,"live");else if(stats.mtimeMs>cutoff)tally.keep(sessionId,"recent");else await rm(path,{force:!0}),tally.removed.push(sessionId);context.budget?.done("ledgers",name)}return tally.result()}init_resilient();import{randomUUID as randomUUID15}from"node:crypto";import{join as join42}from"node:path";var CURSOR_FILE="retention.json";function retentionCursorPath(runtimeDir){return join42(runtimeDir,CURSOR_FILE)}async function readRetentionResumePoints(runtimeDir){let parsed;try{parsed=JSON.parse(await readFile(retentionCursorPath(runtimeDir),"utf8"))}catch{return{}}if(parsed.cursor?.store==="cap")return capResumePoint(parsed.cursor);let resumed=capResumePoint(parsed.cap),cap=resumed.cap!==void 0&&parsed.capStalled===!0?{...resumed,capStalled:!0}:resumed,cursor=parsed.cursor;if(typeof cursor?.store!=="string")return cap;return{cursor:{store:cursor.store,...typeof cursor.lastName==="string"?{lastName:cursor.lastName}:{}},...cap}}function capResumePoint(cursor){if(cursor?.store!=="cap"||typeof cursor.tier!=="string"||typeof cursor.lastName!=="string")return{};if(typeof cursor.clock!=="number"||!Number.isFinite(cursor.clock))return{};return{cap:{store:"cap",tier:cursor.tier,clock:cursor.clock,lastName:cursor.lastName}}}async function writeRetentionResumePoints(runtimeDir,points){let target=retentionCursorPath(runtimeDir),temporary=`${target}.tmp-${randomUUID15()}`;try{await writeFile2(temporary,`${JSON.stringify({version:1,...points})}
|
|
40
|
+
`,{encoding:"utf8",mode:384}),await rename2(temporary,target)}catch(error){throw await rm(temporary,{force:!0}),error}}async function clearRetentionCursor(runtimeDir){await rm(retentionCursorPath(runtimeDir),{force:!0})}async function runRuntimeRetention(options){options.signal?.throwIfAborted();let stored=await readRetentionResumePoints(options.paths.runtime),budget=new PassBudget(options.now,options.policy.passBudgetMs,options.signal,stored.cursor),context={...options,budget},guard=new LazyRetentionGuard(context),runs=await pruneReflectionRuns(context,guard),completions=await pruneCompletions(context,guard),reflectionSessions=await pruneLegacyReflectionSessions(context,guard),unreflectedGate=options.policy.discardUnreflectedJournals?await readUnreflectedRetentionGate(options.paths.reflection,options.reflectionEnabled??!0,()=>budget.proceed("journals")):void 0,journals=await pruneTranscriptJournals(context,guard,unreflectedGate),sidecarResult=await pruneKibitzerSidecars({recallDir:options.paths.recall,locksDir:options.paths.locks,now:options.now,maxAgeMs:options.policy.retentionDays*DAY_MS,skip:(name)=>budget.skip("sidecars",name),admit:()=>budget.admit("sidecars"),done:(name)=>budget.done("sidecars",name),...options.ownedSidecars===void 0?{}:{owned:options.ownedSidecars},...options.warn===void 0?{}:{warn:options.warn},...options.beforeClaimRename===void 0?{}:{beforeClaimRename:options.beforeClaimRename},...options.beforeTombstoneDelete===void 0?{}:{beforeTombstoneDelete:options.beforeTombstoneDelete}}),ledgers=await pruneRecallLedgers(context),recallRuns=await pruneLegacyRecallRuns(context),capResume=options.maxBytes===void 0?void 0:stored.cap,cap;if(options.maxBytes!==void 0&&budget.stopped===void 0)cap=await runRuntimeSizeCap({...options,maxBytes:options.maxBytes,budgetMs:budget.remainingMs(),measureSignal:options.signal===void 0?AbortSignal.timeout(budget.remainingMs()):AbortSignal.any([options.signal,AbortSignal.timeout(budget.remainingMs())]),...capResume===void 0?{}:{resume:capResume}}),capResume=cap.cursor;let capStalled=cap?.skipped.includes("measure-over-budget")===!0;if(budget.stopped!==void 0||capResume!==void 0){if(await writeRetentionResumePoints(options.paths.runtime,{...budget.stopped===void 0?{}:{cursor:budget.stopped},...capResume===void 0?{}:{cap:capResume,...capStalled?{capStalled:!0}:{}}}),budget.aborted)options.signal?.throwIfAborted()}else if(stored.cursor!==void 0||stored.cap!==void 0)await clearRetentionCursor(options.paths.runtime);let cursor=budget.stopped??cap?.cursor;return{...guard.value===void 0?{}:{highWater:guard.value.highWater},skipped:guard.busy?["reflection-scheduler-busy"]:[],runs,completions,reflectionSessions,journals,sidecars:{removed:[...sidecarResult.pruned].sort(),kept:sidecarResult.keptReasons},ledgers,recallRuns,...unreflectedGate===void 0?{}:{unreflectedGate},...cursor===void 0?{}:{cursor},...cap===void 0?{}:{cap}}}function summarizeRuntimeRetention(report){return{removed:[report.runs,report.completions,report.reflectionSessions,report.journals,report.sidecars,report.ledgers].reduce((total,store)=>total+store.removed.length,0)+(report.recallRuns==="removed"?1:0)+(report.cap?.evicted.length??0),runs:report.runs.removed.length,completions:report.completions.removed.length,reflectionSessions:report.reflectionSessions.removed.length,journals:report.journals.removed.length,sidecars:report.sidecars.removed.length,ledgers:report.ledgers.removed.length,recallRuns:report.recallRuns,skipped:report.skipped,...report.cursor===void 0?{}:{interruptedAt:report.cursor.store},...report.cap===void 0?{}:{capBytes:report.cap.maxBytes,bytesBefore:report.cap.beforeBytes,bytesAfter:report.cap.afterBytes,evicted:report.cap.evicted.length,evictedBytes:report.cap.evicted.reduce((total,entry)=>total+entry.bytes,0),overCapBytes:report.cap.exceededBytes,capKeptHighWater:Object.entries(report.cap.kept).filter(([,reason])=>reason==="high-water").map(([name])=>name)}}}function resolveForeignIdentityDiscardUnreflected(settings,identity){if(settings?.runtime?.discard_unreflected_journals!==!0)return!1;return settings.agents?.[identity]?.runtime?.discard_unreflected_journals!==!1}function window(settings,identity,key,fallback){for(let value of[settings?.agents?.[identity]?.runtime?.[key],settings?.runtime?.[key]])if(typeof value==="number"&&Number.isFinite(value)&&value>=0)return value;return fallback}function resolveForeignIdentityRetentionPolicy(settings,identity){return{retentionDays:window(settings,identity,"retention_days",DEFAULT_RUNTIME_RETENTION.retentionDays),abandonedJournalDays:window(settings,identity,"abandoned_journal_days",DEFAULT_RUNTIME_RETENTION.abandonedJournalDays),completionsDays:window(settings,identity,"completions_days",DEFAULT_RUNTIME_RETENTION.completionsDays),passBudgetMs:window(settings,identity,"pass_budget_ms",DEFAULT_RUNTIME_RETENTION.passBudgetMs),discardUnreflectedJournals:resolveForeignIdentityDiscardUnreflected(settings,identity)}}function resolveForeignIdentityMaxBytes(settings,identity){return window(settings,identity,"max_bytes",DEFAULT_RUNTIME_MAX_BYTES)}function createRetentionHostSweepStep(options={}){let now=options.now??Date.now;return async(identity)=>{if(options.dryRun===!0)return[];if(options.isHostedIdentity?.(identity.name)===!0)return[];let policy=resolveForeignIdentityRetentionPolicy(options.settings,identity.name),remaining=options.deadline===void 0?policy.passBudgetMs:Math.max(1,options.deadline-now());try{let report=await runRuntimeRetention({paths:buildIdentityPaths(dirname7(dirname7(identity.root)),identity.name),policy:{...policy,passBudgetMs:Math.min(policy.passBudgetMs,remaining)},maxBytes:resolveForeignIdentityMaxBytes(options.settings,identity.name),journalFloorMs:policy.retentionDays*DAY_MS,now,reflectionEnabled:!0,...options.signal===void 0?{}:{signal:options.signal}}),summary=summarizeRuntimeRetention(report);if(summary.removed===0&&report.cursor===void 0)return[];let counts=`runs ${summary.runs}, completions ${summary.completions}, journals ${summary.journals}, sidecars ${summary.sidecars}, ledgers ${summary.ledgers}, legacy ${summary.reflectionSessions}${report.recallRuns==="removed"?" + recall/runs":""}${report.cap===void 0||report.cap.evicted.length===0?"":`, size cap ${report.cap.evicted.length}`}`;return[`FIXED ${identity.name} retention removed ${summary.removed} (${counts})${report.cursor===void 0?"":`; resumes at ${report.cursor.store}`}`]}catch(error){if(options.signal?.aborted===!0)throw error;return[`FAIL ${identity.name} retention failed: ${error instanceof Error?error.message:String(error)}`]}}}init_resilient();import{basename as basename7,join as join43}from"node:path";var TERMINAL_SENTINELS3=["final.json","abandoned.json","quarantined.json"];async function exists2(path){return stat(path).then(()=>!0,()=>!1)}async function reservedRunId2(path){try{let parsed=JSON.parse(await readFile(path,"utf8")),runId=typeof parsed==="object"&&parsed!==null?parsed.runId:void 0;return typeof runId==="string"?runId:void 0}catch{return}}async function collectReflectionLiveRunIds(reflectionDir){let live=new Set;for(let name of["active.lock","pending.json"]){let runId=await reservedRunId2(join43(reflectionDir,name));if(runId!==void 0)live.add(runId)}let runsDir=join43(reflectionDir,"runs"),names=await readdir(runsDir).catch(()=>[]);for(let runId of names){if(runId.startsWith("."))continue;let runDir=join43(runsDir,runId);if((await Promise.all(TERMINAL_SENTINELS3.map((file)=>exists2(join43(runDir,file))))).some(Boolean))continue;if(await exists2(join43(runDir,"ledger.json"))||await exists2(join43(runDir,"prelaunch.json")))live.add(runId)}return live}async function sweepIdentityOrphanWorktrees(identityRoot,options){let repoDir=join43(identityRoot,"repo");if(!await exists2(join43(repoDir,".git")))return{skipped:"no-repo",removed:[],kept:[],failed:[]};let runtimeDir=join43(identityRoot,"runtime"),worktreesDir=join43(runtimeDir,"worktrees"),repo=new GitMemoryRepo({dir:repoDir,agentId:basename7(identityRoot)}),liveRunIds=await collectReflectionLiveRunIds(join43(runtimeDir,"reflection")),selection={liveRunIds,now:options.now,graceMs:REFLECTION_ORPHAN_GRACE_MS},leftovers=await listReflectionLeftovers(repo,worktreesDir),orphans=selectReflectionOrphans(leftovers,selection),orphanTargets=new Set([...orphans.registeredWorktrees.map((worktree)=>worktree.dir),...orphans.strayDirs,...orphans.branches]),keptReason=(target)=>[...liveRunIds].some((runId)=>basename7(target).endsWith(runId))?"live":"grace",kept=[...leftovers.registeredWorktrees.map((worktree)=>worktree.dir),...leftovers.strayDirs,...leftovers.branches].filter((target)=>!orphanTargets.has(target)).map((target)=>({target,reason:keptReason(target)}));if(options.dryRun===!0)return{removed:[...orphanTargets],kept,failed:[]};let receipts=await sweepReflectionOrphans(repo,worktreesDir,selection);return{removed:receipts.filter((receipt)=>receipt.removed).map((receipt)=>receipt.target),kept,failed:receipts.filter((receipt)=>!receipt.removed).map((receipt)=>({target:receipt.target,detail:receipt.detail??"not removed"}))}}init_resilient();import{join as join44}from"node:path";async function measureUnreflectedJournalBytes(input){let context={paths:input.paths,now:()=>Number.POSITIVE_INFINITY,policy:{...input.policy,retentionDays:0,abandonedJournalDays:0,discardUnreflectedJournals:!0},...input.signal===void 0?{}:{signal:input.signal}},bytes=0;for(let sessionId of await listNames(input.paths.transcripts)){let dir=join44(input.paths.transcripts,sessionId),verdict=await classifyJournalEntry(context,dir);if(verdict===void 0)continue;if(verdict==="state-behind-transcript")bytes+=await measureTreeBytes(dir);if(typeof verdict==="string")continue;if(verdict.kind==="never")bytes+=await measureTreeBytes(dir);else if(verdict.kind==="partly")bytes+=await measureTreeBytes(join44(dir,"transcript.jsonl"))}return bytes}export{DEFAULT_RUNTIME_MAX_BYTES,DEFAULT_RUNTIME_RETENTION,buildIdentityPaths,classifyReflectionLockHolder,createRetentionHostSweepStep,decideStaleReflectionLock,decideStrandedRun,describeRuntimeCapExcess,formatRuntimeBytes,formatStaleLockFixLines,measureRuntimeCapEvictableBytes,measureRuntimeSizeWithinBudget,measureUnreflectedJournalBytes,reclaimDeadOwnerLocks,runStaleLockReaper,runtimeSizeStanding,sweepHostIdentities,sweepIdentityOrphanWorktrees};
|