omo-ai 5.1.79 → 5.1.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/bin/darwin/omo-keychain +0 -0
  2. package/bin/lib/doctor.js +6 -17
  3. package/bin/lib/engine-commands.js +2 -0
  4. package/bin/lib/engine-environment.js +3 -0
  5. package/bin/lib/path-omo.js +53 -0
  6. package/bin/lib/provider-map.json +1 -1
  7. package/bin/lib/reflection-lock.generated.js +7 -7
  8. package/bin/lib/self-update.js +18 -2
  9. package/bin/lib/service-auth.generated.js +44 -42
  10. package/bin/lib/thread-output.js +9 -1
  11. package/bin/lib/thread.js +23 -3
  12. package/bin/lib/versioned-install.js +173 -0
  13. package/bin/lib/versioned-leftovers.js +58 -0
  14. package/package.json +2 -2
  15. package/plugin/CHANGELOG.md +117 -0
  16. package/plugin/README.md +2 -1
  17. package/plugin/extensions/gateway-store-worker.mjs +2 -2
  18. package/plugin/extensions/memory-run-supervisor.mjs +1 -1
  19. package/plugin/extensions/omo-claim-receipt.js +2 -2
  20. package/plugin/extensions/omo-computer-run-worker.mjs +1 -1
  21. package/plugin/extensions/omo-computer-use.js +1 -1
  22. package/plugin/extensions/omo-desktop-toolkit.js +1 -1
  23. package/plugin/extensions/omo-device-account.js +7 -7
  24. package/plugin/extensions/omo-device-service.js +6 -6
  25. package/plugin/extensions/omo-feedback.js +2 -2
  26. package/plugin/extensions/omo-init-deep-advisor.js +2 -2
  27. package/plugin/extensions/omo-member.js +2 -2
  28. package/plugin/extensions/omo-memory-commands.js +2 -2
  29. package/plugin/extensions/omo-memory-doctor.js +3 -3
  30. package/plugin/extensions/omo-memory-memfs.js +1 -1
  31. package/plugin/extensions/omo-memory-palace.js +2 -2
  32. package/plugin/extensions/omo-memory-sync.js +1 -1
  33. package/plugin/extensions/omo-onboarding-scan.js +2 -2
  34. package/plugin/extensions/omo-recall-store.js +1 -1
  35. package/plugin/extensions/omo-session-history.js +1 -1
  36. package/plugin/extensions/omo-side-panel.js +2 -2
  37. package/plugin/extensions/omo-task.js +2 -2
  38. package/plugin/extensions/omo-telemetry-otlp.js +2 -2
  39. package/plugin/extensions/omo-telemetry-posthog.js +1 -1
  40. package/plugin/extensions/omo-telemetry-recovery.js +1 -1
  41. package/plugin/extensions/omo-thread-client.js +3 -3
  42. package/plugin/extensions/omo-wake.js +6 -6
  43. package/plugin/extensions/omo.js +3 -3
  44. package/plugin/package.json +3 -2
  45. package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
  46. package/plugin/runtime/ast-grep-mcp/manifest.json +1 -1
  47. package/plugin/runtime/bunshin-ts/sdk.js +2 -2
  48. package/plugin/runtime/category-coverage/index.js +3 -3
  49. package/plugin/runtime/omo-sdk/sdk.js +65 -0
  50. package/plugin/runtime/rollback-migrate.js +1 -1
  51. package/plugin/runtime/task-config/index.js +1 -1
  52. package/plugin/runtime/thread-sdk/sdk.js +3 -3
  53. package/plugin/scripts/install.mjs +3 -1
  54. package/plugin/skills/browser/runtime/omowright/manifest.json +1 -1
  55. package/plugin/skills/omo-relay/SKILL.md +38 -0
  56. package/plugin/skills/omo-relay/references/errors.md +16 -0
  57. package/plugin/skills/omo-relay/references/machines.md +53 -0
  58. package/plugin/skills/omo-relay/references/parallel.md +51 -0
  59. package/plugin/skills/omo-relay/scripts/sdk/bind-eval.ts +153 -0
  60. package/plugin/skills/omo-relay/scripts/sdk/index.ts +5 -0
  61. package/plugin/skills/omo-relay/scripts/sdk/machines.ts +123 -0
  62. package/plugin/skills/omo-relay/scripts/sdk/outcome.ts +77 -0
  63. package/plugin/skills/omo-relay/scripts/sdk/ports.ts +78 -0
  64. package/plugin/skills/omo-relay/scripts/sdk/threads.ts +89 -0
  65. package/plugin/skills/omo-relay/scripts/sdk/tsconfig.json +19 -0
  66. package/plugin/skills/programming/SKILL.md +1 -0
  67. package/plugin/skills/ultrawork/SKILL.md +0 -22
  68. package/plugin/skills/ultrawork/references/gpt.md +67 -0
  69. package/plugin/skills/ulw-execute/SKILL.md +15 -5
  70. package/plugin/telemetry-schema.json +2 -1
  71. package/plugin/telemetry-schema.omo-cloud.json +2 -1
  72. package/plugin/skills/ultrawork/references/astra-variant.md +0 -66
