daecore 0.3.0__py3-none-any.whl

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 (1051) hide show
  1. _daecore_entry.py +2145 -0
  2. daecore/__init__.py +22 -0
  3. daecore/__main__.py +21 -0
  4. daecore/_atomic_file.py +153 -0
  5. daecore/_durable_file.py +75 -0
  6. daecore/_error_mode.py +24 -0
  7. daecore/_exclusive_lock.py +521 -0
  8. daecore/_handover.py +548 -0
  9. daecore/_release/core.lock +4 -0
  10. daecore/_release/handover.lock +47 -0
  11. daecore/_release/overlay-cuda.lock +126 -0
  12. daecore/_release/overlay-metal.lock +6 -0
  13. daecore/_release/overlay-vulkan.lock +6 -0
  14. daecore/_release/python-version +1 -0
  15. daecore/_release/runtime.lock +1633 -0
  16. daecore/_release/tools.lock +20 -0
  17. daecore/_survey_store.py +156 -0
  18. daecore/_version.py +10 -0
  19. daecore/_windows_directory.py +69 -0
  20. daecore/agent_use/__init__.py +1 -0
  21. daecore/agent_use/capabilities.py +680 -0
  22. daecore/agent_use/constitution.py +185 -0
  23. daecore/agent_use/features.py +40 -0
  24. daecore/approval.py +150 -0
  25. daecore/artifact_cleanup.py +136 -0
  26. daecore/artifact_observation.py +278 -0
  27. daecore/assurance/__init__.py +1 -0
  28. daecore/assurance/access.py +54 -0
  29. daecore/assurance/campaign.py +267 -0
  30. daecore/assurance/catalog.py +235 -0
  31. daecore/assurance/census.py +67 -0
  32. daecore/assurance/contracts.py +212 -0
  33. daecore/assurance/control.py +90 -0
  34. daecore/assurance/control_provider.py +40 -0
  35. daecore/assurance/declarations.py +32 -0
  36. daecore/assurance/diagnostics.py +144 -0
  37. daecore/assurance/events.py +586 -0
  38. daecore/assurance/integrity/__init__.py +5 -0
  39. daecore/assurance/integrity/breach.py +309 -0
  40. daecore/assurance/integrity/proof.py +512 -0
  41. daecore/assurance/integrity/transparency.py +249 -0
  42. daecore/assurance/intent.py +367 -0
  43. daecore/assurance/ledger/__init__.py +445 -0
  44. daecore/assurance/ledger/_chain.py +169 -0
  45. daecore/assurance/ledger/_checkpoints.py +131 -0
  46. daecore/assurance/ledger/_heartbeats.py +290 -0
  47. daecore/assurance/ledger/_projections.py +390 -0
  48. daecore/assurance/ledger/_records.py +224 -0
  49. daecore/assurance/monitoring.py +784 -0
  50. daecore/assurance/providers.py +208 -0
  51. daecore/assurance/repair/__init__.py +1 -0
  52. daecore/assurance/repair/contracts.py +255 -0
  53. daecore/assurance/repair/engine.py +639 -0
  54. daecore/assurance/repair/registry.py +199 -0
  55. daecore/assurance/schema.py +174 -0
  56. daecore/assurance_runtime/__init__.py +1 -0
  57. daecore/assurance_runtime/authority.py +98 -0
  58. daecore/assurance_runtime/builtin.py +252 -0
  59. daecore/assurance_runtime/census.py +56 -0
  60. daecore/assurance_runtime/provider_set.py +337 -0
  61. daecore/assurance_runtime/repair.py +155 -0
  62. daecore/backup/__init__.py +1 -0
  63. daecore/backup/assurance.py +68 -0
  64. daecore/backup/checkpoint/__init__.py +1 -0
  65. daecore/backup/checkpoint/contracts.py +301 -0
  66. daecore/backup/checkpoint/engine.py +1048 -0
  67. daecore/backup/checkpoint/inspection.py +352 -0
  68. daecore/backup/checkpoint/inventory.py +255 -0
  69. daecore/backup/checkpoint/provider.py +347 -0
  70. daecore/backup/checkpoint/restore.py +1009 -0
  71. daecore/backup/checkpoint/verify.py +772 -0
  72. daecore/backup/core.py +244 -0
  73. daecore/chunk_identity.py +131 -0
  74. daecore/chunking/__init__.py +1 -0
  75. daecore/chunking/_packing_fit.py +217 -0
  76. daecore/chunking/contract.py +20 -0
  77. daecore/chunking/counter.py +173 -0
  78. daecore/chunking/geometry.py +35 -0
  79. daecore/chunking/import_packer.py +218 -0
  80. daecore/chunking/packer.py +300 -0
  81. daecore/chunking/record_packer.py +272 -0
  82. daecore/chunking/structural.py +87 -0
  83. daecore/classifier/__init__.py +1 -0
  84. daecore/classifier/agent_contract.py +113 -0
  85. daecore/classifier/facets.py +18 -0
  86. daecore/classifier/inputs.py +85 -0
  87. daecore/classifier/installation.py +127 -0
  88. daecore/classifier/labels.py +283 -0
  89. daecore/cli/__init__.py +19 -0
  90. daecore/cli/__main__.py +9 -0
  91. daecore/cli/client_names.py +34 -0
  92. daecore/cli/commands/__init__.py +1 -0
  93. daecore/cli/commands/add.py +327 -0
  94. daecore/cli/commands/doctor.py +153 -0
  95. daecore/cli/commands/drift.py +66 -0
  96. daecore/cli/commands/forget.py +443 -0
  97. daecore/cli/commands/lifecycle.py +452 -0
  98. daecore/cli/commands/memory/__init__.py +1 -0
  99. daecore/cli/commands/memory/backup.py +592 -0
  100. daecore/cli/commands/memory/common.py +35 -0
  101. daecore/cli/commands/memory/health.py +260 -0
  102. daecore/cli/commands/memory/reclassify.py +194 -0
  103. daecore/cli/commands/memory/remember.py +287 -0
  104. daecore/cli/commands/memory/transfer.py +301 -0
  105. daecore/cli/commands/memory/verbs.py +468 -0
  106. daecore/cli/commands/memory/word_index.py +61 -0
  107. daecore/cli/commands/models.py +210 -0
  108. daecore/cli/commands/relocate.py +366 -0
  109. daecore/cli/commands/remove.py +148 -0
  110. daecore/cli/commands/restart.py +338 -0
  111. daecore/cli/commands/retrieval/__init__.py +1 -0
  112. daecore/cli/commands/retrieval/inspection.py +285 -0
  113. daecore/cli/commands/retrieval/refresh.py +519 -0
  114. daecore/cli/commands/retrieval/refresh_offline.py +135 -0
  115. daecore/cli/commands/retrieval/refresh_reporting.py +445 -0
  116. daecore/cli/commands/retrieval/refresh_targets.py +99 -0
  117. daecore/cli/commands/retrieval/search.py +295 -0
  118. daecore/cli/commands/serve.py +35 -0
  119. daecore/cli/commands/setup.py +581 -0
  120. daecore/cli/commands/sources.py +352 -0
  121. daecore/cli/commands/status.py +767 -0
  122. daecore/cli/commands/sync.py +683 -0
  123. daecore/cli/commands/update.py +813 -0
  124. daecore/cli/common.py +88 -0
  125. daecore/cli/content_output.py +21 -0
  126. daecore/cli/data.py +37 -0
  127. daecore/cli/dispatch.py +503 -0
  128. daecore/cli/entry.py +274 -0
  129. daecore/cli/handlers.py +62 -0
  130. daecore/cli/help_screens.py +120 -0
  131. daecore/cli/machine.py +155 -0
  132. daecore/cli/model_repair.py +112 -0
  133. daecore/cli/old_folder.py +21 -0
  134. daecore/cli/parser/__init__.py +1 -0
  135. daecore/cli/parser/builder.py +87 -0
  136. daecore/cli/parser/groups.py +119 -0
  137. daecore/cli/parser/suggest.py +79 -0
  138. daecore/cli/parser/surface.py +353 -0
  139. daecore/cli/parser/verbs.py +404 -0
  140. daecore/cli/parser/visibility.py +200 -0
  141. daecore/cli/results.py +123 -0
  142. daecore/cli/source_output.py +90 -0
  143. daecore/cli/update_currency.py +203 -0
  144. daecore/cli/update_profile.py +110 -0
  145. daecore/cli/update_receipt.py +256 -0
  146. daecore/cli/update_reconcile.py +164 -0
  147. daecore/cli/version_notice.py +137 -0
  148. daecore/command_help.py +281 -0
  149. daecore/config/__init__.py +159 -0
  150. daecore/config/application.py +334 -0
  151. daecore/config/assurance.py +91 -0
  152. daecore/config/authority.py +580 -0
  153. daecore/config/authority_store.py +177 -0
  154. daecore/config/changes.py +112 -0
  155. daecore/config/loader.py +533 -0
  156. daecore/config/schema.py +373 -0
  157. daecore/config/settings.py +121 -0
  158. daecore/config/source_parsing.py +111 -0
  159. daecore/corpus_pause.py +269 -0
  160. daecore/cpu_capacity.py +27 -0
  161. daecore/daemon/__init__.py +1 -0
  162. daecore/daemon/_version_util.py +25 -0
  163. daecore/daemon/activation.py +376 -0
  164. daecore/daemon/assurance.py +132 -0
  165. daecore/daemon/assurance_provider.py +1160 -0
  166. daecore/daemon/attachments.py +470 -0
  167. daecore/daemon/automatic_recovery.py +192 -0
  168. daecore/daemon/candidate_checks.py +213 -0
  169. daecore/daemon/classifier_setup.py +186 -0
  170. daecore/daemon/disable.py +250 -0
  171. daecore/daemon/drain.py +247 -0
  172. daecore/daemon/drift_state.py +262 -0
  173. daecore/daemon/embedding_transition.py +153 -0
  174. daecore/daemon/fence.py +807 -0
  175. daecore/daemon/frozen_read_window.py +165 -0
  176. daecore/daemon/handover_steps.py +69 -0
  177. daecore/daemon/identity.py +149 -0
  178. daecore/daemon/labeler.py +611 -0
  179. daecore/daemon/maintenance/__init__.py +1 -0
  180. daecore/daemon/maintenance/_manifest_errors.py +13 -0
  181. daecore/daemon/maintenance/_manifest_rules.py +322 -0
  182. daecore/daemon/maintenance/_manifest_validation.py +266 -0
  183. daecore/daemon/maintenance/adjudication.py +282 -0
  184. daecore/daemon/maintenance/completion.py +238 -0
  185. daecore/daemon/maintenance/decisions.py +498 -0
  186. daecore/daemon/maintenance/events.py +122 -0
  187. daecore/daemon/maintenance/identity.py +402 -0
  188. daecore/daemon/maintenance/intent.py +309 -0
  189. daecore/daemon/maintenance/manifest.py +504 -0
  190. daecore/daemon/maintenance/pause_fields.py +84 -0
  191. daecore/daemon/maintenance/records.py +144 -0
  192. daecore/daemon/maintenance/status.py +262 -0
  193. daecore/daemon/maintenance/verification.py +137 -0
  194. daecore/daemon/maintenance_client.py +346 -0
  195. daecore/daemon/operation_hooks.py +115 -0
  196. daecore/daemon/pidfile.py +270 -0
  197. daecore/daemon/profile_setup.py +144 -0
  198. daecore/daemon/quiescence.py +294 -0
  199. daecore/daemon/recovery.py +432 -0
  200. daecore/daemon/refresh.py +150 -0
  201. daecore/daemon/refresh_recovery.py +193 -0
  202. daecore/daemon/release_notices.py +388 -0
  203. daecore/daemon/relocation/__init__.py +1 -0
  204. daecore/daemon/relocation/_backup.py +232 -0
  205. daecore/daemon/relocation/capacity.py +85 -0
  206. daecore/daemon/relocation/coordinator.py +907 -0
  207. daecore/daemon/relocation/copy.py +425 -0
  208. daecore/daemon/relocation/last_move.py +127 -0
  209. daecore/daemon/relocation/recovery.py +345 -0
  210. daecore/daemon/relocation/retirement.py +593 -0
  211. daecore/daemon/relocation/state.py +511 -0
  212. daecore/daemon/replacement.py +226 -0
  213. daecore/daemon/retrieval_client.py +335 -0
  214. daecore/daemon/runtime/__init__.py +557 -0
  215. daecore/daemon/runtime/_console_wrapper.py +114 -0
  216. daecore/daemon/runtime/_currency.py +160 -0
  217. daecore/daemon/runtime/_custody.py +40 -0
  218. daecore/daemon/runtime/_relay.py +190 -0
  219. daecore/daemon/runtime/_relocation.py +144 -0
  220. daecore/daemon/runtime/_seed_launcher.py +460 -0
  221. daecore/daemon/runtime/packages.py +196 -0
  222. daecore/daemon/runtime_change.py +165 -0
  223. daecore/daemon/runtime_install.py +262 -0
  224. daecore/daemon/runtime_retirement.py +430 -0
  225. daecore/daemon/runtime_switch.py +210 -0
  226. daecore/daemon/scheduler.py +308 -0
  227. daecore/daemon/spawn_guard.py +507 -0
  228. daecore/daemon/spawning.py +641 -0
  229. daecore/daemon/status.py +307 -0
  230. daecore/daemon/sync_policy.py +251 -0
  231. daecore/daemon/ticket_auth.py +162 -0
  232. daecore/daemon/tls.py +62 -0
  233. daecore/daemon/trust.py +456 -0
  234. daecore/daemon/uninstall_transaction.py +959 -0
  235. daecore/daemon/update/__init__.py +1 -0
  236. daecore/daemon/update/artifacts.py +779 -0
  237. daecore/daemon/update/completion.py +190 -0
  238. daecore/daemon/update/convergence.py +302 -0
  239. daecore/daemon/update/dispatch.py +155 -0
  240. daecore/daemon/update/journal.py +245 -0
  241. daecore/daemon/update/model_evidence.py +153 -0
  242. daecore/daemon/update/ownership.py +171 -0
  243. daecore/daemon/update/preimage.py +93 -0
  244. daecore/daemon/update/progress.py +55 -0
  245. daecore/daemon/update/proof.py +242 -0
  246. daecore/daemon/update/protocol.py +135 -0
  247. daecore/daemon/update/recovery.py +81 -0
  248. daecore/daemon/update/rollback.py +91 -0
  249. daecore/daemon/update/state.py +334 -0
  250. daecore/daemon/update/transaction.py +325 -0
  251. daecore/daemon/version_policy.py +29 -0
  252. daecore/daemon_lock.py +92 -0
  253. daecore/daemon_process/__init__.py +1 -0
  254. daecore/daemon_process/convergence.py +138 -0
  255. daecore/daemon_process/database_observation.py +157 -0
  256. daecore/daemon_process/name_observation.py +217 -0
  257. daecore/daemon_process/notes.py +14 -0
  258. daecore/daemon_process/resource_observation.py +167 -0
  259. daecore/daemon_process/serve.py +464 -0
  260. daecore/daemon_process/services.py +532 -0
  261. daecore/daemon_process/start.py +618 -0
  262. daecore/daemon_process/stop.py +219 -0
  263. daecore/daemon_process/watch.py +139 -0
  264. daecore/data/rerank_calibration.json +65 -0
  265. daecore/decoder_activation.py +87 -0
  266. daecore/decoder_installation.py +369 -0
  267. daecore/decoder_tree.py +138 -0
  268. daecore/digests.py +14 -0
  269. daecore/disk_capacity.py +128 -0
  270. daecore/doctor/__init__.py +1 -0
  271. daecore/doctor/contracts.py +351 -0
  272. daecore/doctor/guidance.py +246 -0
  273. daecore/doctor/identity.py +190 -0
  274. daecore/doctor/render.py +750 -0
  275. daecore/doctor/results.py +42 -0
  276. daecore/doctor/runner.py +800 -0
  277. daecore/doctor/session.py +245 -0
  278. daecore/doctor/store.py +190 -0
  279. daecore/document_extraction/__init__.py +64 -0
  280. daecore/document_extraction/entry.py +81 -0
  281. daecore/document_extraction/frames.py +60 -0
  282. daecore/document_extraction/level.py +281 -0
  283. daecore/document_extraction/level_probe.py +331 -0
  284. daecore/document_extraction/limits.py +53 -0
  285. daecore/document_extraction/office.py +531 -0
  286. daecore/document_extraction/posix_launcher.py +53 -0
  287. daecore/document_extraction/posix_policy.py +146 -0
  288. daecore/document_extraction/probe_entry.py +144 -0
  289. daecore/document_extraction/providers.py +613 -0
  290. daecore/document_extraction/registry_storage.py +46 -0
  291. daecore/document_extraction/result.py +84 -0
  292. daecore/document_extraction/session.py +338 -0
  293. daecore/document_extraction/warmup.zip +0 -0
  294. daecore/document_extraction/windows_access.py +239 -0
  295. daecore/document_extraction/windows_launcher.py +150 -0
  296. daecore/document_extraction/windows_probe_owner.py +35 -0
  297. daecore/document_extraction/worker.py +114 -0
  298. daecore/document_formats.py +72 -0
  299. daecore/documents/__init__.py +1 -0
  300. daecore/documents/_html.py +98 -0
  301. daecore/documents/_json_syntax.py +143 -0
  302. daecore/documents/_line_units.py +57 -0
  303. daecore/documents/_markdown.py +208 -0
  304. daecore/documents/_raw_positions.py +118 -0
  305. daecore/documents/_reader_metadata.py +16 -0
  306. daecore/documents/_record_input.py +30 -0
  307. daecore/documents/_slug_table.py +137 -0
  308. daecore/documents/_text_input.py +12 -0
  309. daecore/documents/csv_reader.py +155 -0
  310. daecore/documents/csv_records.py +40 -0
  311. daecore/documents/excerpts.py +174 -0
  312. daecore/documents/fidelity.py +178 -0
  313. daecore/documents/hygiene.py +202 -0
  314. daecore/documents/identity.py +49 -0
  315. daecore/documents/import_markdown.py +63 -0
  316. daecore/documents/json_reader.py +161 -0
  317. daecore/documents/links.py +672 -0
  318. daecore/documents/locators.py +713 -0
  319. daecore/documents/markdown_reader.py +161 -0
  320. daecore/documents/markup_reader.py +218 -0
  321. daecore/documents/model.py +245 -0
  322. daecore/documents/native.py +549 -0
  323. daecore/documents/outline.py +404 -0
  324. daecore/documents/plaintext_reader.py +57 -0
  325. daecore/documents/ranges.py +281 -0
  326. daecore/documents/readers.py +85 -0
  327. daecore/documents/record_units.py +61 -0
  328. daecore/documents/resolution.py +553 -0
  329. daecore/documents/sections.py +20 -0
  330. daecore/documents/slugs.py +36 -0
  331. daecore/documents/source_maps.py +49 -0
  332. daecore/documents/text.py +141 -0
  333. daecore/eligibility.py +1139 -0
  334. daecore/enablement.py +411 -0
  335. daecore/entry.py +138 -0
  336. daecore/envconf.py +419 -0
  337. daecore/evidence_dates.py +108 -0
  338. daecore/evidence_identity.py +515 -0
  339. daecore/exception_text.py +67 -0
  340. daecore/exit_codes.py +24 -0
  341. daecore/file_hash.py +17 -0
  342. daecore/file_probe.py +139 -0
  343. daecore/file_read.py +257 -0
  344. daecore/file_status.py +65 -0
  345. daecore/file_watch.py +247 -0
  346. daecore/filesystem_walk.py +703 -0
  347. daecore/health_readiness.py +130 -0
  348. daecore/held_lock.py +188 -0
  349. daecore/home_pointer.py +205 -0
  350. daecore/ignore_policy.py +1102 -0
  351. daecore/inference/__init__.py +1 -0
  352. daecore/inference/_execution_state.py +327 -0
  353. daecore/inference/_memory_state.py +148 -0
  354. daecore/inference/accelerator.py +505 -0
  355. daecore/inference/assurance.py +123 -0
  356. daecore/inference/assurance_provider.py +613 -0
  357. daecore/inference/batch_geometry.py +419 -0
  358. daecore/inference/device_memory.py +551 -0
  359. daecore/inference/execution.py +800 -0
  360. daecore/inference/failures.py +474 -0
  361. daecore/inference/hardware.py +241 -0
  362. daecore/inference/memory_budget.py +539 -0
  363. daecore/inference/model/__init__.py +1 -0
  364. daecore/inference/model/_file_identity.py +35 -0
  365. daecore/inference/model/_locking.py +62 -0
  366. daecore/inference/model/assets.py +1172 -0
  367. daecore/inference/model/blob_store.py +209 -0
  368. daecore/inference/model/cache/__init__.py +426 -0
  369. daecore/inference/model/cache/_collection.py +272 -0
  370. daecore/inference/model/cache/_leases.py +241 -0
  371. daecore/inference/model/cache/_observation.py +173 -0
  372. daecore/inference/model/cache/_pool.py +176 -0
  373. daecore/inference/model/cache/_records.py +311 -0
  374. daecore/inference/model/cache/_storage.py +232 -0
  375. daecore/inference/model/cache/_types.py +116 -0
  376. daecore/inference/model/registry.py +330 -0
  377. daecore/inference/model_fallback.py +227 -0
  378. daecore/inference/model_preparation.py +592 -0
  379. daecore/inference/model_progress.py +210 -0
  380. daecore/inference/model_status.py +407 -0
  381. daecore/inference/passage_geometry.py +215 -0
  382. daecore/inference/placement.py +352 -0
  383. daecore/inference/probe.py +119 -0
  384. daecore/inference/profile/__init__.py +393 -0
  385. daecore/inference/profile/circuit.py +262 -0
  386. daecore/inference/profile/contracts.py +188 -0
  387. daecore/inference/profile/incidents.py +502 -0
  388. daecore/inference/profile/registry.py +264 -0
  389. daecore/inference/profile/resolve.py +177 -0
  390. daecore/inference/profile/state.py +861 -0
  391. daecore/inference/providers.py +231 -0
  392. daecore/inference/residency.py +124 -0
  393. daecore/inference/role_health.py +139 -0
  394. daecore/inference/roles/__init__.py +1 -0
  395. daecore/inference/roles/classifier.py +1155 -0
  396. daecore/inference/roles/classifier_artifacts.py +799 -0
  397. daecore/inference/roles/embedding.py +337 -0
  398. daecore/inference/roles/lora_reranker.py +1098 -0
  399. daecore/inference/sequence_budget.py +254 -0
  400. daecore/inference/sessions/__init__.py +1 -0
  401. daecore/inference/sessions/_recovery.py +346 -0
  402. daecore/inference/sessions/_worker_client.py +387 -0
  403. daecore/inference/sessions/_worker_protocol.py +140 -0
  404. daecore/inference/sessions/_worker_transport.py +357 -0
  405. daecore/inference/sessions/locked_session.py +149 -0
  406. daecore/inference/sessions/model_worker.py +828 -0
  407. daecore/inference/system.py +72 -0
  408. daecore/inference/webgpu.py +89 -0
  409. daecore/input_budget.py +154 -0
  410. daecore/json_records.py +45 -0
  411. daecore/lifecycle_gate.py +657 -0
  412. daecore/link_contract.py +48 -0
  413. daecore/live_output.py +27 -0
  414. daecore/local_zone.py +143 -0
  415. daecore/memory/__init__.py +1 -0
  416. daecore/memory/_correction_inspection.py +161 -0
  417. daecore/memory/_inspection_contract.py +110 -0
  418. daecore/memory/_memory_inspection.py +368 -0
  419. daecore/memory/_source_inspection.py +269 -0
  420. daecore/memory/action_preflight.py +378 -0
  421. daecore/memory/annotation_writes.py +206 -0
  422. daecore/memory/assurance.py +151 -0
  423. daecore/memory/assurance_provider.py +719 -0
  424. daecore/memory/canonical/__init__.py +1 -0
  425. daecore/memory/canonical/_erasure.py +461 -0
  426. daecore/memory/canonical/_erasure_proofs.py +290 -0
  427. daecore/memory/canonical/_erasure_records.py +273 -0
  428. daecore/memory/canonical/_erasure_schema.py +521 -0
  429. daecore/memory/canonical/_facet_labels.py +195 -0
  430. daecore/memory/canonical/_history_reads.py +218 -0
  431. daecore/memory/canonical/_imported_files.py +207 -0
  432. daecore/memory/canonical/_mirrors.py +195 -0
  433. daecore/memory/canonical/_name_history.py +716 -0
  434. daecore/memory/canonical/_projection.py +63 -0
  435. daecore/memory/canonical/_record_reads.py +584 -0
  436. daecore/memory/canonical/_returns.py +277 -0
  437. daecore/memory/canonical/_revisions.py +208 -0
  438. daecore/memory/canonical/_rows.py +421 -0
  439. daecore/memory/canonical/_transfer.py +317 -0
  440. daecore/memory/canonical/access_lock.py +275 -0
  441. daecore/memory/canonical/admission.py +59 -0
  442. daecore/memory/canonical/citation_index.py +169 -0
  443. daecore/memory/canonical/connections.py +557 -0
  444. daecore/memory/canonical/correction_erasure.py +156 -0
  445. daecore/memory/canonical/correction_integrity.py +176 -0
  446. daecore/memory/canonical/correction_reads.py +812 -0
  447. daecore/memory/canonical/correction_references.py +187 -0
  448. daecore/memory/canonical/correction_row_data.py +176 -0
  449. daecore/memory/canonical/correction_rows.py +842 -0
  450. daecore/memory/canonical/correction_schema.py +144 -0
  451. daecore/memory/canonical/correction_transfer.py +227 -0
  452. daecore/memory/canonical/correction_winners.py +113 -0
  453. daecore/memory/canonical/database.py +1096 -0
  454. daecore/memory/canonical/erasure_ledger.py +857 -0
  455. daecore/memory/canonical/errors.py +149 -0
  456. daecore/memory/canonical/imported_file_schema.py +124 -0
  457. daecore/memory/canonical/location.py +57 -0
  458. daecore/memory/canonical/mirror_evidence.py +82 -0
  459. daecore/memory/canonical/name_schema.py +196 -0
  460. daecore/memory/canonical/project_links.py +138 -0
  461. daecore/memory/canonical/query_projection.py +272 -0
  462. daecore/memory/canonical/recall_returns.py +154 -0
  463. daecore/memory/canonical/record_holds.py +329 -0
  464. daecore/memory/canonical/reference_cleanup.py +801 -0
  465. daecore/memory/canonical/reference_index.py +146 -0
  466. daecore/memory/canonical/retry_outcome_schema.py +85 -0
  467. daecore/memory/canonical/retry_outcomes.py +586 -0
  468. daecore/memory/canonical/store_schema.py +931 -0
  469. daecore/memory/canonical/word_index.py +89 -0
  470. daecore/memory/citation_lookup.py +150 -0
  471. daecore/memory/citation_resolution.py +288 -0
  472. daecore/memory/citation_updates.py +207 -0
  473. daecore/memory/citation_upkeep.py +381 -0
  474. daecore/memory/consent.py +537 -0
  475. daecore/memory/correction.py +668 -0
  476. daecore/memory/correction_blockers.py +191 -0
  477. daecore/memory/correction_citations.py +172 -0
  478. daecore/memory/correction_dates.py +81 -0
  479. daecore/memory/correction_dependencies.py +420 -0
  480. daecore/memory/correction_errors.py +61 -0
  481. daecore/memory/correction_request.py +428 -0
  482. daecore/memory/correction_state.py +231 -0
  483. daecore/memory/correction_undo.py +566 -0
  484. daecore/memory/erasure_selection.py +387 -0
  485. daecore/memory/evidence_inspection.py +228 -0
  486. daecore/memory/exclusion_recovery.py +40 -0
  487. daecore/memory/filter_request.py +433 -0
  488. daecore/memory/filter_sql.py +363 -0
  489. daecore/memory/filtering.py +239 -0
  490. daecore/memory/forget.py +656 -0
  491. daecore/memory/index_projection.py +695 -0
  492. daecore/memory/inventory.py +103 -0
  493. daecore/memory/mirrored_documents.py +308 -0
  494. daecore/memory/name_files.py +210 -0
  495. daecore/memory/name_round.py +56 -0
  496. daecore/memory/name_state.py +766 -0
  497. daecore/memory/name_support.py +502 -0
  498. daecore/memory/native_folders.py +206 -0
  499. daecore/memory/native_import/__init__.py +137 -0
  500. daecore/memory/native_import/claude.py +400 -0
  501. daecore/memory/native_import/codex.py +58 -0
  502. daecore/memory/native_import/consented_routes.py +157 -0
  503. daecore/memory/native_import/contracts.py +161 -0
  504. daecore/memory/native_import/discovery.py +62 -0
  505. daecore/memory/native_import/folder_scan.py +178 -0
  506. daecore/memory/native_import/import_pass.py +342 -0
  507. daecore/memory/native_import/mapping.py +585 -0
  508. daecore/memory/native_import/reconcile.py +197 -0
  509. daecore/memory/native_import/store_rules.py +100 -0
  510. daecore/memory/native_providers.py +185 -0
  511. daecore/memory/policy.py +76 -0
  512. daecore/memory/projection_outbox.py +626 -0
  513. daecore/memory/publication.py +173 -0
  514. daecore/memory/read_facts.py +346 -0
  515. daecore/memory/records/__init__.py +1 -0
  516. daecore/memory/records/annotations.py +144 -0
  517. daecore/memory/records/authoring.py +107 -0
  518. daecore/memory/records/authorship.py +170 -0
  519. daecore/memory/records/cancellation.py +586 -0
  520. daecore/memory/records/citation_changes.py +90 -0
  521. daecore/memory/records/citations.py +890 -0
  522. daecore/memory/records/continuity_provenance.py +187 -0
  523. daecore/memory/records/contracts.py +214 -0
  524. daecore/memory/records/coordinates.py +119 -0
  525. daecore/memory/records/correction_history/__init__.py +5 -0
  526. daecore/memory/records/correction_history/contracts.py +19 -0
  527. daecore/memory/records/correction_history/derivation.py +437 -0
  528. daecore/memory/records/correction_history/erasure.py +107 -0
  529. daecore/memory/records/correction_history/naming.py +106 -0
  530. daecore/memory/records/correction_history/operations.py +219 -0
  531. daecore/memory/records/correction_history/recording.py +114 -0
  532. daecore/memory/records/correction_history/reference_fields.py +21 -0
  533. daecore/memory/records/correction_history/snapshots.py +46 -0
  534. daecore/memory/records/correction_history/undone_effects.py +101 -0
  535. daecore/memory/records/correction_history/validation.py +149 -0
  536. daecore/memory/records/exclusion_identity.py +54 -0
  537. daecore/memory/records/exclusions.py +350 -0
  538. daecore/memory/records/metadata.py +118 -0
  539. daecore/memory/records/origin_rights.py +197 -0
  540. daecore/memory/records/remember.py +68 -0
  541. daecore/memory/records/retirement.py +185 -0
  542. daecore/memory/records/revisions.py +135 -0
  543. daecore/memory/records/schema.py +428 -0
  544. daecore/memory/records/succession.py +287 -0
  545. daecore/memory/records/validation.py +226 -0
  546. daecore/memory/reference.py +172 -0
  547. daecore/memory/review_queues.py +116 -0
  548. daecore/memory/search.py +154 -0
  549. daecore/memory/store.py +903 -0
  550. daecore/memory/support.py +35 -0
  551. daecore/memory/support_reads.py +57 -0
  552. daecore/memory/writes.py +390 -0
  553. daecore/model_ids.py +6 -0
  554. daecore/name_coverage.py +266 -0
  555. daecore/name_presence.py +192 -0
  556. daecore/named_references.py +277 -0
  557. daecore/observability/__init__.py +1 -0
  558. daecore/observability/assurance.py +66 -0
  559. daecore/observability/assurance_provider.py +337 -0
  560. daecore/observability/crash_log.py +37 -0
  561. daecore/observability/event_log.py +229 -0
  562. daecore/observability/mcp_connections.py +274 -0
  563. daecore/observability/operation_status.py +101 -0
  564. daecore/observability/profile_io.py +42 -0
  565. daecore/observability/query_log.py +284 -0
  566. daecore/observability/rolling.py +224 -0
  567. daecore/observability/rotate.py +264 -0
  568. daecore/observability/semconv.py +1273 -0
  569. daecore/observability/telemetry_seal.py +310 -0
  570. daecore/observability/usage.py +225 -0
  571. daecore/operation_files/__init__.py +1103 -0
  572. daecore/operation_files/_coordination.py +283 -0
  573. daecore/operation_files/_files.py +316 -0
  574. daecore/operation_files/_records.py +204 -0
  575. daecore/operation_files/_types.py +30 -0
  576. daecore/operations/__init__.py +1 -0
  577. daecore/operations/admission.py +534 -0
  578. daecore/operations/barriers.py +81 -0
  579. daecore/operations/context.py +366 -0
  580. daecore/operations/contract.py +220 -0
  581. daecore/operations/errors.py +44 -0
  582. daecore/operations/frozen_read.py +101 -0
  583. daecore/operations/lease.py +340 -0
  584. daecore/operations/recovery.py +221 -0
  585. daecore/operations/recovery_contracts.py +214 -0
  586. daecore/operations/registry.py +1343 -0
  587. daecore/operations/rollback_snapshot.py +423 -0
  588. daecore/operations/runtime.py +281 -0
  589. daecore/operations/trace.py +121 -0
  590. daecore/operations/tree_snapshot.py +270 -0
  591. daecore/package_build.py +305 -0
  592. daecore/package_install.py +282 -0
  593. daecore/path_lock.py +168 -0
  594. daecore/paths.py +299 -0
  595. daecore/private_files.py +557 -0
  596. daecore/read_posture.py +52 -0
  597. daecore/read_vocabulary.py +227 -0
  598. daecore/reconcile.py +298 -0
  599. daecore/relay.py +8557 -0
  600. daecore/relay_support/__init__.py +1 -0
  601. daecore/relay_support/conversation.py +314 -0
  602. daecore/relay_support/custody.py +242 -0
  603. daecore/relay_support/diagnostics.py +114 -0
  604. daecore/relay_support/environment.py +65 -0
  605. daecore/relay_support/forwarding.py +248 -0
  606. daecore/relay_support/handshake.py +239 -0
  607. daecore/relay_support/home_location.py +215 -0
  608. daecore/relay_support/home_rename.py +188 -0
  609. daecore/relay_support/http_transport.py +451 -0
  610. daecore/relay_support/identity.py +672 -0
  611. daecore/relay_support/jsonrpc.py +167 -0
  612. daecore/relay_support/pinned_http.py +252 -0
  613. daecore/relay_support/processes.py +245 -0
  614. daecore/relay_support/protocol.py +742 -0
  615. daecore/relay_support/readiness.py +267 -0
  616. daecore/relay_support/relay_state.py +331 -0
  617. daecore/relay_support/runtime_selection.py +357 -0
  618. daecore/relay_support/spawn_broker.py +462 -0
  619. daecore/relay_support/spawn_process.py +249 -0
  620. daecore/relay_support/spawn_records.py +176 -0
  621. daecore/relay_support/spawn_tracking.py +647 -0
  622. daecore/relay_support/startup.py +744 -0
  623. daecore/relay_support/startup_files.py +178 -0
  624. daecore/relay_support/transport.py +510 -0
  625. daecore/release_install.py +481 -0
  626. daecore/request_deadline.py +173 -0
  627. daecore/resources/__init__.py +98 -0
  628. daecore/resources/_disk.py +463 -0
  629. daecore/resources/artifacts.py +134 -0
  630. daecore/retrieval/__init__.py +1 -0
  631. daecore/retrieval/_contract_primitives.py +105 -0
  632. daecore/retrieval/_evidence_validation.py +271 -0
  633. daecore/retrieval/_request_validation.py +101 -0
  634. daecore/retrieval/_response_validation.py +251 -0
  635. daecore/retrieval/assurance.py +103 -0
  636. daecore/retrieval/assurance_provider.py +573 -0
  637. daecore/retrieval/build/__init__.py +1 -0
  638. daecore/retrieval/build/cancellation.py +79 -0
  639. daecore/retrieval/build/candidate.py +159 -0
  640. daecore/retrieval/build/capture.py +159 -0
  641. daecore/retrieval/build/contract.py +199 -0
  642. daecore/retrieval/build/global_build.py +135 -0
  643. daecore/retrieval/build/identity.py +229 -0
  644. daecore/retrieval/build/ledger_candidate.py +1036 -0
  645. daecore/retrieval/build/ledger_publication.py +256 -0
  646. daecore/retrieval/build/ledger_rows.py +143 -0
  647. daecore/retrieval/build/memory.py +246 -0
  648. daecore/retrieval/build/metrics.py +131 -0
  649. daecore/retrieval/build/pipeline.py +401 -0
  650. daecore/retrieval/build/precommit.py +122 -0
  651. daecore/retrieval/build/residency.py +163 -0
  652. daecore/retrieval/build/results.py +98 -0
  653. daecore/retrieval/build/source.py +36 -0
  654. daecore/retrieval/build/source_selection.py +81 -0
  655. daecore/retrieval/build/state.py +843 -0
  656. daecore/retrieval/build/vectors.py +262 -0
  657. daecore/retrieval/build/workspace_progress.py +160 -0
  658. daecore/retrieval/candidate_cache.py +191 -0
  659. daecore/retrieval/capacity.py +90 -0
  660. daecore/retrieval/channel_fusion.py +73 -0
  661. daecore/retrieval/context_composer.py +413 -0
  662. daecore/retrieval/contracts.py +216 -0
  663. daecore/retrieval/corpus_date.py +545 -0
  664. daecore/retrieval/dense.py +1055 -0
  665. daecore/retrieval/document_projection.py +121 -0
  666. daecore/retrieval/embedders.py +221 -0
  667. daecore/retrieval/evidence.py +82 -0
  668. daecore/retrieval/file_ingest.py +587 -0
  669. daecore/retrieval/file_passages.py +125 -0
  670. daecore/retrieval/file_turns.py +435 -0
  671. daecore/retrieval/freshness.py +104 -0
  672. daecore/retrieval/index_state.py +56 -0
  673. daecore/retrieval/ingest_governor.py +127 -0
  674. daecore/retrieval/lexical.py +137 -0
  675. daecore/retrieval/name_history.py +306 -0
  676. daecore/retrieval/name_moves.py +161 -0
  677. daecore/retrieval/name_scan.py +357 -0
  678. daecore/retrieval/packed_files.py +427 -0
  679. daecore/retrieval/prefix_selection.py +266 -0
  680. daecore/retrieval/presentation.py +162 -0
  681. daecore/retrieval/query_cache.py +193 -0
  682. daecore/retrieval/rebuild.py +625 -0
  683. daecore/retrieval/reranking.py +492 -0
  684. daecore/retrieval/resource_budget.py +101 -0
  685. daecore/retrieval/resource_posture.py +213 -0
  686. daecore/retrieval/result_rows.py +193 -0
  687. daecore/retrieval/searcher.py +1172 -0
  688. daecore/retrieval/selection.py +161 -0
  689. daecore/retrieval/survey_storage.py +26 -0
  690. daecore/retrieval/sweep.py +1075 -0
  691. daecore/retrieval/watch_specs.py +70 -0
  692. daecore/retrieval/workspace_resolution.py +55 -0
  693. daecore/retrieval/workspace_withdrawal.py +231 -0
  694. daecore/runtime_contracts.py +80 -0
  695. daecore/runtime_enrollment.py +82 -0
  696. daecore/runtime_use.py +565 -0
  697. daecore/schema_versions.py +83 -0
  698. daecore/scripts/__init__.py +10 -0
  699. daecore/scripts/mcp_launcher.py +485 -0
  700. daecore/security/__init__.py +9 -0
  701. daecore/security/key_material/__init__.py +1139 -0
  702. daecore/security/key_material/_derivation.py +152 -0
  703. daecore/security/key_material/_dpapi.py +222 -0
  704. daecore/security/key_material/_errors.py +24 -0
  705. daecore/security/key_material/_machine.py +78 -0
  706. daecore/security/key_material/_os_keychain.py +191 -0
  707. daecore/security/key_material/_records.py +234 -0
  708. daecore/security/key_material/_registry.py +81 -0
  709. daecore/security/lock_state.py +55 -0
  710. daecore/security/posture.py +475 -0
  711. daecore/sentinel/__init__.py +1 -0
  712. daecore/sentinel/frontmatter.py +37 -0
  713. daecore/sentinel/hashing.py +50 -0
  714. daecore/sentinel/header.py +73 -0
  715. daecore/sentinel/marker.py +74 -0
  716. daecore/sentinel/ownership.py +34 -0
  717. daecore/sentinel/types.py +46 -0
  718. daecore/server/__init__.py +1 -0
  719. daecore/server/_embedding_handoff.py +96 -0
  720. daecore/server/_packet_render.py +239 -0
  721. daecore/server/_read_packets.py +314 -0
  722. daecore/server/_recall_packet.py +239 -0
  723. daecore/server/_utils.py +38 -0
  724. daecore/server/_write_packets.py +155 -0
  725. daecore/server/application.py +271 -0
  726. daecore/server/attachments.py +214 -0
  727. daecore/server/attribution.py +217 -0
  728. daecore/server/auth_gate.py +297 -0
  729. daecore/server/boot.py +317 -0
  730. daecore/server/boot_profile.py +66 -0
  731. daecore/server/candidate_check.py +68 -0
  732. daecore/server/change_queue.py +881 -0
  733. daecore/server/config_observer.py +688 -0
  734. daecore/server/content_access.py +521 -0
  735. daecore/server/corpus_mutation.py +260 -0
  736. daecore/server/frozen_reads.py +364 -0
  737. daecore/server/health.py +537 -0
  738. daecore/server/http/__init__.py +1 -0
  739. daecore/server/http/admin.py +187 -0
  740. daecore/server/http/admission.py +83 -0
  741. daecore/server/http/builder.py +66 -0
  742. daecore/server/http/middleware.py +258 -0
  743. daecore/server/http/retrieval.py +227 -0
  744. daecore/server/http/routes.py +98 -0
  745. daecore/server/index_rebuilds.py +289 -0
  746. daecore/server/lifecycle.py +1017 -0
  747. daecore/server/maintenance.py +317 -0
  748. daecore/server/memory_projection.py +157 -0
  749. daecore/server/model_health.py +209 -0
  750. daecore/server/model_residency.py +349 -0
  751. daecore/server/mutations.py +287 -0
  752. daecore/server/native_sync.py +331 -0
  753. daecore/server/next_calls.py +93 -0
  754. daecore/server/notices.py +137 -0
  755. daecore/server/observer_lifetime.py +374 -0
  756. daecore/server/packet_contracts.py +865 -0
  757. daecore/server/packets.py +345 -0
  758. daecore/server/proof_process.py +165 -0
  759. daecore/server/publication.py +231 -0
  760. daecore/server/rate_limit.py +179 -0
  761. daecore/server/readiness.py +497 -0
  762. daecore/server/reads/__init__.py +1 -0
  763. daecore/server/reads/_exact_documents.py +200 -0
  764. daecore/server/reads/_exact_lanes.py +278 -0
  765. daecore/server/reads/_exact_memory_facts.py +270 -0
  766. daecore/server/reads/_exact_paging.py +310 -0
  767. daecore/server/reads/_exact_passage_counts.py +193 -0
  768. daecore/server/reads/_exact_population.py +425 -0
  769. daecore/server/reads/_exact_reports.py +347 -0
  770. daecore/server/reads/_exact_request.py +212 -0
  771. daecore/server/reads/_exact_snapshot.py +325 -0
  772. daecore/server/reads/_exact_statistics.py +395 -0
  773. daecore/server/reads/_exact_types.py +273 -0
  774. daecore/server/reads/attribution.py +26 -0
  775. daecore/server/reads/browse.py +146 -0
  776. daecore/server/reads/browse_links.py +275 -0
  777. daecore/server/reads/bucket_listing.py +345 -0
  778. daecore/server/reads/clamps.py +20 -0
  779. daecore/server/reads/continuations.py +151 -0
  780. daecore/server/reads/dating.py +127 -0
  781. daecore/server/reads/degradation.py +123 -0
  782. daecore/server/reads/exact.py +58 -0
  783. daecore/server/reads/execution.py +869 -0
  784. daecore/server/reads/inspection.py +35 -0
  785. daecore/server/reads/inspection_pages.py +315 -0
  786. daecore/server/reads/link_graph.py +453 -0
  787. daecore/server/reads/link_items.py +301 -0
  788. daecore/server/reads/link_presentation.py +173 -0
  789. daecore/server/reads/link_report.py +172 -0
  790. daecore/server/reads/link_rows.py +415 -0
  791. daecore/server/reads/link_upkeep.py +145 -0
  792. daecore/server/reads/link_walks.py +754 -0
  793. daecore/server/reads/links.py +518 -0
  794. daecore/server/reads/pagination.py +148 -0
  795. daecore/server/reads/recall.py +210 -0
  796. daecore/server/reads/recall_links.py +198 -0
  797. daecore/server/reads/recall_log.py +105 -0
  798. daecore/server/reads/recall_pages.py +251 -0
  799. daecore/server/reads/recent_context.py +475 -0
  800. daecore/server/reads/retries.py +34 -0
  801. daecore/server/reads/write_reply.py +189 -0
  802. daecore/server/recall_handoff.py +176 -0
  803. daecore/server/recall_returns.py +129 -0
  804. daecore/server/refusals.py +191 -0
  805. daecore/server/rendering.py +466 -0
  806. daecore/server/reply_contracts.py +567 -0
  807. daecore/server/reply_views.py +496 -0
  808. daecore/server/response_write.py +333 -0
  809. daecore/server/result_catalog.py +226 -0
  810. daecore/server/review_health.py +195 -0
  811. daecore/server/scoping.py +221 -0
  812. daecore/server/tool_audit.py +340 -0
  813. daecore/server/tool_codes.py +29 -0
  814. daecore/server/tool_inventory.py +79 -0
  815. daecore/server/tool_requests.py +319 -0
  816. daecore/server/tool_runtime.py +884 -0
  817. daecore/server/tools/__init__.py +1 -0
  818. daecore/server/tools/_arguments.py +304 -0
  819. daecore/server/tools/_evidence.py +351 -0
  820. daecore/server/tools/_mutation_replies.py +82 -0
  821. daecore/server/tools/_variants.py +92 -0
  822. daecore/server/tools/admin.py +469 -0
  823. daecore/server/tools/annotation.py +275 -0
  824. daecore/server/tools/browse.py +353 -0
  825. daecore/server/tools/correction.py +385 -0
  826. daecore/server/tools/explore.py +217 -0
  827. daecore/server/tools/inspect.py +386 -0
  828. daecore/server/tools/memory.py +414 -0
  829. daecore/server/tools/recall.py +567 -0
  830. daecore/server/transport.py +156 -0
  831. daecore/server/update_window.py +217 -0
  832. daecore/server/warmup.py +293 -0
  833. daecore/server/watch_events.py +287 -0
  834. daecore/server/watch_queues.py +436 -0
  835. daecore/server/watch_routing.py +286 -0
  836. daecore/server/watcher.py +957 -0
  837. daecore/server/work.py +128 -0
  838. daecore/server/workspace_lifecycle.py +320 -0
  839. daecore/setup/__init__.py +37 -0
  840. daecore/setup/_application.py +353 -0
  841. daecore/setup/_contracts.py +84 -0
  842. daecore/setup/_planning.py +502 -0
  843. daecore/setup/_uninstall_removal.py +493 -0
  844. daecore/setup/_uninstall_runtime.py +123 -0
  845. daecore/setup/assurance.py +90 -0
  846. daecore/setup/assurance_provider.py +399 -0
  847. daecore/setup/bootstrap/__init__.py +280 -0
  848. daecore/setup/bootstrap/_acceleration.py +138 -0
  849. daecore/setup/bootstrap/_activation_receipts.py +115 -0
  850. daecore/setup/bootstrap/_plan_actions.py +221 -0
  851. daecore/setup/bootstrap/apply.py +555 -0
  852. daecore/setup/bootstrap/doctor.py +147 -0
  853. daecore/setup/bootstrap/fs_safety.py +93 -0
  854. daecore/setup/bootstrap/native_memory.py +457 -0
  855. daecore/setup/bootstrap/planning.py +708 -0
  856. daecore/setup/bootstrap/readiness.py +459 -0
  857. daecore/setup/bootstrap/receipt.py +85 -0
  858. daecore/setup/bootstrap/types.py +273 -0
  859. daecore/setup/bootstrap/wizard.py +389 -0
  860. daecore/setup/cli.py +222 -0
  861. daecore/setup/config.py +19 -0
  862. daecore/setup/detection.py +39 -0
  863. daecore/setup/execute.py +270 -0
  864. daecore/setup/guide.py +40 -0
  865. daecore/setup/hosts.py +674 -0
  866. daecore/setup/interaction.py +415 -0
  867. daecore/setup/merge/__init__.py +1 -0
  868. daecore/setup/merge/_json_patch_identity.py +178 -0
  869. daecore/setup/merge/_json_patch_operations.py +284 -0
  870. daecore/setup/merge/_json_patch_ownership.py +378 -0
  871. daecore/setup/merge/_json_patch_values.py +95 -0
  872. daecore/setup/merge/_publish.py +96 -0
  873. daecore/setup/merge/_toml_edit.py +416 -0
  874. daecore/setup/merge/_toml_structure.py +273 -0
  875. daecore/setup/merge/json_patch.py +324 -0
  876. daecore/setup/merge/jsonc.py +211 -0
  877. daecore/setup/merge/markdown_section.py +267 -0
  878. daecore/setup/merge/skill_file.py +41 -0
  879. daecore/setup/merge/syntax.py +146 -0
  880. daecore/setup/merge/toml_block.py +307 -0
  881. daecore/setup/merge/types.py +129 -0
  882. daecore/setup/merge/whole_file_sentinel.py +248 -0
  883. daecore/setup/merge/yaml_text.py +300 -0
  884. daecore/setup/plan.py +322 -0
  885. daecore/setup/plan_file.py +83 -0
  886. daecore/setup/record.py +224 -0
  887. daecore/setup/refresh_snapshot.py +361 -0
  888. daecore/setup/render.py +447 -0
  889. daecore/setup/templates/antigravity/continuity.md +8 -0
  890. daecore/setup/templates/antigravity/mcp.json.patch +19 -0
  891. daecore/setup/templates/claude-code/mcp.json.patch +22 -0
  892. daecore/setup/templates/codex/config.toml.patch +64 -0
  893. daecore/setup/templates/constitution-section.md.tmpl +3 -0
  894. daecore/setup/templates/copilot/mcp-config.json.patch +24 -0
  895. daecore/setup/templates/cursor/continuity.md +7 -0
  896. daecore/setup/templates/cursor/daecore-continuity.js +31 -0
  897. daecore/setup/templates/cursor/hooks.json.patch +24 -0
  898. daecore/setup/templates/cursor/mcp.json.patch +22 -0
  899. daecore/setup/templates/devin/continuity.md +8 -0
  900. daecore/setup/templates/devin/mcp.json.patch +20 -0
  901. daecore/setup/templates/hermes/config.yaml.patch +19 -0
  902. daecore/setup/templates/opencode/config.json.patch +28 -0
  903. daecore/setup/templates/skill/SKILL.md +38 -0
  904. daecore/setup/templates/skill/references/connect-any-host.md +84 -0
  905. daecore/setup/templates/skill/references/diagnose.md +62 -0
  906. daecore/setup/templates/skill/references/maintain.md +63 -0
  907. daecore/setup/uninstall.py +1298 -0
  908. daecore/setup/uninstall_execution.py +536 -0
  909. daecore/setup/uninstall_types.py +41 -0
  910. daecore/source_build.py +143 -0
  911. daecore/source_capture.py +117 -0
  912. daecore/source_identity.py +12 -0
  913. daecore/sqlite_identity.py +257 -0
  914. daecore/sqlite_space.py +153 -0
  915. daecore/stage_timings.py +119 -0
  916. daecore/status/__init__.py +1 -0
  917. daecore/status/inventory.py +192 -0
  918. daecore/status/memory_health.py +235 -0
  919. daecore/status/process_memory.py +141 -0
  920. daecore/status/snapshot.py +482 -0
  921. daecore/status/source_review.py +154 -0
  922. daecore/status/sources.py +271 -0
  923. daecore/status/watch.py +70 -0
  924. daecore/storage/__init__.py +3 -0
  925. daecore/storage/assurance.py +93 -0
  926. daecore/storage/assurance_provider.py +306 -0
  927. daecore/storage/database/__init__.py +71 -0
  928. daecore/storage/database/encrypted.py +451 -0
  929. daecore/storage/database/fs_probe.py +135 -0
  930. daecore/storage/database/fs_safety.py +576 -0
  931. daecore/storage/database/read_pool.py +94 -0
  932. daecore/storage/encrypted_meta_schema.py +374 -0
  933. daecore/storage/encrypted_snapshot.py +249 -0
  934. daecore/storage/index/__init__.py +3 -0
  935. daecore/storage/index/_diagnostic_moves.py +135 -0
  936. daecore/storage/index/_diagnostic_records.py +208 -0
  937. daecore/storage/index/chunk_projection.py +405 -0
  938. daecore/storage/index/citation_reading.py +510 -0
  939. daecore/storage/index/connections.py +269 -0
  940. daecore/storage/index/diagnostics.py +554 -0
  941. daecore/storage/index/document_reads.py +467 -0
  942. daecore/storage/index/document_schema.py +395 -0
  943. daecore/storage/index/document_visibility.py +77 -0
  944. daecore/storage/index/document_writers.py +474 -0
  945. daecore/storage/index/errors.py +46 -0
  946. daecore/storage/index/file_ledger.py +713 -0
  947. daecore/storage/index/generations.py +970 -0
  948. daecore/storage/index/hygiene_review.py +380 -0
  949. daecore/storage/index/key.py +130 -0
  950. daecore/storage/index/lexical.py +429 -0
  951. daecore/storage/index/link_revisions.py +87 -0
  952. daecore/storage/index/link_view.py +518 -0
  953. daecore/storage/index/memory_links.py +274 -0
  954. daecore/storage/index/metadata.py +65 -0
  955. daecore/storage/index/model_policy.py +69 -0
  956. daecore/storage/index/name_inventory.py +275 -0
  957. daecore/storage/index/payloads.py +513 -0
  958. daecore/storage/index/pointer.py +181 -0
  959. daecore/storage/index/profiles.py +581 -0
  960. daecore/storage/index/publication_undo.py +240 -0
  961. daecore/storage/index/schema.py +374 -0
  962. daecore/storage/index/search_atoms.py +782 -0
  963. daecore/storage/index/shared_generations.py +485 -0
  964. daecore/storage/index/shared_objects.py +831 -0
  965. daecore/storage/index/snapshots.py +118 -0
  966. daecore/storage/index/text_match.py +379 -0
  967. daecore/storage/index/vector_encoding.py +122 -0
  968. daecore/storage/integrity.py +222 -0
  969. daecore/storage/janitor/__init__.py +149 -0
  970. daecore/storage/janitor/_artifacts.py +426 -0
  971. daecore/storage/janitor/_audit.py +345 -0
  972. daecore/storage/meta_store.py +360 -0
  973. daecore/storage/native.py +51 -0
  974. daecore/subprocesses.py +404 -0
  975. daecore/sync/__init__.py +6 -0
  976. daecore/sync/catchup.py +203 -0
  977. daecore/sync/consent.py +905 -0
  978. daecore/sync/discovery.py +521 -0
  979. daecore/sync/full_scan.py +95 -0
  980. daecore/sync/identity.py +74 -0
  981. daecore/sync/recorded_sources.py +111 -0
  982. daecore/sync/result.py +86 -0
  983. daecore/sync/snapshot.py +586 -0
  984. daecore/templates/__init__.py +2 -0
  985. daecore/templates/global-config.toml +121 -0
  986. daecore/term/__init__.py +88 -0
  987. daecore/term/_brand.py +77 -0
  988. daecore/term/_console.py +96 -0
  989. daecore/term/_errors.py +62 -0
  990. daecore/term/_prompt.py +162 -0
  991. daecore/term/_questionary.py +62 -0
  992. daecore/term/_references.py +69 -0
  993. daecore/term/capabilities.py +153 -0
  994. daecore/term/lifecycle.py +917 -0
  995. daecore/term/live_region.py +260 -0
  996. daecore/term/loader.py +118 -0
  997. daecore/term/progress.py +958 -0
  998. daecore/term/prompts.py +58 -0
  999. daecore/term/rendering.py +971 -0
  1000. daecore/term/safety.py +13 -0
  1001. daecore/term/verb_help.py +207 -0
  1002. daecore/term/wizard.py +86 -0
  1003. daecore/testing/__init__.py +13 -0
  1004. daecore/testing/crashpoints.py +81 -0
  1005. daecore/testing/launch.py +97 -0
  1006. daecore/text_decoding.py +68 -0
  1007. daecore/time_utils.py +430 -0
  1008. daecore/tokenizer_assets.py +39 -0
  1009. daecore/transfer/__init__.py +1 -0
  1010. daecore/transfer/_eff_wordlist.py +661 -0
  1011. daecore/transfer/_verify.py +169 -0
  1012. daecore/transfer/capacity.py +87 -0
  1013. daecore/transfer/citations.py +253 -0
  1014. daecore/transfer/classification.py +189 -0
  1015. daecore/transfer/completion.py +155 -0
  1016. daecore/transfer/contracts.py +280 -0
  1017. daecore/transfer/convert.py +500 -0
  1018. daecore/transfer/event_policy.py +85 -0
  1019. daecore/transfer/export.py +163 -0
  1020. daecore/transfer/export_file.py +371 -0
  1021. daecore/transfer/export_payload.py +222 -0
  1022. daecore/transfer/import_flow.py +278 -0
  1023. daecore/transfer/import_job.py +296 -0
  1024. daecore/transfer/journal.py +96 -0
  1025. daecore/transfer/members.py +792 -0
  1026. daecore/transfer/publication.py +584 -0
  1027. daecore/transfer/publish.py +306 -0
  1028. daecore/transfer/receipt.py +120 -0
  1029. daecore/transfer/recovery.py +228 -0
  1030. daecore/transfer/snapshot.py +950 -0
  1031. daecore/transfer/verification.py +64 -0
  1032. daecore/tree_copy.py +178 -0
  1033. daecore/workspace/__init__.py +1 -0
  1034. daecore/workspace/availability.py +192 -0
  1035. daecore/workspace/config_transaction.py +772 -0
  1036. daecore/workspace/filesystem.py +269 -0
  1037. daecore/workspace/identity.py +327 -0
  1038. daecore/workspace/intake.py +669 -0
  1039. daecore/workspace/probes.py +221 -0
  1040. daecore/workspace/project_links.py +252 -0
  1041. daecore/workspace/project_membership.py +35 -0
  1042. daecore/workspace/reattach.py +446 -0
  1043. daecore/workspace/recovery.py +25 -0
  1044. daecore/workspace/registry.py +645 -0
  1045. daecore/workspace/scope.py +507 -0
  1046. daecore-0.3.0.dist-info/METADATA +285 -0
  1047. daecore-0.3.0.dist-info/RECORD +1051 -0
  1048. daecore-0.3.0.dist-info/WHEEL +4 -0
  1049. daecore-0.3.0.dist-info/entry_points.txt +3 -0
  1050. daecore-0.3.0.dist-info/licenses/LICENSE +201 -0
  1051. daecore-0.3.0.dist-info/licenses/NOTICE +99 -0
