nova-personal-agent-server 0.0.0-stage → 0.4.0

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 (345) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/bin/novapersonal-server.mjs +4 -0
  4. package/package.json +61 -4
  5. package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
  6. package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
  7. package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
  8. package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
  9. package/resources/native/codex-sandbox-probe +0 -0
  10. package/resources/native/project-native/nova_project_native.node +0 -0
  11. package/resources/native-resources-v1.json +1 -0
  12. package/runtime/dist/eval/demos.js +156 -0
  13. package/runtime/dist/eval/fixture-host.js +385 -0
  14. package/runtime/dist/eval/fixtures.js +319 -0
  15. package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
  16. package/runtime/dist/eval/scorecard.js +285 -0
  17. package/runtime/dist/eval/sim.js +43 -0
  18. package/runtime/dist/src/cascaded-text-provider.js +31 -0
  19. package/runtime/dist/src/cli.js +96 -0
  20. package/runtime/dist/src/composition/assembly.js +352 -0
  21. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
  22. package/runtime/dist/src/composition/production-composition.js +389 -0
  23. package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
  24. package/runtime/dist/src/config/capability-registry.js +315 -0
  25. package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
  26. package/runtime/dist/src/config/coding-backends.js +8 -0
  27. package/runtime/dist/src/config/coding-profiles.js +98 -0
  28. package/runtime/dist/src/config/config.js +857 -0
  29. package/runtime/dist/src/config/diagnostics.js +139 -0
  30. package/runtime/dist/src/config/environment-contract.js +202 -0
  31. package/runtime/dist/src/config/self-hosted.js +23 -0
  32. package/runtime/dist/src/connectors/composio/client.js +195 -0
  33. package/runtime/dist/src/connectors/composio/google.js +208 -0
  34. package/runtime/dist/src/connectors/composio/index.js +334 -0
  35. package/runtime/dist/src/connectors/feishu/cli.js +220 -0
  36. package/runtime/dist/src/connectors/feishu/index.js +980 -0
  37. package/runtime/dist/src/connectors/macos/calendar.js +35 -0
  38. package/runtime/dist/src/connectors/macos/mail.js +32 -0
  39. package/runtime/dist/src/connectors/macos/reader.js +62 -0
  40. package/runtime/dist/src/conversation-voice-provider.js +41 -0
  41. package/runtime/dist/src/core/approval-port.js +9 -0
  42. package/runtime/dist/src/core/approval.js +1328 -0
  43. package/runtime/dist/src/core/calls.js +35 -0
  44. package/runtime/dist/src/core/camera-session.js +32 -0
  45. package/runtime/dist/src/core/causal-runtime.js +650 -0
  46. package/runtime/dist/src/core/clock.js +139 -0
  47. package/runtime/dist/src/core/context-view.js +156 -0
  48. package/runtime/dist/src/core/effects.js +62 -0
  49. package/runtime/dist/src/core/events.js +217 -0
  50. package/runtime/dist/src/core/executor-diagnostic.js +9 -0
  51. package/runtime/dist/src/core/ids.js +32 -0
  52. package/runtime/dist/src/core/media-store.js +104 -0
  53. package/runtime/dist/src/core/memory.js +296 -0
  54. package/runtime/dist/src/core/pending-decision.js +64 -0
  55. package/runtime/dist/src/core/ports.js +125 -0
  56. package/runtime/dist/src/core/runtime.js +1459 -0
  57. package/runtime/dist/src/core/schedule-tools.js +15 -0
  58. package/runtime/dist/src/core/sims.js +186 -0
  59. package/runtime/dist/src/core/slots.js +97 -0
  60. package/runtime/dist/src/core/source-processing-instructions.js +3 -0
  61. package/runtime/dist/src/core/source-processing-tools.js +12 -0
  62. package/runtime/dist/src/core/suggestions.js +143 -0
  63. package/runtime/dist/src/core/task-tools.js +22 -0
  64. package/runtime/dist/src/core/tool-schema.js +212 -0
  65. package/runtime/dist/src/core/trace.js +34 -0
  66. package/runtime/dist/src/core/work-tools.js +94 -0
  67. package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
  68. package/runtime/dist/src/desktop/desktop-camera.js +281 -0
  69. package/runtime/dist/src/desktop/desktop-control.js +140 -0
  70. package/runtime/dist/src/desktop/desktop-progress.js +162 -0
  71. package/runtime/dist/src/desktop/desktop-session.js +2106 -0
  72. package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
  73. package/runtime/dist/src/desktop/desktop-wire.js +605 -0
  74. package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
  75. package/runtime/dist/src/desktop/startup-error.js +18 -0
  76. package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
  77. package/runtime/dist/src/desktop-entry.js +106 -0
  78. package/runtime/dist/src/desktop.js +1092 -0
  79. package/runtime/dist/src/executors/acp/backends.js +105 -0
  80. package/runtime/dist/src/executors/acp/mcp.js +81 -0
  81. package/runtime/dist/src/executors/acp/preflight.js +14 -0
  82. package/runtime/dist/src/executors/acp/process-owner.js +112 -0
  83. package/runtime/dist/src/executors/acp/transport.js +760 -0
  84. package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
  85. package/runtime/dist/src/executors/agent-controller.js +244 -0
  86. package/runtime/dist/src/executors/autoglm.js +376 -0
  87. package/runtime/dist/src/executors/browser-device.js +102 -0
  88. package/runtime/dist/src/executors/browser.js +61 -0
  89. package/runtime/dist/src/executors/camera.js +101 -0
  90. package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
  91. package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
  92. package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
  93. package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
  94. package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
  95. package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
  96. package/runtime/dist/src/executors/codex/common.js +655 -0
  97. package/runtime/dist/src/executors/codex/contract.js +581 -0
  98. package/runtime/dist/src/executors/codex/controller.js +141 -0
  99. package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
  100. package/runtime/dist/src/executors/codex/factory.js +463 -0
  101. package/runtime/dist/src/executors/codex/host-config.js +238 -0
  102. package/runtime/dist/src/executors/codex/host.js +17 -0
  103. package/runtime/dist/src/executors/codex/index.js +19 -0
  104. package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
  105. package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
  106. package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
  107. package/runtime/dist/src/executors/codex/process-owner.js +398 -0
  108. package/runtime/dist/src/executors/codex/production-host.js +887 -0
  109. package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
  110. package/runtime/dist/src/executors/codex/protocol.js +581 -0
  111. package/runtime/dist/src/executors/codex/safe-json.js +87 -0
  112. package/runtime/dist/src/executors/codex/session-title.js +61 -0
  113. package/runtime/dist/src/executors/codex/shared-home.js +29 -0
  114. package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
  115. package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
  116. package/runtime/dist/src/executors/codex/version.js +38 -0
  117. package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
  118. package/runtime/dist/src/executors/coding/intake-model.js +103 -0
  119. package/runtime/dist/src/executors/coding/intake.js +824 -0
  120. package/runtime/dist/src/executors/coding/json-completion.js +14 -0
  121. package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
  122. package/runtime/dist/src/executors/coding/work-order.js +50 -0
  123. package/runtime/dist/src/executors/coding-executor.js +23 -0
  124. package/runtime/dist/src/executors/computer-backend.js +188 -0
  125. package/runtime/dist/src/executors/computer-device.js +187 -0
  126. package/runtime/dist/src/executors/computer-worker.js +125 -0
  127. package/runtime/dist/src/executors/computer.js +100 -0
  128. package/runtime/dist/src/executors/device-lock.js +127 -0
  129. package/runtime/dist/src/executors/frame-source.js +29 -0
  130. package/runtime/dist/src/executors/gui-evidence.js +30 -0
  131. package/runtime/dist/src/executors/gui-execution.js +237 -0
  132. package/runtime/dist/src/executors/gui-runner.js +88 -0
  133. package/runtime/dist/src/executors/host-executor-capability.js +12 -0
  134. package/runtime/dist/src/executors/index.js +13 -0
  135. package/runtime/dist/src/executors/mcp-client.js +198 -0
  136. package/runtime/dist/src/executors/mcp.js +210 -0
  137. package/runtime/dist/src/executors/mobile-android.js +180 -0
  138. package/runtime/dist/src/executors/mobile-ios.js +303 -0
  139. package/runtime/dist/src/executors/mobile.js +78 -0
  140. package/runtime/dist/src/executors/search-mcp.js +146 -0
  141. package/runtime/dist/src/executors/search.js +524 -0
  142. package/runtime/dist/src/executors/task-resources.js +38 -0
  143. package/runtime/dist/src/executors/vision/assess.js +296 -0
  144. package/runtime/dist/src/executors/vision/controller-core.js +373 -0
  145. package/runtime/dist/src/executors/vision/controller.js +164 -0
  146. package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
  147. package/runtime/dist/src/executors/vision.js +5 -0
  148. package/runtime/dist/src/executors/watcher.js +718 -0
  149. package/runtime/dist/src/http/bounded-response.js +37 -0
  150. package/runtime/dist/src/index.js +56 -0
  151. package/runtime/dist/src/knowledge/assembly.js +60 -0
  152. package/runtime/dist/src/knowledge/documents.js +520 -0
  153. package/runtime/dist/src/knowledge/embeddings.js +201 -0
  154. package/runtime/dist/src/knowledge/mcp.js +218 -0
  155. package/runtime/dist/src/knowledge/parse-worker.js +122 -0
  156. package/runtime/dist/src/knowledge/references.js +51 -0
  157. package/runtime/dist/src/knowledge/service.js +526 -0
  158. package/runtime/dist/src/knowledge/store-client.js +185 -0
  159. package/runtime/dist/src/knowledge/store-worker.js +843 -0
  160. package/runtime/dist/src/knowledge/types.js +2 -0
  161. package/runtime/dist/src/mcp/http-server.js +177 -0
  162. package/runtime/dist/src/mem0/resource.js +35 -0
  163. package/runtime/dist/src/mem0/store-worker.js +330 -0
  164. package/runtime/dist/src/memory/blackboard-session.js +205 -0
  165. package/runtime/dist/src/memory/blackboard-store.js +194 -0
  166. package/runtime/dist/src/memory/blackboard-worker.js +369 -0
  167. package/runtime/dist/src/memory/entry.js +39 -0
  168. package/runtime/dist/src/memory/factory.js +20 -0
  169. package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
  170. package/runtime/dist/src/memory/personal-memory.js +10 -0
  171. package/runtime/dist/src/memory/prerecall.js +20 -0
  172. package/runtime/dist/src/memory/provenance.js +17 -0
  173. package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
  174. package/runtime/dist/src/memory/retrieval.js +235 -0
  175. package/runtime/dist/src/memory/sensitivity.js +261 -0
  176. package/runtime/dist/src/memory-ledger/models.js +98 -0
  177. package/runtime/dist/src/memory-ledger/store-client.js +210 -0
  178. package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
  179. package/runtime/dist/src/memory-ledger/store.js +597 -0
  180. package/runtime/dist/src/memory-substrate/candidates.js +16 -0
  181. package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
  182. package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
  183. package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
  184. package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
  185. package/runtime/dist/src/memory-substrate/migration.js +87 -0
  186. package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
  187. package/runtime/dist/src/memory-substrate/purge.js +398 -0
  188. package/runtime/dist/src/memory-substrate/resolution.js +32 -0
  189. package/runtime/dist/src/memory-substrate/resource.js +867 -0
  190. package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
  191. package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
  192. package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
  193. package/runtime/dist/src/memory-substrate/source-state.js +93 -0
  194. package/runtime/dist/src/memory-substrate/store.js +534 -0
  195. package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
  196. package/runtime/dist/src/memory-substrate/workspace.js +21 -0
  197. package/runtime/dist/src/model/jev-client.js +25 -0
  198. package/runtime/dist/src/model/model-adapters.js +64 -0
  199. package/runtime/dist/src/model/model-gateway.js +399 -0
  200. package/runtime/dist/src/model/model-lane.js +34 -0
  201. package/runtime/dist/src/model/model-purpose.js +5 -0
  202. package/runtime/dist/src/model/personal-writer.js +361 -0
  203. package/runtime/dist/src/model/proactivity.js +72 -0
  204. package/runtime/dist/src/model/prompting.js +279 -0
  205. package/runtime/dist/src/model/task-verifier.js +217 -0
  206. package/runtime/dist/src/model/vision-capability.js +10 -0
  207. package/runtime/dist/src/news/feeds.js +114 -0
  208. package/runtime/dist/src/news/jev-ranking.js +25 -0
  209. package/runtime/dist/src/news/ranking.js +26 -0
  210. package/runtime/dist/src/news/service.js +262 -0
  211. package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
  212. package/runtime/dist/src/notifications/adapters/nova.js +15 -0
  213. package/runtime/dist/src/notifications/content.js +15 -0
  214. package/runtime/dist/src/notifications/contracts.js +9 -0
  215. package/runtime/dist/src/notifications/feed.js +8 -0
  216. package/runtime/dist/src/notifications/service.js +412 -0
  217. package/runtime/dist/src/notifications/store.js +4 -0
  218. package/runtime/dist/src/personal-agent/app-context.js +113 -0
  219. package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
  220. package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
  221. package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
  222. package/runtime/dist/src/personal-agent/contracts.js +32 -0
  223. package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
  224. package/runtime/dist/src/personal-agent/conversations.js +187 -0
  225. package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2403 -0
  227. package/runtime/dist/src/personal-agent/intake-task.js +37 -0
  228. package/runtime/dist/src/personal-agent/life.js +260 -0
  229. package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
  230. package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
  231. package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
  232. package/runtime/dist/src/personal-agent/project-digests.js +242 -0
  233. package/runtime/dist/src/personal-agent/sampling.js +20 -0
  234. package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
  235. package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
  236. package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
  237. package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
  238. package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
  239. package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
  240. package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
  241. package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
  242. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
  243. package/runtime/dist/src/personal-agent/source-priority.js +142 -0
  244. package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
  245. package/runtime/dist/src/personal-agent/source-walk.js +25 -0
  246. package/runtime/dist/src/personal-agent/sources.js +1484 -0
  247. package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
  248. package/runtime/dist/src/personal-agent/store.js +146 -0
  249. package/runtime/dist/src/personal-agent/task-loop.js +163 -0
  250. package/runtime/dist/src/personal-agent/tasks.js +920 -0
  251. package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
  252. package/runtime/dist/src/personal-agent/understanding.js +160 -0
  253. package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
  254. package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
  255. package/runtime/dist/src/projects/host-paths.js +133 -0
  256. package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
  257. package/runtime/dist/src/projects/project-confirmation.js +486 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +284 -0
  259. package/runtime/dist/src/projects/project-node-files.js +169 -0
  260. package/runtime/dist/src/projects/project-root-file.js +16 -0
  261. package/runtime/dist/src/projects/project-state.js +504 -0
  262. package/runtime/dist/src/projects/project-store-files.js +1271 -0
  263. package/runtime/dist/src/projects/project-store.js +1345 -0
  264. package/runtime/dist/src/realtime/aoq.js +141 -0
  265. package/runtime/dist/src/realtime/bridge.js +652 -0
  266. package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
  267. package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
  268. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
  269. package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
  270. package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
  271. package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
  272. package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
  273. package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
  274. package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
  275. package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
  276. package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
  277. package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
  278. package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
  279. package/runtime/dist/src/realtime/dictation.js +28 -0
  280. package/runtime/dist/src/realtime/evidence.js +276 -0
  281. package/runtime/dist/src/realtime/floor.js +43 -0
  282. package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
  283. package/runtime/dist/src/realtime/gemini.js +517 -0
  284. package/runtime/dist/src/realtime/history.js +122 -0
  285. package/runtime/dist/src/realtime/host-delivery.js +1711 -0
  286. package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
  287. package/runtime/dist/src/realtime/memory-board.js +105 -0
  288. package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
  289. package/runtime/dist/src/realtime/playback.js +242 -0
  290. package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
  291. package/runtime/dist/src/realtime/prompt-language.js +17 -0
  292. package/runtime/dist/src/realtime/protocol.js +428 -0
  293. package/runtime/dist/src/realtime/provider-projection.js +526 -0
  294. package/runtime/dist/src/realtime/provider-session.js +491 -0
  295. package/runtime/dist/src/realtime/qwen-transport.js +144 -0
  296. package/runtime/dist/src/realtime/qwen.js +1377 -0
  297. package/runtime/dist/src/realtime/recall.js +341 -0
  298. package/runtime/dist/src/realtime/service-ports.js +8 -0
  299. package/runtime/dist/src/realtime/service-state.js +259 -0
  300. package/runtime/dist/src/realtime/service.js +1726 -0
  301. package/runtime/dist/src/realtime/session-state.js +684 -0
  302. package/runtime/dist/src/realtime/session.js +1976 -0
  303. package/runtime/dist/src/realtime/speech-prep.js +63 -0
  304. package/runtime/dist/src/realtime/streaming-speech.js +120 -0
  305. package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
  306. package/runtime/dist/src/realtime/telemetry.js +144 -0
  307. package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
  308. package/runtime/dist/src/realtime/transport.js +8 -0
  309. package/runtime/dist/src/realtime/usage.js +55 -0
  310. package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
  311. package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
  312. package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
  313. package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
  314. package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
  315. package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
  316. package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
  317. package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
  318. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
  319. package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
  320. package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
  321. package/runtime/dist/src/server/aoq-chat-server.js +497 -0
  322. package/runtime/dist/src/server/client-pairing.js +192 -0
  323. package/runtime/dist/src/server/client-protocol.js +87 -0
  324. package/runtime/dist/src/server/client-server.js +312 -0
  325. package/runtime/dist/src/server/server-config.js +72 -0
  326. package/runtime/dist/src/server-entry.js +135 -0
  327. package/runtime/dist/src/storage/bounded-json.js +63 -0
  328. package/runtime/dist/src/storage/native-file-lock.js +8 -0
  329. package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
  330. package/runtime/dist/src/storage/private-database.js +120 -0
  331. package/runtime/dist/src/text/canonical-json.js +60 -0
  332. package/runtime/dist/src/text/python-number.js +18 -0
  333. package/runtime/dist/src/text/python-text.js +92 -0
  334. package/runtime/dist/src/text/unicode-casefold.js +29 -0
  335. package/runtime/dist/src/text/unicode-normalize.js +138 -0
  336. package/runtime/dist/src/text/unicode-tables.js +210 -0
  337. package/runtime/dist/src/understanding/candidates.js +77 -0
  338. package/runtime/dist/src/understanding/fixture.js +7 -0
  339. package/runtime/dist/src/understanding/jev.js +20 -0
  340. package/runtime/dist/src/understanding/pipeline.js +38 -0
  341. package/runtime/dist/src/voicemem/store-client.js +476 -0
  342. package/runtime/dist/src/voicemem/store-worker.js +380 -0
  343. package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
  344. package/runtime/scripts/pair-device.mjs +109 -0
  345. package/src/command.mjs +48 -0