Binary file
package/bin/lib/doctor.js CHANGED
@@ -2,6 +2,7 @@ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"
2
2
  import { homedir } from "node:os"
3
3
  import { join, resolve } from "node:path"
4
4
  import { canonicalAgentDir } from "./agent-dir.js"
5
+ import { isEngineCommand } from "./engine-commands.js"
5
6
  import { fetchNpmDistTagsSync } from "./npm-dist-tags.js"
6
7
  import {
7
8
  channelDistTagVersion,
@@ -101,29 +102,17 @@ const MANAGED_MODE_FLAG = "--mode"
101
102
  // or engine flags count; those other roles are never engines.
102
103
  const BINARY_RUNTIME_EXECUTABLE = String.raw`[\\/]binary-runtime[\\/][^\\/\s]+[\\/]omo(?:\.exe)?`
103
104
  const BINARY_ENGINE = new RegExp(String.raw`${BINARY_RUNTIME_EXECUTABLE}(?=\s|$)\s*(\S*)`)
104
- const BINARY_NON_ENGINE_COMMANDS = new Set([
105
- "doctor",
106
- "setup",
107
- "daemon",
108
- "update",
109
- "upgrade",
110
- "host",
111
- "install",
112
- "remove",
113
- "list",
114
- "config",
115
- "auth",
116
- "ulw-loop",
117
- "--version",
118
- "-v",
119
- ])
105
+ // omo's own commands; the engine's one-shot commands come from engine-commands.js (isEngineCommand).
106
+ const BINARY_NON_ENGINE_COMMANDS = new Set(["doctor", "setup", "daemon", "upgrade", "ulw-loop", "--version", "-v"])
120
107
 
121
108
  function isBinaryEngine(command) {
122
109
  const match = BINARY_ENGINE.exec(command)
123
110
  if (!match) return false
124
111
  const first = match[1] ?? ""
125
112
  if (first.startsWith("--internal-") || /\.(?:m?js|cjs|ts)$/.test(first)) return false
126
- return !BINARY_NON_ENGINE_COMMANDS.has(first)
113
+ // A one-shot command omo hands to the engine unchanged runs to completion and is never a session (#14336).
114
+ const args = command.slice(match.index + match[0].length - first.length).split(/\s+/)
115
+ return !BINARY_NON_ENGINE_COMMANDS.has(first) && !isEngineCommand(args)
127
116
  }
128
117
 
129
118
  function isEngine(entry) {
@@ -11,6 +11,8 @@ const ENGINE_COMMANDS = new Set([
11
11
  "auth",
12
12
  "host",
13
13
  "schedule",
14
+ // omo#14253: senpi answers `session-of-pid <pid> --json` itself (one JSON line, its own usage errors).
15
+ "session-of-pid",
14
16
  ])
15
17
 
16
18
  export function isEngineCommand(args) {
@@ -46,6 +46,9 @@ function brandProfile() {
46
46
  userAgent: "omo",
47
47
  originator: "omo",
48
48
  ...(changelog ? { changelog } : {}),
49
+ // The plugin spawnSenpi prepends with --extension: the engine's own, never a user flag an attaching start
50
+ // could not apply to a host-held session (#14465).
51
+ extensions: [join(packageRoot, "plugin")],
49
52
  update: {
50
53
  packageName: "omo-ai",
51
54
  distTag: releaseChannel(),
@@ -0,0 +1,53 @@
1
+ import { execFile } from "node:child_process"
2
+ import { accessSync, constants, realpathSync, statSync } from "node:fs"
3
+ import { delimiter, join } from "node:path"
4
+ import { promisify } from "node:util"
5
+
6
+ const execFileAsync = promisify(execFile)
7
+ const VERSION_TIMEOUT_MS = 60_000
8
+
9
+ /**
10
+ * The first executable `omo` on `env.PATH`, the one a shell runs, or undefined when there is none.
11
+ * @param {NodeJS.ProcessEnv} env
12
+ * @returns {string | undefined}
13
+ */
14
+ export function findOmoOnPath(env) {
15
+ for (const entry of (env.PATH ?? "").split(delimiter).filter(Boolean)) {
16
+ const candidate = join(entry, "omo")
17
+ try {
18
+ accessSync(candidate, constants.X_OK)
19
+ if (statSync(candidate).isFile()) return candidate
20
+ } catch {
21
+ // Not on this PATH entry; the shell would keep looking too.
22
+ }
23
+ }
24
+ return undefined
25
+ }
26
+
27
+ export function realpathOrSelf(path) {
28
+ try {
29
+ return realpathSync(path)
30
+ } catch {
31
+ return path
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Runs `<launcher> --version` and returns its last output line (`omo <version> (engine: ...)`), or a
37
+ * `failed: ...` line when it cannot run, so a broken launcher is reported instead of thrown.
38
+ * @param {string} launcher
39
+ * @param {NodeJS.ProcessEnv} env
40
+ * @returns {Promise<string>}
41
+ */
42
+ export async function readLauncherVersion(launcher, env) {
43
+ try {
44
+ const { stdout } = await execFileAsync(launcher, ["--version"], { env, timeout: VERSION_TIMEOUT_MS })
45
+ return stdout.trim().split("\n").at(-1) ?? ""
46
+ } catch (error) {
47
+ return `failed: ${String(error instanceof Error ? error.message : error).split("\n")[0]}`
48
+ }
49
+ }
50
+
51
+ export function reportsVersion(line, version) {
52
+ return line === `omo ${version}` || line.startsWith(`omo ${version} `)
53
+ }
@@ -1,5 +1,5 @@
1
1
  {
2
- "_comment": "Derived from @code-yeongyu/senpi 2026.11.18-3 builtinProviders(). builtinProviderIds and oauthProviderIds are the engine registry verbatim; providers maps a source harness id onto the omo provider that serves the same endpoint; oauthLogins maps a source OAuth id onto the omo provider to run /login for. Re-derive all four whenever the senpi pin changes.",
2
+ "_comment": "Derived from @code-yeongyu/senpi 2026.11.19-5 builtinProviders(). builtinProviderIds and oauthProviderIds are the engine registry verbatim; providers maps a source harness id onto the omo provider that serves the same endpoint; oauthLogins maps a source OAuth id onto the omo provider to run /login for. Re-derive all four whenever the senpi pin changes.",
3
3
  "builtinProviderIds": [
4
4
  "alibaba-token-plan",
5
5
  "amazon-bedrock",
@@ -19,7 +19,7 @@ omo: git stdin was not fully delivered (${error.code??error.message})
19
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
20
  `)}
21
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 randomUUID9}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}.${randomUUID9()}.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 randomUUID10}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)}
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{Buffer as Buffer5}from"node:buffer";import{randomUUID as randomUUID10}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
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
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
25
  …[truncated ${dropped} chars]…
@@ -27,14 +27,14 @@ ${tail}`}function projectTranscriptEntries(message,capturedAt){if(message.kind==
27
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
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
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(`
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 parseTranscriptRows(raw){return raw.split(`
31
+ `).filter((line)=>line.trim().length>0).map((line)=>{let parsed=JSON.parse(line);if(!isTranscriptEntry(parsed))throw Error("Invalid transcript journal row");return parsed})}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;transcriptTail;persistedStateJson;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(`
32
+ `)){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);let allEntries;if(fresh.length>0){await appendFile2(this.transcriptPath,`${fresh.map((entry)=>JSON.stringify(entry)).join(`
32
33
  `)}
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-${randomUUID10()}`;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 randomUUID11}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-${randomUUID11()}`;try{await writeFile2(temporary,`${JSON.stringify({version:1,highWater:next})}
34
+ `,"utf8"),allEntries=[...existing,...fresh];let appended=await stat(this.transcriptPath);this.transcriptTail={byteOffset:appended.size,mtimeMs:appended.mtimeMs,entries:[...allEntries]}}else allEntries=existing;let 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 size,mtimeMs;try{let stats=await stat(this.transcriptPath);size=stats.size,mtimeMs=stats.mtimeMs}catch(error){if(errorCode15(error)!=="ENOENT")throw error;return this.transcriptTail=void 0,[]}let cached=this.transcriptTail;if(cached!==void 0&&size===cached.byteOffset&&mtimeMs===cached.mtimeMs)return cached.entries;if(cached!==void 0&&size>cached.byteOffset){let tail=await this.readTailEntriesUnlocked(size,cached.byteOffset);if(tail!==void 0){let entries=[...cached.entries,...tail];return this.transcriptTail={byteOffset:size,mtimeMs,entries},entries}}let raw;try{raw=await readFile(this.transcriptPath,"utf8")}catch(error){if(errorCode15(error)!=="ENOENT")throw error;return this.transcriptTail=void 0,[]}let entries=parseTranscriptRows(raw);return this.transcriptTail={byteOffset:size,mtimeMs,entries},entries}async readTailEntriesUnlocked(size,byteOffset){let handle;try{handle=await open3(this.transcriptPath,"r");let length=size-byteOffset,buffer=Buffer5.alloc(length),{bytesRead}=await handle.read(buffer,0,length,byteOffset);return parseTranscriptRows(buffer.subarray(0,bytesRead).toString("utf8"))}catch{return}finally{await handle?.close().catch(()=>{})}}async readStateUnlocked(){try{let persisted=parseState(await readFile(this.statePath,"utf8"));return this.persistedStateJson=JSON.stringify(persisted),persisted}catch(error){if(errorCode15(error)==="ENOENT")return this.persistedStateJson=void 0,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),derivedJson=JSON.stringify(derived);if(derivedJson===this.persistedStateJson)return;let temporaryPath=`${this.statePath}.tmp-${randomUUID10()}`;await writeFile2(temporaryPath,`${JSON.stringify(derived,null,2)}
35
+ `,"utf8");try{await(this.options.renameFile??rename2)(temporaryPath,this.statePath),this.persistedStateJson=derivedJson}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 randomUUID11}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-${randomUUID11()}`;try{await writeFile2(temporary,`${JSON.stringify({version:1,highWater:next})}
36
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 randomUUID12}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-${randomUUID12()}`;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";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 randomUUID13}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)}
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";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 Buffer6}from"node:buffer";import{randomUUID as randomUUID13}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+Buffer6.byteLength(`${JSON.stringify(entry)}
38
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-${randomUUID13()}`;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
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 randomUUID14}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}-${randomUUID14()}`);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 randomUUID15}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)}-${randomUUID15()}`);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}}))}))}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 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";var RETENTION_LOG_FILE="retention-log.jsonl",RETENTION_LOG_PREVIOUS_FILE="retention-log.1.jsonl",DEFAULT_MAX_BYTES=524288,DEFAULT_MAX_NAMES_PER_STORE=200,MAX_LINE_BYTES=32768,TAIL_BYTES=65536;async function appendRetentionLog(runtimeDir,input,limits={}){let stores=Object.entries(input.removed).filter(([,names])=>names.length>0),total=stores.reduce((sum,[,names])=>sum+names.length,0);if(total===0)return;let line="";for(let maxNames=limits.maxNamesPerStore??DEFAULT_MAX_NAMES_PER_STORE;;maxNames=Math.floor(maxNames/2))if(line=formatLine(input,total,stores,maxNames),Buffer.byteLength(line)<=MAX_LINE_BYTES||maxNames===0)break;let path=join41(runtimeDir,RETENTION_LOG_FILE),size=await stat(path).then((stats)=>stats.size,(error)=>{if(errorCode19(error)==="ENOENT")return 0;throw error});if(size>0&&size+Buffer.byteLength(line)>(limits.maxBytes??DEFAULT_MAX_BYTES))await rename2(path,join41(runtimeDir,RETENTION_LOG_PREVIOUS_FILE));await appendFile2(path,line,{encoding:"utf8",mode:384})}function formatLine(input,total,stores,maxNames){let removed={},more={};for(let[store,names]of stores)if(removed[store]=names.slice(0,maxNames),names.length>maxNames)more[store]=names.length-maxNames;return`${JSON.stringify({v:1,at:new Date(input.at).toISOString(),total,removed,...Object.keys(more).length===0?{}:{more},...input.capEvictedBytes===void 0||input.capEvictedBytes===0?{}:{capEvictedBytes:input.capEvictedBytes}})}
40
40
  `}async function readLastRetentionLogEntry(runtimeDir){for(let file of[RETENTION_LOG_FILE,RETENTION_LOG_PREVIOUS_FILE]){let entry=lastEntry(await readTail(join41(runtimeDir,file)));if(entry!==void 0)return entry}return}async function readTail(path){let handle;try{handle=await open3(path,"r")}catch(error){if(errorCode19(error)==="ENOENT"||errorCode19(error)==="ENOTDIR")return"";throw error}try{let{size}=await handle.stat(),length=Math.min(size,TAIL_BYTES),buffer=Buffer.alloc(length);return await handle.read(buffer,0,length,size-length),buffer.toString("utf8")}finally{await handle.close()}}function lastEntry(tail){let lines=tail.split(`
@@ -13,6 +13,7 @@ import {
13
13
  } from "./package-paths.js"
14
14
  import { isPrintOnlyUpdate, updateUsageAnswer } from "./update-args.js"
15
15
  import { findHolders, heldTarget, isLockFailure, listWindowsProcesses, LOCK_RETRY_DELAYS_MS } from "./update-lock.js"
16
+ import { findVersionedInstall, updateVersionedInstall, versionedUpdateTarget } from "./versioned-install.js"
16
17
 
17
18
  export { isPrintOnlyUpdate }
18
19
 
@@ -44,13 +45,17 @@ export function formatVersionChange(before, after) {
44
45
  * prove the install moved (#9198). An unreachable registry falls back to the unpinned channel spec.
45
46
  * `run` defaults to `runChild` so tests inject a spawn without touching the child-process helper.
46
47
  *
48
+ * When the running package sits in a side-by-side versions layout (`<versions>/current -> <version>`,
49
+ * #12022), the update installs the target into a new version dir with bun and switches `current`
50
+ * (`versioned-install.js`) instead of `npm i -g`, which would install a copy PATH never runs.
51
+ *
47
52
  * On Windows a manager failure whose stderr says a file is held (EPERM/EBUSY, #10090) is retried with
48
53
  * backoff. If the file stays held, the report names the file, the processes of this install that hold it
49
54
  * and one action, and only an install that can no longer be read is reinstalled at the previous version; any readable version is kept.
50
55
  *
51
56
  * @typedef {{ omo: string, engine: string }} InstalledVersion
52
57
  * @typedef {{ status: number | null, signal: string | null, stderr?: string }} ChildResult
53
- * @typedef {{ stdio?: "inherit", windowsHide?: boolean, env?: NodeJS.ProcessEnv, captureStderr?: boolean }} RunOptions
58
+ * @typedef {{ stdio?: "inherit", windowsHide?: boolean, env?: NodeJS.ProcessEnv, captureStderr?: boolean, cwd?: string }} RunOptions
54
59
  * @typedef {import("./update-lock.js").ProcessEntry} ProcessEntry
55
60
  * @typedef {{ manager: string, command: string, argv: string[], env?: Record<string, string> }} UpdateTarget
56
61
  * @typedef {{
@@ -66,6 +71,7 @@ export function formatVersionChange(before, after) {
66
71
  * listProcesses?: () => ProcessEntry[],
67
72
  * installDir?: string,
68
73
  * selfPids?: number[],
74
+ * root?: string,
69
75
  * }} SelfUpdateOptions
70
76
  * @param {string[]} args
71
77
  * @param {SelfUpdateOptions} [options]
@@ -93,7 +99,14 @@ export async function runSelfUpdate(args, options = {}) {
93
99
  const before = readInstalled()
94
100
  const channel = releaseChannel(before.omo)
95
101
  const target = channelDistTagVersion(fetchDistTags(), before.omo)
96
- const update = resolveUpdate(target)
102
+ const versioned = findVersionedInstall(options.root ?? packageRoot, platform)
103
+ if (versioned !== undefined && target === undefined) {
104
+ error(
105
+ `omo: could not confirm the ${channel} omo-ai version from the npm registry; ${versioned.versionsDir} installs exact versions only, so retry when the registry answers`,
106
+ )
107
+ return 1
108
+ }
109
+ const update = versioned === undefined ? resolveUpdate(target) : versionedUpdateTarget(versioned, target)
97
110
 
98
111
  if (target === undefined) {
99
112
  log(
@@ -116,6 +129,9 @@ export async function runSelfUpdate(args, options = {}) {
116
129
  return 0
117
130
  }
118
131
  log(formatUpdateCommand(update))
132
+ if (versioned !== undefined) {
133
+ return updateVersionedInstall({ install: versioned, before: before.omo, target, run, env, platform, log, error })
134
+ }
119
135
 
120
136
  const install = async (target) => {
121
137
  const [command, ...argv] = target.argv