_daecore_entry.py ADDED
@@ -0,0 +1,2145 @@
1
+ """The launcher behind the ``daecore`` and ``daecore-mcp`` commands.
2
+
3
+ The pipx or uv tool environment holds only this file and uv. Daecore itself runs
4
+ from a managed runtime under ``~/.daecore/runtime/daecore-<version>/``, on a
5
+ managed Python, and ``~/.daecore/runtime/current`` names the active one -- a real
6
+ symlink on platforms that support it, and on Windows (where creating a symlink
7
+ needs a privilege most installs do not have) a small text file whose body is the
8
+ target path.
9
+
10
+ The launcher does three things. It routes a command, it stages a release for the
11
+ few commands a runtime cannot serve for itself, and it hands over: to the selected
12
+ runtime, or to a staged release's ``_handover.py``. It uses the standard library
13
+ alone and never imports the ``daecore`` package, because whatever it does freezes
14
+ on every machine that holds it, and a later release cannot repair code already
15
+ running. ``python -m daecore`` shares this exact authority: ``daecore.__main__``
16
+ delegates to :func:`main`, so both public spellings select the same runtime.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import contextlib
21
+ import copy
22
+ import hashlib
23
+ import json
24
+ import os
25
+ import stat
26
+ import subprocess
27
+ import sys
28
+ import tempfile
29
+ import threading
30
+ import time
31
+ import tomllib
32
+ from importlib import metadata
33
+ from pathlib import Path
34
+ from types import SimpleNamespace
35
+
36
+
37
+ def suppress_windows_error_dialogs() -> None:
38
+ """Set the process policy before child creation; descendants inherit it."""
39
+ if os.name != 'nt':
40
+ return
41
+ import ctypes
42
+
43
+ kernel = ctypes.WinDLL('kernel32', use_last_error=True)
44
+ kernel.GetErrorMode.restype = ctypes.c_uint
45
+ kernel.SetErrorMode.argtypes = [ctypes.c_uint]
46
+ kernel.SetErrorMode.restype = ctypes.c_uint
47
+ # SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX.
48
+ required = 0x0001 | 0x0002 | 0x8000
49
+ mode = kernel.GetErrorMode()
50
+ if mode & required != required:
51
+ kernel.SetErrorMode(mode | required)
52
+
53
+
54
+ suppress_windows_error_dialogs()
55
+
56
+ # Updated independently inside the tool seed by ``daecore update``. The seed
57
+ # is a stable handoff point, not a second Daecore runtime; this integer lets a
58
+ # managed runtime tell an older launcher from a current one without importing
59
+ # anything from the seed.
60
+ LAUNCHER_PROTOCOL_VERSION = 11
61
+
62
+ # BEGIN GENERATED RUNTIME USE
63
+ def _runtime_control_windows_known_folder(folder_id: str) -> Path:
64
+ """Ask Windows for one of the account's folders, which needs no environment variable."""
65
+ import ctypes
66
+ from ctypes import wintypes
67
+ first, second, third, fourth, fifth = folder_id.split('-')
68
+ raw = int(first, 16).to_bytes(4, 'little') + int(second, 16).to_bytes(2, 'little') + int(third, 16).to_bytes(2, 'little') + bytes.fromhex(fourth + fifth)
69
+ shell = ctypes.WinDLL('shell32', use_last_error=True)
70
+ ole = ctypes.WinDLL('ole32', use_last_error=True)
71
+ shell.SHGetKnownFolderPath.argtypes = [ctypes.c_void_p, wintypes.DWORD, wintypes.HANDLE, ctypes.POINTER(ctypes.c_wchar_p)]
72
+ shell.SHGetKnownFolderPath.restype = ctypes.c_long
73
+ ole.CoTaskMemFree.argtypes = [ctypes.c_void_p]
74
+ ole.CoTaskMemFree.restype = None
75
+ found = ctypes.c_wchar_p()
76
+ status = shell.SHGetKnownFolderPath(ctypes.c_char_p(raw), 0, None, ctypes.byref(found))
77
+ try:
78
+ if status != 0 or not found.value:
79
+ raise OSError(f'Windows could not locate the account folder {folder_id}')
80
+ return Path(found.value)
81
+ finally:
82
+ ole.CoTaskMemFree(ctypes.cast(found, ctypes.c_void_p))
83
+
84
+ def _runtime_control_user_profile_dir() -> Path:
85
+ """The account's home folder, found even when a host passes no environment."""
86
+ try:
87
+ return Path.home()
88
+ except RuntimeError:
89
+ if os.name != 'nt':
90
+ raise
91
+ try:
92
+ return _runtime_control_windows_known_folder('5E6C858F-0E22-4760-9AFE-EA3317B67173')
93
+ except OSError as exc:
94
+ raise RuntimeError('Could not determine home directory.') from exc
95
+
96
+ def _runtime_control_per_user_state_dir() -> Path:
97
+ """The per-user folder that holds Daecore's control directory.
98
+
99
+ ``LOCALAPPDATA`` or ``XDG_STATE_HOME`` selects it when set, which is how tests and isolated runs
100
+ keep their own. Otherwise the operating system's own answer for the account is used.
101
+ """
102
+ if os.name == 'nt':
103
+ base = os.environ.get('LOCALAPPDATA')
104
+ return Path(base) if base else _runtime_control_windows_known_folder('F1B32785-6FBA-4FCF-9D55-7B8E7F157091')
105
+ state = os.environ.get('XDG_STATE_HOME')
106
+ return Path(state) if state else _runtime_control_user_profile_dir() / '.local' / 'state'
107
+
108
+ def _runtime_control_control_root_under(state_dir: Path) -> Path:
109
+ name = 'DaecoreControl' if os.name == 'nt' else 'daecore-control'
110
+ return state_dir.expanduser().resolve(strict=False) / name / 'control'
111
+
112
+ def _runtime_control_external_state_root() -> Path:
113
+ """The per-user control directory, outside every home."""
114
+ return _runtime_control_control_root_under(_runtime_control_per_user_state_dir())
115
+
116
+ class _runtime_control_UnsafeControlPathError(RuntimeError):
117
+ """The external control path cannot provide independent physical custody."""
118
+
119
+ def _runtime_control_validate_external_control_dir(control: Path, removable_homes) -> Path:
120
+ """Resolve ``control`` and refuse it inside any removable home.
121
+
122
+ The lifecycle lease, the uninstall journal, and the maintenance intent must
123
+ outlive the home they govern: a control file inside the home would vanish
124
+ with a purge and lose the barrier that refuses the next spawn.
125
+ """
126
+ lexical = control.expanduser().absolute()
127
+ directory = Path(lexical.anchor)
128
+ for name in lexical.parts[1:]:
129
+ directory /= name
130
+ try:
131
+ info = directory.lstat()
132
+ except FileNotFoundError:
133
+ break
134
+ if not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 1024:
135
+ raise _runtime_control_UnsafeControlPathError(f'lifecycle control directory is linked or nonphysical: {directory}')
136
+ resolved = lexical.resolve(strict=False)
137
+ for home in removable_homes:
138
+ removable = Path(home).expanduser().resolve(strict=False)
139
+ if resolved == removable or resolved.is_relative_to(removable):
140
+ raise _runtime_control_UnsafeControlPathError(f'lifecycle control path {resolved} is inside removable Daecore home {removable}')
141
+ return lexical
142
+
143
+ def _runtime_control_lifecycle_state_dir(home: Path) -> Path:
144
+ """Durable per-user lifecycle state that survives a POSIX reboot."""
145
+ return _runtime_control_validate_external_control_dir(_runtime_control_external_state_root(), (home,))
146
+
147
+ def _runtime_custody_identity_sid_text(sid):
148
+ import ctypes
149
+ from ctypes import wintypes
150
+ security = ctypes.WinDLL('advapi32', use_last_error=True)
151
+ kernel = ctypes.WinDLL('kernel32', use_last_error=True)
152
+ security.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)]
153
+ security.ConvertSidToStringSidW.restype = wintypes.BOOL
154
+ kernel.LocalFree.argtypes = [ctypes.c_void_p]
155
+ kernel.LocalFree.restype = ctypes.c_void_p
156
+ value = ctypes.c_void_p()
157
+ if not security.ConvertSidToStringSidW(sid, ctypes.byref(value)):
158
+ raise ctypes.WinError(ctypes.get_last_error())
159
+ try:
160
+ return ctypes.wstring_at(value)
161
+ finally:
162
+ kernel.LocalFree(value)
163
+
164
+ def _runtime_custody_identity_windows_user():
165
+ import _winapi
166
+ import ctypes
167
+ from ctypes import wintypes
168
+ security = ctypes.WinDLL('advapi32', use_last_error=True)
169
+ kernel = ctypes.WinDLL('kernel32', use_last_error=True)
170
+ kernel.GetCurrentProcess.restype = wintypes.HANDLE
171
+ security.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
172
+ security.OpenProcessToken.restype = wintypes.BOOL
173
+ security.GetTokenInformation.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
174
+ security.GetTokenInformation.restype = wintypes.BOOL
175
+ token = wintypes.HANDLE()
176
+ if not security.OpenProcessToken(kernel.GetCurrentProcess(), 8, ctypes.byref(token)):
177
+ raise ctypes.WinError(ctypes.get_last_error())
178
+ try:
179
+ size = wintypes.DWORD()
180
+ security.GetTokenInformation(token, 1, None, 0, ctypes.byref(size))
181
+ if not 0 < size.value <= 65536:
182
+ raise OSError('Windows user identity is unavailable')
183
+ buffer = ctypes.create_string_buffer(size.value)
184
+ if not security.GetTokenInformation(token, 1, buffer, len(buffer), ctypes.byref(size)):
185
+ raise ctypes.WinError(ctypes.get_last_error())
186
+ return _runtime_custody_identity_sid_text(ctypes.c_void_p.from_buffer(buffer).value)
187
+ finally:
188
+ _winapi.CloseHandle(token.value)
189
+
190
+ def _runtime_custody_identity_windows_security(handle):
191
+ """Read owner and discretionary grants from the opened kernel object."""
192
+ import ctypes
193
+ from ctypes import wintypes
194
+ security = ctypes.WinDLL('advapi32', use_last_error=True)
195
+ kernel = ctypes.WinDLL('kernel32', use_last_error=True)
196
+ pointer = ctypes.c_void_p
197
+ security.GetSecurityInfo.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, *[ctypes.POINTER(pointer)] * 5]
198
+ security.GetSecurityInfo.restype = wintypes.DWORD
199
+ security.GetAce.argtypes = [pointer, wintypes.DWORD, ctypes.POINTER(pointer)]
200
+ security.GetAce.restype = wintypes.BOOL
201
+ kernel.LocalFree.argtypes = [pointer]
202
+ kernel.LocalFree.restype = pointer
203
+ owner, dacl, descriptor = (pointer(), pointer(), pointer())
204
+ result = security.GetSecurityInfo(handle, 1, 5, ctypes.byref(owner), None, ctypes.byref(dacl), None, ctypes.byref(descriptor))
205
+ if result:
206
+ raise ctypes.WinError(result)
207
+ try:
208
+ if not owner.value or not dacl.value:
209
+ raise OSError('daemon identity has no owner or discretionary ACL')
210
+ grants = []
211
+ count = ctypes.c_ushort.from_address(dacl.value + 4).value
212
+ for index in range(count):
213
+ ace = pointer()
214
+ if not security.GetAce(dacl, index, ctypes.byref(ace)):
215
+ raise ctypes.WinError(ctypes.get_last_error())
216
+ kind = ctypes.c_ubyte.from_address(ace.value).value
217
+ ace_flags = ctypes.c_ubyte.from_address(ace.value + 1).value
218
+ if ace_flags & 8:
219
+ continue
220
+ if kind in {1, 6, 10, 12}:
221
+ continue
222
+ if kind not in {0, 5, 9, 11}:
223
+ raise OSError('daemon identity has an unsupported discretionary grant')
224
+ mask = ctypes.c_uint32.from_address(ace.value + 4).value
225
+ offset = 8
226
+ if kind in {5, 11}:
227
+ flags = ctypes.c_uint32.from_address(ace.value + 8).value
228
+ offset = 12 + 16 * bool(flags & 1) + 16 * bool(flags & 2)
229
+ grants.append((mask, _runtime_custody_identity_sid_text(ace.value + offset)))
230
+ return (_runtime_custody_identity_sid_text(owner), grants)
231
+ finally:
232
+ kernel.LocalFree(descriptor)
233
+
234
+ def _runtime_private_create_windows_private_directory_for_sid(path, user):
235
+ """The private-directory primitive also used before dependencies install."""
236
+ import ctypes
237
+ from ctypes import wintypes
238
+
239
+ class SecurityAttributes(ctypes.Structure):
240
+ _fields_ = [('length', wintypes.DWORD), ('descriptor', ctypes.c_void_p), ('inherit', wintypes.BOOL)]
241
+ security = ctypes.WinDLL('advapi32', use_last_error=True)
242
+ kernel = ctypes.WinDLL('kernel32', use_last_error=True)
243
+ convert = security.ConvertStringSecurityDescriptorToSecurityDescriptorW
244
+ convert.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p]
245
+ convert.restype = wintypes.BOOL
246
+ kernel.CreateDirectoryW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(SecurityAttributes)]
247
+ kernel.CreateDirectoryW.restype = wintypes.BOOL
248
+ kernel.LocalFree.argtypes = [ctypes.c_void_p]
249
+ kernel.LocalFree.restype = ctypes.c_void_p
250
+ descriptor = ctypes.c_void_p()
251
+ sddl = f'O:{user}D:P(A;OICI;FA;;;{user})(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)'
252
+ if not convert(sddl, 1, ctypes.byref(descriptor), None):
253
+ raise ctypes.WinError(ctypes.get_last_error())
254
+ try:
255
+ attributes = SecurityAttributes(ctypes.sizeof(SecurityAttributes), descriptor, False)
256
+ if not kernel.CreateDirectoryW(str(path), ctypes.byref(attributes)):
257
+ error = ctypes.get_last_error()
258
+ if error in {80, 183}:
259
+ raise FileExistsError(str(path))
260
+ raise ctypes.WinError(error)
261
+ finally:
262
+ kernel.LocalFree(descriptor)
263
+
264
+ RUNTIME_USE_PROTOCOL = 1
265
+
266
+ RUNTIME_USE_RECORD = '.daecore-runtime.json'
267
+
268
+ def is_managed_runtime_location(root):
269
+ """Recognize the address only; the current enrollment proves ownership."""
270
+ root = Path(root)
271
+ parent, name = root.parent.name, root.name
272
+ if os.name == 'nt':
273
+ parent, name = parent.casefold(), name.casefold()
274
+ return parent == 'runtime' and name.startswith('daecore-')
275
+
276
+ def runtime_directory_identity(root):
277
+ info = Path(root).lstat()
278
+ if not stat.S_ISDIR(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400:
279
+ raise OSError('runtime directory is linked or unavailable')
280
+ return info.st_dev, info.st_ino
281
+
282
+ def runtime_use_record(root, *, read_bytes=None):
283
+ """Read only the current protocol; absence means untracked process use."""
284
+ root = Path(root)
285
+ path = root / RUNTIME_USE_RECORD
286
+ try:
287
+ info = path.lstat()
288
+ except FileNotFoundError:
289
+ return None
290
+ if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size > 4096
291
+ or getattr(info, 'st_file_attributes', 0) & 0x400):
292
+ raise OSError('runtime use record is not an owned bounded file')
293
+ try:
294
+ if read_bytes is not None:
295
+ value = json.loads(read_bytes(path))
296
+ else:
297
+ with path.open('rb') as stream:
298
+ opened = os.fstat(stream.fileno())
299
+ if (opened.st_dev, opened.st_ino, opened.st_size) != (info.st_dev, info.st_ino, info.st_size):
300
+ raise OSError('runtime use record changed during inspection')
301
+ value = json.loads(stream.read(4097))
302
+ except (ValueError, UnicodeError) as exc:
303
+ raise OSError('runtime use record is unreadable') from exc
304
+ if (not isinstance(value, dict) or not {'protocol', 'id', 'control', 'state'} <= set(value)
305
+ or type(value['protocol']) is not int or value['protocol'] != RUNTIME_USE_PROTOCOL
306
+ or not isinstance(value['id'], str) or len(value['id']) != 32
307
+ or any(character not in '0123456789abcdef' for character in value['id'])
308
+ or not isinstance(value['control'], str) or not 0 < len(value['control']) <= 2048
309
+ or value['state'] not in ('staged', 'verified', 'failed')):
310
+ raise OSError('runtime use protocol is unsupported')
311
+ _runtime_control_pool_path(value['control'], root.parent.parent)
312
+ return value
313
+
314
+ def runtime_fallback_problem(root):
315
+ """Structural completeness alone never grants ordinary fallback eligibility."""
316
+ try:
317
+ record = runtime_use_record(root)
318
+ if record is None:
319
+ return 'runtime has no verified completion or tracked process-use protocol'
320
+ if record['state'] != 'verified':
321
+ return f"runtime is {record['state']}; no verified activation permits fallback"
322
+ except OSError as exc:
323
+ return str(exc)
324
+ return None
325
+
326
+ def runtime_control_directory(home):
327
+ """Choose the durable lifecycle namespace once, when enrolling the runtime."""
328
+ try:
329
+ return _runtime_control_lifecycle_state_dir(home) / 'runtime-use'
330
+ except (_runtime_control_UnsafeControlPathError, ValueError, UnicodeError) as exc:
331
+ raise OSError(str(exc)) from exc
332
+
333
+ def _runtime_control_pool_path(control, home):
334
+ pool = Path(control)
335
+ names = (pool.name, pool.parent.name, pool.parent.parent.name)
336
+ if os.name == 'nt':
337
+ names = tuple(name.casefold() for name in names)
338
+ expected = ('runtime-use', 'control', 'daecorecontrol' if os.name == 'nt' else 'daecore-control')
339
+ if not pool.is_absolute() or '..' in pool.parts or names != expected:
340
+ raise OSError('runtime control location is outside its owned namespace')
341
+ try:
342
+ return _runtime_control_validate_external_control_dir(pool, (home,))
343
+ except (_runtime_control_UnsafeControlPathError, ValueError, UnicodeError) as exc:
344
+ raise OSError(str(exc)) from exc
345
+
346
+ def ensure_runtime_control_pool(control, home):
347
+ """Recreate missing control storage with physical custody and private ACLs."""
348
+ pool = _runtime_control_pool_path(control, home)
349
+ if os.name == 'nt':
350
+ try:
351
+ _close_runtime_handle(_runtime_windows_handle(pool, False, pool=True))
352
+ return pool
353
+ except FileNotFoundError:
354
+ pass
355
+ with contextlib.ExitStack() as held:
356
+ if os.name == 'nt':
357
+ user = _runtime_custody_identity_windows_user()
358
+ current = Path(pool.anchor)
359
+ held.callback(_close_runtime_handle, _runtime_windows_handle(current, False, pool=True, custody=False))
360
+ for name in pool.parts[1:]:
361
+ current /= name
362
+ try:
363
+ _runtime_private_create_windows_private_directory_for_sid(current, user)
364
+ except FileExistsError:
365
+ pass
366
+ handle = _runtime_windows_handle(current, False, pool=True, custody=current == pool)
367
+ held.callback(_close_runtime_handle, handle)
368
+ else:
369
+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
370
+ fd = os.open(pool.anchor, flags)
371
+ held.callback(os.close, fd)
372
+ for name in pool.parts[1:]:
373
+ ancestor = os.fstat(fd)
374
+ if (ancestor.st_uid not in {0, os.getuid()}
375
+ or ancestor.st_mode & 0o022 and not ancestor.st_mode & stat.S_ISVTX):
376
+ raise OSError('runtime control storage has an untrusted ancestor')
377
+ try:
378
+ child = os.open(name, flags, dir_fd=fd)
379
+ except FileNotFoundError:
380
+ try:
381
+ os.mkdir(name, 0o700, dir_fd=fd)
382
+ except FileExistsError:
383
+ pass
384
+ child = os.open(name, flags, dir_fd=fd)
385
+ fd = child
386
+ held.callback(os.close, fd)
387
+ info = os.fstat(fd)
388
+ if info.st_uid != os.getuid() or info.st_mode & 0o077:
389
+ raise OSError('runtime control pool is not private to its owner')
390
+ return pool
391
+
392
+ def _runtime_windows_handle(root, exclusive, *, pool=False, custody=True):
393
+ import ctypes
394
+ from ctypes import wintypes
395
+
396
+ kernel = ctypes.WinDLL('kernel32', use_last_error=True)
397
+ create = kernel.CreateFileW
398
+ create.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p,
399
+ wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
400
+ create.restype = wintypes.HANDLE
401
+ # Read handles deny write/delete. The exclusive holder requests both,
402
+ # denies other writers, and may delete its gate after the runtime detaches.
403
+ handle = create(str(root), 0x80000000 | 0x20000 | (0x40000000 | 0x10000 if exclusive else 0),
404
+ 3 if pool else 1 | (4 if exclusive else 0), None, 3, 0x02000000 | 0x00200000, None)
405
+ if handle == wintypes.HANDLE(-1).value:
406
+ raise ctypes.WinError(ctypes.get_last_error())
407
+ try:
408
+ runtime_directory_identity(root)
409
+ if custody:
410
+ owner, grants = _runtime_custody_identity_windows_security(handle)
411
+ user = _runtime_custody_identity_windows_user()
412
+ # OWNER RIGHTS is allowed only after proving this user's ownership.
413
+ if owner != user or any(mask and sid not in {user, 'S-1-3-4', 'S-1-5-18', 'S-1-5-32-544'} for mask, sid in grants):
414
+ raise OSError('runtime gate control directory is not private to its owner')
415
+ except BaseException:
416
+ _close_runtime_handle(handle)
417
+ raise
418
+ return handle
419
+
420
+ def _close_runtime_handle(handle):
421
+ if os.name == 'nt':
422
+ import ctypes
423
+ from ctypes import wintypes
424
+
425
+ close = ctypes.WinDLL('kernel32', use_last_error=True).CloseHandle
426
+ close.argtypes = [wintypes.HANDLE]
427
+ close.restype = wintypes.BOOL
428
+ close(handle)
429
+ else:
430
+ os.close(handle)
431
+
432
+ def _open_runtime_gate(directory, exclusive):
433
+ """Create one private external gate under its already enrolled control pool."""
434
+ if os.name == 'nt':
435
+ parent = _runtime_windows_handle(directory.parent, False, pool=True)
436
+ try:
437
+ try:
438
+ _runtime_private_create_windows_private_directory_for_sid(directory, _runtime_custody_identity_windows_user())
439
+ except FileExistsError:
440
+ pass
441
+ return _runtime_windows_handle(directory, exclusive)
442
+ finally:
443
+ _close_runtime_handle(parent)
444
+ import fcntl
445
+
446
+ with contextlib.ExitStack() as held:
447
+ parent = os.open(directory.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
448
+ held.callback(os.close, parent)
449
+ info = os.fstat(parent)
450
+ if info.st_uid != os.getuid() or info.st_mode & 0o077:
451
+ raise OSError('runtime gate pool is not private to its owner')
452
+ try:
453
+ os.mkdir(directory.name, 0o700, dir_fd=parent)
454
+ except FileExistsError:
455
+ pass
456
+ gate = os.open(directory.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
457
+ held.callback(os.close, gate)
458
+ info = os.fstat(gate)
459
+ if info.st_uid != os.getuid() or info.st_mode & 0o077:
460
+ raise OSError('runtime gate directory is not private to its owner')
461
+ fd = os.open('lease', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600, dir_fd=gate)
462
+ try:
463
+ info = os.fstat(fd)
464
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != os.getuid() or info.st_mode & 0o077:
465
+ raise OSError('runtime gate is not a private owned file')
466
+ fcntl.flock(fd, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB)
467
+ return fd
468
+ except BaseException:
469
+ os.close(fd)
470
+ raise
471
+
472
+ class RuntimeUsePin:
473
+ """One OS-held admission, explicitly closed by owners or by process exit."""
474
+
475
+ def __init__(self, root, *, exclusive=False, home=None):
476
+ self.root = Path(root).absolute()
477
+ self.identity = runtime_directory_identity(self.root)
478
+ self.handle = None
479
+ self.windows = os.name == 'nt'
480
+ self.exclusive = exclusive
481
+ try:
482
+ record = runtime_use_record(self.root)
483
+ if record is None:
484
+ raise OSError('runtime has no tracked process-use protocol; automatic retirement is blocked')
485
+ pool = ensure_runtime_control_pool(record['control'], self.root.parent.parent if home is None else home)
486
+ self.gate = pool / f"{record['id']}-{self.identity[0]:x}-{self.identity[1]:x}"
487
+ self.handle = _open_runtime_gate(self.gate, exclusive)
488
+ current = runtime_use_record(self.root)
489
+ if (runtime_directory_identity(self.root) != self.identity
490
+ or current is None or (current['id'], current['control']) != (record['id'], record['control'])):
491
+ raise OSError('runtime identity changed during admission')
492
+ except BaseException:
493
+ self.close()
494
+ raise
495
+
496
+ def close(self):
497
+ handle, self.handle = self.handle, None
498
+ if handle is not None:
499
+ _close_runtime_handle(handle)
500
+
501
+ def retire_gate(self, detached):
502
+ """Forget the gate while its directory identity still exists in disposal."""
503
+ if (not self.exclusive or self.handle is None or is_managed_runtime_location(detached)
504
+ or runtime_directory_identity(detached) != self.identity):
505
+ raise OSError('runtime gate release requires its exact detached directory')
506
+ if not self.windows:
507
+ info = (self.gate / 'lease').lstat()
508
+ opened = os.fstat(self.handle)
509
+ if (info.st_dev, info.st_ino) != (opened.st_dev, opened.st_ino):
510
+ raise OSError('runtime gate changed before release')
511
+ (self.gate / 'lease').unlink()
512
+ self.gate.rmdir()
513
+
514
+ def __enter__(self):
515
+ return self
516
+
517
+ def __exit__(self, *_error):
518
+ self.close()
519
+
520
+ def hold_current_runtime():
521
+ """Pin this interpreter once; never release early during interpreter shutdown."""
522
+ root = Path(sys.prefix).absolute()
523
+ if getattr(sys, '_daecore_runtime_pin', None) is not None:
524
+ return
525
+ if not is_managed_runtime_location(root):
526
+ return
527
+ if runtime_use_record(root) is not None:
528
+ sys._daecore_runtime_pin = RuntimeUsePin(root)
529
+
530
+ def hold_runtime_startup():
531
+ """A .pth failure must stop startup, since site otherwise only prints it."""
532
+ try:
533
+ hold_current_runtime()
534
+ except Exception as exc: # noqa: BLE001 - site would otherwise print the failure and run unprotected code
535
+ print(f'daecore: runtime admission failed: {exc}', file=sys.stderr, flush=True)
536
+ os._exit(78)
537
+
538
+ def _runtime_command_roots(command, roots, environment):
539
+ selected = {Path(root).absolute() for root in roots}
540
+ executables = []
541
+ if isinstance(command, (list, tuple)) and command:
542
+ executables.append(command[0])
543
+ if os.name == 'nt' and environment is not None and environment.get('__PYVENV_LAUNCHER__'):
544
+ executables.append(environment['__PYVENV_LAUNCHER__'])
545
+ for value in executables:
546
+ executable = Path(os.fsdecode(value))
547
+ scripts = executable.parent.name.casefold() if os.name == 'nt' else executable.parent.name
548
+ if executable.is_absolute() and scripts in ('scripts' if os.name == 'nt' else 'Scripts', 'bin'):
549
+ root = executable.parent.parent
550
+ if is_managed_runtime_location(root):
551
+ selected.add(root)
552
+ return sorted(selected, key=str)
553
+
554
+ @contextlib.contextmanager
555
+ def runtime_child(command, *, roots=(), **kwargs):
556
+ """Pin before launch and inherit only these fresh handles into the child."""
557
+ if os.name == 'nt':
558
+ # An explicit console handoff supplies zero after checking the console.
559
+ kwargs.setdefault('creationflags', subprocess.CREATE_NO_WINDOW)
560
+ with contextlib.ExitStack() as held:
561
+ pins = []
562
+ for root in _runtime_command_roots(command, roots, kwargs.get('env', os.environ)):
563
+ if runtime_use_record(root) is not None:
564
+ pins.append(held.enter_context(RuntimeUsePin(root)))
565
+ if pins:
566
+ if os.name == 'nt':
567
+ startup = copy.copy(kwargs.get('startupinfo')) if kwargs.get('startupinfo') else subprocess.STARTUPINFO()
568
+ startup.lpAttributeList = dict(startup.lpAttributeList or {})
569
+ handles = list(startup.lpAttributeList.get('handle_list', ()))
570
+ for pin in pins:
571
+ os.set_handle_inheritable(pin.handle, True)
572
+ handles.append(pin.handle)
573
+ startup.lpAttributeList['handle_list'] = handles
574
+ kwargs.update(startupinfo=startup, close_fds=True)
575
+ else:
576
+ descriptors = list(kwargs.get('pass_fds', ()))
577
+ for pin in pins:
578
+ os.set_inheritable(pin.handle, True)
579
+ descriptors.append(pin.handle)
580
+ kwargs['pass_fds'] = tuple(descriptors)
581
+ yield kwargs
582
+
583
+ def runtime_popen(command, *, runtime_roots=(), **kwargs):
584
+ with runtime_child(command, roots=runtime_roots, **kwargs) as options:
585
+ return subprocess.Popen(command, **options)
586
+
587
+ def runtime_run(command, *, runtime_roots=(), **kwargs):
588
+ with runtime_child(command, roots=runtime_roots, **kwargs) as options:
589
+ return subprocess.run(command, **options)
590
+ # END GENERATED RUNTIME USE
591
+
592
+ # BEGIN GENERATED FILESYSTEM OBSERVATION
593
+ def path_stat(path: str | os.PathLike, *, follow_symlinks: bool = True) -> os.stat_result | None:
594
+ """Inspect a path, returning None only when the OS confirms it is missing."""
595
+ try:
596
+ return Path(path).stat(follow_symlinks=follow_symlinks)
597
+ except FileNotFoundError:
598
+ return None
599
+
600
+ def path_exists(path: str | os.PathLike, *, follow_symlinks: bool = True) -> bool:
601
+ """Test presence; non-following probes count a dangling link as present."""
602
+ return path_stat(path, follow_symlinks=follow_symlinks) is not None
603
+
604
+ def path_is_file(path: str | os.PathLike, *, follow_symlinks: bool = True) -> bool:
605
+ """Test regular-file type without suppressing inspection errors."""
606
+ info = path_stat(path, follow_symlinks=follow_symlinks)
607
+ return info is not None and stat.S_ISREG(info.st_mode)
608
+
609
+ def path_is_dir(path: str | os.PathLike, *, follow_symlinks: bool = True) -> bool:
610
+ """Test directory type without suppressing inspection errors."""
611
+ info = path_stat(path, follow_symlinks=follow_symlinks)
612
+ return info is not None and stat.S_ISDIR(info.st_mode)
613
+
614
+ def path_is_symlink(path: str | os.PathLike) -> bool:
615
+ """Inspect the directory entry itself; an unreadable link is not a plain file."""
616
+ info = path_stat(path, follow_symlinks=False)
617
+ return info is not None and stat.S_ISLNK(info.st_mode)
618
+
619
+ file_probe = SimpleNamespace(
620
+ path_stat=path_stat,
621
+ path_exists=path_exists,
622
+ path_is_file=path_is_file,
623
+ path_is_dir=path_is_dir,
624
+ path_is_symlink=path_is_symlink,
625
+ )
626
+ # END GENERATED FILESYSTEM OBSERVATION
627
+
628
+ # BEGIN GENERATED HANDOFF ENVIRONMENT
629
+ HANDOFF_ENV_VARS = frozenset({
630
+ 'DAECORE_SERVE_HANDOFF', 'DAECORE_SPAWN_OUTCOME',
631
+ 'DAECORE_INSTALL_TRANSACTION_ID', 'DAECORE_UPDATE_CONVERGENCE',
632
+ 'DAECORE_SEED_VENV', 'DAECORE_WMI_SPAWN_COMMAND', 'DAECORE_LAUNCHER_WAITING',
633
+ 'DAECORE_SCREEN', 'DAECORE_LAUNCHER_RENAMES', 'DAECORE_RENAME_OUTCOME',
634
+ })
635
+
636
+ SCREEN_HANDOFF = 'DAECORE_SCREEN'
637
+
638
+ REMOVE_RUNTIME_EXIT = 0x44414543
639
+
640
+ REMOVE_HOME_EXIT = 0x44414544
641
+
642
+ RENAME_HOME_EXIT = 0x44414545
643
+
644
+ LAUNCHER_RENAMES = 'DAECORE_LAUNCHER_RENAMES'
645
+
646
+ RENAME_OUTCOME = 'DAECORE_RENAME_OUTCOME'
647
+
648
+ _CAPTURED_HANDOFFS = None
649
+
650
+ def capture_handoffs(source=None) -> None:
651
+ """Move entry-time handoffs out of the environment before starting work.
652
+
653
+ The seed stub can transfer its capture directly when it enters the package
654
+ in the same process. Repeated entry calls cannot replace or revive values.
655
+ """
656
+ global _CAPTURED_HANDOFFS
657
+ source = os.environ if source is None else source
658
+ if _CAPTURED_HANDOFFS is None:
659
+ _CAPTURED_HANDOFFS = {name: source[name] for name in HANDOFF_ENV_VARS if name in source}
660
+ for name in tuple(source):
661
+ if name.upper() in HANDOFF_ENV_VARS:
662
+ source.pop(name)
663
+
664
+ def handoff_value(name: str, *, consume: bool = False) -> str | None:
665
+ """Read captured transport evidence; the receiver must still validate it."""
666
+ if _CAPTURED_HANDOFFS is None:
667
+ return None
668
+ return _CAPTURED_HANDOFFS.pop(name, None) if consume else _CAPTURED_HANDOFFS.get(name)
669
+
670
+ def child_environment(environ=None, *, handoff=None) -> dict[str, str]:
671
+ """Copy ordinary configuration; forward only explicitly selected handoffs.
672
+
673
+ Receivers still validate their evidence. Host configuration and the test
674
+ lease are not handoffs and keep their existing inheritance.
675
+ """
676
+ env = {name: value for name, value in (os.environ if environ is None else environ).items()
677
+ if name.upper() not in HANDOFF_ENV_VARS}
678
+ if handoff:
679
+ env.update(handoff)
680
+ return env
681
+ # END GENERATED HANDOFF ENVIRONMENT
682
+
683
+ # Set on the child: the venv this stub is running from (the tool seed).
684
+ # The redirected runtime compares the seed's installed version against its
685
+ # own to detect an external `pipx upgrade`/reinstall that the pointer
686
+ # redirect would otherwise hide forever (see
687
+ # ``daecore.daemon.runtime.detect_seed_drift``). Exporting one env var
688
+ # leaves version comparison and reporting in the real CLI.
689
+ _SEED_ENV_VAR = "DAECORE_SEED_VENV"
690
+
691
+ # How long a finished uninstall waits for the files of the runtime it left.
692
+ RUNTIME_REMOVAL_WAIT_SECONDS = 20.0
693
+
694
+
695
+
696
+
697
+ def seed_manager(venv: Path) -> str | None:
698
+ """Identify a persistent tool environment from its installer's receipt.
699
+
700
+ A directory name or an environment hint alone cannot make a development
701
+ environment a launcher seed. Conflicting or malformed receipts prove no owner.
702
+ This reader also runs before the Daecore package can be imported.
703
+ """
704
+ if not venv.is_absolute():
705
+ return None
706
+ try:
707
+ pipx = venv / 'pipx_metadata.json'
708
+ uv = venv / 'uv-receipt.toml'
709
+ if file_probe.path_exists(pipx) == file_probe.path_exists(uv):
710
+ return None
711
+ if file_probe.path_exists(pipx):
712
+ apps = json.loads(pipx.read_text(encoding='utf-8'))['main_package']['apps']
713
+ return 'pipx' if isinstance(apps, list) and any(
714
+ isinstance(app, str) and app.lower() in {'daecore', 'daecore.exe'}
715
+ for app in apps
716
+ ) else None
717
+ tool = tomllib.loads(uv.read_text(encoding='utf-8'))['tool']
718
+ requirements, entrypoints = tool['requirements'], tool['entrypoints']
719
+ if not isinstance(requirements, list) or not isinstance(entrypoints, list):
720
+ return None
721
+ # uv defines the first requirement as the tool target; later rows
722
+ # are --with dependencies and do not own the environment's uninstall.
723
+ owns_package = bool(requirements) and isinstance(requirements[0], dict) and requirements[0].get('name') == 'daecore'
724
+ owns_command = any(
725
+ isinstance(row, dict) and row.get('name') in {'daecore', 'daecore.exe'}
726
+ and row.get('from', 'daecore') == 'daecore'
727
+ and isinstance(row.get('install-path'), str)
728
+ and Path(row['install-path']).is_absolute()
729
+ for row in entrypoints
730
+ )
731
+ return 'uv' if owns_package and owns_command else None
732
+ except (KeyError, TypeError, ValueError, OSError, RecursionError, RuntimeError):
733
+ return None
734
+
735
+
736
+ def _managed_seed_venv(venv: Path) -> Path | None:
737
+ return venv if seed_manager(venv) is not None else None
738
+
739
+
740
+ # The home is resolved as ``daecore.paths.home()`` resolves it, from the same
741
+ # source: the daemon and the relay locate ``runtime/current`` there, so a second
742
+ # rule here would send the launcher to a different folder.
743
+ # BEGIN GENERATED HOME LOCATION
744
+ HOME_ENV_VAR = 'DAECORE_HOME'
745
+
746
+ HOME_POINTER_NAME = 'home.json'
747
+
748
+ HOME_POINTER_VERSION = 1
749
+
750
+ HOME_POINTER_MAX_BYTES = 65536
751
+
752
+ HOME_POINTER_READ_ATTEMPTS = 3
753
+
754
+ _POINTER_PATHS = {}
755
+
756
+ _POINTER_HOMES = {}
757
+
758
+ class HomePointerError(RuntimeError):
759
+ """The home pointer exists and cannot be trusted, so no home is resolved."""
760
+
761
+ def windows_known_folder(folder_id: str) -> Path:
762
+ """Ask Windows for one of the account's folders, which needs no environment variable."""
763
+ import ctypes
764
+ from ctypes import wintypes
765
+
766
+ first, second, third, fourth, fifth = folder_id.split('-')
767
+ raw = (int(first, 16).to_bytes(4, 'little') + int(second, 16).to_bytes(2, 'little')
768
+ + int(third, 16).to_bytes(2, 'little') + bytes.fromhex(fourth + fifth))
769
+ shell = ctypes.WinDLL('shell32', use_last_error=True)
770
+ ole = ctypes.WinDLL('ole32', use_last_error=True)
771
+ shell.SHGetKnownFolderPath.argtypes = [ctypes.c_void_p, wintypes.DWORD, wintypes.HANDLE,
772
+ ctypes.POINTER(ctypes.c_wchar_p)]
773
+ shell.SHGetKnownFolderPath.restype = ctypes.c_long
774
+ ole.CoTaskMemFree.argtypes = [ctypes.c_void_p]
775
+ ole.CoTaskMemFree.restype = None
776
+ found = ctypes.c_wchar_p()
777
+ status = shell.SHGetKnownFolderPath(ctypes.c_char_p(raw), 0, None, ctypes.byref(found))
778
+ try:
779
+ if status != 0 or not found.value:
780
+ raise OSError(f'Windows could not locate the account folder {folder_id}')
781
+ return Path(found.value)
782
+ finally:
783
+ ole.CoTaskMemFree(ctypes.cast(found, ctypes.c_void_p))
784
+
785
+ def user_profile_dir() -> Path:
786
+ """The account's home folder, found even when a host passes no environment."""
787
+ try:
788
+ return Path.home()
789
+ except RuntimeError:
790
+ if os.name != 'nt':
791
+ raise
792
+ try:
793
+ return windows_known_folder('5E6C858F-0E22-4760-9AFE-EA3317B67173')
794
+ except OSError as exc:
795
+ # Callers already treat ``Path.home()``'s error as "no home can be found".
796
+ raise RuntimeError('Could not determine home directory.') from exc
797
+
798
+ def per_user_state_dir() -> Path:
799
+ """The per-user folder that holds Daecore's control directory.
800
+
801
+ ``LOCALAPPDATA`` or ``XDG_STATE_HOME`` selects it when set, which is how tests and isolated runs
802
+ keep their own. Otherwise the operating system's own answer for the account is used.
803
+ """
804
+ if os.name == 'nt':
805
+ base = os.environ.get('LOCALAPPDATA')
806
+ return Path(base) if base else windows_known_folder('F1B32785-6FBA-4FCF-9D55-7B8E7F157091')
807
+ state = os.environ.get('XDG_STATE_HOME')
808
+ return Path(state) if state else user_profile_dir() / '.local' / 'state'
809
+
810
+ def control_root_under(state_dir: Path) -> Path:
811
+ name = 'DaecoreControl' if os.name == 'nt' else 'daecore-control'
812
+ return state_dir.expanduser().resolve(strict=False) / name / 'control'
813
+
814
+ def external_state_root() -> Path:
815
+ """The per-user control directory, outside every home."""
816
+ return control_root_under(per_user_state_dir())
817
+
818
+ def home_pointer_path() -> Path:
819
+ state_dir = per_user_state_dir()
820
+ path = _POINTER_PATHS.get(state_dir)
821
+ if path is None:
822
+ path = _POINTER_PATHS[state_dir] = control_root_under(state_dir) / HOME_POINTER_NAME
823
+ return path
824
+
825
+ def default_home() -> Path:
826
+ return user_profile_dir() / '.daecore'
827
+
828
+ def home_pointer_digest(fields: dict) -> str:
829
+ """The digest a pointer carries: SHA-256 over every other field, as canonical JSON."""
830
+ covered = {name: value for name, value in fields.items() if name != 'sha256'}
831
+ body = json.dumps(covered, sort_keys=True, separators=(',', ':'), ensure_ascii=False)
832
+ return hashlib.sha256(body.encode('utf-8')).hexdigest()
833
+
834
+ def encode_home_pointer(home: Path, *, journal: str | None = None) -> bytes:
835
+ """The exact bytes of a pointer naming ``home``, for a writer to publish atomically."""
836
+ home = Path(home)
837
+ if not home.is_absolute():
838
+ raise ValueError(f'a home pointer names an absolute path, not {home}')
839
+ fields = {
840
+ 'version': HOME_POINTER_VERSION,
841
+ 'home': str(home),
842
+ 'set_at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
843
+ 'journal': journal,
844
+ }
845
+ fields['sha256'] = home_pointer_digest(fields)
846
+ return json.dumps(fields, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')
847
+
848
+ def decode_home_pointer(raw: bytes) -> Path:
849
+ """The home a pointer names; ``ValueError`` says why its bytes cannot be trusted."""
850
+ try:
851
+ fields = json.loads(raw.decode('utf-8'))
852
+ except (UnicodeError, ValueError, RecursionError):
853
+ raise ValueError('it is not valid JSON') from None
854
+ if not isinstance(fields, dict):
855
+ raise ValueError('it is not a JSON object')
856
+ if fields.get('sha256') != home_pointer_digest(fields):
857
+ raise ValueError('its contents do not match its digest')
858
+ home = fields.get('home')
859
+ if not isinstance(home, str) or '\x00' in home or not Path(home).is_absolute():
860
+ raise ValueError('it names no absolute folder')
861
+ return Path(home)
862
+
863
+ def read_home_pointer_file(path: Path) -> Path | None:
864
+ """One bounded, physical read of the pointer file; ``None`` when there is none.
865
+
866
+ A writer replaces the file and never edits it in place, so a file with the same identity, size
867
+ and modification time is the file already parsed.
868
+ """
869
+ try:
870
+ info = path.lstat()
871
+ except FileNotFoundError:
872
+ _POINTER_HOMES.clear()
873
+ return None
874
+ seen = (str(path), info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns)
875
+ if seen in _POINTER_HOMES:
876
+ return _POINTER_HOMES[seen]
877
+ if stat.S_ISDIR(info.st_mode):
878
+ # Writing the record replaces a file; it never removes a folder someone put there.
879
+ raise ValueError('a folder is in its place; move that folder away first')
880
+ if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size > HOME_POINTER_MAX_BYTES
881
+ or getattr(info, 'st_file_attributes', 0) & 0x400):
882
+ raise ValueError('it is not a plain file of the expected size')
883
+ with path.open('rb') as stream:
884
+ opened = os.fstat(stream.fileno())
885
+ if (opened.st_dev, opened.st_ino, opened.st_size) != (info.st_dev, info.st_ino, info.st_size):
886
+ raise OSError('the file changed while it was read')
887
+ home = decode_home_pointer(stream.read(HOME_POINTER_MAX_BYTES + 1))
888
+ _POINTER_HOMES.clear()
889
+ _POINTER_HOMES[seen] = home
890
+ return home
891
+
892
+ def read_home_pointer() -> Path | None:
893
+ """The home the pointer names, ``None`` when no pointer exists, or :class:`HomePointerError`.
894
+
895
+ A writer replaces the file atomically, so a read that collides with a replacement is tried
896
+ again; contents that fail their checks are never retried, because they cannot be half-written.
897
+ """
898
+ path = home_pointer_path()
899
+ problem = 'it could not be read'
900
+ for attempt in range(HOME_POINTER_READ_ATTEMPTS):
901
+ try:
902
+ return read_home_pointer_file(path)
903
+ except ValueError as exc:
904
+ problem = str(exc)
905
+ break
906
+ except OSError as exc:
907
+ problem = exc.strerror or str(exc)
908
+ if attempt + 1 < HOME_POINTER_READ_ATTEMPTS:
909
+ time.sleep(0.02)
910
+ raise HomePointerError(
911
+ f"the record of Daecore's location is damaged: {path} ({problem}). Run `daecore setup` once "
912
+ f"with {HOME_ENV_VAR} set to Daecore's folder; it writes the record again"
913
+ )
914
+
915
+ def daecore_home() -> Path:
916
+ """Resolve the Daecore home; the directory is not created here.
917
+
918
+ ``DAECORE_HOME`` wins when set to a non-blank value, then the pointer, then ``~/.daecore``.
919
+ """
920
+ override = os.environ.get(HOME_ENV_VAR, '').strip()
921
+ if override:
922
+ return Path(override).expanduser().resolve()
923
+ pointed = read_home_pointer()
924
+ return pointed if pointed is not None else default_home()
925
+ # END GENERATED HOME LOCATION
926
+
927
+
928
+ # BEGIN GENERATED HOME RENAME
929
+ LIFECYCLE_LOCK_NAME = "lifecycle.lock"
930
+
931
+ LIFECYCLE_LOCK_BYTE = 1 << 29
932
+
933
+ RENAME_NOTE_NAME = 'home-rename.json'
934
+
935
+ RENAME_NOTE_VERSION = 1
936
+
937
+ RENAME_NOTE_MAX_BYTES = 65536
938
+
939
+ RENAME_LOCK_WAIT_SECONDS = 30.0
940
+
941
+ _RENAME_NOTE_FIELDS = frozenset({'version', 'journal', 'source', 'target', 'source_identity', 'runtimes',
942
+ 'pointer_sha256', 'sha256'})
943
+
944
+ def rename_note_path() -> Path:
945
+ """The note sits beside the location record, in the per-user control directory."""
946
+ return home_pointer_path().with_name(RENAME_NOTE_NAME)
947
+
948
+ def staged_pointer_path(journal: str) -> Path:
949
+ """The location record a move stages for the launcher, beside the one it replaces."""
950
+ return home_pointer_path().with_name(f'home-rename-{journal}.json')
951
+
952
+ def rename_note_digest(fields: dict) -> str:
953
+ """SHA-256 over every other field, as canonical JSON."""
954
+ covered = {name: value for name, value in fields.items() if name != 'sha256'}
955
+ body = json.dumps(covered, sort_keys=True, separators=(',', ':'), ensure_ascii=False)
956
+ return hashlib.sha256(body.encode('utf-8')).hexdigest()
957
+
958
+ def encode_rename_note(*, journal: str, source: Path, target: Path, source_identity: list[int],
959
+ runtimes: list[Path], pointer_sha256: str) -> bytes:
960
+ """The exact bytes of the note, for the runtime to publish."""
961
+ fields = {
962
+ 'version': RENAME_NOTE_VERSION, 'journal': journal, 'source': str(source), 'target': str(target),
963
+ 'source_identity': list(source_identity), 'runtimes': [str(path) for path in runtimes],
964
+ 'pointer_sha256': pointer_sha256,
965
+ }
966
+ fields['sha256'] = rename_note_digest(fields)
967
+ return json.dumps(fields, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')
968
+
969
+ def read_rename_note() -> dict | None:
970
+ """The sealed note, ``None`` when there is none; ``ValueError`` when it cannot be trusted."""
971
+ try:
972
+ with open(rename_note_path(), 'rb') as stream:
973
+ raw = stream.read(RENAME_NOTE_MAX_BYTES + 1)
974
+ except FileNotFoundError:
975
+ return None
976
+ if len(raw) > RENAME_NOTE_MAX_BYTES:
977
+ raise ValueError('the home move note is too large')
978
+ fields = json.loads(raw)
979
+ if (not isinstance(fields, dict) or set(fields) != _RENAME_NOTE_FIELDS
980
+ or fields['version'] != RENAME_NOTE_VERSION or fields['sha256'] != rename_note_digest(fields)
981
+ or not all(isinstance(fields[name], str) for name in ('journal', 'source', 'target', 'pointer_sha256'))
982
+ or not isinstance(fields['runtimes'], list) or not all(isinstance(item, str) for item in fields['runtimes'])
983
+ or not (isinstance(fields['source_identity'], list) and len(fields['source_identity']) == 2
984
+ and all(type(item) is int for item in fields['source_identity']))):
985
+ raise ValueError('the home move note is damaged')
986
+ return fields
987
+
988
+ @contextlib.contextmanager
989
+ def held_lifecycle_lock(wait: float = RENAME_LOCK_WAIT_SECONDS):
990
+ """Hold the lock maintenance recovery takes, so no recovery runs while the home is renamed.
991
+
992
+ Only the Windows launcher, which waits for the runtime, renames on its own, and there that
993
+ lock is one byte of ``lifecycle.lock`` beside the location record. Raises ``TimeoutError``
994
+ when another lifecycle operation keeps it past ``wait`` seconds.
995
+ """
996
+ import msvcrt
997
+
998
+ fd = os.open(home_pointer_path().with_name(LIFECYCLE_LOCK_NAME), os.O_RDWR | os.O_CREAT | os.O_BINARY, 0o600)
999
+ try:
1000
+ deadline = time.monotonic() + wait
1001
+ while True:
1002
+ os.lseek(fd, LIFECYCLE_LOCK_BYTE, os.SEEK_SET)
1003
+ try:
1004
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
1005
+ break
1006
+ except OSError:
1007
+ if time.monotonic() >= deadline:
1008
+ raise TimeoutError('another Daecore operation holds the lifecycle lock') from None
1009
+ time.sleep(0.1)
1010
+ try:
1011
+ yield
1012
+ finally:
1013
+ os.lseek(fd, LIFECYCLE_LOCK_BYTE, os.SEEK_SET)
1014
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
1015
+ finally:
1016
+ os.close(fd)
1017
+
1018
+ def finish_interrupted_rename(home: Path) -> Path:
1019
+ """The home to use when a move stopped between renaming the folder and recording it.
1020
+
1021
+ Runs only when the recorded home is missing, so it costs nothing on a normal start. When a
1022
+ note says this folder was being renamed, the folder at the new name is the one the move
1023
+ prepared, and the record still names the old name, it puts the move's staged record in place,
1024
+ which commits the move; recovery then finishes it at the new name. Otherwise ``home`` is
1025
+ returned as it was.
1026
+ """
1027
+ if file_probe.path_exists(home, follow_symlinks=False):
1028
+ return home
1029
+ try:
1030
+ note = read_rename_note()
1031
+ if note is None or Path(note['source']) != home or read_home_pointer() != home:
1032
+ return home
1033
+ target = Path(note['target'])
1034
+ info = os.lstat(target)
1035
+ if ([info.st_dev, info.st_ino] != note['source_identity'] or file_probe.path_is_symlink(target)
1036
+ or not file_probe.path_is_dir(target, follow_symlinks=False)):
1037
+ return home
1038
+ staged = staged_pointer_path(note['journal'])
1039
+ try:
1040
+ with open(staged, 'rb') as stream:
1041
+ matches = hashlib.sha256(stream.read()).hexdigest() == note['pointer_sha256']
1042
+ if matches:
1043
+ os.replace(staged, home_pointer_path())
1044
+ except FileNotFoundError:
1045
+ pass # Another program starting at the same moment put it in place first.
1046
+ return target if read_home_pointer() == target else home
1047
+ except (OSError, ValueError):
1048
+ return home
1049
+
1050
+ def rename_by_note(note: dict) -> str | None:
1051
+ """Rename the home as ``note`` says and put the staged location record in place.
1052
+
1053
+ Returns ``None`` once the move is recorded, or why nothing changed. All of these must hold
1054
+ first: the recorded location still names the folder being moved, that folder is the one the
1055
+ move prepared, nothing exists at the new name, the staged record is the one the note names,
1056
+ and no program runs from the home's runtimes, which the exclusive holds prove and keep so
1057
+ while the folder is renamed. A record that cannot be put in place renames the folder back.
1058
+ """
1059
+ source, target = Path(note['source']), Path(note['target'])
1060
+ if read_home_pointer() != source:
1061
+ return 'the recorded location no longer names the folder being moved'
1062
+ try:
1063
+ info = os.lstat(source)
1064
+ except FileNotFoundError:
1065
+ return f'{source} is gone'
1066
+ if ([info.st_dev, info.st_ino] != note['source_identity'] or file_probe.path_is_symlink(source)
1067
+ or not file_probe.path_is_dir(source, follow_symlinks=False)):
1068
+ return f'{source} is not the folder the move prepared'
1069
+ if file_probe.path_exists(target, follow_symlinks=False):
1070
+ return f'{target} already exists'
1071
+ staged = staged_pointer_path(note['journal'])
1072
+ try:
1073
+ with open(staged, 'rb') as stream:
1074
+ if hashlib.sha256(stream.read()).hexdigest() != note['pointer_sha256']:
1075
+ return 'the staged location record is not the one the move wrote'
1076
+ with contextlib.ExitStack() as held:
1077
+ for runtime in note['runtimes']:
1078
+ try:
1079
+ held.enter_context(RuntimeUsePin(Path(runtime), exclusive=True, home=source))
1080
+ except OSError as exc:
1081
+ return f'a program is running from {runtime} ({exc.strerror or exc})'
1082
+ os.rename(source, target)
1083
+ except OSError as exc:
1084
+ return f'{source} could not be renamed ({exc.strerror or exc})'
1085
+ try:
1086
+ os.replace(staged, home_pointer_path())
1087
+ except OSError as exc:
1088
+ os.rename(target, source) # Unrecorded, so undone; a failure here is left to the interrupted-move check.
1089
+ return f'the new location could not be recorded ({exc.strerror or exc}); the folder was renamed back'
1090
+ return None
1091
+ # END GENERATED HOME RENAME
1092
+
1093
+
1094
+ # BEGIN GENERATED RUNTIME SELECTION
1095
+ def exception_reason(exc: BaseException) -> str:
1096
+ """An exception's own words for a note or problem, never its class name:
1097
+ the system's text for an OS error, else the message."""
1098
+ return (getattr(exc, 'strerror', None) or ' '.join(str(exc).split())
1099
+ or 'no further detail was reported')
1100
+
1101
+ def read_runtime_pointer(link: Path, *, max_bytes: int | None = None) -> Path | None:
1102
+ """Read ``runtime/current``: a symlink (POSIX) or a UTF-8 text marker (Windows).
1103
+
1104
+ A broken symlink still yields its dead target so a caller can classify the
1105
+ install as broken rather than absent. An empty marker, a directory, or an
1106
+ unreadable file is ``None``. Relative symlinks are relative to the pointer's
1107
+ parent; text markers must contain an absolute path.
1108
+ """
1109
+ try:
1110
+ if file_probe.path_is_symlink(link):
1111
+ value = os.readlink(link)
1112
+ if max_bytes is not None and len(value.encode('utf-8')) > max_bytes:
1113
+ return None
1114
+ target = Path(value)
1115
+ return target if target.is_absolute() else link.parent / target
1116
+ if file_probe.path_is_file(link):
1117
+ if max_bytes is None:
1118
+ text = link.read_text(encoding="utf-8").strip()
1119
+ else:
1120
+ with link.open('rb') as handle:
1121
+ raw = handle.read(max_bytes + 1)
1122
+ if len(raw) > max_bytes:
1123
+ return None
1124
+ text = raw.decode('utf-8').strip()
1125
+ target = Path(text) if text else None
1126
+ return target if target is not None and target.is_absolute() else None
1127
+ except (OSError, ValueError):
1128
+ return None
1129
+ return None
1130
+
1131
+
1132
+ def installed_sites(root: Path) -> list[Path]:
1133
+ """Venv layouts, without hiding an unreadable directory as an empty one."""
1134
+ sites = [root / "Lib" / "site-packages"]
1135
+ for base in ("lib", "lib64"):
1136
+ try:
1137
+ children = list((root / base).iterdir())
1138
+ except FileNotFoundError:
1139
+ continue
1140
+ sites.extend(
1141
+ path / "site-packages" for path in sorted(children)
1142
+ if path.name.startswith("python") and file_probe.path_is_dir(path)
1143
+ )
1144
+ return sites
1145
+
1146
+
1147
+ def installed_package_root(runtime_root: Path) -> Path | None:
1148
+ """The one installed ``daecore`` package tree under a runtime, found without
1149
+ trusting distribution metadata."""
1150
+ try:
1151
+ root = Path(runtime_root).expanduser().resolve()
1152
+ sites = list(dict.fromkeys(
1153
+ site.resolve() for site in installed_sites(root)
1154
+ if file_probe.path_is_file(site / "daecore" / "__init__.py")
1155
+ ))
1156
+ if len(sites) != 1:
1157
+ return None
1158
+ package = (sites[0] / "daecore").resolve()
1159
+ return package if package.is_relative_to(root) else None
1160
+ except (OSError, ValueError, RuntimeError):
1161
+ return None
1162
+
1163
+
1164
+ def installed_distribution_evidence(runtime_root: Path) -> tuple[Path, str, str] | None:
1165
+ """``(package_root, version, RECORD)`` for the single complete Daecore
1166
+ distribution under a runtime, or ``None``."""
1167
+ package_root = installed_package_root(runtime_root)
1168
+ if package_root is None:
1169
+ return None
1170
+ try:
1171
+ dist_dirs = [
1172
+ path for path in package_root.parent.iterdir()
1173
+ if path.name.startswith("daecore-") and path.name.endswith(".dist-info") and file_probe.path_is_dir(path)
1174
+ ]
1175
+ if len(dist_dirs) != 1 or not dist_dirs[0].resolve().is_relative_to(runtime_root.resolve()):
1176
+ return None
1177
+ metadata_text = (dist_dirs[0] / "METADATA").read_text(encoding="utf-8")
1178
+ record = (dist_dirs[0] / "RECORD").read_text(encoding="utf-8")
1179
+ except (OSError, ValueError, RuntimeError):
1180
+ return None
1181
+ version = next(
1182
+ (
1183
+ line.partition(":")[2].strip()
1184
+ for line in metadata_text.splitlines()
1185
+ if line.lower().startswith("version:")
1186
+ ),
1187
+ "",
1188
+ )
1189
+ if not version:
1190
+ return None
1191
+ return package_root, version, record
1192
+
1193
+
1194
+ def venv_base_python(runtime_root: Path) -> Path | None:
1195
+ """Read the venv's base interpreter without executing a redirector."""
1196
+ try:
1197
+ entries = dict(
1198
+ (key.strip().lower(), value.strip())
1199
+ for line in (runtime_root / 'pyvenv.cfg').read_text(encoding='utf-8').splitlines()
1200
+ for key, sep, value in (line.partition('='),) if sep
1201
+ )
1202
+ home = Path(entries.get('home', ''))
1203
+ if not home.is_absolute():
1204
+ return None
1205
+ version = entries.get('version_info') or entries.get('version', '')
1206
+ parts = version.split('.')
1207
+ versioned = (f'python{parts[0]}.{parts[1]}',) if len(parts) >= 2 and all(part.isdigit() for part in parts[:2]) else ()
1208
+ names = ('python.exe',) if os.name == 'nt' else (*versioned, 'python', 'python3')
1209
+ for name in names:
1210
+ candidate = home / name
1211
+ if file_probe.path_is_file(candidate):
1212
+ base = candidate.resolve()
1213
+ if not file_probe.path_exists(base.parent / 'pyvenv.cfg') and not file_probe.path_exists(base.parent.parent / 'pyvenv.cfg'):
1214
+ return base
1215
+ except (OSError, ValueError, RuntimeError, UnicodeError):
1216
+ pass
1217
+ return None
1218
+
1219
+
1220
+ def runtime_target_problem(target: Path, runtime_root: Path) -> str | None:
1221
+ """The structural launch predicate; None means an intact, anchored runtime.
1222
+
1223
+ The standalone entry and relay embed this same source; checking a target
1224
+ never imports or executes its package.
1225
+ """
1226
+ try:
1227
+ if not target.is_absolute():
1228
+ return "target path is not absolute"
1229
+ if target.name.endswith(".gc-tmp"):
1230
+ return "target is a retired runtime"
1231
+ # Resolve the home, but do not allow a runtime-directory junction to
1232
+ # move the authority boundary outside it.
1233
+ root = runtime_root.parent.resolve() / runtime_root.name
1234
+ resolved = target.resolve()
1235
+ if resolved.parent != root or not resolved.name.startswith("daecore-"):
1236
+ return "target is not an immediate managed runtime child"
1237
+ if resolved.name.endswith(".gc-tmp"):
1238
+ return "target is a retired runtime"
1239
+ if not file_probe.path_is_dir(resolved):
1240
+ return "target directory is missing"
1241
+ return _runtime_files_problem(resolved)
1242
+ except (OSError, ValueError, RuntimeError) as exc:
1243
+ return f"target cannot be inspected ({exception_reason(exc)})"
1244
+
1245
+
1246
+ def _runtime_files_problem(resolved: Path) -> str | None:
1247
+ binaries = (
1248
+ ("Scripts/python.exe", "Scripts/daecore.exe", "Scripts/daecore-mcp.exe")
1249
+ if os.name == "nt" else ("bin/python", "bin/daecore", "bin/daecore-mcp")
1250
+ )
1251
+ missing = [name for name in binaries if not file_probe.path_is_file(resolved / name)]
1252
+ if missing:
1253
+ return "missing " + ", ".join(missing)
1254
+ if venv_base_python(resolved) is None:
1255
+ return "pyvenv.cfg does not name an available base interpreter"
1256
+ evidence = installed_distribution_evidence(resolved)
1257
+ if evidence is None:
1258
+ return "installed package or unique versioned distribution metadata is unavailable"
1259
+ if not evidence[2].strip():
1260
+ return "distribution RECORD is empty"
1261
+ return None
1262
+
1263
+
1264
+ def _names_runtime_entry(target: Path, runtime_root: Path) -> bool:
1265
+ """Whether a recorded update target is an entry of this home's runtime directory.
1266
+
1267
+ A relative or uninspectable path counts as one, so damaged evidence is
1268
+ never read as a fresh install.
1269
+ """
1270
+ try:
1271
+ if not target.is_absolute():
1272
+ return True
1273
+ # Evidence is what the receipt names, even when that entry is now
1274
+ # an escaping link. Launch validity is a separate resolved-path check.
1275
+ if target.parent == runtime_root:
1276
+ return True
1277
+ root = runtime_root.parent.resolve() / runtime_root.name
1278
+ return target.parent.resolve() == root or target.resolve().parent == root
1279
+ except (OSError, ValueError, RuntimeError):
1280
+ return True
1281
+
1282
+
1283
+ class DaemonRuntimeError(RuntimeError):
1284
+ """A managed installation cannot safely select its serving runtime."""
1285
+
1286
+
1287
+ class RuntimeSelection:
1288
+ """One observation: a managed target, a fresh install, or a refusal."""
1289
+
1290
+ def __init__(self, target: Path | None, managed: bool, problems: tuple[str, ...] = ()):
1291
+ self.target = target
1292
+ self.managed = managed
1293
+ self.problems = problems
1294
+
1295
+ def require_target(self) -> Path | None:
1296
+ """Return the serving target, or None only for an unmanaged install."""
1297
+ if self.target is None and self.managed:
1298
+ raise DaemonRuntimeError(
1299
+ self.refusal() + ". To repair, restore access to any unreadable managed state, "
1300
+ "then run `daecore update`."
1301
+ )
1302
+ return self.target
1303
+
1304
+ def refusal(self) -> str:
1305
+ return "No intact managed runtime is available: " + "; ".join(self.problems)
1306
+
1307
+
1308
+ def select_runtime(home: Path, *, skip_current: bool = False) -> RuntimeSelection:
1309
+ """Select current, the committed update target, then newest verified eligible runtime.
1310
+
1311
+ An existing current entry, a named update target, or unreadable managed
1312
+ state commits this installation to managed code. With no such evidence,
1313
+ stray candidate directories belong to an uncommitted first update and
1314
+ cannot displace the seed. Mtime orders the final scan; names break ties
1315
+ in ascending order. Custody skips current when looking for its repair.
1316
+ """
1317
+ return _RuntimeSelector(home).select(skip_current=skip_current)
1318
+
1319
+
1320
+ class _RuntimeSelector:
1321
+ """Keep one ordered observation of managed evidence and eligible targets."""
1322
+
1323
+ def __init__(self, home: Path):
1324
+ self.home = home
1325
+ self.root = home / 'runtime'
1326
+ self.current = self.root / 'current'
1327
+ self.problems: list[str] = []
1328
+ self.managed = False
1329
+
1330
+ def select(self, *, skip_current: bool) -> RuntimeSelection:
1331
+ current = self._from_current(skip_current)
1332
+ if current is not None:
1333
+ return current
1334
+ recorded = self._from_receipt()
1335
+ if recorded is not None:
1336
+ return recorded
1337
+ return self._from_fallback()
1338
+
1339
+ def _from_current(self, skip_current: bool) -> RuntimeSelection | None:
1340
+ try:
1341
+ self.current.lstat()
1342
+ except FileNotFoundError:
1343
+ self.problems.append("runtime/current: missing")
1344
+ except OSError as exc:
1345
+ self.managed = True
1346
+ self.problems.append(f"runtime/current: unreadable ({exception_reason(exc)})")
1347
+ else:
1348
+ self.managed = True
1349
+ if not skip_current:
1350
+ target = read_runtime_pointer(self.current)
1351
+ problem = runtime_target_problem(target, self.root) if target is not None else "unreadable or invalid pointer"
1352
+ if problem is None:
1353
+ return RuntimeSelection(target.resolve(), True)
1354
+ self.problems.append(f"runtime/current: {problem}")
1355
+ return None
1356
+
1357
+ def _receipt_target(self) -> Path | None:
1358
+ update_target = None
1359
+ try:
1360
+ payload = json.loads((self.home / "update-state.json").read_text(encoding="utf-8"))
1361
+ if not isinstance(payload, dict):
1362
+ raise ValueError("not a JSON object")
1363
+ raw = payload.get("runtime_target")
1364
+ if raw is not None and not isinstance(raw, str):
1365
+ raise ValueError("runtime_target is not a path")
1366
+ # Every installation's release check records the interpreter it runs
1367
+ # from here, managed or not. Only an entry of this home's runtime
1368
+ # directory commits the installation to managed code.
1369
+ if raw and raw.strip() and _names_runtime_entry(Path(raw), self.root):
1370
+ update_target = Path(raw)
1371
+ self.managed = True
1372
+ except FileNotFoundError:
1373
+ # A dangling receipt link is damaged evidence, not a fresh install.
1374
+ try:
1375
+ (self.home / "update-state.json").lstat()
1376
+ except FileNotFoundError:
1377
+ self.problems.append("update-state.json: missing")
1378
+ except OSError as exc:
1379
+ self.managed = True
1380
+ self.problems.append(f"update-state.json: unreadable ({exception_reason(exc)})")
1381
+ else:
1382
+ self.managed = True
1383
+ self.problems.append("update-state.json: broken link")
1384
+ except (OSError, ValueError) as exc:
1385
+ self.managed = True
1386
+ self.problems.append(f"update-state.json: unreadable or malformed ({exception_reason(exc)})")
1387
+ return update_target
1388
+
1389
+ def _from_receipt(self) -> RuntimeSelection | None:
1390
+ update_target = self._receipt_target()
1391
+ if update_target is not None:
1392
+ problem = runtime_target_problem(update_target, self.root) or runtime_fallback_problem(update_target)
1393
+ if problem is None:
1394
+ return RuntimeSelection(update_target.resolve(), True)
1395
+ self.problems.append(f"update-state.json runtime_target: {problem}")
1396
+ return None
1397
+
1398
+ def _ordered_targets(self, entries):
1399
+ candidates = []
1400
+ for path in entries:
1401
+ try:
1402
+ candidates.append((-path.lstat().st_mtime_ns, path.name, path))
1403
+ except OSError as exc:
1404
+ self.problems.append(f"runtime/{path.name}: unreadable ({exception_reason(exc)})")
1405
+ return sorted(candidates)
1406
+
1407
+ def _from_fallback(self) -> RuntimeSelection:
1408
+ try:
1409
+ entries = [path for path in self.root.iterdir() if path.name.startswith("daecore-")]
1410
+ except FileNotFoundError:
1411
+ entries = []
1412
+ try:
1413
+ self.root.lstat()
1414
+ except FileNotFoundError:
1415
+ pass
1416
+ except OSError:
1417
+ self.managed = True
1418
+ else:
1419
+ self.managed = True
1420
+ except OSError as exc:
1421
+ self.managed = True
1422
+ self.problems.append(f"runtime/daecore-*: directory unreadable ({exception_reason(exc)})")
1423
+ return RuntimeSelection(None, self.managed, tuple(self.problems))
1424
+ if not self.managed:
1425
+ return RuntimeSelection(None, False)
1426
+ for _mtime, _name, target in self._ordered_targets(entries):
1427
+ problem = runtime_target_problem(target, self.root) or runtime_fallback_problem(target)
1428
+ if problem is None:
1429
+ return RuntimeSelection(target.resolve(), True)
1430
+ self.problems.append(f"runtime/{target.name}: {problem}")
1431
+ self.problems.append("runtime/daecore-*: no verified eligible candidate")
1432
+ return RuntimeSelection(None, True, tuple(self.problems))
1433
+ # END GENERATED RUNTIME SELECTION
1434
+
1435
+
1436
+ def managed_python_root() -> Path:
1437
+ """The private folder holding managed Pythons, outside any home and off PATH.
1438
+
1439
+ A home relocation does not move it, so a host configuration naming one of its
1440
+ interpreters stays valid, and an ordinary ``uv python uninstall`` does not look here.
1441
+ The relay script hosts launch sits beside it, in ``relay``, for the same reason.
1442
+ """
1443
+ if os.name == 'nt':
1444
+ base = os.environ.get('LOCALAPPDATA')
1445
+ return (Path(base) if base else Path.home() / 'AppData' / 'Local') / 'Daecore' / 'python'
1446
+ if sys.platform == 'darwin':
1447
+ return Path.home() / 'Library' / 'Application Support' / 'Daecore' / 'python'
1448
+ base = os.environ.get('XDG_DATA_HOME')
1449
+ return (Path(base) if base else Path.home() / '.local' / 'share') / 'daecore' / 'python'
1450
+
1451
+
1452
+ def remove_managed_python(ran_on: Path | None) -> str | None:
1453
+ """After a purge, remove the managed Pythons if the runtime it removed ran on them.
1454
+
1455
+ They belong to the one installation a user account has, so a runtime that ran on
1456
+ another Python, such as a source checkout's, leaves them alone. The relay script beside
1457
+ them belongs to that same installation and goes with them. A purge calls this from
1458
+ outside them on Windows, where a running interpreter cannot be deleted. They are moved
1459
+ aside before they are deleted: deleted in place, a Python some program still ran would
1460
+ keep only the files that program held, which uv neither starts nor installs over. Moved,
1461
+ the place is empty for the next install. Returns what stayed, for the purge to report.
1462
+ """
1463
+ import time
1464
+
1465
+ root = managed_python_root()
1466
+ try:
1467
+ if ran_on is None or root.resolve() not in Path(ran_on).resolve().parents:
1468
+ return None
1469
+ except (OSError, RuntimeError):
1470
+ return None
1471
+ try:
1472
+ os.replace(root, root.with_name(f'{root.name}-removing-{time.time_ns()}'))
1473
+ except FileNotFoundError:
1474
+ pass # Gone already; a copy an earlier purge moved aside may still be there.
1475
+ except OSError as exc:
1476
+ # Whatever blocks the move would keep files through a delete as well, so the Python stays whole.
1477
+ return f'{root} remains: {exception_reason(exc)}'
1478
+ import shutil
1479
+
1480
+ # A relay still running has read its script already, so the file can go under it.
1481
+ shutil.rmtree(root.with_name('relay'), ignore_errors=True)
1482
+ left = sweep_moved_pythons(root)
1483
+ return f'files a program still uses remain in {", ".join(left)}' if left else None
1484
+
1485
+
1486
+ def sweep_moved_pythons(root: Path) -> list[str]:
1487
+ """Delete the managed Pythons a removal moved aside, and return those a program still holds."""
1488
+ import shutil
1489
+
1490
+ if not file_probe.path_is_dir(root.parent):
1491
+ return []
1492
+ left = []
1493
+ for aside in root.parent.iterdir():
1494
+ if aside.name.startswith(f'{root.name}-removing-'):
1495
+ shutil.rmtree(aside, ignore_errors=True)
1496
+ if file_probe.path_exists(aside, follow_symlinks=False):
1497
+ left.append(str(aside))
1498
+ return left
1499
+
1500
+
1501
+ def forget_home_location(home: Path) -> None:
1502
+ """After a purge removed ``home``, remove the record that names it.
1503
+
1504
+ A later setup then starts at the default folder. Until the home is gone the record stays, so
1505
+ a purge that could not finish is found again by the next ``daecore uninstall``. A record
1506
+ naming another folder belongs to another installation and stays.
1507
+ """
1508
+ try:
1509
+ recorded = read_home_pointer()
1510
+ if recorded is not None and os.path.normcase(os.path.abspath(recorded)) == os.path.normcase(
1511
+ os.path.abspath(home)):
1512
+ home_pointer_path().unlink()
1513
+ except (OSError, RuntimeError):
1514
+ # A record left behind only makes the next setup offer the folder it names.
1515
+ pass
1516
+
1517
+
1518
+ def remove_uninstalled_runtime(home: Path, target: Path, *, purge: bool) -> int:
1519
+ """Finish an uninstall by removing the runtime it ran from.
1520
+
1521
+ Windows refuses to delete a program while it runs, so the uninstall leaves
1522
+ ``runtime/`` to this launcher, which runs from outside it and outlives it.
1523
+ The exclusive pin proves that nothing still runs from that runtime and keeps
1524
+ new processes out; the move alone proves nothing, because Windows moves a
1525
+ folder with a program running from it. The move then takes the pointer and
1526
+ every runtime together, once: a runtime in use stays whole and working, and
1527
+ one rebuilt after the move is never touched.
1528
+ """
1529
+ import shutil
1530
+ import stat
1531
+ import time
1532
+
1533
+ # Read while the runtime is still here: a purge removes the managed Pythons only if it ran on them.
1534
+ ran_on = venv_base_python(target) if purge else None
1535
+ root = home / "runtime"
1536
+ aside = home / f".runtime-removing-{os.getpid()}"
1537
+ text = os.path.abspath(aside)
1538
+ # Retired runtimes can exceed the ordinary Windows path limit.
1539
+ extended = text if text.startswith("\\\\") else "\\\\?\\" + text
1540
+
1541
+ def clear_read_only(function, path, exc):
1542
+ if function not in (os.unlink, os.rmdir):
1543
+ raise exc
1544
+ os.chmod(path, stat.S_IWRITE)
1545
+ function(path)
1546
+
1547
+ def move_aside():
1548
+ with contextlib.ExitStack() as held:
1549
+ pin = None
1550
+ if runtime_use_record(target) is not None:
1551
+ pin = held.enter_context(RuntimeUsePin(target, exclusive=True, home=home))
1552
+ with contextlib.suppress(FileNotFoundError):
1553
+ os.replace(root, aside)
1554
+ if pin is not None:
1555
+ pin.retire_gate(aside / target.name)
1556
+
1557
+ left = root
1558
+ deadline = time.monotonic() + RUNTIME_REMOVAL_WAIT_SECONDS
1559
+ while True:
1560
+ try:
1561
+ if left == root:
1562
+ move_aside()
1563
+ left = aside
1564
+ if left == aside:
1565
+ # A file going during the walk raises this too, so only the check below says it finished.
1566
+ with contextlib.suppress(FileNotFoundError):
1567
+ shutil.rmtree(extended, onexc=clear_read_only)
1568
+ if file_probe.path_exists(aside, follow_symlinks=False):
1569
+ raise OSError("its files kept changing")
1570
+ left = home
1571
+ if purge:
1572
+ with contextlib.suppress(FileNotFoundError):
1573
+ os.rmdir(home)
1574
+ forget_home_location(home)
1575
+ left_outside = remove_managed_python(ran_on)
1576
+ if left_outside:
1577
+ # Outside the home, like leftover lock files: the purge itself has finished.
1578
+ print(f"daecore: uninstall finished, but {left_outside}. Delete it once nothing is using it.",
1579
+ file=sys.stderr)
1580
+ return 0
1581
+ except OSError as exc:
1582
+ problem = exception_reason(exc)
1583
+ if time.monotonic() >= deadline:
1584
+ remedy = ("Close any program using it and run `daecore uninstall` again." if left == root
1585
+ else "Delete it once nothing is using it.")
1586
+ print(f"daecore: uninstall finished, but {left} remains: {problem}. {remedy}", file=sys.stderr)
1587
+ return 1
1588
+ time.sleep(0.1)
1589
+
1590
+
1591
+ _HELP = frozenset({'-h', '--help'})
1592
+ _UPDATE_IN_RUNTIME = frozenset({'--models', '--classifier'})
1593
+ _SETUP_IN_RUNTIME = frozenset({'--check', '--guide', '--refresh-templates', '--accelerator'})
1594
+ #: The one sentence every surface says before setup: this launcher, status, doctor and memory health.
1595
+ NOT_SET_UP = 'Daecore is not set up yet'
1596
+ _UNINSTALL_JOURNAL = 'uninstall-transaction.json'
1597
+ #: In a handover's staging folder: the runtime a release built to finish an uninstall, for the launcher to remove.
1598
+ UNINSTALL_RUNTIME_NAME = 'uninstall-runtime'
1599
+ _HANDOVER_SCHEMA = 1
1600
+
1601
+
1602
+ def _verb(args: list[str]) -> str | None:
1603
+ return next((arg for arg in args if not arg.startswith('-')), None)
1604
+
1605
+
1606
+ def _names_option(args: list[str], names: frozenset[str]) -> bool:
1607
+ return any(arg.split('=', 1)[0] in names for arg in args)
1608
+
1609
+
1610
+ def _source_tree(args: list[str]) -> str | None:
1611
+ for index, arg in enumerate(args):
1612
+ name, separator, value = arg.partition('=')
1613
+ if name == '--source':
1614
+ return value if separator else next(iter(args[index + 1:]), '')
1615
+ return None
1616
+
1617
+
1618
+ def own_version() -> str | None:
1619
+ try:
1620
+ return metadata.version('daecore')
1621
+ except metadata.PackageNotFoundError:
1622
+ return None
1623
+
1624
+
1625
+ def uninstall_unfinished(home: Path) -> bool:
1626
+ """Whether an uninstall began here and its journal does not say it finished."""
1627
+ try:
1628
+ journal = _runtime_control_lifecycle_state_dir(home) / _UNINSTALL_JOURNAL
1629
+ except (OSError, ValueError):
1630
+ return False
1631
+ if not file_probe.path_exists(journal):
1632
+ return False
1633
+ try:
1634
+ return json.loads(journal.read_text(encoding='utf-8')).get('phase') != 'complete'
1635
+ except (OSError, ValueError, AttributeError):
1636
+ # A journal that stands but cannot be read is not a finished uninstall.
1637
+ return True
1638
+
1639
+
1640
+ def handover_route(command: str, args: list[str], selection: RuntimeSelection,
1641
+ home: Path | None = None) -> tuple[str, dict] | None:
1642
+ """The mode and artifact a command needs staged, or ``None`` to run it in the runtime."""
1643
+ if command != 'daecore' or _names_option(args, _HELP):
1644
+ return None
1645
+ verb = _verb(args)
1646
+ if (verb == 'uninstall' and selection.target is None and home is not None
1647
+ and uninstall_unfinished(home)):
1648
+ # Only a runtime can finish it, so the newest release brings one and runs the uninstall again.
1649
+ return 'repair', {'kind': 'index', 'version': None}
1650
+ if verb == 'update' and not _names_option(args, _UPDATE_IN_RUNTIME):
1651
+ tree = _source_tree(args)
1652
+ if tree is not None:
1653
+ return 'update', {'kind': 'source', 'tree': str(Path(tree).resolve())}
1654
+ return 'update' if selection.target is not None else 'repair', {'kind': 'index', 'version': None}
1655
+ if (verb == 'setup' and selection.target is None and not selection.managed
1656
+ and not _names_option(args, _SETUP_IN_RUNTIME)):
1657
+ return 'provision', {'kind': 'index', 'version': own_version()}
1658
+ return None
1659
+
1660
+
1661
+ class Loader:
1662
+ """The loader beside work the launcher waits on, gone when the install code takes over.
1663
+
1664
+ It draws as ``daecore.term`` does: nothing for the command's first second, then the
1665
+ logo's diamond and the work's time on a colour UTF-8 terminal, or one line on a terminal
1666
+ without animation, and nothing on a pipe. tests/term/test_install_screen.py keeps these
1667
+ values equal to the terminal package's. Drawing never fails the command.
1668
+ """
1669
+
1670
+ DELAY = 1.0
1671
+ FRAME_SECONDS = 0.15
1672
+ FRAMES = ('⠐⠔', '⠐⠅', '⠐⠑', '⠀⠕')
1673
+
1674
+ def __init__(self, label: str, *, stream=None) -> None:
1675
+ self.label = label
1676
+ self.stream = sys.stdout if stream is None else stream
1677
+ self.started = time.time()
1678
+ tty = _isatty(self.stream)
1679
+ self.live = tty and _color(self.stream) and _unicode(self.stream)
1680
+ self.plain_tty = tty and not self.live
1681
+ self.written = False
1682
+ self._drawn = False
1683
+ self._stop = threading.Event()
1684
+ self._lock = threading.Lock()
1685
+ self._thread = None
1686
+
1687
+ def __enter__(self) -> Loader:
1688
+ if self.live or self.plain_tty:
1689
+ if self.live:
1690
+ _enable_windows_vt()
1691
+ self._thread = threading.Thread(target=self._run, daemon=True)
1692
+ self._thread.start()
1693
+ return self
1694
+
1695
+ def __exit__(self, *_error) -> None:
1696
+ self._stop.set()
1697
+ if self._thread is not None:
1698
+ self._thread.join(timeout=1.0)
1699
+ with self._lock:
1700
+ if self._drawn:
1701
+ self._write('\r\x1b[K')
1702
+ self._drawn = False
1703
+
1704
+ def state(self) -> dict:
1705
+ """What the install code needs to continue this screen: when the command began, and
1706
+ which line a terminal without animation already shows."""
1707
+ return {'started': self.started, 'label': self.label, 'written': self.written}
1708
+
1709
+ def _write(self, text: str) -> None:
1710
+ try:
1711
+ self.stream.write(text)
1712
+ self.stream.flush()
1713
+ except (OSError, ValueError, UnicodeError):
1714
+ pass
1715
+
1716
+ def _row(self, now: float) -> str:
1717
+ """The row as the terminal package draws a wait: the diamond, the work and its time,
1718
+ cut to the terminal's width, since a wrapped row could not be repainted in place."""
1719
+ frame = self.FRAMES[int(max(0.0, now - self.started - self.DELAY) / self.FRAME_SECONDS) % len(self.FRAMES)]
1720
+ timing = f' · {_fmt_secs(max(0.0, now - self.started))}'
1721
+ lead = ' ' * (4 - len(frame) - 1)
1722
+ width = _row_width(self.stream)
1723
+ if len(lead + frame + ' ' + self.label + '...' + timing) > width:
1724
+ return lead + frame + ' ' + (self.label + '...' + timing)[:max(1, width - 4)]
1725
+ return lead + _styled(frame, '1', self.stream) + ' ' + self.label + '...' + _styled(timing, '2', self.stream)
1726
+
1727
+ def _run(self) -> None:
1728
+ if self._stop.wait(max(0.0, self.started + self.DELAY - time.time())):
1729
+ return
1730
+ if self.plain_tty:
1731
+ with self._lock:
1732
+ if not self._stop.is_set():
1733
+ self._write(' ' * 4 + self.label + '...\n')
1734
+ self.written = True
1735
+ return
1736
+ while True:
1737
+ with self._lock:
1738
+ if self._stop.is_set():
1739
+ return
1740
+ self._write('\r' + self._row(time.time()) + '\x1b[K')
1741
+ self._drawn = True
1742
+ if self._stop.wait(self.FRAME_SECONDS):
1743
+ return
1744
+
1745
+ def cancel_line(self, note: str, stream) -> str:
1746
+ """The line every interrupted command ends with: ``‒ Cancelled``, its time, and what survived."""
1747
+ mark, dot, dash = ('‒', '·', '—') if _unicode(stream) else ('-', '-', '--')
1748
+ return ('\n' + _styled(mark, '33', stream) + ' ' + _styled('Cancelled', '1', stream)
1749
+ + _styled(f' {dot} {_fmt_secs(max(0.0, time.time() - self.started))}', '2', stream)
1750
+ + ' ' + _styled(f'{dash} ', '2', stream) + _styled(note, '2', stream) + '\n')
1751
+
1752
+ def cancelled(self, note: str) -> None:
1753
+ try:
1754
+ sys.stderr.write(self.cancel_line(note, sys.stderr))
1755
+ sys.stderr.flush()
1756
+ except (OSError, ValueError, UnicodeError):
1757
+ pass
1758
+
1759
+
1760
+ def _row_width(stream) -> int:
1761
+ """The columns a repainted row may use, two short of the terminal's against wrapping."""
1762
+ try:
1763
+ columns = os.get_terminal_size(stream.fileno()).columns
1764
+ except (AttributeError, OSError, ValueError):
1765
+ columns = 80
1766
+ return max(24, columns) - 2
1767
+
1768
+
1769
+ def _isatty(stream) -> bool:
1770
+ try:
1771
+ return bool(stream.isatty())
1772
+ except Exception: # noqa: BLE001 - a stream without isatty is not a terminal
1773
+ return False
1774
+
1775
+
1776
+ def _color(stream) -> bool:
1777
+ if os.environ.get('NO_COLOR'):
1778
+ return False
1779
+ return os.environ.get('FORCE_COLOR', '').strip().lower() in {'1', 'true', 'yes', 'on'} or _isatty(stream)
1780
+
1781
+
1782
+ def _unicode(stream) -> bool:
1783
+ return 'utf' in (getattr(stream, 'encoding', '') or '').lower()
1784
+
1785
+
1786
+ def _styled(text: str, code: str, stream) -> str:
1787
+ return f'\x1b[{code}m{text}\x1b[0m' if _color(stream) else text
1788
+
1789
+
1790
+ def _fmt_secs(seconds: float) -> str:
1791
+ if seconds >= 60:
1792
+ minutes, rest = divmod(int(round(seconds)), 60)
1793
+ return f'{minutes}m {rest:02d}s'
1794
+ return f'{seconds:.1f}s'
1795
+
1796
+
1797
+ def _enable_windows_vt() -> None:
1798
+ """Let a Windows console read the escape codes the loader repaints with."""
1799
+ if os.name != 'nt':
1800
+ return
1801
+ try:
1802
+ import ctypes
1803
+
1804
+ kernel32 = ctypes.windll.kernel32
1805
+ for handle_id in (-11, -12): # stdout, stderr
1806
+ handle = kernel32.GetStdHandle(handle_id)
1807
+ mode = ctypes.c_uint32()
1808
+ if kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
1809
+ kernel32.SetConsoleMode(handle, mode.value | 0x0004)
1810
+ except Exception: # noqa: BLE001 - colour is cosmetic; the words still print
1811
+ pass
1812
+
1813
+
1814
+ def seed_uv() -> str | None:
1815
+ beside = Path(sys.executable).parent / ('uv.exe' if os.name == 'nt' else 'uv')
1816
+ if file_probe.path_is_file(beside):
1817
+ return str(beside)
1818
+ import shutil
1819
+
1820
+ return shutil.which('uv')
1821
+
1822
+
1823
+ def stage_release(uv: str, version: str | None, staging: Path) -> str | None:
1824
+ """Place a release's files in ``staging``; why it could not, or ``None``.
1825
+
1826
+ uv runs from a private empty folder, so a project's ``uv.toml`` or ``pyproject.toml``
1827
+ in the current folder or the folders above it cannot redirect it. User-level uv
1828
+ settings and uv's index variables still apply. Without a version this asks for the
1829
+ newest stable release; the launcher compares no versions, because that release's
1830
+ handover decides whether there is anything to do.
1831
+ """
1832
+ settings = staging / 'settings'
1833
+ settings.mkdir()
1834
+ (settings / 'uv.toml').write_text('', encoding='utf-8')
1835
+ (settings / 'pyproject.toml').write_text(
1836
+ '[project]\nname = "daecore-staging"\nversion = "0"\n[tool.uv.workspace]\nmembers = []\n',
1837
+ encoding='utf-8',
1838
+ )
1839
+ done = subprocess.run(
1840
+ [uv, 'pip', 'install', '--python', sys.executable, '--no-deps', '--only-binary', 'daecore',
1841
+ '--resolution', 'highest', '--refresh-package', 'daecore', '--target', str(staging / 'release'),
1842
+ *(('--prerelease', 'disallow', 'daecore') if version is None else (f'daecore=={version}',))],
1843
+ cwd=settings, env=child_environment(), stdin=subprocess.DEVNULL, capture_output=True, text=True,
1844
+ encoding='utf-8', errors='replace', check=False,
1845
+ **({'creationflags': subprocess.CREATE_NO_WINDOW} if os.name == 'nt' else {}),
1846
+ )
1847
+ if done.returncode:
1848
+ return done.stderr.strip() or f'uv exited {done.returncode}'
1849
+ return None
1850
+
1851
+
1852
+ def console_handoff_kwargs() -> dict:
1853
+ """Keep a child on this console, or on a windowless host's pipes."""
1854
+ if os.name != 'nt':
1855
+ return {}
1856
+ import ctypes
1857
+
1858
+ console_window = ctypes.windll.kernel32.GetConsoleWindow
1859
+ console_window.restype = ctypes.c_void_p
1860
+ if console_window():
1861
+ return {'creationflags': 0}
1862
+ # A host without a console still owns MCP pipes. Pass its usable
1863
+ # descriptors explicitly; missing streams must never allocate one.
1864
+ kwargs = {'creationflags': subprocess.CREATE_NO_WINDOW}
1865
+ for name in ('stdin', 'stdout', 'stderr'):
1866
+ stream = getattr(sys, name, None)
1867
+ try:
1868
+ os.fstat(stream.fileno())
1869
+ except (AttributeError, OSError, TypeError, ValueError):
1870
+ stream = subprocess.DEVNULL
1871
+ kwargs[name] = stream
1872
+ return kwargs
1873
+
1874
+
1875
+ def _recover_from_kit(home: Path, request: dict, staging: Path, environment: dict) -> int | None:
1876
+ """With no way to stage, let an interrupted update finish from its own recovery kit.
1877
+
1878
+ This is the only time the launcher runs recorded code. Anything unreadable here means
1879
+ there is no kit to run, and the caller reports why staging failed.
1880
+ """
1881
+ try:
1882
+ pending = json.loads((home / 'runtime-update.json').read_text(encoding='utf-8'))
1883
+ kit = home / 'recovery' / 'updates' / str(pending['id']) / 'kit' / 'daecore' / '_handover.py'
1884
+ except (OSError, ValueError, KeyError, TypeError):
1885
+ return None
1886
+ if not file_probe.path_is_file(kit):
1887
+ return None
1888
+ return _run_handover(kit, {**request, 'mode': 'recover'}, staging, environment)
1889
+
1890
+
1891
+ def wait_for_child(command: list[str], **options) -> int:
1892
+ """Run a command on this terminal, and return its exit code.
1893
+
1894
+ Ctrl+C reaches the child as well, so the child decides what an interrupt means and this
1895
+ waits for it. ``subprocess.run`` would kill the child a moment after the first interrupt.
1896
+ """
1897
+ with subprocess.Popen(command, **console_handoff_kwargs(), **options) as child:
1898
+ while True:
1899
+ try:
1900
+ return child.wait()
1901
+ except KeyboardInterrupt:
1902
+ continue
1903
+
1904
+
1905
+ def _run_handover(handover: Path, request: dict, staging: Path, environment: dict) -> int:
1906
+ path = staging / 'request.json'
1907
+ path.write_text(json.dumps(request), encoding='utf-8')
1908
+ return wait_for_child([sys.executable, '-I', str(handover), str(path)], env=environment)
1909
+
1910
+
1911
+ def _remove_handed_over_runtime(home: Path, staging: Path, *, purge: bool) -> int:
1912
+ """Remove the runtime a staged release built to finish an uninstall, once nothing runs from it."""
1913
+ try:
1914
+ target = Path((staging / UNINSTALL_RUNTIME_NAME).read_text(encoding='utf-8'))
1915
+ except OSError:
1916
+ print('daecore: the uninstall finished, but its runtime remains; run `daecore uninstall` again',
1917
+ file=sys.stderr)
1918
+ return 1
1919
+ return remove_uninstalled_runtime(home, target, purge=purge)
1920
+
1921
+
1922
+ def _staging_problem(uv: str | None, mode: str, artifact: dict, staging: Path) -> str | None:
1923
+ """Why no release could be staged, or ``None`` once one is."""
1924
+ if uv is None:
1925
+ return 'the uv Daecore installs with is missing; reinstall the Daecore command'
1926
+ if mode == 'provision' and artifact['version'] is None:
1927
+ return 'could not fetch Daecore: the Daecore command does not know its own version; reinstall it'
1928
+ try:
1929
+ problem = stage_release(uv, artifact['version'], staging)
1930
+ except OSError as exc:
1931
+ problem = f'uv could not start ({exception_reason(exc)})'
1932
+ return None if problem is None else f'could not fetch Daecore: {problem}'
1933
+
1934
+
1935
+ def hand_over(home: Path, args: list[str], mode: str, artifact: dict) -> int:
1936
+ """Stage what ``artifact`` names and give it control; nothing after this is the launcher's.
1937
+
1938
+ When nothing can be staged, a missing or broken uv included, an interrupted update still
1939
+ finishes from its own kit, which needs neither once its candidate is there. The loader
1940
+ shows while the release downloads; Ctrl-C then ends with the line every command ends with.
1941
+ """
1942
+ loader = Loader('Checking for updates')
1943
+ try:
1944
+ return _hand_over(home, args, mode, artifact, loader)
1945
+ except KeyboardInterrupt:
1946
+ loader.cancelled('nothing changed')
1947
+ return 130
1948
+
1949
+
1950
+ def _hand_over(home: Path, args: list[str], mode: str, artifact: dict, loader: Loader) -> int:
1951
+ uv = seed_uv()
1952
+ environment = child_environment()
1953
+ if (seed := _managed_seed_venv(Path(sys.prefix).resolve())) is not None:
1954
+ environment[_SEED_ENV_VAR] = str(seed)
1955
+ # A release that finishes an uninstall runs it from a runtime Windows cannot delete while it
1956
+ # runs, nor the managed Python under it, so this launcher removes both once they exit.
1957
+ waiting = os.name == 'nt' and _verb(args) == 'uninstall'
1958
+ if waiting:
1959
+ environment['DAECORE_LAUNCHER_WAITING'] = '1'
1960
+ with tempfile.TemporaryDirectory(prefix='daecore-stage-', ignore_cleanup_errors=True) as directory:
1961
+ staging = Path(directory)
1962
+ request = {
1963
+ 'schema': _HANDOVER_SCHEMA, 'mode': mode, 'home': str(home), 'launcher_python': sys.executable,
1964
+ 'python_root': str(managed_python_root()), 'uv': uv, 'staging': str(staging), 'argv': args,
1965
+ 'artifact': artifact, 'screen': loader.state(),
1966
+ }
1967
+ if artifact['kind'] == 'source' and uv is not None:
1968
+ handover = Path(artifact['tree']) / 'src' / 'daecore' / '_handover.py'
1969
+ if not file_probe.path_is_file(handover):
1970
+ print(f'daecore: {artifact["tree"]} is not a Daecore source tree', file=sys.stderr)
1971
+ return 1
1972
+ return _run_handover(handover, request, staging, environment)
1973
+ with loader:
1974
+ problem = _staging_problem(uv, mode, artifact, staging)
1975
+ request['screen'] = loader.state()
1976
+ if problem is not None:
1977
+ recovered = _recover_from_kit(home, request, staging, environment)
1978
+ if recovered is None:
1979
+ print(f'daecore: {problem}', file=sys.stderr)
1980
+ return 1 if recovered is None else recovered
1981
+ code = _run_handover(staging / 'release' / 'daecore' / '_handover.py', request, staging, environment)
1982
+ if waiting and code in (REMOVE_RUNTIME_EXIT, REMOVE_HOME_EXIT):
1983
+ return _remove_handed_over_runtime(home, staging, purge=code == REMOVE_HOME_EXIT)
1984
+ return code
1985
+
1986
+
1987
+ def not_set_up_answer(stream, *, guide: bool = False) -> str:
1988
+ """The answer before setup, in the row layout Daecore's own screens use, without colour.
1989
+
1990
+ ``guide`` says why ``setup --guide`` cannot answer yet: it shows a connection setup creates.
1991
+ """
1992
+ mark, dash = ('▲', '—') if _unicode(stream) else ('!', '--')
1993
+ if guide:
1994
+ return (f' {mark} {NOT_SET_UP} {dash} the guide shows the connection setup creates\n'
1995
+ ' fix: run daecore setup, then daecore setup --guide\n')
1996
+ return f' {mark} {NOT_SET_UP}\n fix: daecore setup\n'
1997
+
1998
+
1999
+ def answer_without_runtime(command: str, args: list[str], selection: RuntimeSelection) -> int:
2000
+ """Answer the few things a launcher with no runtime can."""
2001
+ if selection.managed:
2002
+ print(f'{command}: {selection.refusal()}. To repair, run `daecore update`.', file=sys.stderr)
2003
+ return 1
2004
+ if command == 'daecore' and '--version' in args:
2005
+ print(f'daecore {own_version() or "version unknown"}')
2006
+ return 0
2007
+ if command != 'daecore':
2008
+ # An agent host keeps this in its log, where one line reads best.
2009
+ print(f'{command}: {NOT_SET_UP}; run daecore setup', file=sys.stderr)
2010
+ return 1
2011
+ asked = _names_option(args, _HELP)
2012
+ stream = sys.stdout if asked else sys.stderr
2013
+ guide = not asked and _verb(args) == 'setup' and _names_option(args, frozenset({'--guide'}))
2014
+ try:
2015
+ stream.write(not_set_up_answer(stream, guide=guide))
2016
+ stream.flush()
2017
+ except (OSError, ValueError, UnicodeError):
2018
+ pass
2019
+ return 0 if asked else 1
2020
+
2021
+
2022
+ def runtime_command(command: str, target: Path, args: list[str]) -> list[str]:
2023
+ """The command line that runs ``command`` in the selected runtime.
2024
+
2025
+ A retained runtime can have an older stub that trusts raw current and
2026
+ redirects straight back to the target we rejected. Enter its installed
2027
+ package directly, with isolated imports, after making our one selection.
2028
+ These are the same public entry functions used by the console scripts.
2029
+ """
2030
+ module = "daecore.scripts.mcp_launcher" if command == "daecore-mcp" else "daecore.cli"
2031
+ bootstrap = (
2032
+ f"import sys; sys.argv[0] = {command!r}; from {module} import main; "
2033
+ + ("main()" if command == "daecore-mcp" else "sys.exit(main())")
2034
+ )
2035
+ python = target / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
2036
+ return [str(python), "-I", "-c", bootstrap, *args]
2037
+
2038
+
2039
+ def rename_handed_over_home(command: str, environment: dict, *, started: float) -> int:
2040
+ """Rename the home as the move's note asks, then start the runtime again to finish and report.
2041
+
2042
+ The runtime ran from inside the home, so it prepared the move and left the note. The run
2043
+ started here learns what became of the rename and continues the same screen, timed from
2044
+ ``started``. A rename this launcher refuses changed nothing, and that run copies instead.
2045
+ """
2046
+ try:
2047
+ note = read_rename_note()
2048
+ except (OSError, ValueError) as exc:
2049
+ print(f'daecore: the move cannot continue: its note is unreadable ({exception_reason(exc)}); '
2050
+ 'run `daecore status`', file=sys.stderr)
2051
+ return 1
2052
+ if note is None:
2053
+ # Only recovery removes the note, and it undoes the move as it does.
2054
+ print('daecore: the move was undone before its folder could be renamed; nothing was moved, so run it '
2055
+ 'again', file=sys.stderr)
2056
+ return 1
2057
+ try:
2058
+ # Under the lock recovery takes, the note is read again: a recovery that ran meanwhile undid the move.
2059
+ with held_lifecycle_lock():
2060
+ current = read_rename_note()
2061
+ reason = ('Daecore undid the move before it could be renamed'
2062
+ if current is None or current['journal'] != note['journal'] else rename_by_note(current))
2063
+ except (OSError, ValueError, TimeoutError) as exc:
2064
+ reason = f'the home could not be renamed ({exception_reason(exc)})'
2065
+ selection = select_runtime(finish_interrupted_rename(daecore_home()))
2066
+ if selection.target is None:
2067
+ return answer_without_runtime(command, sys.argv[1:], selection)
2068
+ outcome = json.dumps({'journal': note['journal'], 'renamed': reason is None, 'reason': reason})
2069
+ rerun = {**environment, 'DAECORE_RENAME_OUTCOME': outcome, SCREEN_HANDOFF: json.dumps({'started': started})}
2070
+ return runtime_run(runtime_command(command, selection.target, sys.argv[1:]), env=rerun,
2071
+ **console_handoff_kwargs()).returncode
2072
+
2073
+
2074
+ def main() -> None:
2075
+ """Entry point for both public console scripts, selected by executable name.
2076
+
2077
+ Every managed target receives an isolated handoff with the original
2078
+ arguments and console. The handoff enters the package directly, so it does
2079
+ not invoke this stub again. Windows waits for the child so Ctrl-C, pipes
2080
+ and its exit code keep reaching the invoking terminal. POSIX replaces the
2081
+ process image.
2082
+ """
2083
+ command = "daecore-mcp" if Path(sys.argv[0]).stem.lower() == "daecore-mcp" else "daecore"
2084
+ args = sys.argv[1:]
2085
+ try:
2086
+ # A move that stopped between renaming the home and recording it is finished first, so no
2087
+ # command answers "not set up" or makes an empty home at the old name.
2088
+ home = finish_interrupted_rename(daecore_home())
2089
+ selection = select_runtime(home)
2090
+ route = handover_route(command, args, selection, home)
2091
+ if route is not None:
2092
+ sys.exit(hand_over(home, args, *route))
2093
+ except (OSError, ValueError, RuntimeError) as exc:
2094
+ print(f"daecore: {exc}", file=sys.stderr)
2095
+ sys.exit(1)
2096
+ except KeyboardInterrupt:
2097
+ # Interrupted before anything was handed over.
2098
+ sys.exit(130)
2099
+ target = selection.target
2100
+ if target is None:
2101
+ sys.exit(answer_without_runtime(command, args, selection))
2102
+
2103
+ own_venv = Path(sys.prefix).resolve()
2104
+ # Redirect the same logical command. The selected package validates
2105
+ # attempts, install journals and update ownership before using them.
2106
+ forwarded = {}
2107
+ waiting = False
2108
+ if command == 'daecore':
2109
+ forwarded = {name: value for name in (
2110
+ 'DAECORE_SERVE_HANDOFF', 'DAECORE_SPAWN_OUTCOME', 'DAECORE_INSTALL_TRANSACTION_ID',
2111
+ 'DAECORE_UPDATE_CONVERGENCE',
2112
+ ) if (value := os.environ.get(name)) is not None}
2113
+ # Windows waits for the child below. Only a launcher outside the
2114
+ # runtimes can remove one, so only that launcher offers to.
2115
+ waiting = os.name == 'nt' and not own_venv.is_relative_to((home / 'runtime').resolve())
2116
+ if waiting:
2117
+ forwarded['DAECORE_LAUNCHER_WAITING'] = '1'
2118
+ if _verb(args) == 'relocate':
2119
+ # A runtime cannot rename the home it runs from; this launcher, waiting outside it, can.
2120
+ forwarded['DAECORE_LAUNCHER_RENAMES'] = '1'
2121
+ env = child_environment(handoff=forwarded)
2122
+ if (seed := _managed_seed_venv(own_venv)) is not None:
2123
+ env[_SEED_ENV_VAR] = str(seed)
2124
+ elif runtime_target_problem(own_venv, home / 'runtime') is None:
2125
+ # An update candidate's wrapper may redirect once more. Preserve its
2126
+ # seed hint only for the final package's full provenance check.
2127
+ raw_seed = os.environ.get(_SEED_ENV_VAR)
2128
+ if raw_seed and (seed := _managed_seed_venv(Path(raw_seed))) is not None:
2129
+ env[_SEED_ENV_VAR] = str(seed)
2130
+ argv = runtime_command(command, target, sys.argv[1:])
2131
+
2132
+ if os.name == "nt":
2133
+ started = time.time()
2134
+ try:
2135
+ proc = runtime_run(argv, env=env, **console_handoff_kwargs())
2136
+ if waiting and proc.returncode in (REMOVE_RUNTIME_EXIT, REMOVE_HOME_EXIT):
2137
+ sys.exit(remove_uninstalled_runtime(home, target, purge=proc.returncode == REMOVE_HOME_EXIT))
2138
+ if waiting and proc.returncode == RENAME_HOME_EXIT:
2139
+ sys.exit(rename_handed_over_home(command, env, started=started))
2140
+ except KeyboardInterrupt:
2141
+ sys.exit(130)
2142
+ sys.exit(proc.returncode)
2143
+ else:
2144
+ with runtime_child(argv):
2145
+ os.execve(argv[0], argv, env)