@@ -0,0 +1,1345 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { constants, realpathSync } from 'node:fs';
3
+ import { open, realpath } from 'node:fs/promises';
4
+ import { basename, join } from 'node:path';
5
+ import { CODING_BACKEND_IDS } from '../config/coding-backends.js';
6
+ import { stripLikePython } from '../text/python-text.js';
7
+ import { hostHomeValue, hostPersistentHomeFromConfig, hostWorkspaceFromConfig, hostWorkspacePath, } from './host-paths.js';
8
+ import {} from './project-root-file.js';
9
+ import { bumpActiveBindingRevision, compareCreated, MAINTENANCE_TOMBSTONE, MAX_PROJECT_SESSION_TITLE, mostRecentlyUsed, newestReadySession, normalizeProjectSessionTitle, normalizeProjectWorkspaceName, ProjectStateError, pruneForSessionInsert, recentWorkspaces, requireUniqueWorkspaceName, requireWorkspaceCapacity, slugPrefix, snapshotState, STORED_ID, uniqueSessionTitle, uniqueWorkspaceName, validateThreadId, } from './project-state.js';
10
+ import { directoryFlag, fileIdentity, isCommittedTransactionFailure, isDirectChild, isNodeError, LEGACY_PROJECT_CODEX_HOMES_DIRECTORY, noFollowFlag, privateDirectoryMetadata, PROJECT_CODEX_HOMES_DIRECTORY, PROJECT_OWNER_LOCK_FILE, ProjectStoreFiles, sameFileIdentity, validateRegisteredWorkspace, } from './project-store-files.js';
11
+ export { MAX_PROJECT_SESSION_TITLE, MAX_PROJECT_SESSIONS_PER_WORKSPACE, MAX_PROJECT_SESSIONS_TOTAL, MAX_PROJECT_WORKSPACE_NAME, MAX_PROJECT_WORKSPACES, normalizeProjectSessionTitle, normalizeProjectWorkspaceName, PROJECT_STATE_VERSION, ProjectStateError, } from './project-state.js';
12
+ export { hostManagedProjectRootForTest, hostManagedProjectRootFromConfig, hostProjectRootForTest, hostProjectRootFromConfig, MAX_PROJECT_STATE_BYTES, PROJECT_MAINTENANCE_JOURNAL_FILE, PROJECT_OWNER_LOCK_FILE, PROJECT_STATE_FILE, PROJECT_TRANSACTION_LOCK_FILE, } from './project-store-files.js';
13
+ const MAX_ID_FACTORY_ATTEMPTS = 32;
14
+ class MaintenanceFaultError extends Error {
15
+ constructor(step) {
16
+ super(`maintenance fault: ${step}`);
17
+ this.name = 'MaintenanceFaultError';
18
+ }
19
+ }
20
+ /** Project/session operations and managed-workspace recovery, under one filesystem transaction owner. */
21
+ export class ProjectStore {
22
+ #now;
23
+ #idFactory;
24
+ #maintenanceFault;
25
+ #workspaceIdentities = new Map();
26
+ #files;
27
+ constructor(options) {
28
+ this.#files = new ProjectStoreFiles(options);
29
+ this.#now = options.now ?? (() => Date.now() / 1000);
30
+ this.#idFactory = options.idFactory ?? (() => randomUUID().replaceAll('-', ''));
31
+ this.#maintenanceFault = options.maintenanceFault;
32
+ }
33
+ static async open(options) {
34
+ const store = new ProjectStore(options);
35
+ try {
36
+ await store.#files.open();
37
+ if (store.#files.hasOwnerLock && await store.#files.loadMaintenanceJournal() !== null) {
38
+ await store.cleanupManagedMaintenanceJournal();
39
+ }
40
+ return store;
41
+ }
42
+ catch (error) {
43
+ await store.#files.disposeFailedOpen();
44
+ throw error;
45
+ }
46
+ }
47
+ close() {
48
+ return this.#files.close();
49
+ }
50
+ async snapshot() {
51
+ return await this.#files.transaction(state => [snapshotState(state), false], { wait: true });
52
+ }
53
+ async reconcileExternallyRemovedManagedWorkspaces() {
54
+ const created = [];
55
+ try {
56
+ return await this.#files.transaction(async (state) => {
57
+ if (await this.#files.loadMaintenanceJournal() !== null) {
58
+ throw new ProjectStateError('state_busy');
59
+ }
60
+ const managed = await this.#files.validateManagedRoot();
61
+ const root = this.#files.requireManagedRootHandle();
62
+ const missing = [];
63
+ let managedWorkspaceCount = 0;
64
+ for (const workspace of [...state.workspaces.values()].sort(compareCreated)) {
65
+ if (workspace.origin !== 'managed')
66
+ continue;
67
+ managedWorkspaceCount += 1;
68
+ if (!isDirectChild(managed, workspace.canonical_path)) {
69
+ throw new ProjectStateError('workspace_boundary_changed');
70
+ }
71
+ const present = this.#files.lookupWorkspaceAt(root, basename(workspace.canonical_path), 'workspace_boundary_changed');
72
+ if (present.status === 'missing') {
73
+ missing.push(workspace);
74
+ continue;
75
+ }
76
+ const binding = await this.#files.validateManagedWorkspaceBinding(workspace.canonical_path);
77
+ this.#pinWorkspaceIdentity(workspace.workspace_id, binding.identity);
78
+ }
79
+ if (missing.length === 0) {
80
+ return [Object.freeze({
81
+ status: 'unchanged',
82
+ recreated_count: 0,
83
+ active_workspace_reset: false,
84
+ }), false];
85
+ }
86
+ for (const workspace of missing) {
87
+ const recreated = await this.#files.ensurePrivateDirectoryAt(root, managed, basename(workspace.canonical_path), true);
88
+ try {
89
+ const identity = recreated.binding.identity;
90
+ created.push({
91
+ path: workspace.canonical_path,
92
+ identity,
93
+ workspaceId: workspace.workspace_id,
94
+ previousIdentity: this.#workspaceIdentities.get(workspace.workspace_id),
95
+ });
96
+ this.#workspaceIdentities.set(workspace.workspace_id, identity);
97
+ }
98
+ finally {
99
+ await recreated.file.close().catch(() => undefined);
100
+ }
101
+ }
102
+ await this.#files.syncManagedRoot();
103
+ const activeWorkspaceReset = state.activeWorkspaceId !== null
104
+ && (missing.length === managedWorkspaceCount
105
+ || missing.some(workspace => workspace.workspace_id === state.activeWorkspaceId));
106
+ if (activeWorkspaceReset) {
107
+ state.activeWorkspaceId = null;
108
+ bumpActiveBindingRevision(state);
109
+ }
110
+ return [Object.freeze({
111
+ status: 'reconciled',
112
+ recreated_count: missing.length,
113
+ active_workspace_reset: activeWorkspaceReset,
114
+ }), activeWorkspaceReset];
115
+ }, { wait: true });
116
+ }
117
+ catch (error) {
118
+ if (!isCommittedTransactionFailure(error)) {
119
+ for (const candidate of [...created].reverse()) {
120
+ const removed = await this.#files.rollbackCreatedDirectory(candidate);
121
+ if (!removed)
122
+ continue;
123
+ const current = this.#workspaceIdentities.get(candidate.workspaceId);
124
+ if (current === undefined || !sameFileIdentity(current, candidate.identity))
125
+ continue;
126
+ if (candidate.previousIdentity === undefined) {
127
+ this.#workspaceIdentities.delete(candidate.workspaceId);
128
+ }
129
+ else {
130
+ this.#workspaceIdentities.set(candidate.workspaceId, candidate.previousIdentity);
131
+ }
132
+ }
133
+ }
134
+ throw error;
135
+ }
136
+ }
137
+ async maintenanceSnapshot() {
138
+ return await this.#files.transaction(async (state) => {
139
+ await this.#files.validateManagedRoot();
140
+ const targets = [];
141
+ for (const workspace of [...state.workspaces.values()].sort(compareCreated)) {
142
+ if (workspace.origin !== 'managed')
143
+ continue;
144
+ const binding = await this.#files.validateManagedWorkspaceBinding(workspace.canonical_path);
145
+ this.#pinWorkspaceIdentity(workspace.workspace_id, binding.identity);
146
+ targets.push(Object.freeze({
147
+ workspace: Object.freeze({ ...workspace }),
148
+ identity: Object.freeze({ ...binding.identity }),
149
+ }));
150
+ }
151
+ return [Object.freeze({
152
+ state_revision: state.stateRevision,
153
+ active_workspace_id: state.activeWorkspaceId,
154
+ managed_targets: Object.freeze(targets),
155
+ }), false];
156
+ }, { wait: true });
157
+ }
158
+ async currentMaintenanceSnapshot() {
159
+ return await this.#files.transaction(async (state) => {
160
+ await this.#files.validateManagedRoot();
161
+ const workspace = state.activeWorkspaceId === null
162
+ ? undefined
163
+ : state.workspaces.get(state.activeWorkspaceId);
164
+ const targets = [];
165
+ if (workspace?.origin === 'managed') {
166
+ const binding = await this.#files.validateManagedWorkspaceBinding(workspace.canonical_path);
167
+ this.#pinWorkspaceIdentity(workspace.workspace_id, binding.identity);
168
+ targets.push(Object.freeze({
169
+ workspace: Object.freeze({ ...workspace }),
170
+ identity: Object.freeze({ ...binding.identity }),
171
+ }));
172
+ }
173
+ return [Object.freeze({
174
+ state_revision: state.stateRevision,
175
+ active_workspace_id: state.activeWorkspaceId,
176
+ managed_targets: Object.freeze(targets),
177
+ }), false];
178
+ }, { wait: true });
179
+ }
180
+ async withCurrentManagedWorkspacePath(callback) {
181
+ return await this.#files.transaction(async (state) => {
182
+ await this.#files.validateManagedRoot();
183
+ const workspace = state.activeWorkspaceId === null
184
+ ? undefined
185
+ : state.workspaces.get(state.activeWorkspaceId);
186
+ if (workspace?.origin !== 'managed')
187
+ return [false, false];
188
+ const before = await this.#files.validateManagedWorkspaceBinding(workspace.canonical_path);
189
+ this.#pinWorkspaceIdentity(workspace.workspace_id, before.identity);
190
+ callback(workspace.canonical_path);
191
+ await this.#files.validateManagedRoot();
192
+ const after = await this.#files.validateManagedWorkspaceBinding(workspace.canonical_path);
193
+ if (!sameFileIdentity(before.identity, after.identity)) {
194
+ throw new ProjectStateError('workspace_boundary_changed');
195
+ }
196
+ return [true, false];
197
+ }, { wait: true });
198
+ }
199
+ async executeManagedReplacement(input) {
200
+ return await this.#files.transaction(async (state) => {
201
+ if (state.stateRevision !== input.expected_state_revision || input.targets.length === 0) {
202
+ return [{ status: 'stale', committed: false, tombstones: [] }, false];
203
+ }
204
+ const managed = await this.#files.validateManagedRoot();
205
+ const root = this.#files.requireManagedRootHandle();
206
+ const prepared = [];
207
+ const operationIds = new Set();
208
+ const seenWorkspaces = new Set();
209
+ const seenTombstones = new Set();
210
+ for (const target of input.targets) {
211
+ const workspace = state.workspaces.get(target.workspace_id);
212
+ const match = MAINTENANCE_TOMBSTONE.exec(target.tombstone_name);
213
+ if (workspace?.origin !== 'managed'
214
+ || workspace.canonical_path !== target.canonical_path
215
+ || !isDirectChild(managed, target.canonical_path)
216
+ || match === null
217
+ || seenWorkspaces.has(target.workspace_id)
218
+ || seenTombstones.has(target.tombstone_name))
219
+ return [{ status: 'stale', committed: false, tombstones: [] }, false];
220
+ const binding = await this.#files.validateManagedWorkspaceBinding(target.canonical_path);
221
+ if (!sameFileIdentity(binding.identity, target.identity)) {
222
+ return [{ status: 'stale', committed: false, tombstones: [] }, false];
223
+ }
224
+ this.#pinWorkspaceIdentity(workspace.workspace_id, binding.identity);
225
+ operationIds.add(match[1] ?? '');
226
+ seenWorkspaces.add(target.workspace_id);
227
+ seenTombstones.add(target.tombstone_name);
228
+ prepared.push({
229
+ workspace,
230
+ originalName: basename(target.canonical_path),
231
+ tombstoneName: target.tombstone_name,
232
+ replacementName: target.tombstone_name.replace('.nova-maintenance-', '.nova-replacement-'),
233
+ identity: binding.identity,
234
+ });
235
+ }
236
+ if (operationIds.size !== 1) {
237
+ return [{ status: 'stale', committed: false, tombstones: [] }, false];
238
+ }
239
+ const operationId = [...operationIds][0];
240
+ if (operationId === undefined || !STORED_ID.test(operationId)) {
241
+ return [{ status: 'stale', committed: false, tombstones: [] }, false];
242
+ }
243
+ let journal = Object.freeze({
244
+ version: 2,
245
+ operation_id: operationId,
246
+ phase: 'prepared',
247
+ entries: Object.freeze(prepared.map(target => Object.freeze({
248
+ workspace_id: target.workspace.workspace_id,
249
+ original_name: target.originalName,
250
+ tombstone_name: target.tombstoneName,
251
+ replacement_name: target.replacementName,
252
+ identity: Object.freeze({ ...target.identity }),
253
+ replacement_identity: null,
254
+ }))),
255
+ });
256
+ if (await this.#files.loadMaintenanceJournal() !== null) {
257
+ throw new ProjectStateError('state_busy');
258
+ }
259
+ await this.#files.writeMaintenanceJournal(journal);
260
+ const replaced = prepared.map(target => ({ target, replacementIdentity: null, renamed: false }));
261
+ try {
262
+ for (const item of replaced) {
263
+ const target = item.target;
264
+ const tombstoneBefore = this.#files.lookupAt(root, target.tombstoneName, 'workspace_boundary_changed');
265
+ const replacementBefore = this.#files.lookupAt(root, target.replacementName, 'workspace_boundary_changed');
266
+ if (tombstoneBefore.status !== 'missing' || replacementBefore.status !== 'missing') {
267
+ throw new ProjectStateError('workspace_boundary_changed');
268
+ }
269
+ const renamed = this.#files.renameManagedNoReplace(root, target.originalName, target.tombstoneName, target.identity);
270
+ if (renamed.status !== 'ok')
271
+ throw new ProjectStateError('workspace_boundary_changed');
272
+ item.renamed = true;
273
+ const tombstone = this.#files.lookupAt(root, target.tombstoneName, 'workspace_boundary_changed');
274
+ if (tombstone.status !== 'ok' || !sameFileIdentity(tombstone.identity, target.identity)) {
275
+ throw new ProjectStateError('workspace_boundary_changed');
276
+ }
277
+ }
278
+ for (const [index, item] of replaced.entries()) {
279
+ const target = item.target;
280
+ const replacement = await this.#files.ensurePrivateDirectoryAt(root, managed, target.replacementName, true);
281
+ item.replacementIdentity = replacement.binding.identity;
282
+ await replacement.file.close();
283
+ this.#maintenanceCheckpoint('replacement_created');
284
+ journal = Object.freeze({
285
+ ...journal,
286
+ entries: Object.freeze(journal.entries.map((entry, entryIndex) => entryIndex === index
287
+ ? Object.freeze({
288
+ ...entry,
289
+ replacement_identity: Object.freeze({ ...replacement.binding.identity }),
290
+ })
291
+ : entry)),
292
+ });
293
+ await this.#files.writeMaintenanceJournal(journal);
294
+ this.#maintenanceCheckpoint('replacement_identity_persisted');
295
+ const placed = this.#files.renameManagedNoReplace(root, target.replacementName, target.originalName, replacement.binding.identity);
296
+ if (placed.status !== 'ok')
297
+ throw new ProjectStateError('workspace_boundary_changed');
298
+ const placedIdentity = this.#files.lookupAt(root, target.originalName, 'workspace_boundary_changed');
299
+ if (placedIdentity.status !== 'ok'
300
+ || !sameFileIdentity(placedIdentity.identity, replacement.binding.identity))
301
+ throw new ProjectStateError('workspace_boundary_changed');
302
+ this.#maintenanceCheckpoint('replacement_placed');
303
+ this.#advanceWorkspaceIdentity(target.workspace.workspace_id, target.identity, replacement.binding.identity);
304
+ }
305
+ await this.#files.syncManagedRoot();
306
+ await this.#files.writeMaintenanceJournal(Object.freeze({ ...journal, phase: 'committed' }));
307
+ }
308
+ catch (error) {
309
+ if (error instanceof MaintenanceFaultError)
310
+ throw error;
311
+ let rollbackComplete = true;
312
+ for (const item of [...replaced].reverse()) {
313
+ const replacementNames = item.replacementIdentity === null
314
+ ? [item.target.replacementName]
315
+ : [item.target.originalName, item.target.replacementName];
316
+ for (const name of replacementNames) {
317
+ try {
318
+ const present = this.#files.lookupAt(root, name, 'workspace_boundary_changed');
319
+ if (present.status === 'missing')
320
+ continue;
321
+ if (present.status !== 'ok') {
322
+ rollbackComplete = false;
323
+ continue;
324
+ }
325
+ const removable = item.replacementIdentity === null
326
+ ? name === item.target.replacementName
327
+ : sameFileIdentity(present.identity, item.replacementIdentity);
328
+ if (!removable) {
329
+ rollbackComplete = false;
330
+ continue;
331
+ }
332
+ const removed = this.#files.unlinkAt(root, name, present.identity, 'directory', 'workspace_boundary_changed');
333
+ if (removed.status !== 'ok' && removed.status !== 'missing')
334
+ rollbackComplete = false;
335
+ }
336
+ catch {
337
+ rollbackComplete = false;
338
+ }
339
+ }
340
+ if (item.renamed) {
341
+ const restored = this.#files.renameManagedNoReplace(root, item.target.tombstoneName, item.target.originalName, item.target.identity);
342
+ if (restored.status === 'ok') {
343
+ try {
344
+ this.#restoreWorkspaceIdentity(item.target.workspace.workspace_id, item.replacementIdentity, item.target.identity);
345
+ }
346
+ catch {
347
+ rollbackComplete = false;
348
+ }
349
+ }
350
+ else
351
+ rollbackComplete = false;
352
+ }
353
+ }
354
+ if (rollbackComplete) {
355
+ try {
356
+ await this.#files.syncManagedRoot();
357
+ await this.#files.clearMaintenanceJournal(operationId);
358
+ }
359
+ catch {
360
+ rollbackComplete = false;
361
+ }
362
+ }
363
+ if (!rollbackComplete)
364
+ throw new ProjectStateError('workspace_boundary_changed');
365
+ return [{ status: 'rolled_back', committed: false, tombstones: [] }, false];
366
+ }
367
+ return [Object.freeze({
368
+ status: 'committed',
369
+ committed: true,
370
+ tombstones: Object.freeze(prepared.map(target => Object.freeze({
371
+ name: target.tombstoneName,
372
+ identity: Object.freeze({ ...target.identity }),
373
+ }))),
374
+ }), false];
375
+ }, { wait: true });
376
+ }
377
+ async loadManagedMaintenanceJournal() {
378
+ return await this.#files.transaction(async () => [await this.#files.loadMaintenanceJournal(), false], { wait: true });
379
+ }
380
+ async cleanupManagedMaintenanceJournal() {
381
+ return await this.#files.transaction(async () => {
382
+ const journal = await this.#files.loadMaintenanceJournal();
383
+ if (journal === null)
384
+ return [{ status: 'clean' }, false];
385
+ // Inspection needs only the transaction lock. Replay also needs the live-owner lock;
386
+ // a non-live desktop observer must not mutate a running backend's workspaces.
387
+ let owner = null;
388
+ if (!this.#files.hasOwnerLock) {
389
+ try {
390
+ owner = await this.#files.openAndAcquireLock(PROJECT_OWNER_LOCK_FILE);
391
+ }
392
+ catch (error) {
393
+ if (!(error instanceof ProjectStateError) || error.code !== 'state_busy')
394
+ throw error;
395
+ return [{ status: journal.phase === 'prepared' ? 'rollback_pending' : 'cleanup_pending' }, false];
396
+ }
397
+ }
398
+ try {
399
+ await this.#files.validateManagedRoot();
400
+ const root = this.#files.requireManagedRootHandle();
401
+ if (journal.phase === 'prepared') {
402
+ const remaining = [];
403
+ for (const entry of [...journal.entries].reverse()) {
404
+ const tombstone = this.#files.lookupAt(root, entry.tombstone_name, 'workspace_boundary_changed');
405
+ const original = this.#files.lookupAt(root, entry.original_name, 'workspace_boundary_changed');
406
+ const temporary = entry.replacement_name === entry.original_name
407
+ ? { status: 'missing' }
408
+ : this.#files.lookupAt(root, entry.replacement_name, 'workspace_boundary_changed');
409
+ if (tombstone.status === 'missing') {
410
+ if (original.status !== 'ok'
411
+ || !sameFileIdentity(original.identity, entry.identity)
412
+ || temporary.status !== 'missing') {
413
+ remaining.push(entry);
414
+ }
415
+ else {
416
+ this.#restoreWorkspaceIdentity(entry.workspace_id, null, entry.identity);
417
+ }
418
+ continue;
419
+ }
420
+ if (tombstone.status !== 'ok' || !sameFileIdentity(tombstone.identity, entry.identity)) {
421
+ remaining.push(entry);
422
+ continue;
423
+ }
424
+ let replacementSafe = true;
425
+ const candidates = entry.replacement_name === entry.original_name
426
+ ? [{ name: entry.original_name, result: original }]
427
+ : [
428
+ { name: entry.original_name, result: original },
429
+ { name: entry.replacement_name, result: temporary },
430
+ ];
431
+ for (const candidate of candidates) {
432
+ if (candidate.result.status === 'missing')
433
+ continue;
434
+ if (candidate.result.status !== 'ok') {
435
+ replacementSafe = false;
436
+ continue;
437
+ }
438
+ const bound = entry.replacement_identity !== null
439
+ && sameFileIdentity(candidate.result.identity, entry.replacement_identity);
440
+ const reservedUnboundTemporary = entry.replacement_identity === null
441
+ && entry.replacement_name !== entry.original_name
442
+ && candidate.name === entry.replacement_name;
443
+ if (!bound && !reservedUnboundTemporary) {
444
+ replacementSafe = false;
445
+ continue;
446
+ }
447
+ try {
448
+ const removed = this.#files.unlinkAt(root, candidate.name, candidate.result.identity, 'directory', 'workspace_boundary_changed');
449
+ if (removed.status !== 'ok' && removed.status !== 'missing')
450
+ replacementSafe = false;
451
+ }
452
+ catch {
453
+ replacementSafe = false;
454
+ }
455
+ }
456
+ if (!replacementSafe) {
457
+ remaining.push(entry);
458
+ continue;
459
+ }
460
+ const originalAfter = this.#files.lookupAt(root, entry.original_name, 'workspace_boundary_changed');
461
+ if (originalAfter.status !== 'missing') {
462
+ remaining.push(entry);
463
+ continue;
464
+ }
465
+ const restored = this.#files.renameManagedNoReplace(root, entry.tombstone_name, entry.original_name, entry.identity);
466
+ const restoredIdentity = this.#files.lookupAt(root, entry.original_name, 'workspace_boundary_changed');
467
+ if (restored.status !== 'ok'
468
+ || restoredIdentity.status !== 'ok'
469
+ || !sameFileIdentity(restoredIdentity.identity, entry.identity)) {
470
+ remaining.push(entry);
471
+ continue;
472
+ }
473
+ this.#restoreWorkspaceIdentity(entry.workspace_id, entry.replacement_identity, entry.identity);
474
+ }
475
+ if (remaining.length === 0) {
476
+ await this.#files.syncManagedRoot();
477
+ await this.#files.clearMaintenanceJournal(journal.operation_id);
478
+ return [{ status: 'clean' }, false];
479
+ }
480
+ if (remaining.length !== journal.entries.length) {
481
+ await this.#files.syncManagedRoot();
482
+ await this.#files.writeMaintenanceJournal(Object.freeze({
483
+ version: journal.version,
484
+ operation_id: journal.operation_id,
485
+ phase: 'prepared',
486
+ entries: Object.freeze(remaining.reverse()),
487
+ }));
488
+ }
489
+ return [{ status: 'rollback_pending' }, false];
490
+ }
491
+ const remaining = [];
492
+ for (const entry of journal.entries) {
493
+ const result = this.#files.removeManagedTree(root, entry.tombstone_name, entry.identity);
494
+ if (result.status !== 'ok' && result.status !== 'missing')
495
+ remaining.push(entry);
496
+ else if (result.status === 'ok')
497
+ this.#maintenanceCheckpoint('cleanup_entry_deleted');
498
+ }
499
+ if (remaining.length === 0) {
500
+ await this.#files.syncManagedRoot();
501
+ await this.#files.clearMaintenanceJournal(journal.operation_id);
502
+ return [{ status: 'clean' }, false];
503
+ }
504
+ if (remaining.length !== journal.entries.length) {
505
+ await this.#files.syncManagedRoot();
506
+ await this.#files.writeMaintenanceJournal(Object.freeze({
507
+ version: journal.version,
508
+ operation_id: journal.operation_id,
509
+ phase: 'committed',
510
+ entries: Object.freeze(remaining),
511
+ }));
512
+ }
513
+ return [{ status: 'cleanup_pending' }, false];
514
+ }
515
+ finally {
516
+ if (owner !== null) {
517
+ try {
518
+ await owner.release();
519
+ }
520
+ finally {
521
+ await owner.file.close();
522
+ }
523
+ }
524
+ }
525
+ }, { wait: true });
526
+ }
527
+ async listWorkspaces() {
528
+ return (await this.snapshot()).workspaces;
529
+ }
530
+ async listSessions(workspace) {
531
+ const workspaceId = typeof workspace === 'string' ? workspace : workspace.workspace_id;
532
+ return (await this.snapshot()).sessions.filter(session => session.workspace_id === workspaceId);
533
+ }
534
+ async ensureImported(displayName, workspace) {
535
+ const requested = normalizeProjectWorkspaceName(displayName);
536
+ const createdPin = [];
537
+ try {
538
+ return await this.#files.transaction(async (state) => {
539
+ const binding = await validateRegisteredWorkspace(hostWorkspacePath(workspace));
540
+ const existing = [...state.workspaces.values()].find(record => record.canonical_path === binding.canonical);
541
+ if (existing !== undefined) {
542
+ const approved = existing.origin === 'managed'
543
+ ? await this.#files.validateManagedWorkspaceBinding(existing.canonical_path)
544
+ : binding;
545
+ this.#pinWorkspaceIdentity(existing.workspace_id, approved.identity);
546
+ return [existing, false];
547
+ }
548
+ requireWorkspaceCapacity(state);
549
+ const initialImport = state.workspaces.size === 0;
550
+ const unique = uniqueWorkspaceName(state, requested.display);
551
+ const normalized = normalizeProjectWorkspaceName(unique);
552
+ const record = this.#newWorkspace(state, normalized, binding.canonical, 'registered');
553
+ this.#pinWorkspaceIdentity(record.workspace_id, binding.identity);
554
+ createdPin.push({ workspaceId: record.workspace_id, identity: binding.identity });
555
+ state.workspaces.set(record.workspace_id, record);
556
+ if (state.activeWorkspaceId === null && initialImport) {
557
+ state.activeWorkspaceId = record.workspace_id;
558
+ bumpActiveBindingRevision(state);
559
+ }
560
+ return [record, true];
561
+ });
562
+ }
563
+ catch (error) {
564
+ const created = createdPin[0];
565
+ if (created !== undefined && !isCommittedTransactionFailure(error)) {
566
+ this.#deleteWorkspaceIdentityIfExact(created.workspaceId, created.identity);
567
+ }
568
+ throw error;
569
+ }
570
+ }
571
+ async registerWorkspace(displayName, workspace) {
572
+ const name = normalizeProjectWorkspaceName(displayName);
573
+ const createdPin = [];
574
+ try {
575
+ return await this.#files.transaction(async (state) => {
576
+ const binding = await validateRegisteredWorkspace(hostWorkspacePath(workspace));
577
+ requireWorkspaceCapacity(state);
578
+ requireUniqueWorkspaceName(state, name.normalized);
579
+ if ([...state.workspaces.values()].some(record => record.canonical_path === binding.canonical)) {
580
+ throw new ProjectStateError('workspace_path_conflict');
581
+ }
582
+ const record = this.#newWorkspace(state, name, binding.canonical, 'registered');
583
+ this.#pinWorkspaceIdentity(record.workspace_id, binding.identity);
584
+ createdPin.push({ workspaceId: record.workspace_id, identity: binding.identity });
585
+ state.workspaces.set(record.workspace_id, record);
586
+ if (state.activeWorkspaceId === null) {
587
+ state.activeWorkspaceId = record.workspace_id;
588
+ bumpActiveBindingRevision(state);
589
+ }
590
+ return [record, true];
591
+ });
592
+ }
593
+ catch (error) {
594
+ const created = createdPin[0];
595
+ if (created !== undefined && !isCommittedTransactionFailure(error)) {
596
+ this.#deleteWorkspaceIdentityIfExact(created.workspaceId, created.identity);
597
+ }
598
+ throw error;
599
+ }
600
+ }
601
+ async validateManagedCreate(displayName) {
602
+ const name = normalizeProjectWorkspaceName(displayName);
603
+ return await this.#files.transaction(state => {
604
+ requireWorkspaceCapacity(state);
605
+ requireUniqueWorkspaceName(state, name.normalized);
606
+ return [name.display, false];
607
+ });
608
+ }
609
+ async createManaged(displayName) {
610
+ const name = normalizeProjectWorkspaceName(displayName);
611
+ const rollback = { created: null };
612
+ try {
613
+ return await this.#files.transaction(async (state) => {
614
+ const managed = await this.#files.validateManagedRoot();
615
+ const managedHandle = this.#files.requireManagedRootHandle();
616
+ requireWorkspaceCapacity(state);
617
+ requireUniqueWorkspaceName(state, name.normalized);
618
+ const workspaceId = this.#newUniqueId(state);
619
+ const candidate = join(managed, `${slugPrefix(name.display)}-${[...workspaceId].slice(-12).join('')}`);
620
+ if (!isDirectChild(managed, candidate))
621
+ throw new ProjectStateError('workspace_boundary_changed');
622
+ const candidateName = basename(candidate);
623
+ let candidateFile = null;
624
+ try {
625
+ const created = this.#files.mkdirPrivateAt(managedHandle, candidateName, 'workspace_create_failed');
626
+ if (created.status === 'exists')
627
+ throw new ProjectStateError('workspace_path_conflict');
628
+ if (created.status !== 'ok')
629
+ throw new ProjectStateError('workspace_create_failed');
630
+ const initialIdentity = created.identity;
631
+ rollback.created = { path: candidate, identity: initialIdentity, workspaceId };
632
+ candidateFile = await open(candidate, constants.O_RDONLY | directoryFlag() | noFollowFlag());
633
+ this.#files.requireMatchesAt(managedHandle, candidateName, candidateFile, 'workspace_boundary_changed');
634
+ const initialInfo = await candidateFile.stat({ bigint: true });
635
+ if (!initialInfo.isDirectory()
636
+ || !sameFileIdentity(initialIdentity, fileIdentity(initialInfo)))
637
+ throw new ProjectStateError('workspace_boundary_changed');
638
+ this.#files.protectAt(managedHandle, candidateName, candidateFile, 'workspace_boundary_changed');
639
+ if (this.#files.platform !== 'win32')
640
+ await candidateFile.chmod(0o700);
641
+ const verified = await candidateFile.stat({ bigint: true });
642
+ const canonical = realpathSync(candidate);
643
+ this.#files.requireMatchesAt(managedHandle, candidateName, candidateFile, 'workspace_boundary_changed');
644
+ await this.#files.validateManagedRoot();
645
+ if (!verified.isDirectory()
646
+ || !privateDirectoryMetadata(verified, this.#files.platform)
647
+ || canonical !== candidate
648
+ || !isDirectChild(managed, canonical)
649
+ || !sameFileIdentity(initialIdentity, fileIdentity(verified))) {
650
+ throw new ProjectStateError('workspace_boundary_changed');
651
+ }
652
+ }
653
+ catch (error) {
654
+ if (error instanceof ProjectStateError)
655
+ throw error;
656
+ if (isNodeError(error, 'EEXIST'))
657
+ throw new ProjectStateError('workspace_path_conflict');
658
+ throw new ProjectStateError('workspace_create_failed');
659
+ }
660
+ finally {
661
+ await candidateFile?.close().catch(() => undefined);
662
+ }
663
+ const stamp = this.#stamp();
664
+ const record = Object.freeze({
665
+ workspace_id: workspaceId,
666
+ display_name: name.display,
667
+ normalized_name: name.normalized,
668
+ canonical_path: candidate,
669
+ origin: 'managed',
670
+ codex_home_key: `home-${workspaceId}`,
671
+ active_session_id: null,
672
+ created_at: stamp,
673
+ last_used_at: stamp,
674
+ });
675
+ const created = rollback.created;
676
+ const createdIdentity = created?.identity;
677
+ if (createdIdentity === undefined || createdIdentity === null) {
678
+ throw new ProjectStateError('workspace_create_failed');
679
+ }
680
+ this.#pinWorkspaceIdentity(workspaceId, createdIdentity);
681
+ state.workspaces.set(workspaceId, record);
682
+ state.activeWorkspaceId = workspaceId;
683
+ bumpActiveBindingRevision(state);
684
+ return [record, true];
685
+ });
686
+ }
687
+ catch (error) {
688
+ const created = rollback.created;
689
+ if (created !== null && !isCommittedTransactionFailure(error)) {
690
+ if (await this.#files.rollbackCreatedDirectory(created)) {
691
+ const identity = created.identity;
692
+ if (identity !== null) {
693
+ this.#deleteWorkspaceIdentityIfExact(created.workspaceId, identity);
694
+ }
695
+ }
696
+ }
697
+ throw error;
698
+ }
699
+ }
700
+ async rollbackManagedCreate(workspaceId, options) {
701
+ const rollback = { removed: null };
702
+ try {
703
+ const result = await this.#files.transaction(async (state) => {
704
+ const workspace = state.workspaces.get(workspaceId);
705
+ if (workspace?.origin !== 'managed')
706
+ return [false, false];
707
+ if ([...state.sessions.values()].some(session => session.workspace_id === workspaceId)) {
708
+ return [false, false];
709
+ }
710
+ const managed = await this.#files.validateManagedRoot();
711
+ if (!isDirectChild(managed, workspace.canonical_path))
712
+ return [false, false];
713
+ try {
714
+ const binding = await this.#files.validateManagedWorkspaceBinding(workspace.canonical_path);
715
+ const pinned = this.#workspaceIdentities.get(workspaceId);
716
+ if (pinned !== undefined && !sameFileIdentity(pinned, binding.identity)) {
717
+ return [false, false];
718
+ }
719
+ this.#pinWorkspaceIdentity(workspaceId, binding.identity);
720
+ const name = basename(binding.canonical);
721
+ const unlinked = this.#files.unlinkAt(this.#files.requireManagedRootHandle(), name, binding.identity, 'directory', 'workspace_boundary_changed');
722
+ if (unlinked.status !== 'ok')
723
+ return [false, false];
724
+ rollback.removed = { name, path: binding.canonical, identity: binding.identity };
725
+ }
726
+ catch {
727
+ return [false, false];
728
+ }
729
+ state.workspaces.delete(workspaceId);
730
+ if (state.activeWorkspaceId === workspaceId) {
731
+ // Restore only while deleting the active binding, under the same transaction. A later
732
+ // selection owns its binding even when this old create still needs resource cleanup.
733
+ const previous = options?.previousWorkspaceId;
734
+ state.activeWorkspaceId = previous != null && state.workspaces.has(previous)
735
+ ? previous
736
+ : mostRecentlyUsed(state.workspaces.values())?.workspace_id ?? null;
737
+ bumpActiveBindingRevision(state);
738
+ }
739
+ return [true, true];
740
+ }, options);
741
+ const deleted = rollback.removed;
742
+ if (result && deleted !== null) {
743
+ this.#deleteWorkspaceIdentityIfExact(workspaceId, deleted.identity);
744
+ }
745
+ return result;
746
+ }
747
+ catch (error) {
748
+ const deleted = rollback.removed;
749
+ if (deleted !== null) {
750
+ if (isCommittedTransactionFailure(error)) {
751
+ this.#deleteWorkspaceIdentityIfExact(workspaceId, deleted.identity);
752
+ }
753
+ else {
754
+ await this.#restoreManagedDirectory(workspaceId, deleted);
755
+ }
756
+ }
757
+ throw error;
758
+ }
759
+ }
760
+ async resolveWorkspace(displayName) {
761
+ const normalized = displayName === null ? null : normalizeProjectWorkspaceName(displayName);
762
+ return await this.#files.transaction(state => {
763
+ const record = normalized === null
764
+ ? (state.activeWorkspaceId === null ? undefined : state.workspaces.get(state.activeWorkspaceId))
765
+ : [...state.workspaces.values()].find(item => item.normalized_name === normalized.normalized);
766
+ if (record === undefined)
767
+ throw new ProjectStateError('workspace_not_found');
768
+ return [record, false];
769
+ });
770
+ }
771
+ async selectWorkspace(displayName) {
772
+ const name = normalizeProjectWorkspaceName(displayName);
773
+ return await this.#files.transaction(state => {
774
+ const found = [...state.workspaces.values()].find(record => record.normalized_name === name.normalized);
775
+ if (found === undefined)
776
+ throw new ProjectStateError('workspace_not_found');
777
+ const record = Object.freeze({ ...found, last_used_at: this.#stamp() });
778
+ state.workspaces.set(record.workspace_id, record);
779
+ state.activeWorkspaceId = record.workspace_id;
780
+ bumpActiveBindingRevision(state);
781
+ return [record, true];
782
+ });
783
+ }
784
+ /** Select the exact workspace that a user confirmed, with validation and mutation under one lock. */
785
+ async selectWorkspaceExact(displayName, workspaceId) {
786
+ const name = normalizeProjectWorkspaceName(displayName);
787
+ return await this.#files.transaction(async (state) => {
788
+ const found = state.workspaces.get(workspaceId);
789
+ if (found?.normalized_name !== name.normalized) {
790
+ throw new ProjectStateError('workspace_boundary_changed');
791
+ }
792
+ const binding = found.origin === 'managed'
793
+ ? await this.#files.validateManagedWorkspaceBinding(found.canonical_path)
794
+ : await validateRegisteredWorkspace(found.canonical_path, 'workspace_boundary_changed');
795
+ this.#pinWorkspaceIdentity(found.workspace_id, binding.identity);
796
+ const record = Object.freeze({ ...found, last_used_at: this.#stamp() });
797
+ state.workspaces.set(record.workspace_id, record);
798
+ state.activeWorkspaceId = record.workspace_id;
799
+ bumpActiveBindingRevision(state);
800
+ return [record, true];
801
+ });
802
+ }
803
+ async revalidateWorkspace(workspaceId) {
804
+ return await this.#files.transaction(async (state) => {
805
+ const workspace = state.workspaces.get(workspaceId);
806
+ if (workspace === undefined)
807
+ throw new ProjectStateError('workspace_not_found');
808
+ let binding;
809
+ if (workspace.origin === 'managed') {
810
+ binding = await this.#files.validateManagedWorkspaceBinding(workspace.canonical_path, true);
811
+ }
812
+ else {
813
+ binding = await validateRegisteredWorkspace(workspace.canonical_path, 'workspace_boundary_changed');
814
+ }
815
+ this.#pinWorkspaceIdentity(workspaceId, binding.identity);
816
+ return [hostWorkspaceFromConfig(binding.canonical, [binding.canonical]), false];
817
+ });
818
+ }
819
+ /** Revalidate and activate the exact persisted resume target immediately before process setup. */
820
+ async prepareSessionResume(workspaceId, sessionId, threadId) {
821
+ return (await this.prepareSessionResumeForRun(workspaceId, sessionId, threadId)).workspace;
822
+ }
823
+ /** Atomically activate a resume target and capture the exact state needed to undo it. */
824
+ async prepareSessionResumeForRun(workspaceId, sessionId, threadId) {
825
+ const expectedThread = validateThreadId(threadId);
826
+ return await this.#files.transaction(async (state) => {
827
+ const workspace = state.workspaces.get(workspaceId);
828
+ const session = state.sessions.get(sessionId);
829
+ if (workspace === undefined || session?.workspace_id !== workspaceId) {
830
+ throw new ProjectStateError('session_workspace_mismatch');
831
+ }
832
+ if (session.state !== 'ready'
833
+ || session.backend_session_id !== expectedThread)
834
+ throw new ProjectStateError('session_unavailable');
835
+ const previousActiveWorkspaceId = state.activeWorkspaceId;
836
+ const previousActiveSessionId = workspace.active_session_id;
837
+ const binding = workspace.origin === 'managed'
838
+ ? await this.#files.validateManagedWorkspaceBinding(workspace.canonical_path, true)
839
+ : await validateRegisteredWorkspace(workspace.canonical_path, 'workspace_boundary_changed');
840
+ this.#pinWorkspaceIdentity(workspaceId, binding.identity);
841
+ const stamp = this.#stamp();
842
+ state.sessions.set(sessionId, Object.freeze({ ...session, last_used_at: stamp }));
843
+ state.workspaces.set(workspaceId, Object.freeze({
844
+ ...workspace,
845
+ active_session_id: sessionId,
846
+ last_used_at: stamp,
847
+ }));
848
+ state.activeWorkspaceId = workspaceId;
849
+ const activationRevision = bumpActiveBindingRevision(state);
850
+ const rollback = Object.freeze({
851
+ activationRevision,
852
+ previousActiveWorkspaceId,
853
+ workspaceId,
854
+ previousActiveSessionId,
855
+ resumedSessionId: sessionId,
856
+ });
857
+ return [Object.freeze({
858
+ workspace: hostWorkspaceFromConfig(binding.canonical, [binding.canonical]),
859
+ rollback,
860
+ }), true];
861
+ });
862
+ }
863
+ /** Undo only the exact resume activation represented by the token. */
864
+ async rollbackSessionResume(rollback, options) {
865
+ return await this.#files.transaction(state => {
866
+ const workspace = state.workspaces.get(rollback.workspaceId);
867
+ if (workspace === undefined
868
+ || state.activeBindingRevision !== rollback.activationRevision
869
+ || state.activeWorkspaceId !== rollback.workspaceId
870
+ || workspace.active_session_id !== rollback.resumedSessionId)
871
+ return [false, false];
872
+ if (rollback.previousActiveWorkspaceId !== null
873
+ && !state.workspaces.has(rollback.previousActiveWorkspaceId))
874
+ return [false, false];
875
+ if (rollback.previousActiveSessionId !== null) {
876
+ const previousSession = state.sessions.get(rollback.previousActiveSessionId);
877
+ if (previousSession?.workspace_id !== rollback.workspaceId)
878
+ return [false, false];
879
+ }
880
+ state.workspaces.set(rollback.workspaceId, Object.freeze({
881
+ ...workspace,
882
+ active_session_id: rollback.previousActiveSessionId,
883
+ }));
884
+ state.activeWorkspaceId = rollback.previousActiveWorkspaceId;
885
+ bumpActiveBindingRevision(state);
886
+ return [true, true];
887
+ }, options);
888
+ }
889
+ async resolveSession(workspaceId, displayTitle) {
890
+ const title = displayTitle === null ? null : normalizeProjectSessionTitle(displayTitle);
891
+ return await this.#files.transaction(state => {
892
+ const workspace = state.workspaces.get(workspaceId);
893
+ if (workspace === undefined)
894
+ throw new ProjectStateError('workspace_not_found');
895
+ const record = title === null
896
+ ? (workspace.active_session_id === null ? undefined : state.sessions.get(workspace.active_session_id))
897
+ : [...state.sessions.values()].find(session => session.workspace_id === workspaceId
898
+ && session.normalized_title === title.normalized);
899
+ if (record === undefined)
900
+ throw new ProjectStateError('session_not_found');
901
+ return [record, false];
902
+ });
903
+ }
904
+ async importSession(workspaceId, input) {
905
+ const threadId = validateThreadId(input.threadId);
906
+ // Use native canonicalization, including Windows short-name aliases, like the catalog scanner.
907
+ const home = await realpath(input.home);
908
+ const title = normalizeProjectSessionTitle([...input.title].slice(0, MAX_PROJECT_SESSION_TITLE).join(''));
909
+ return await this.#files.transaction(state => {
910
+ if (!state.workspaces.has(workspaceId))
911
+ throw new ProjectStateError('workspace_not_found');
912
+ const existing = [...state.sessions.values()].find(session => session.backend_id === 'codex'
913
+ && session.backend_profile_id === 'codex:legacy'
914
+ && session.backend_session_id === threadId && session.executor_home === home);
915
+ if (existing && existing.workspace_id !== workspaceId)
916
+ throw new ProjectStateError('session_state_conflict');
917
+ if (existing?.origin === 'nova')
918
+ return [existing, false];
919
+ // Evict like every other insert path: a full workspace must not freeze out newer discoveries.
920
+ if (!existing)
921
+ pruneForSessionInsert(state, workspaceId);
922
+ const normalized = normalizeProjectSessionTitle(uniqueSessionTitle({ ...state, sessions: new Map([...state.sessions].filter(([id]) => id !== existing?.session_id)) }, workspaceId, title.display));
923
+ const session = Object.freeze({
924
+ session_id: existing?.session_id ?? this.#newUniqueId(state), workspace_id: workspaceId,
925
+ executor_home: home, origin: 'external', codex_thread_id: threadId, state: 'ready',
926
+ backend_id: 'codex', backend_profile_id: 'codex:legacy', backend_session_id: threadId,
927
+ display_title: normalized.display, normalized_title: normalized.normalized,
928
+ created_at: existing?.created_at ?? input.updatedAt,
929
+ last_used_at: Math.max(existing?.last_used_at ?? 0, input.updatedAt),
930
+ });
931
+ state.sessions.set(session.session_id, session);
932
+ const workspace = state.workspaces.get(workspaceId);
933
+ state.workspaces.set(workspaceId, Object.freeze({ ...workspace, last_used_at: Math.max(workspace.last_used_at, input.updatedAt) }));
934
+ return [session, JSON.stringify(existing) !== JSON.stringify(session)];
935
+ });
936
+ }
937
+ async beginSession(workspaceId, displayTitle) {
938
+ return (await this.beginSessionForRun(workspaceId, displayTitle)).session;
939
+ }
940
+ /** The host derives `displayTitle` from the work order (spec 08 Titles); there is no default title. */
941
+ async beginSessionForRun(workspaceId, displayTitle, executorHome, binding = { backend_id: 'codex', backend_profile_id: 'codex:legacy' }) {
942
+ const { backend_id: backendId, backend_profile_id: profileId } = binding;
943
+ if (!CODING_BACKEND_IDS.includes(backendId) || typeof profileId !== 'string'
944
+ || !/^[a-zA-Z0-9][a-zA-Z0-9:_./-]{0,255}$/u.test(profileId)) {
945
+ throw new ProjectStateError('state_corrupt');
946
+ }
947
+ const home = executorHome === undefined ? undefined : hostHomeValue(hostPersistentHomeFromConfig(executorHome, [executorHome])).path;
948
+ const supplied = normalizeProjectSessionTitle(displayTitle);
949
+ return await this.#files.transaction(state => {
950
+ const workspace = state.workspaces.get(workspaceId);
951
+ if (workspace === undefined)
952
+ throw new ProjectStateError('workspace_not_found');
953
+ const previousActiveWorkspaceId = state.activeWorkspaceId;
954
+ const previousActiveSessionId = workspace.active_session_id;
955
+ pruneForSessionInsert(state, workspaceId);
956
+ const title = uniqueSessionTitle(state, workspaceId, supplied.display);
957
+ const normalized = normalizeProjectSessionTitle(title);
958
+ const stamp = this.#stamp();
959
+ const sessionId = this.#newUniqueId(state);
960
+ const session = Object.freeze({
961
+ session_id: sessionId,
962
+ workspace_id: workspaceId,
963
+ origin: 'nova',
964
+ ...(home === undefined ? {} : { executor_home: home }),
965
+ display_title: normalized.display,
966
+ normalized_title: normalized.normalized,
967
+ codex_thread_id: null,
968
+ backend_id: backendId,
969
+ backend_profile_id: profileId,
970
+ backend_session_id: null,
971
+ state: 'starting',
972
+ created_at: stamp,
973
+ last_used_at: stamp,
974
+ });
975
+ state.sessions.set(sessionId, session);
976
+ state.workspaces.set(workspaceId, Object.freeze({
977
+ ...workspace,
978
+ active_session_id: sessionId,
979
+ last_used_at: stamp,
980
+ }));
981
+ state.activeWorkspaceId = workspaceId;
982
+ const activationRevision = bumpActiveBindingRevision(state);
983
+ const rollback = Object.freeze({
984
+ activationRevision,
985
+ previousActiveWorkspaceId,
986
+ workspaceId,
987
+ previousActiveSessionId,
988
+ startedSessionId: sessionId,
989
+ });
990
+ return [Object.freeze({ session, rollback }), true];
991
+ });
992
+ }
993
+ /** Mirror of Codex `thread/name/updated` (spec 08): Codex owns the name once one exists; clipped to the title limit. */
994
+ async setSessionTitle(sessionId, title) {
995
+ const clipped = stripLikePython([...title].slice(0, MAX_PROJECT_SESSION_TITLE).join(''));
996
+ if (clipped === '')
997
+ return false;
998
+ return await this.#files.transaction(state => {
999
+ const session = state.sessions.get(sessionId);
1000
+ if (session === undefined)
1001
+ return [false, false];
1002
+ const normalized = normalizeProjectSessionTitle(uniqueSessionTitle({ ...state, sessions: new Map([...state.sessions].filter(([id]) => id !== sessionId)) }, session.workspace_id, clipped));
1003
+ if (normalized.display === session.display_title)
1004
+ return [true, false];
1005
+ state.sessions.set(sessionId, Object.freeze({
1006
+ ...session, display_title: normalized.display, normalized_title: normalized.normalized,
1007
+ }));
1008
+ return [true, true];
1009
+ });
1010
+ }
1011
+ async rollbackSessionStart(sessionId, options) {
1012
+ return await this.#files.transaction(state => {
1013
+ const session = state.sessions.get(sessionId);
1014
+ if (session?.state !== 'starting' || session.backend_session_id !== null) {
1015
+ return [false, false];
1016
+ }
1017
+ state.sessions.delete(sessionId);
1018
+ const workspace = state.workspaces.get(session.workspace_id);
1019
+ if (workspace?.active_session_id === sessionId) {
1020
+ const replacement = newestReadySession(state, workspace.workspace_id);
1021
+ state.workspaces.set(workspace.workspace_id, Object.freeze({
1022
+ ...workspace,
1023
+ active_session_id: replacement?.session_id ?? null,
1024
+ }));
1025
+ bumpActiveBindingRevision(state);
1026
+ }
1027
+ return [true, true];
1028
+ }, options);
1029
+ }
1030
+ async rollbackSessionStartForRun(rollback, options) {
1031
+ return await this.#files.transaction(state => {
1032
+ const session = state.sessions.get(rollback.startedSessionId);
1033
+ if (session?.workspace_id !== rollback.workspaceId
1034
+ || session.state !== 'starting'
1035
+ || session.backend_session_id !== null) {
1036
+ return [false, false];
1037
+ }
1038
+ const workspace = state.workspaces.get(rollback.workspaceId);
1039
+ const exactActivation = workspace !== undefined
1040
+ && state.activeBindingRevision === rollback.activationRevision
1041
+ && state.activeWorkspaceId === rollback.workspaceId
1042
+ && workspace.active_session_id === rollback.startedSessionId;
1043
+ state.sessions.delete(rollback.startedSessionId);
1044
+ let bindingChanged = false;
1045
+ if (workspace?.active_session_id === rollback.startedSessionId) {
1046
+ const previousSession = rollback.previousActiveSessionId === null
1047
+ ? undefined
1048
+ : state.sessions.get(rollback.previousActiveSessionId);
1049
+ const restoredSession = previousSession?.workspace_id === rollback.workspaceId
1050
+ && previousSession.state === 'ready'
1051
+ ? previousSession
1052
+ : newestReadySession(state, rollback.workspaceId);
1053
+ state.workspaces.set(rollback.workspaceId, Object.freeze({
1054
+ ...workspace,
1055
+ active_session_id: restoredSession?.session_id ?? null,
1056
+ }));
1057
+ bindingChanged = true;
1058
+ }
1059
+ if (exactActivation
1060
+ && (rollback.previousActiveWorkspaceId === null
1061
+ || state.workspaces.has(rollback.previousActiveWorkspaceId))) {
1062
+ state.activeWorkspaceId = rollback.previousActiveWorkspaceId;
1063
+ bindingChanged = true;
1064
+ }
1065
+ if (bindingChanged)
1066
+ bumpActiveBindingRevision(state);
1067
+ return [true, true];
1068
+ }, options);
1069
+ }
1070
+ async markSessionReady(sessionId, threadId, options) {
1071
+ const cleanThreadId = validateThreadId(threadId);
1072
+ return await this.#files.transaction(state => {
1073
+ const session = state.sessions.get(sessionId);
1074
+ if (session === undefined)
1075
+ throw new ProjectStateError('session_not_found');
1076
+ if (session.state !== 'starting' || session.backend_session_id !== null) {
1077
+ throw new ProjectStateError('session_state_conflict');
1078
+ }
1079
+ if (session.origin === 'nova') {
1080
+ const duplicates = [...state.sessions.values()].filter(other => other.session_id !== sessionId
1081
+ && other.backend_id === session.backend_id && other.backend_profile_id === session.backend_profile_id
1082
+ && other.executor_home === session.executor_home && other.backend_session_id === cleanThreadId);
1083
+ if (duplicates.some(other => other.workspace_id !== session.workspace_id || other.origin === 'nova')) {
1084
+ throw new ProjectStateError('session_state_conflict');
1085
+ }
1086
+ for (const duplicate of duplicates) {
1087
+ state.sessions.delete(duplicate.session_id);
1088
+ const workspace = state.workspaces.get(duplicate.workspace_id);
1089
+ if (workspace.active_session_id === duplicate.session_id) {
1090
+ state.workspaces.set(workspace.workspace_id, Object.freeze({ ...workspace, active_session_id: sessionId }));
1091
+ bumpActiveBindingRevision(state);
1092
+ }
1093
+ }
1094
+ }
1095
+ const ready = Object.freeze({
1096
+ ...session,
1097
+ codex_thread_id: session.backend_id === 'codex' ? cleanThreadId : null,
1098
+ backend_session_id: cleanThreadId,
1099
+ state: 'ready',
1100
+ last_used_at: this.#stamp(),
1101
+ });
1102
+ state.sessions.set(sessionId, ready);
1103
+ return [ready, true];
1104
+ }, options);
1105
+ }
1106
+ async markSessionUnavailable(sessionId, options) {
1107
+ return await this.#files.transaction(state => {
1108
+ const session = state.sessions.get(sessionId);
1109
+ if (session === undefined)
1110
+ throw new ProjectStateError('session_not_found');
1111
+ const unavailable = Object.freeze({
1112
+ ...session,
1113
+ state: 'unavailable',
1114
+ last_used_at: this.#stamp(),
1115
+ });
1116
+ state.sessions.set(sessionId, unavailable);
1117
+ const workspace = state.workspaces.get(session.workspace_id);
1118
+ if (workspace?.active_session_id === sessionId) {
1119
+ state.workspaces.set(workspace.workspace_id, Object.freeze({
1120
+ ...workspace,
1121
+ active_session_id: newestReadySession(state, workspace.workspace_id)?.session_id ?? null,
1122
+ }));
1123
+ bumpActiveBindingRevision(state);
1124
+ }
1125
+ return [unavailable, true];
1126
+ }, options);
1127
+ }
1128
+ async activateSession(workspaceId, sessionId) {
1129
+ return await this.#files.transaction(state => {
1130
+ const workspace = state.workspaces.get(workspaceId);
1131
+ const session = state.sessions.get(sessionId);
1132
+ if (workspace === undefined)
1133
+ throw new ProjectStateError('workspace_not_found');
1134
+ if (session?.workspace_id !== workspaceId) {
1135
+ throw new ProjectStateError('session_workspace_mismatch');
1136
+ }
1137
+ if (session.state !== 'ready' || session.backend_session_id === null) {
1138
+ throw new ProjectStateError('session_unavailable');
1139
+ }
1140
+ const stamp = this.#stamp();
1141
+ const activated = Object.freeze({ ...session, last_used_at: stamp });
1142
+ state.sessions.set(sessionId, activated);
1143
+ state.workspaces.set(workspaceId, Object.freeze({
1144
+ ...workspace,
1145
+ active_session_id: sessionId,
1146
+ last_used_at: stamp,
1147
+ }));
1148
+ state.activeWorkspaceId = workspaceId;
1149
+ bumpActiveBindingRevision(state);
1150
+ return [activated, true];
1151
+ });
1152
+ }
1153
+ async persistentHome(workspaceId, { create = true } = {}) {
1154
+ return await this.#files.transaction(async (state) => {
1155
+ const workspace = state.workspaces.get(workspaceId);
1156
+ if (workspace === undefined)
1157
+ throw new ProjectStateError('workspace_not_found');
1158
+ await this.#files.revalidateStateRoot();
1159
+ const stateRoot = this.#files.requireStateRootHandle();
1160
+ if (create)
1161
+ await this.#files.migrateLegacyHomes(stateRoot);
1162
+ const directory = !create && this.#files.lookupAt(stateRoot, PROJECT_CODEX_HOMES_DIRECTORY, 'state_permissions').status === 'missing'
1163
+ ? LEGACY_PROJECT_CODEX_HOMES_DIRECTORY : PROJECT_CODEX_HOMES_DIRECTORY;
1164
+ const homesRoot = join(this.#files.stateRoot, directory);
1165
+ const home = join(homesRoot, workspace.codex_home_key);
1166
+ if (!isDirectChild(homesRoot, home))
1167
+ throw new ProjectStateError('workspace_boundary_changed');
1168
+ let homes = null;
1169
+ let workspaceHome = null;
1170
+ try {
1171
+ homes = await this.#files.ensurePrivateDirectoryAt(stateRoot, this.#files.stateRoot, directory, false, create);
1172
+ workspaceHome = await this.#files.ensurePrivateDirectoryAt(homes.file, homes.binding.canonical, workspace.codex_home_key, false, create);
1173
+ const canonical = workspaceHome.binding.canonical;
1174
+ if (canonical !== home || !isDirectChild(homesRoot, canonical)) {
1175
+ throw new ProjectStateError('state_permissions');
1176
+ }
1177
+ await this.#files.revalidateStateRoot();
1178
+ this.#files.requireMatchesAt(stateRoot, directory, homes.file, 'state_permissions');
1179
+ this.#files.requireMatchesAt(homes.file, workspace.codex_home_key, workspaceHome.file, 'state_permissions');
1180
+ const branded = hostPersistentHomeFromConfig(canonical, [canonical]);
1181
+ if (hostHomeValue(branded).path !== canonical) {
1182
+ throw new ProjectStateError('state_permissions');
1183
+ }
1184
+ this.#files.requireMatchesAt(homes.file, workspace.codex_home_key, workspaceHome.file, 'state_permissions');
1185
+ return [branded, false];
1186
+ }
1187
+ finally {
1188
+ await workspaceHome?.file.close().catch(() => undefined);
1189
+ await homes?.file.close().catch(() => undefined);
1190
+ }
1191
+ });
1192
+ }
1193
+ async publicView(pendingConfirmation) {
1194
+ return (await this.publicContext(pendingConfirmation)).view;
1195
+ }
1196
+ async publicContext(pendingConfirmation) {
1197
+ const state = await this.snapshot();
1198
+ const workspace = state.workspaces.find(record => record.workspace_id === state.active_workspace_id);
1199
+ const session = workspace?.active_session_id === null || workspace === undefined
1200
+ ? undefined
1201
+ : state.sessions.find(record => record.session_id === workspace.active_session_id);
1202
+ return Object.freeze({
1203
+ workspace_id: workspace?.workspace_id ?? null,
1204
+ view: Object.freeze({
1205
+ workspace_display_name: workspace?.display_name ?? null,
1206
+ session_title: session?.display_title ?? null,
1207
+ // Running works are adapter-owned; the project adapter merges them into this store roster.
1208
+ roster: recentWorkspaces(state.workspaces).map(record => Object.freeze({
1209
+ name: record.display_name, last_used_at: record.last_used_at, running: [],
1210
+ })),
1211
+ pending_confirmation: pendingConfirmation,
1212
+ pending_confirmation_busy: false,
1213
+ }),
1214
+ });
1215
+ }
1216
+ #newWorkspace(state, name, canonicalPath, origin) {
1217
+ const workspaceId = this.#newUniqueId(state);
1218
+ const stamp = this.#stamp();
1219
+ return Object.freeze({
1220
+ workspace_id: workspaceId,
1221
+ display_name: name.display,
1222
+ normalized_name: name.normalized,
1223
+ canonical_path: canonicalPath,
1224
+ origin,
1225
+ codex_home_key: `home-${workspaceId}`,
1226
+ active_session_id: null,
1227
+ created_at: stamp,
1228
+ last_used_at: stamp,
1229
+ });
1230
+ }
1231
+ #newUniqueId(state) {
1232
+ for (let attempt = 0; attempt < MAX_ID_FACTORY_ATTEMPTS; attempt += 1) {
1233
+ let value;
1234
+ try {
1235
+ value = this.#idFactory();
1236
+ }
1237
+ catch {
1238
+ throw new ProjectStateError('id_factory_invalid');
1239
+ }
1240
+ if (typeof value !== 'string' || !STORED_ID.test(value)) {
1241
+ throw new ProjectStateError('id_factory_invalid');
1242
+ }
1243
+ if (!state.workspaces.has(value)
1244
+ && !state.sessions.has(value)
1245
+ && !this.#workspaceIdentities.has(value))
1246
+ return value;
1247
+ }
1248
+ throw new ProjectStateError('id_factory_invalid');
1249
+ }
1250
+ #pinWorkspaceIdentity(workspaceId, identity) {
1251
+ const expected = this.#workspaceIdentities.get(workspaceId);
1252
+ if (expected !== undefined && !sameFileIdentity(expected, identity)) {
1253
+ throw new ProjectStateError('workspace_boundary_changed');
1254
+ }
1255
+ this.#workspaceIdentities.set(workspaceId, identity);
1256
+ }
1257
+ #advanceWorkspaceIdentity(workspaceId, expected, replacement) {
1258
+ const current = this.#workspaceIdentities.get(workspaceId);
1259
+ if (current === undefined || !sameFileIdentity(current, expected)) {
1260
+ throw new ProjectStateError('workspace_boundary_changed');
1261
+ }
1262
+ this.#workspaceIdentities.set(workspaceId, replacement);
1263
+ }
1264
+ #restoreWorkspaceIdentity(workspaceId, replacement, original) {
1265
+ const current = this.#workspaceIdentities.get(workspaceId);
1266
+ if (current === undefined || sameFileIdentity(current, original)) {
1267
+ this.#workspaceIdentities.set(workspaceId, original);
1268
+ return;
1269
+ }
1270
+ if (replacement !== null && sameFileIdentity(current, replacement)) {
1271
+ this.#workspaceIdentities.set(workspaceId, original);
1272
+ return;
1273
+ }
1274
+ throw new ProjectStateError('workspace_boundary_changed');
1275
+ }
1276
+ #deleteWorkspaceIdentityIfExact(workspaceId, identity) {
1277
+ const current = this.#workspaceIdentities.get(workspaceId);
1278
+ if (current !== undefined && sameFileIdentity(current, identity)) {
1279
+ this.#workspaceIdentities.delete(workspaceId);
1280
+ }
1281
+ }
1282
+ #stamp() {
1283
+ const value = this.#now();
1284
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
1285
+ throw new ProjectStateError('clock_invalid');
1286
+ }
1287
+ return value;
1288
+ }
1289
+ #maintenanceCheckpoint(step) {
1290
+ if (this.#maintenanceFault?.(step) === true)
1291
+ throw new MaintenanceFaultError(step);
1292
+ }
1293
+ async #restoreManagedDirectory(workspaceId, removed) {
1294
+ let file = null;
1295
+ let createdRoot = null;
1296
+ let createdIdentity = null;
1297
+ let adopted = false;
1298
+ try {
1299
+ const managed = await this.#files.validateManagedRoot();
1300
+ if (!isDirectChild(managed, removed.path))
1301
+ return;
1302
+ const root = this.#files.requireManagedRootHandle();
1303
+ const created = this.#files.mkdirPrivateAt(root, removed.name, 'workspace_boundary_changed');
1304
+ if (created.status !== 'ok')
1305
+ return;
1306
+ createdRoot = root;
1307
+ createdIdentity = created.identity;
1308
+ file = await open(removed.path, constants.O_RDONLY | directoryFlag() | noFollowFlag());
1309
+ this.#files.requireMatchesAt(root, removed.name, file, 'workspace_boundary_changed');
1310
+ const initialInfo = await file.stat({ bigint: true });
1311
+ if (!sameFileIdentity(created.identity, fileIdentity(initialInfo)))
1312
+ return;
1313
+ this.#files.protectAt(root, removed.name, file, 'workspace_boundary_changed');
1314
+ if (this.#files.platform !== 'win32')
1315
+ await file.chmod(0o700);
1316
+ const info = await file.stat({ bigint: true });
1317
+ const canonical = realpathSync(removed.path);
1318
+ if (!info.isDirectory()
1319
+ || !privateDirectoryMetadata(info, this.#files.platform)
1320
+ || canonical !== removed.path)
1321
+ return;
1322
+ this.#files.requireMatchesAt(root, removed.name, file, 'workspace_boundary_changed');
1323
+ const current = this.#workspaceIdentities.get(workspaceId);
1324
+ if (current !== undefined && sameFileIdentity(current, removed.identity)) {
1325
+ this.#workspaceIdentities.set(workspaceId, fileIdentity(info));
1326
+ adopted = true;
1327
+ }
1328
+ }
1329
+ catch {
1330
+ // A failed transaction leaves the original pin in place unless an exact safe restore succeeds.
1331
+ }
1332
+ finally {
1333
+ await file?.close().catch(() => undefined);
1334
+ if (!adopted && createdRoot !== null && createdIdentity !== null) {
1335
+ try {
1336
+ this.#files.unlinkAt(createdRoot, removed.name, createdIdentity, 'directory', 'workspace_boundary_changed');
1337
+ }
1338
+ catch {
1339
+ // A restore failure never removes an unproven same-name replacement.
1340
+ }
1341
+ }
1342
+ }
1343
+ }
1344
+ }
1345
+ //# sourceMappingURL=project-store.js.map