agentera 3.0.0-dev.4 → 3.0.0-dev.46

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 (585) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +108 -22
  3. package/bundle/.agentera-npx-bundle.json +1 -1
  4. package/bundle/CHANGELOG.md +1351 -0
  5. package/bundle/DESIGN.md +229 -0
  6. package/bundle/LICENSE +201 -0
  7. package/bundle/README.md +143 -0
  8. package/bundle/UPGRADE.md +236 -0
  9. package/bundle/extract-corpus-parity.json +21 -0
  10. package/bundle/fixtures/routing/hybrid-corpus.yaml +154 -0
  11. package/bundle/references/adapters/package-publication.json +437 -0
  12. package/bundle/references/adapters/package-registry.yaml +434 -189
  13. package/bundle/references/adapters/package-surface-characterization.md +66 -35
  14. package/bundle/references/adapters/runtime-lifecycle-adapters.yaml +74 -0
  15. package/bundle/references/adapters/runtime-lifecycle-authority.yaml +62 -0
  16. package/bundle/references/adapters/runtime-lifecycle-operation-contract.yaml +84 -0
  17. package/bundle/references/adapters/runtime-retired-resources.yaml +333 -0
  18. package/bundle/references/analysis/evidence-tier-authority.yaml +518 -0
  19. package/bundle/references/analysis/verification-policy.yaml +191 -0
  20. package/bundle/references/artifacts/artifact-registry-interface-model.yaml +20 -10
  21. package/bundle/references/artifacts/glossary-entry-contract.yaml +1254 -0
  22. package/bundle/references/artifacts/state-storage-authority.yaml +2982 -0
  23. package/bundle/references/artifacts/verbosity-budget-authority.yaml +42 -0
  24. package/bundle/references/cli/app-lifecycle-vocabulary.yaml +7 -8
  25. package/bundle/references/cli/capability-instruction-contract.yaml +97 -59
  26. package/bundle/references/cli/hybrid-route-contract.yaml +438 -0
  27. package/bundle/references/cli/routing-model.md +155 -0
  28. package/bundle/references/cli/trigger-schema-enrichment.md +147 -0
  29. package/bundle/references/cli/update-channels.yaml +35 -2
  30. package/bundle/references/cli/vocabulary-index.yaml +23 -20
  31. package/bundle/references/cli/vocabulary.md +337 -366
  32. package/bundle/references/meta/retained-reference-authority.yaml +151 -0
  33. package/bundle/registry.json +14 -14
  34. package/bundle/skills/agentera/SKILL.md +218 -408
  35. package/bundle/skills/agentera/capabilities/audit/schemas/artifacts.yaml +84 -0
  36. package/bundle/skills/agentera/capabilities/{inspektera → audit}/schemas/exit.yaml +2 -2
  37. package/bundle/skills/agentera/capabilities/audit/schemas/triggers.yaml +25 -0
  38. package/bundle/skills/agentera/capabilities/{inspektera → audit}/schemas/validation.yaml +37 -18
  39. package/bundle/skills/agentera/capabilities/build/schemas/artifacts.yaml +102 -0
  40. package/bundle/skills/agentera/capabilities/{realisera → build}/schemas/exit.yaml +6 -5
  41. package/bundle/skills/agentera/capabilities/build/schemas/triggers.yaml +27 -0
  42. package/bundle/skills/agentera/capabilities/build/schemas/validation.yaml +176 -0
  43. package/bundle/skills/agentera/capabilities/{visualisera → design}/schemas/artifacts.yaml +12 -12
  44. package/bundle/skills/agentera/capabilities/{visualisera → design}/schemas/exit.yaml +5 -5
  45. package/bundle/skills/agentera/capabilities/design/schemas/triggers.yaml +16 -0
  46. package/bundle/skills/agentera/capabilities/{visualisera → design}/schemas/validation.yaml +7 -7
  47. package/bundle/skills/agentera/capabilities/discuss/schemas/artifacts.yaml +51 -0
  48. package/bundle/skills/agentera/capabilities/{resonera → discuss}/schemas/exit.yaml +2 -2
  49. package/bundle/skills/agentera/capabilities/discuss/schemas/triggers.yaml +20 -0
  50. package/bundle/skills/agentera/capabilities/discuss/schemas/validation.yaml +144 -0
  51. package/bundle/skills/agentera/capabilities/document/schemas/artifacts.yaml +80 -0
  52. package/bundle/skills/agentera/capabilities/document/schemas/triggers.yaml +16 -0
  53. package/bundle/skills/agentera/capabilities/{dokumentera → document}/schemas/validation.yaml +18 -18
  54. package/bundle/skills/agentera/capabilities/{optimera → optimize}/schemas/artifacts.yaml +18 -18
  55. package/bundle/skills/agentera/capabilities/{optimera → optimize}/schemas/exit.yaml +2 -2
  56. package/bundle/skills/agentera/capabilities/optimize/schemas/triggers.yaml +16 -0
  57. package/bundle/skills/agentera/capabilities/{optimera → optimize}/schemas/validation.yaml +9 -9
  58. package/bundle/skills/agentera/capabilities/orchestrate/schemas/artifacts.yaml +76 -0
  59. package/bundle/skills/agentera/capabilities/{orkestrera → orchestrate}/schemas/exit.yaml +9 -7
  60. package/bundle/skills/agentera/capabilities/orchestrate/schemas/triggers.yaml +23 -0
  61. package/bundle/skills/agentera/capabilities/orchestrate/schemas/validation.yaml +121 -0
  62. package/bundle/skills/agentera/capabilities/plan/schemas/artifacts.yaml +66 -0
  63. package/bundle/skills/agentera/capabilities/{planera → plan}/schemas/exit.yaml +2 -2
  64. package/bundle/skills/agentera/capabilities/plan/schemas/triggers.yaml +23 -0
  65. package/bundle/skills/agentera/capabilities/plan/schemas/validation.yaml +121 -0
  66. package/bundle/skills/agentera/capabilities/profile/schemas/artifacts.yaml +23 -0
  67. package/bundle/skills/agentera/capabilities/{profilera → profile}/schemas/exit.yaml +6 -5
  68. package/bundle/skills/agentera/capabilities/profile/schemas/triggers.yaml +20 -0
  69. package/bundle/skills/agentera/capabilities/profile/schemas/validation.yaml +115 -0
  70. package/bundle/skills/agentera/capabilities/research/schemas/artifacts.yaml +24 -0
  71. package/bundle/skills/agentera/capabilities/research/schemas/triggers.yaml +16 -0
  72. package/bundle/skills/agentera/capabilities/{inspirera → research}/schemas/validation.yaml +2 -2
  73. package/bundle/skills/agentera/capabilities/status/schemas/artifacts.yaml +73 -0
  74. package/bundle/skills/agentera/capabilities/status/schemas/triggers.yaml +22 -0
  75. package/bundle/skills/agentera/capabilities/{hej → status}/schemas/validation.yaml +5 -5
  76. package/bundle/skills/agentera/capabilities/{visionera → vision}/schemas/artifacts.yaml +16 -16
  77. package/bundle/skills/agentera/capabilities/{visionera → vision}/schemas/exit.yaml +7 -6
  78. package/bundle/skills/agentera/capabilities/vision/schemas/triggers.yaml +23 -0
  79. package/bundle/skills/agentera/capabilities/{visionera → vision}/schemas/validation.yaml +18 -20
  80. package/bundle/skills/agentera/capability_schema_contract.yaml +200 -37
  81. package/bundle/skills/agentera/protocol.yaml +31 -31
  82. package/bundle/skills/agentera/route-phrases.yaml +81 -0
  83. package/bundle/skills/agentera/schemas/artifacts/changelog.yaml +5 -4
  84. package/bundle/skills/agentera/schemas/artifacts/decisions.yaml +40 -22
  85. package/bundle/skills/agentera/schemas/artifacts/design.yaml +5 -4
  86. package/bundle/skills/agentera/schemas/artifacts/docs.yaml +15 -19
  87. package/bundle/skills/agentera/schemas/artifacts/experiments.yaml +145 -14
  88. package/bundle/skills/agentera/schemas/artifacts/glossary.yaml +82 -0
  89. package/bundle/skills/agentera/schemas/artifacts/health.yaml +58 -21
  90. package/bundle/skills/agentera/schemas/artifacts/objective.yaml +22 -8
  91. package/bundle/skills/agentera/schemas/artifacts/plan.yaml +421 -33
  92. package/bundle/skills/agentera/schemas/artifacts/progress.yaml +143 -53
  93. package/bundle/skills/agentera/schemas/artifacts/todo.yaml +345 -31
  94. package/bundle/skills/agentera/schemas/artifacts/vision.yaml +3 -3
  95. package/dist/analytics/extractCorpus/cli.js +190 -0
  96. package/dist/analytics/extractCorpus/copilotSessions.js +275 -0
  97. package/dist/analytics/extractCorpus/core.js +392 -0
  98. package/dist/analytics/extractCorpus/corpus.js +167 -0
  99. package/dist/analytics/extractCorpus/coverageAudit.js +260 -0
  100. package/dist/analytics/extractCorpus/cursorSessions.js +425 -0
  101. package/dist/analytics/extractCorpus/evidenceTiers.js +603 -0
  102. package/dist/analytics/extractCorpus/extractCorpusParity.js +105 -0
  103. package/dist/analytics/extractCorpus/filesystemSources.js +118 -0
  104. package/dist/analytics/extractCorpus/index.js +14 -0
  105. package/dist/analytics/extractCorpus/jsonlSessions.js +204 -0
  106. package/dist/analytics/extractCorpus/sqliteCaps.js +43 -0
  107. package/dist/analytics/extractCorpus/sqliteSessions.js +367 -0
  108. package/dist/analytics/extractCorpus/tierReader.js +108 -0
  109. package/dist/analytics/extractCorpus.js +2 -1791
  110. package/dist/analytics/glossaryAdviceResolution.js +166 -0
  111. package/dist/analytics/glossaryInputAcquisition.js +319 -0
  112. package/dist/analytics/personalGlossaryAdmission.js +133 -0
  113. package/dist/analytics/personalGlossaryProfile.js +219 -0
  114. package/dist/analytics/profileSignals.js +211 -0
  115. package/dist/analytics/usageStats.js +169 -42
  116. package/dist/audit/terminologyDrift.js +281 -0
  117. package/dist/bin/agentera.js +3 -2
  118. package/dist/capabilities/audit/instructions.js +16 -0
  119. package/dist/capabilities/build/instructions.js +56 -0
  120. package/dist/capabilities/design/instructions.js +4 -0
  121. package/dist/capabilities/discuss/instructions.js +29 -0
  122. package/dist/capabilities/document/instructions.js +11 -0
  123. package/dist/capabilities/index.js +40 -0
  124. package/dist/capabilities/optimize/instructions.js +14 -0
  125. package/dist/capabilities/orchestrate/instructions.js +40 -0
  126. package/dist/capabilities/plan/instructions.js +32 -0
  127. package/dist/capabilities/profile/instructions.js +70 -0
  128. package/dist/capabilities/research/instructions.js +5 -0
  129. package/dist/capabilities/status/instructions.js +11 -0
  130. package/dist/capabilities/status/startupInstructions.js +34 -0
  131. package/dist/capabilities/vision/instructions.js +4 -0
  132. package/dist/cli/appContext.js +30 -24
  133. package/dist/cli/argvalidate.js +0 -1
  134. package/dist/cli/capabilityContext/benchmark.js +565 -0
  135. package/dist/cli/capabilityContext/bespoke.js +44 -0
  136. package/dist/cli/capabilityContext/build.js +242 -0
  137. package/dist/cli/capabilityContext/closeout.js +233 -0
  138. package/dist/cli/capabilityContext/contract.js +179 -0
  139. package/dist/cli/capabilityContext/evidence.js +463 -0
  140. package/dist/cli/capabilityContext/index.js +3 -0
  141. package/dist/cli/capabilityContext/orchestration.js +131 -0
  142. package/dist/cli/capabilityContext/planState.js +260 -0
  143. package/dist/cli/capabilityContext/progress.js +142 -0
  144. package/dist/cli/capabilityContext/projectVerification.js +409 -0
  145. package/dist/cli/capabilityContext/shared.js +83 -0
  146. package/dist/cli/capabilityContext/slim.js +152 -0
  147. package/dist/cli/capabilityContext/startup.js +150 -0
  148. package/dist/cli/capabilityContext/startupAggregation.js +68 -0
  149. package/dist/cli/capabilityContext/types.js +56 -0
  150. package/dist/cli/capabilityContext.js +1 -2421
  151. package/dist/cli/commands/appHome.js +22 -0
  152. package/dist/cli/commands/capability.js +5 -12
  153. package/dist/cli/commands/compact.js +41 -13
  154. package/dist/cli/commands/doctor.js +127 -97
  155. package/dist/cli/commands/durability.js +81 -0
  156. package/dist/cli/commands/glossaryAdvice.js +138 -0
  157. package/dist/cli/commands/lint.js +26 -44
  158. package/dist/cli/commands/personalGlossary.js +176 -0
  159. package/dist/cli/commands/prime/briefOrientation.js +747 -0
  160. package/dist/cli/commands/prime/buildExecutionRequest.js +165 -0
  161. package/dist/cli/commands/prime/bundleStatus.js +190 -0
  162. package/dist/cli/commands/prime/collectEntityOrientation.js +311 -0
  163. package/dist/cli/commands/prime/collectOrientationState.js +212 -0
  164. package/dist/cli/commands/prime/orientationOutput.js +397 -0
  165. package/dist/cli/commands/prime/types.js +1 -0
  166. package/dist/cli/commands/prime/v1Migration.js +38 -0
  167. package/dist/cli/commands/prime.js +80 -558
  168. package/dist/cli/commands/profileGrounding.js +55 -0
  169. package/dist/cli/commands/query.js +78 -53
  170. package/dist/cli/commands/report.js +96 -25
  171. package/dist/cli/commands/route.js +142 -0
  172. package/dist/cli/commands/schema.js +266 -143
  173. package/dist/cli/commands/state/decisions.js +387 -0
  174. package/dist/cli/commands/state/docs.js +70 -0
  175. package/dist/cli/commands/state/experimentRecords.js +151 -0
  176. package/dist/cli/commands/state/experiments.js +14 -0
  177. package/dist/cli/commands/state/get.js +129 -0
  178. package/dist/cli/commands/state/health.js +14 -0
  179. package/dist/cli/commands/state/index.js +16 -0
  180. package/dist/cli/commands/state/list.js +194 -0
  181. package/dist/cli/commands/state/objective.js +25 -0
  182. package/dist/cli/commands/state/plan.js +14 -0
  183. package/dist/cli/commands/state/planTasks.js +154 -0
  184. package/dist/cli/commands/state/plans.js +154 -0
  185. package/dist/cli/commands/state/progress.js +13 -0
  186. package/dist/cli/commands/state/shared.js +14 -0
  187. package/dist/cli/commands/state/todo.js +42 -0
  188. package/dist/cli/commands/state/write.js +434 -0
  189. package/dist/cli/commands/upgrade.js +146 -5
  190. package/dist/cli/commands/upgradeVerify.js +118 -0
  191. package/dist/cli/commands/validate.js +272 -213
  192. package/dist/cli/commands/verify.js +24 -9
  193. package/dist/cli/contracts/bundleStatus.js +1 -0
  194. package/dist/cli/contracts/orientationState.js +1 -0
  195. package/dist/cli/dispatch/argvParser.js +32 -0
  196. package/dist/cli/dispatch/check.js +372 -0
  197. package/dist/cli/dispatch/commands.js +27 -0
  198. package/dist/cli/dispatch/index.js +207 -0
  199. package/dist/cli/dispatch/lifecycle.js +652 -0
  200. package/dist/cli/dispatch/prime.js +139 -0
  201. package/dist/cli/dispatch/projections.js +17 -0
  202. package/dist/cli/dispatch/shared.js +63 -0
  203. package/dist/cli/dispatch/state.js +140 -0
  204. package/dist/cli/dispatch.js +1 -996
  205. package/dist/cli/errors.js +52 -0
  206. package/dist/cli/help.js +390 -43
  207. package/dist/cli/migrationRequired.js +87 -0
  208. package/dist/cli/orientation/attention.js +59 -0
  209. package/dist/cli/orientation/corpusCoverage.js +102 -0
  210. package/dist/cli/orientation.js +444 -173
  211. package/dist/cli/planArtifacts.js +350 -0
  212. package/dist/cli/planEvidence.js +157 -0
  213. package/dist/cli/planLifecycleState.js +36 -0
  214. package/dist/cli/planTaskIndex.js +11 -0
  215. package/dist/cli/preCutoverCommand.js +32 -0
  216. package/dist/cli/prime-blob.js +71 -3
  217. package/dist/cli/profileAcquisition.js +167 -0
  218. package/dist/cli/startupCompletenessContract.js +59 -0
  219. package/dist/cli/stateQuery.js +63 -14
  220. package/dist/cli/structured.js +0 -1
  221. package/dist/cli/todoMarkdown.js +46 -0
  222. package/dist/cli/todoReadinessSelection.js +192 -0
  223. package/dist/cli/todoSeverity.js +18 -0
  224. package/dist/core/atomicWriter.js +20 -0
  225. package/dist/core/developmentChannel.js +1 -0
  226. package/dist/core/developmentInvocation.js +374 -0
  227. package/dist/core/difflib.js +0 -1
  228. package/dist/core/envPaths.js +20 -0
  229. package/dist/core/jsonValue.js +5 -0
  230. package/dist/core/paths.js +0 -1
  231. package/dist/core/pyjson.js +67 -3
  232. package/dist/core/shell.js +4 -0
  233. package/dist/core/skillIdentity.js +23 -0
  234. package/dist/core/sourceRoot.js +9 -12
  235. package/dist/core/text.js +10 -0
  236. package/dist/core/toml.js +0 -1
  237. package/dist/core/yaml.js +8 -1
  238. package/dist/eval/evalSkills.js +30 -26
  239. package/dist/eval/hybridRouteEvaluation.js +155 -0
  240. package/dist/eval/semanticEval.js +43 -20
  241. package/dist/eval/semanticFixtures.js +16 -5
  242. package/dist/hooks/common.js +11 -81
  243. package/dist/hooks/compaction/apply.js +446 -0
  244. package/dist/hooks/compaction/dryRun.js +184 -0
  245. package/dist/hooks/compaction/index.js +22 -0
  246. package/dist/hooks/compaction/parse.js +325 -0
  247. package/dist/hooks/compaction/retention.js +202 -0
  248. package/dist/hooks/compaction/status.js +360 -0
  249. package/dist/hooks/compaction/types.js +5 -0
  250. package/dist/hooks/validateArtifact/agentFacing.js +9 -0
  251. package/dist/hooks/validateArtifact/index.js +92 -0
  252. package/dist/hooks/validateArtifact/markdown.js +145 -0
  253. package/dist/hooks/validateArtifact/schema.js +546 -0
  254. package/dist/hooks/validateArtifact/traversal.js +107 -0
  255. package/dist/hooks/validateArtifact/violations.js +107 -0
  256. package/dist/migrate/v2HandoffManifest.js +452 -0
  257. package/dist/registries/activationContract.js +2 -0
  258. package/dist/registries/activationTuples.js +106 -0
  259. package/dist/registries/artifactProtocolIds.js +78 -0
  260. package/dist/registries/artifactRegistry.js +224 -63
  261. package/dist/registries/artifactSchemaProjection.js +45 -0
  262. package/dist/registries/capabilityContract.js +141 -13
  263. package/dist/registries/evaluatorHandoffContract.js +170 -0
  264. package/dist/registries/evidenceTierContract.js +371 -0
  265. package/dist/registries/glossaryAdviceContract.js +79 -0
  266. package/dist/registries/glossaryCaveatContract.js +67 -0
  267. package/dist/registries/glossaryConsumerContractValidation.js +787 -0
  268. package/dist/registries/glossaryEntryContract.js +757 -0
  269. package/dist/registries/glossaryTermIdentity.js +17 -0
  270. package/dist/registries/glossaryTermOccurrence.js +20 -0
  271. package/dist/registries/hybridRoute.js +274 -0
  272. package/dist/registries/hybridRouteReceipt.js +221 -0
  273. package/dist/registries/packagePublication.js +229 -0
  274. package/dist/registries/packageRegistry.js +187 -211
  275. package/dist/registries/todoReadinessContract.js +448 -0
  276. package/dist/registries/triggerLoader.js +174 -0
  277. package/dist/registries/verbosityBudgetContract.js +205 -0
  278. package/dist/release/releaseMetadata.js +385 -0
  279. package/dist/runtime/lifecycleAdapterContract.js +457 -0
  280. package/dist/runtime/lifecycleAdapters.js +777 -0
  281. package/dist/runtime/lifecycleAuthority.js +453 -0
  282. package/dist/runtime/lifecycleOperationContract.js +123 -0
  283. package/dist/runtime/lifecycleOperations.js +634 -0
  284. package/dist/runtime/lifecycleOwnershipJournal.js +622 -0
  285. package/dist/runtime/lifecyclePublication.js +415 -0
  286. package/dist/runtime/lifecycleSnapshot.js +438 -0
  287. package/dist/runtime/nativeResourceCleanup.js +502 -0
  288. package/dist/setup/opencode.js +20 -0
  289. package/dist/setup/opencodeConstants.js +1 -0
  290. package/dist/setup/sharedSkill.js +45 -0
  291. package/dist/setup/smokeChecks.js +21 -82
  292. package/dist/state/archiveDiscovery.js +580 -0
  293. package/dist/state/archivePublication.js +225 -0
  294. package/dist/state/archiveRecovery.js +237 -0
  295. package/dist/state/archiveReplay.js +53 -0
  296. package/dist/state/canonicalMigrationRecord.js +36 -0
  297. package/dist/state/changelog.js +221 -0
  298. package/dist/state/decisionEntities.js +367 -0
  299. package/dist/state/decisionLegacyValidation.js +215 -0
  300. package/dist/state/decisionMigrationProvenance.js +199 -0
  301. package/dist/state/decisionOverlay.js +254 -0
  302. package/dist/state/decisionRevision.js +256 -0
  303. package/dist/state/decisionRevisionMigration.js +89 -0
  304. package/dist/state/directRetrieval.js +323 -0
  305. package/dist/state/durability.js +324 -0
  306. package/dist/state/entityCutover.js +459 -0
  307. package/dist/state/entityCutoverGit.js +127 -0
  308. package/dist/state/entityGlossaryAuthority.js +13 -0
  309. package/dist/state/entityListProjection.js +187 -0
  310. package/dist/state/entityListRuntimeRegistry.js +85 -0
  311. package/dist/state/entityMigrationCausality.js +97 -0
  312. package/dist/state/entityMigrationIdentity.js +5 -0
  313. package/dist/state/entityMigrationPreview.js +846 -0
  314. package/dist/state/entityMigrationTodo.js +133 -0
  315. package/dist/state/entityPublicationContext.js +806 -0
  316. package/dist/state/entityRetrievalHelp.js +506 -0
  317. package/dist/state/entityStorage.js +896 -0
  318. package/dist/state/exactReplacementRecovery.js +18 -0
  319. package/dist/state/experimentArchive.js +63 -0
  320. package/dist/state/experimentIdentity.js +202 -0
  321. package/dist/state/healthEntities.js +262 -0
  322. package/dist/state/healthEntityValidation.js +18 -0
  323. package/dist/state/healthRepair.js +69 -0
  324. package/dist/state/installRoot.js +64 -25
  325. package/dist/state/legacyEntityCutoverEvidence.js +65 -0
  326. package/dist/state/legacyIdentity.js +47 -0
  327. package/dist/state/legacySummaryRecord.js +6 -0
  328. package/dist/state/listAccounting.js +54 -0
  329. package/dist/state/listClassification.js +17 -0
  330. package/dist/state/listCursor.js +42 -0
  331. package/dist/state/listRetrieval.js +781 -0
  332. package/dist/state/migrationSourceBinding.js +30 -0
  333. package/dist/state/objectiveExperimentEntities.js +322 -0
  334. package/dist/state/planEntities.js +530 -0
  335. package/dist/state/planIdentity.js +47 -0
  336. package/dist/state/planRetrieval.js +313 -0
  337. package/dist/state/planTaskRetrieval.js +294 -0
  338. package/dist/state/progressEntities.js +512 -0
  339. package/dist/state/progressGlossaryCaveat.js +168 -0
  340. package/dist/state/progressPublicationOrder.js +19 -0
  341. package/dist/state/projectRoot.js +62 -0
  342. package/dist/state/projectionPolicy.js +190 -0
  343. package/dist/state/retrievalAuthority.js +156 -0
  344. package/dist/state/safeProjectFile.js +155 -0
  345. package/dist/state/startupAnalysis/benchmark.js +432 -0
  346. package/dist/state/startupAnalysis/contract.js +160 -0
  347. package/dist/state/startupAnalysis/helpers.js +286 -0
  348. package/dist/state/startupAnalysis/index.js +6 -0
  349. package/dist/state/startupAnalysis/metrics.js +340 -0
  350. package/dist/state/startupAnalysis/records.js +198 -0
  351. package/dist/state/startupAnalysis/report.js +111 -0
  352. package/dist/state/startupAnalysis/threshold.js +512 -0
  353. package/dist/state/startupAnalysis.js +2 -1953
  354. package/dist/state/startupProjection.js +499 -0
  355. package/dist/state/stateMode.js +85 -0
  356. package/dist/state/stateStorageAuthority.js +47 -0
  357. package/dist/state/summaryEntityRead.js +25 -0
  358. package/dist/state/summaryMigrationProvenance.js +66 -0
  359. package/dist/state/summarySourceRowAuthority.js +36 -0
  360. package/dist/state/todoDocsEntities.js +1064 -0
  361. package/dist/state/todoDocsEntityValidation.js +158 -0
  362. package/dist/state/todoMarkdownProjection.js +51 -0
  363. package/dist/state/todoReconciliationActivation.js +132 -0
  364. package/dist/state/todoReconciliationInspection.js +173 -0
  365. package/dist/state/todoReconciliationRepair.js +170 -0
  366. package/dist/state/todoReconciliationTransaction.js +582 -0
  367. package/dist/state/write/assign.js +20 -0
  368. package/dist/state/write/candidateMutation.js +269 -0
  369. package/dist/state/write/errors.js +11 -0
  370. package/dist/state/write/experimentPublication.js +192 -0
  371. package/dist/state/write/explain.js +332 -0
  372. package/dist/state/write/fields.js +61 -0
  373. package/dist/state/write/glossaryPublication.js +263 -0
  374. package/dist/state/write/grammar.js +280 -0
  375. package/dist/state/write/helpers.js +29 -0
  376. package/dist/state/write/index.js +12 -0
  377. package/dist/state/write/input.js +367 -0
  378. package/dist/state/write/lock.js +837 -0
  379. package/dist/state/write/mutation.js +234 -0
  380. package/dist/state/write/operations.js +169 -0
  381. package/dist/state/write/planEvaluation.js +128 -0
  382. package/dist/state/write/planPublication.js +179 -0
  383. package/dist/state/write/runtimeOperations.js +142 -0
  384. package/dist/state/write/serialize.js +1 -0
  385. package/dist/state/write/transaction.js +52 -0
  386. package/dist/state/write/validate.js +7 -0
  387. package/dist/upgrade/appContentRefresh.js +383 -0
  388. package/dist/upgrade/appModel.js +8 -7
  389. package/dist/upgrade/atomicWriter.js +1 -0
  390. package/dist/upgrade/bundleEvidence.js +33 -0
  391. package/dist/upgrade/channels.js +12 -8
  392. package/dist/upgrade/compatibility.js +56 -21
  393. package/dist/upgrade/doctor.js +197 -192
  394. package/dist/upgrade/doctorClassifier.js +187 -0
  395. package/dist/upgrade/installedHooksRetirement.js +196 -0
  396. package/dist/upgrade/legacyAgentCleanup.js +282 -0
  397. package/dist/upgrade/lifecycleUpgrade.js +113 -0
  398. package/dist/upgrade/migrateArtifactsV2ToV3.js +367 -149
  399. package/dist/upgrade/migrationPublication.js +122 -0
  400. package/dist/upgrade/nextMajorDoctor.js +155 -0
  401. package/dist/upgrade/npxPlatformStatus.js +22 -0
  402. package/dist/upgrade/projectIntegration.js +145 -187
  403. package/dist/upgrade/projectIntegrationDecision.js +50 -0
  404. package/dist/upgrade/retiredResourceDiagnostics.js +117 -0
  405. package/dist/upgrade/runtimeMigration.js +278 -352
  406. package/dist/upgrade/upgradeCommands.js +14 -1
  407. package/dist/upgrade/upgradeLock.js +85 -0
  408. package/dist/upgrade/upgradeOrchestrator.js +263 -59
  409. package/dist/upgrade/v3CapabilitySurface.js +14 -0
  410. package/dist/upgrade/versionResolution.js +12 -5
  411. package/dist/validate/activationArtifactEvidence.js +844 -0
  412. package/dist/validate/activationConjunction.js +816 -0
  413. package/dist/validate/activationEvidenceManifest.js +515 -0
  414. package/dist/validate/activationPackageSemantics.js +29 -0
  415. package/dist/validate/appHomeContract.js +5 -11
  416. package/dist/validate/bootstrapAuthority.js +44 -0
  417. package/dist/validate/capability.js +144 -15
  418. package/dist/validate/crossCapability.js +15 -10
  419. package/dist/validate/retainedReferenceAuthority.js +879 -0
  420. package/dist/validate/selfAudit.js +73 -37
  421. package/dist/validate/v1LegacyCruft.js +131 -0
  422. package/dist/validate/vocabularyAuthority.js +303 -0
  423. package/package.json +53 -27
  424. package/bundle/references/adapters/cursor.md +0 -213
  425. package/bundle/references/adapters/opencode.md +0 -530
  426. package/bundle/references/adapters/package-manifest-interface-model.yaml +0 -337
  427. package/bundle/references/adapters/runtime-adapter-characterization.md +0 -79
  428. package/bundle/references/adapters/runtime-adapter-interface-model.yaml +0 -200
  429. package/bundle/references/adapters/runtime-adapter-registry.yaml +0 -548
  430. package/bundle/references/adapters/runtime-feature-parity.md +0 -189
  431. package/bundle/references/analysis/benchmark.md +0 -267
  432. package/bundle/references/analysis/startup-measurement-contract.yaml +0 -424
  433. package/bundle/references/cli/agent-ready-state-contract.yaml +0 -953
  434. package/bundle/references/cli/audience-namespace-cli-migration.yaml +0 -355
  435. package/bundle/references/cli/bundle-skill-vocabulary.yaml +0 -278
  436. package/bundle/references/cli/capability-tool-classification.yaml +0 -53
  437. package/bundle/references/cli/routing-execution-vocabulary.yaml +0 -281
  438. package/bundle/references/meta/documentation-inventory.md +0 -43
  439. package/bundle/references/v1-section-mapping.md +0 -47
  440. package/bundle/skills/agentera/.claude-plugin/plugin.json +0 -27
  441. package/bundle/skills/agentera/agents/dokumentera.toml +0 -6
  442. package/bundle/skills/agentera/agents/hej.toml +0 -6
  443. package/bundle/skills/agentera/agents/inspektera.toml +0 -6
  444. package/bundle/skills/agentera/agents/inspirera.toml +0 -6
  445. package/bundle/skills/agentera/agents/optimera.toml +0 -6
  446. package/bundle/skills/agentera/agents/orkestrera.toml +0 -6
  447. package/bundle/skills/agentera/agents/planera.toml +0 -6
  448. package/bundle/skills/agentera/agents/profilera.toml +0 -6
  449. package/bundle/skills/agentera/agents/realisera.toml +0 -6
  450. package/bundle/skills/agentera/agents/resonera.toml +0 -6
  451. package/bundle/skills/agentera/agents/visionera.toml +0 -6
  452. package/bundle/skills/agentera/agents/visualisera.toml +0 -6
  453. package/bundle/skills/agentera/capabilities/dokumentera/instructions.md +0 -428
  454. package/bundle/skills/agentera/capabilities/dokumentera/schemas/artifacts.yaml +0 -73
  455. package/bundle/skills/agentera/capabilities/dokumentera/schemas/triggers.yaml +0 -35
  456. package/bundle/skills/agentera/capabilities/hej/instructions.md +0 -331
  457. package/bundle/skills/agentera/capabilities/hej/schemas/artifacts.yaml +0 -69
  458. package/bundle/skills/agentera/capabilities/hej/schemas/triggers.yaml +0 -58
  459. package/bundle/skills/agentera/capabilities/inspektera/instructions.md +0 -514
  460. package/bundle/skills/agentera/capabilities/inspektera/schemas/artifacts.yaml +0 -76
  461. package/bundle/skills/agentera/capabilities/inspektera/schemas/triggers.yaml +0 -38
  462. package/bundle/skills/agentera/capabilities/inspirera/instructions.md +0 -280
  463. package/bundle/skills/agentera/capabilities/inspirera/schemas/artifacts.yaml +0 -24
  464. package/bundle/skills/agentera/capabilities/inspirera/schemas/triggers.yaml +0 -34
  465. package/bundle/skills/agentera/capabilities/optimera/instructions.md +0 -437
  466. package/bundle/skills/agentera/capabilities/optimera/schemas/triggers.yaml +0 -39
  467. package/bundle/skills/agentera/capabilities/orkestrera/instructions.md +0 -433
  468. package/bundle/skills/agentera/capabilities/orkestrera/schemas/artifacts.yaml +0 -64
  469. package/bundle/skills/agentera/capabilities/orkestrera/schemas/triggers.yaml +0 -42
  470. package/bundle/skills/agentera/capabilities/orkestrera/schemas/validation.yaml +0 -107
  471. package/bundle/skills/agentera/capabilities/planera/instructions.md +0 -368
  472. package/bundle/skills/agentera/capabilities/planera/schemas/artifacts.yaml +0 -62
  473. package/bundle/skills/agentera/capabilities/planera/schemas/triggers.yaml +0 -34
  474. package/bundle/skills/agentera/capabilities/planera/schemas/validation.yaml +0 -61
  475. package/bundle/skills/agentera/capabilities/profilera/instructions.md +0 -419
  476. package/bundle/skills/agentera/capabilities/profilera/schemas/artifacts.yaml +0 -18
  477. package/bundle/skills/agentera/capabilities/profilera/schemas/triggers.yaml +0 -45
  478. package/bundle/skills/agentera/capabilities/profilera/schemas/validation.yaml +0 -57
  479. package/bundle/skills/agentera/capabilities/realisera/instructions.md +0 -403
  480. package/bundle/skills/agentera/capabilities/realisera/schemas/artifacts.yaml +0 -80
  481. package/bundle/skills/agentera/capabilities/realisera/schemas/triggers.yaml +0 -39
  482. package/bundle/skills/agentera/capabilities/realisera/schemas/validation.yaml +0 -110
  483. package/bundle/skills/agentera/capabilities/resonera/instructions.md +0 -329
  484. package/bundle/skills/agentera/capabilities/resonera/schemas/artifacts.yaml +0 -47
  485. package/bundle/skills/agentera/capabilities/resonera/schemas/triggers.yaml +0 -46
  486. package/bundle/skills/agentera/capabilities/resonera/schemas/validation.yaml +0 -77
  487. package/bundle/skills/agentera/capabilities/visionera/instructions.md +0 -309
  488. package/bundle/skills/agentera/capabilities/visionera/schemas/triggers.yaml +0 -41
  489. package/bundle/skills/agentera/capabilities/visualisera/instructions.md +0 -400
  490. package/bundle/skills/agentera/capabilities/visualisera/schemas/triggers.yaml +0 -33
  491. package/bundle/skills/agentera/references/contract.md +0 -1039
  492. package/bundle/skills/hej/.claude-plugin/plugin.json +0 -6
  493. package/bundle/skills/hej/SKILL.md +0 -69
  494. package/bundle/skills/hej/agents/hej.toml +0 -11
  495. package/bundle/skills/hej/agents/openai.yaml +0 -8
  496. package/dist/analytics/extractCorpus.js.map +0 -1
  497. package/dist/analytics/usageStats.js.map +0 -1
  498. package/dist/bin/agentera.js.map +0 -1
  499. package/dist/cli/appContext.js.map +0 -1
  500. package/dist/cli/argvalidate.js.map +0 -1
  501. package/dist/cli/capabilityContext.js.map +0 -1
  502. package/dist/cli/commands/backfill.js +0 -84
  503. package/dist/cli/commands/backfill.js.map +0 -1
  504. package/dist/cli/commands/capability.js.map +0 -1
  505. package/dist/cli/commands/compact.js.map +0 -1
  506. package/dist/cli/commands/doctor.js.map +0 -1
  507. package/dist/cli/commands/lint.js.map +0 -1
  508. package/dist/cli/commands/prime.js.map +0 -1
  509. package/dist/cli/commands/query.js.map +0 -1
  510. package/dist/cli/commands/report.js.map +0 -1
  511. package/dist/cli/commands/schema.js.map +0 -1
  512. package/dist/cli/commands/state.js +0 -1012
  513. package/dist/cli/commands/state.js.map +0 -1
  514. package/dist/cli/commands/upgrade.js.map +0 -1
  515. package/dist/cli/commands/validate.js.map +0 -1
  516. package/dist/cli/commands/verify.js.map +0 -1
  517. package/dist/cli/dispatch.js.map +0 -1
  518. package/dist/cli/help.js.map +0 -1
  519. package/dist/cli/orientation.js.map +0 -1
  520. package/dist/cli/prime-blob.js.map +0 -1
  521. package/dist/cli/stateQuery.js.map +0 -1
  522. package/dist/cli/structured.js.map +0 -1
  523. package/dist/core/difflib.js.map +0 -1
  524. package/dist/core/git.js +0 -43
  525. package/dist/core/git.js.map +0 -1
  526. package/dist/core/paths.js.map +0 -1
  527. package/dist/core/pyjson.js.map +0 -1
  528. package/dist/core/sourceRoot.js.map +0 -1
  529. package/dist/core/toml.js.map +0 -1
  530. package/dist/core/yaml.js.map +0 -1
  531. package/dist/eval/evalSkills.js.map +0 -1
  532. package/dist/eval/semanticEval.js.map +0 -1
  533. package/dist/eval/semanticFixtures.js.map +0 -1
  534. package/dist/hooks/common.js.map +0 -1
  535. package/dist/hooks/compaction.js +0 -935
  536. package/dist/hooks/compaction.js.map +0 -1
  537. package/dist/hooks/cursorPreToolUse.js +0 -19
  538. package/dist/hooks/cursorPreToolUse.js.map +0 -1
  539. package/dist/hooks/cursorSessionStart.js +0 -71
  540. package/dist/hooks/cursorSessionStart.js.map +0 -1
  541. package/dist/hooks/sessionStart.js +0 -209
  542. package/dist/hooks/sessionStart.js.map +0 -1
  543. package/dist/hooks/sessionStop.js +0 -212
  544. package/dist/hooks/sessionStop.js.map +0 -1
  545. package/dist/hooks/validateArtifact.js +0 -933
  546. package/dist/hooks/validateArtifact.js.map +0 -1
  547. package/dist/registries/artifactRegistry.js.map +0 -1
  548. package/dist/registries/capabilityContract.js.map +0 -1
  549. package/dist/registries/packageRegistry.js.map +0 -1
  550. package/dist/registries/runtimeAdapterRegistry.js +0 -315
  551. package/dist/registries/runtimeAdapterRegistry.js.map +0 -1
  552. package/dist/setup/codex.js +0 -1056
  553. package/dist/setup/codex.js.map +0 -1
  554. package/dist/setup/copilot.js +0 -227
  555. package/dist/setup/copilot.js.map +0 -1
  556. package/dist/setup/cursor.js +0 -127
  557. package/dist/setup/cursor.js.map +0 -1
  558. package/dist/setup/doctor.js +0 -1297
  559. package/dist/setup/doctor.js.map +0 -1
  560. package/dist/setup/smokeChecks.js.map +0 -1
  561. package/dist/state/installRoot.js.map +0 -1
  562. package/dist/state/progressCommit.js +0 -289
  563. package/dist/state/progressCommit.js.map +0 -1
  564. package/dist/state/startupAnalysis.js.map +0 -1
  565. package/dist/upgrade/appModel.js.map +0 -1
  566. package/dist/upgrade/channels.js.map +0 -1
  567. package/dist/upgrade/compatibility.js.map +0 -1
  568. package/dist/upgrade/doctor.js.map +0 -1
  569. package/dist/upgrade/migrateArtifactsV1ToV2.js +0 -571
  570. package/dist/upgrade/migrateArtifactsV1ToV2.js.map +0 -1
  571. package/dist/upgrade/migrateArtifactsV2ToV3.js.map +0 -1
  572. package/dist/upgrade/projectIntegration.js.map +0 -1
  573. package/dist/upgrade/runtimeMigration.js.map +0 -1
  574. package/dist/upgrade/upgradeCommands.js.map +0 -1
  575. package/dist/upgrade/upgradeOrchestrator.js.map +0 -1
  576. package/dist/upgrade/versionResolution.js.map +0 -1
  577. package/dist/validate/appHomeContract.js.map +0 -1
  578. package/dist/validate/capability.js.map +0 -1
  579. package/dist/validate/crossCapability.js.map +0 -1
  580. package/dist/validate/lifecycleAdapters.js +0 -772
  581. package/dist/validate/lifecycleAdapters.js.map +0 -1
  582. package/dist/validate/selfAudit.js.map +0 -1
  583. /package/bundle/skills/agentera/capabilities/{dokumentera → document}/schemas/exit.yaml +0 -0
  584. /package/bundle/skills/agentera/capabilities/{inspirera → research}/schemas/exit.yaml +0 -0
  585. /package/bundle/skills/agentera/capabilities/{hej → status}/schemas/exit.yaml +0 -0
@@ -0,0 +1,846 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import YAML from "yaml";
5
+ import { fullEntityUpgradePreviewCommand } from "../upgrade/upgradeCommands.js";
6
+ import { loadYamlMapping } from "../core/yaml.js";
7
+ import { discoverPlanArtifacts, planDocumentParts } from "../cli/planArtifacts.js";
8
+ import { assertRealpathBoundary, docsPathOverridesFromBytes, loadArtifactRecord, resolveArtifactPath } from "../registries/artifactRegistry.js";
9
+ import { canonicalRecordJson, validateStateRecord } from "./archiveDiscovery.js";
10
+ import { canonicalEntityEnvelopeBytes, entityForbiddenCanonicalAliases, entityPreservedAggregateCollections, validateCanonicalEntityTargets } from "./entityStorage.js";
11
+ import { discoverObjectiveArtifacts, inspectExperimentIdentities } from "./experimentIdentity.js";
12
+ import { decisionRevisionContract, decisionRevisionViolations } from "./decisionRevision.js";
13
+ import { classifyCompleteDecisionConfidence, decisionLegacyCoexistence } from "./decisionLegacyValidation.js";
14
+ import { migrateDecisionRevisionEntries } from "./decisionRevisionMigration.js";
15
+ import { entityMigrationId } from "./entityMigrationIdentity.js";
16
+ import { assertValidatedProjectRoot, validateRealProjectRoot } from "./projectRoot.js";
17
+ import { todoDocsRecordViolations } from "./todoDocsEntityValidation.js";
18
+ import { yamlArchiveEntry } from "../hooks/compaction/retention.js";
19
+ import { truncateWords } from "../hooks/compaction/dryRun.js";
20
+ import { legacyIdentity } from "./legacyIdentity.js";
21
+ import { canonicalMigrationRecord } from "./canonicalMigrationRecord.js";
22
+ import { legacySummaryRecord } from "./legacySummaryRecord.js";
23
+ import { applyCausalBlockers } from "./entityMigrationCausality.js";
24
+ import { todoMigrationObservations, todoReconciliationMigrationPlan } from "./entityMigrationTodo.js";
25
+ import { detectStateMode } from "./stateMode.js";
26
+ import { TODO_RECONCILIATION_ACTIVATION_PATH } from "./todoReconciliationActivation.js";
27
+ import { projectPathIsStable as migrationPathIsStable, readProjectFileSnapshot, resolveProjectDescriptorPath, snapshotProjectPath as snapshotMigrationPath, } from "./safeProjectFile.js";
28
+ export function classifyEntityCutoverProject(project, sourceRoot) {
29
+ if (detectStateMode(project, sourceRoot) === "entities")
30
+ return "v3";
31
+ const stateRoot = path.join(project, ".agentera");
32
+ const aggregateNames = ["plan.yaml", "progress.yaml", "decisions.yaml", "health.yaml"];
33
+ const aggregateCount = aggregateNames.filter((name) => fs.existsSync(path.join(stateRoot, name))).length;
34
+ if (!fs.existsSync(stateRoot) || aggregateCount === 0 && !fs.existsSync(path.join(stateRoot, "entities")))
35
+ return "clean";
36
+ return fs.existsSync(path.join(stateRoot, "entities")) || aggregateCount === 1 ? "partial" : "v2";
37
+ }
38
+ export const ENTITY_MIGRATION_PREVIEW_MAX_OUTPUT_BYTES = 32_768;
39
+ const DEFAULT_LIMIT = 100;
40
+ const MAX_LIMIT = 1000;
41
+ const NUMBERED = {
42
+ progress: { file: ".agentera/progress.yaml", collection: "cycles", boundary: "progress_cycle" },
43
+ decisions: { file: ".agentera/decisions.yaml", collection: "decisions", boundary: "decision" },
44
+ health: { file: ".agentera/health.yaml", collection: "audits", boundary: "health_audit" },
45
+ };
46
+ const COMPACTED_SUMMARY_ARTIFACTS = new Set(["progress", "decisions", "health"]);
47
+ const BLOCKING = new Set(["duplicate", "conflict", "corrupt", "unsupported"]);
48
+ const INVENTORY_ORDER = "artifact_then_boundary_then_source_identity_then_source_path";
49
+ const INVENTORY_FILTER = "complete_declared_inventory";
50
+ const AUTHORITY_PATH = "references/artifacts/state-storage-authority.yaml";
51
+ const PLAN_ARCHIVE_SOURCE = /^\.agentera\/archive\/PLAN-[^/]+\.ya?ml$/i;
52
+ function mapping(value) {
53
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
54
+ }
55
+ function hash(value) {
56
+ return createHash("sha256").update(value).digest("hex");
57
+ }
58
+ function completeRecordAssessment(sourceRoot, artifact, record, source, sourcePath) {
59
+ if (artifact !== "decisions") {
60
+ const violations = validateStateRecord(sourceRoot, artifact, record);
61
+ return { valid: violations.length === 0, violations };
62
+ }
63
+ const assessment = classifyCompleteDecisionConfidence(record, decisionLegacyCoexistence(sourceRoot), (candidate) => validateStateRecord(sourceRoot, artifact, candidate), source);
64
+ return {
65
+ valid: assessment.status !== "invalid",
66
+ violations: assessment.violations,
67
+ ...(assessment.status === "inherited" ? { inheritedConfidenceProvenance: {
68
+ kind: "inherited_decision_confidence",
69
+ source: source === "active" ? "current_projection" : "verified_archive",
70
+ source_path: sourcePath,
71
+ source_record_sha256: hash(canonicalRecordJson(record)),
72
+ confidence: record.confidence,
73
+ } } : {}),
74
+ };
75
+ }
76
+ function relative(root, target) {
77
+ return path.relative(root, target).replaceAll(path.sep, "/");
78
+ }
79
+ /** Migration-only source seam: pin one project file to a verified descriptor. */
80
+ function readMigrationSource(root, relativePath, descriptorPathResolver) {
81
+ return { relative: relativePath, ...readProjectFileSnapshot(root, relativePath, descriptorPathResolver) };
82
+ }
83
+ function directoryFiles(root, validatedRoot, relativeRoot, accept, descriptorPathResolver) {
84
+ const absoluteRoot = path.join(root, relativeRoot);
85
+ const inventoryPath = (directory) => `${relative(root, directory).replace(/\/$/, "")}/`;
86
+ const visit = (directory, isRoot = false) => {
87
+ assertValidatedProjectRoot(validatedRoot);
88
+ const directorySnapshot = snapshotMigrationPath(root, relative(root, directory), "directory");
89
+ if (directorySnapshot.kind !== "stable") {
90
+ if (directorySnapshot.kind === "missing")
91
+ return isRoot ? { files: [], changed: null } : { files: [], changed: inventoryPath(directory) };
92
+ if (path.resolve(directorySnapshot.absolute) !== path.resolve(directory))
93
+ return { files: [], changed: inventoryPath(directory) };
94
+ if (directorySnapshot.reason === "symlink")
95
+ throw new Error(`inventory root '${directory}' is a symbolic link; replace it with a real directory inside project '${root}' and retry`);
96
+ if (directorySnapshot.reason === "type")
97
+ throw new Error(`inventory root '${directory}' is not a directory; replace it with a real directory inside project '${root}' and retry`);
98
+ throw new Error(`inventory root '${directory}' cannot be inspected inside project '${root}'; replace it with a readable real directory and retry`);
99
+ }
100
+ let entries;
101
+ try {
102
+ entries = fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
103
+ }
104
+ catch {
105
+ throw new Error(`inventory root '${directory}' cannot be read inside project '${root}'; replace it with a readable real directory and retry`);
106
+ }
107
+ if (!migrationPathIsStable(directorySnapshot))
108
+ return { files: [], changed: inventoryPath(directory) };
109
+ const files = [];
110
+ for (const entry of entries) {
111
+ const absolute = path.join(directory, entry.name);
112
+ const candidate = relative(root, absolute);
113
+ if (accept(candidate)) {
114
+ files.push(readMigrationSource(validatedRoot, candidate, descriptorPathResolver));
115
+ }
116
+ else if (entry.isSymbolicLink()) {
117
+ throw new Error(`inventory root '${absolute}' is a symbolic link; replace it with a real directory or file inside project '${root}' and retry`);
118
+ }
119
+ else if (entry.isDirectory()) {
120
+ const nested = visit(absolute);
121
+ if (nested.changed)
122
+ return nested;
123
+ files.push(...nested.files);
124
+ }
125
+ }
126
+ assertValidatedProjectRoot(validatedRoot);
127
+ if (!migrationPathIsStable(directorySnapshot))
128
+ return { files: [], changed: inventoryPath(directory) };
129
+ return { files, changed: null };
130
+ };
131
+ const enumeration = visit(absoluteRoot, true);
132
+ return enumeration.changed ? [{ relative: enumeration.changed, bytes: null, kind: "unsafe" }] : enumeration.files;
133
+ }
134
+ function collectSources(root, validatedRoot, todoPath, docsSnapshot, descriptorPathResolver) {
135
+ const exact = [
136
+ todoPath, "CHANGELOG.md", "DESIGN.md", ".agentera/vision.yaml", ".agentera/docs.yaml", ".agentera/progress.yaml", ".agentera/decisions.yaml", ".agentera/health.yaml", ".agentera/plan.yaml",
137
+ ".agentera/overlays/decisions.yaml", ".agentera/revisions/decisions.yaml", ".agentera/archive/recovery/projection-correlation.yaml",
138
+ ].map((candidate) => candidate === docsSnapshot.relative ? docsSnapshot : readMigrationSource(validatedRoot, candidate, descriptorPathResolver));
139
+ const archives = directoryFiles(root, validatedRoot, ".agentera/archive", (candidate) => /^\.agentera\/archive\/(progress|decisions|health)\/.+/.test(candidate)
140
+ || PLAN_ARCHIVE_SOURCE.test(candidate), descriptorPathResolver);
141
+ const objectives = [".agentera/optimize", ".agentera/optimera"].flatMap((directory) => directoryFiles(root, validatedRoot, directory, (candidate) => /\/(objective|experiments)\.yaml$/.test(candidate), descriptorPathResolver));
142
+ const todoEntities = directoryFiles(root, validatedRoot, ".agentera/entities/todo/todo_item", (candidate) => candidate.endsWith(".yaml"), descriptorPathResolver);
143
+ const activation = readMigrationSource(validatedRoot, TODO_RECONCILIATION_ACTIVATION_PATH, descriptorPathResolver);
144
+ const collected = [...exact, ...archives, ...objectives, ...todoEntities, activation];
145
+ const missingRoots = [".agentera/archive/", ".agentera/optimize/", ".agentera/optimera/", ".agentera/entities/todo/todo_item/"]
146
+ .filter((directory) => {
147
+ if (collected.some((source) => source.kind === "unsafe" && source.relative === directory))
148
+ return false;
149
+ try {
150
+ return !fs.lstatSync(path.join(root, directory)).isDirectory();
151
+ }
152
+ catch {
153
+ return true;
154
+ }
155
+ })
156
+ .map((directory) => ({ relative: directory, bytes: null, kind: "missing" }));
157
+ const byPath = new Map([...collected, ...missingRoots].map((source) => [source.relative, source]));
158
+ return [...byPath.values()].sort((a, b) => a.relative.localeCompare(b.relative));
159
+ }
160
+ function authorityBinding(sourceRoot) {
161
+ const authorityPath = path.join(sourceRoot, AUTHORITY_PATH);
162
+ const bytes = fs.readFileSync(authorityPath);
163
+ const authority = loadYamlMapping(bytes.toString("utf8"));
164
+ if (typeof authority.schema_version !== "string" || !mapping(authority.entity_migration)) {
165
+ throw new Error("active entity migration authority is missing its schema version or entity_migration contract");
166
+ }
167
+ return { authority_schema_version: authority.schema_version, authority_sha256: hash(bytes) };
168
+ }
169
+ function sourceFingerprint(files) {
170
+ return hash(canonicalRecordJson(files.map((file) => ({
171
+ path: file.relative,
172
+ presence: file.kind,
173
+ size: file.bytes?.byteLength ?? 0,
174
+ sha256: file.bytes ? hash(file.bytes) : null,
175
+ mode: file.kind === "file" ? file.mode : null,
176
+ dev: file.kind === "file" ? String(file.dev) : null,
177
+ ino: file.kind === "file" ? String(file.ino) : null,
178
+ type: file.kind === "file" ? file.type : null,
179
+ }))));
180
+ }
181
+ function parseYaml(source) {
182
+ if (source.kind !== "file" || !source.bytes)
183
+ throw new Error(source.kind === "unsafe" ? "source path is a symbolic link or non-file" : "source is missing");
184
+ return loadYamlMapping(source.bytes.toString("utf8"));
185
+ }
186
+ function recovery(project, pathName) {
187
+ return `Repair '${pathName}', then run ${fullEntityUpgradePreviewCommand(project)}.`;
188
+ }
189
+ function unsafeSourceMessage(pathName) {
190
+ return `source path '${pathName}' is a symbolic link, non-file, or unreadable; replace it with a readable regular file inside the project`;
191
+ }
192
+ function inventoryFailureObservations(files, observations) {
193
+ for (const source of files.filter((candidate) => candidate.kind === "unsafe" && candidate.relative.endsWith("/"))) {
194
+ observations.push({
195
+ key: `migration_inventory:${source.relative}`,
196
+ artifact: "state",
197
+ boundary: "migration_inventory",
198
+ path: source.relative,
199
+ provenance: "source_inventory",
200
+ record: null,
201
+ detail: "corrupt",
202
+ relationships: [],
203
+ message: `inventory directory '${source.relative}' changed while it was enumerated; no candidate names were accepted`,
204
+ });
205
+ }
206
+ }
207
+ function numberedObservations(root, sourceRoot, files, observations, aggregateCollections) {
208
+ const correlationSource = files.find((source) => source.relative === ".agentera/archive/recovery/projection-correlation.yaml");
209
+ let correlationManifest = null;
210
+ if (correlationSource?.kind === "file") {
211
+ try {
212
+ const manifest = parseYaml(correlationSource);
213
+ const entries = Array.isArray(manifest.entries) ? manifest.entries.map(mapping) : [];
214
+ const validEntries = entries.filter((entry) => Boolean(entry));
215
+ const digest = hash(canonicalRecordJson({ schemaVersion: "agentera.projectionCorrelationSet.v1", entries: validEntries }));
216
+ if (manifest.schemaVersion !== "agentera.projectionCorrelationManifest.v1" || manifest.recovery_set_digest !== digest || validEntries.length !== entries.length)
217
+ throw new Error("projection correlation manifest schema or digest is invalid");
218
+ correlationManifest = new Map(validEntries.map((entry) => [String(entry.identity), entry]));
219
+ }
220
+ catch (error) {
221
+ observations.push({ key: "projection_correlation:manifest", artifact: "state", boundary: "migration_inventory", path: correlationSource.relative, provenance: "source_inventory", record: null, detail: "corrupt", relationships: [], message: error.message });
222
+ }
223
+ }
224
+ else if (correlationSource?.kind === "unsafe") {
225
+ observations.push({ key: "projection_correlation:manifest", artifact: "state", boundary: "migration_inventory", path: correlationSource.relative, provenance: "source_inventory", record: null, detail: "corrupt", relationships: [], message: unsafeSourceMessage(correlationSource.relative) });
226
+ }
227
+ for (const [artifact, declaration] of Object.entries(NUMBERED)) {
228
+ const current = files.find((source) => source.relative === declaration.file);
229
+ if (current?.kind === "file") {
230
+ try {
231
+ const document = parseYaml(current);
232
+ const allowedCollections = new Set(aggregateCollections[declaration.file] ?? []);
233
+ for (const field of Object.keys(document).filter((field) => Array.isArray(document[field]) && !allowedCollections.has(field)).sort()) {
234
+ observations.push({ key: `${artifact}:undeclared_collection:${field}`, artifact, boundary: "migration_inventory", path: declaration.file, provenance: "source_inventory", record: null, detail: "corrupt", relationships: [], message: `aggregate collection '${field}' is not declared for '${declaration.file}' by the state storage authority` });
235
+ }
236
+ const currentValues = document[declaration.collection];
237
+ if (!Array.isArray(currentValues))
238
+ throw new Error(`field '${declaration.collection}' must be a list`);
239
+ const collections = [[declaration.collection, currentValues]];
240
+ if (Array.isArray(document.archive))
241
+ collections.push(["archive", document.archive]);
242
+ collections.flatMap(([collection, values]) => values.map((value, index) => ({ collection, value, index }))).forEach(({ collection, value, index }) => {
243
+ const record = legacySummaryRecord(value);
244
+ const identity = legacyIdentity(record, artifact, "number");
245
+ const number = identity.number;
246
+ const key = number ? `${artifact}:${number}` : `${artifact}:${collection}[${index}]`;
247
+ const assessment = record && typeof record.number === "number"
248
+ ? completeRecordAssessment(sourceRoot, artifact, record, "active", declaration.file)
249
+ : { valid: false, violations: ["record number is required"] };
250
+ const valid = assessment.valid;
251
+ const summary = Boolean(record && (typeof record.summary === "string" || record.detail_availability === "summary_only"));
252
+ const text = typeof record?.summary === "string" ? record.summary : "";
253
+ const decisionRefs = artifact === "decisions" ? [...text.matchAll(/\bD([1-9][0-9]*)\b/g)] : [];
254
+ const residue = artifact === "decisions" && decisionRefs.length > 1 && !number;
255
+ observations.push({ key: residue ? `historical_projection_residue:${declaration.file}:${collection}[${index}]` : key, artifact, boundary: residue ? "historical_projection_residue" : declaration.boundary, path: declaration.file, provenance: residue ? "historical_projection_residue" : "current_projection", record, detail: valid ? "full" : summary ? "summary" : "corrupt", relationships: [], sourceRecordSha256: hash(canonicalRecordJson(value)), message: valid || summary ? undefined : "projection record does not satisfy the declared full-detail schema", ...(assessment.inheritedConfidenceProvenance ? { inheritedConfidenceProvenance: assessment.inheritedConfidenceProvenance } : {}), ...(residue ? { migrationProvenance: { classification: "historical_projection_residue", path: declaration.file, collection, index, content_sha256: hash(canonicalRecordJson(record)), text, inbound_structured_references: 0 } } : {}) });
256
+ if (artifact === "decisions" && valid && mapping(record?.satisfaction)) {
257
+ observations.push({ key: `decision_satisfaction:${key}`, artifact: "decisions", boundary: "decision_satisfaction", path: declaration.file, provenance: "current_projection", record: mapping(record?.satisfaction), detail: "full", relationships: [{ field: "decision", target: key }] });
258
+ }
259
+ });
260
+ }
261
+ catch (error) {
262
+ observations.push({ key: `${artifact}:projection`, artifact, boundary: declaration.boundary, path: declaration.file, provenance: "current_projection", record: null, detail: "corrupt", relationships: [], message: error.message });
263
+ }
264
+ }
265
+ else if (current?.kind === "unsafe") {
266
+ observations.push({ key: `${artifact}:projection`, artifact, boundary: declaration.boundary, path: declaration.file, provenance: "current_projection", record: null, detail: "corrupt", relationships: [], message: unsafeSourceMessage(declaration.file) });
267
+ }
268
+ for (const source of files.filter((candidate) => candidate.relative.startsWith(`.agentera/archive/${artifact}/`))) {
269
+ const match = new RegExp(`^\\.agentera/archive/${artifact}/([1-9][0-9]*)\\.yaml$`).exec(source.relative);
270
+ if (!match) {
271
+ observations.push({ key: `unsupported:${source.relative}`, artifact, boundary: declaration.boundary, path: source.relative, provenance: "archive", record: null, detail: "corrupt", relationships: [], message: "unsupported archive candidate name" });
272
+ continue;
273
+ }
274
+ const key = `${artifact}:${match[1]}`;
275
+ try {
276
+ const envelope = parseYaml(source);
277
+ const record = mapping(envelope.record);
278
+ if (!record || envelope.artifact_id !== artifact || envelope.entry_number !== Number(match[1]))
279
+ throw new Error("archive envelope identity does not match its path");
280
+ const expected = hash(canonicalRecordJson(record));
281
+ if (envelope.record_sha256 !== expected)
282
+ throw new Error("archive record_sha256 does not match record bytes");
283
+ if (mapping(envelope.recovery_provenance)) {
284
+ const correlation = correlationManifest?.get(key);
285
+ if (!correlation)
286
+ throw new Error("recovered archive is absent from the immutable projection correlation manifest");
287
+ if (correlation.artifact !== artifact || correlation.identity !== key || correlation.archive_sha256 !== hash(source.bytes)
288
+ || mapping(correlation.overlay)?.final_record_sha256 !== expected)
289
+ throw new Error("recovered archive does not match its immutable projection correlation manifest entry");
290
+ }
291
+ const assessment = completeRecordAssessment(sourceRoot, artifact, record, "archive", source.relative);
292
+ if (!assessment.valid)
293
+ throw new Error(`archive record is invalid: ${assessment.violations.join("; ")}`);
294
+ observations.push({ key, artifact, boundary: declaration.boundary, path: source.relative, provenance: "verified_archive", record, detail: "full", relationships: [], ...(assessment.inheritedConfidenceProvenance ? { inheritedConfidenceProvenance: assessment.inheritedConfidenceProvenance } : {}), ...(mapping(envelope.recovery_provenance) ? { migrationProvenance: mapping(envelope.recovery_provenance) } : {}) });
295
+ if (artifact === "decisions" && mapping(record.satisfaction)) {
296
+ observations.push({
297
+ key: `decision_satisfaction:${key}`,
298
+ artifact: "decisions",
299
+ boundary: "decision_satisfaction",
300
+ path: source.relative,
301
+ provenance: "verified_archive",
302
+ record: mapping(record.satisfaction),
303
+ detail: "full",
304
+ relationships: [{ field: "decision", target: key }],
305
+ ...(mapping(envelope.recovery_provenance) ? { migrationProvenance: { kind: "nested_verified_archive_evidence", source: mapping(envelope.recovery_provenance) } } : {}),
306
+ });
307
+ }
308
+ }
309
+ catch (error) {
310
+ observations.push({ key, artifact, boundary: declaration.boundary, path: source.relative, provenance: "archive", record: null, detail: "corrupt", relationships: [], message: error.message });
311
+ }
312
+ }
313
+ }
314
+ }
315
+ function decisionEvidence(sourceRoot, files, observations) {
316
+ const overlay = files.find((source) => source.relative === ".agentera/overlays/decisions.yaml");
317
+ if (overlay?.kind === "file") {
318
+ try {
319
+ const document = parseYaml(overlay);
320
+ for (const [identity, value] of Object.entries(document).sort(([a], [b]) => a.localeCompare(b))) {
321
+ const record = mapping(value);
322
+ const match = /^decisions:([1-9][0-9]*)$/.exec(identity);
323
+ const satisfaction = mapping(record?.satisfaction);
324
+ observations.push({ key: `decision_satisfaction:${identity}`, artifact: "decisions", boundary: "decision_satisfaction", path: overlay.relative, provenance: "overlay", record: satisfaction, detail: match && satisfaction ? "full" : "corrupt", relationships: [{ field: "decision", target: match ? `decisions:${match[1]}` : null }], message: match && satisfaction ? undefined : "decision satisfaction overlay has an unsupported identity or shape" });
325
+ }
326
+ }
327
+ catch (error) {
328
+ observations.push({ key: "decision_satisfaction:overlay", artifact: "decisions", boundary: "decision_satisfaction", path: overlay.relative, provenance: "overlay", record: null, detail: "corrupt", relationships: [{ field: "decision", target: null }], message: error.message });
329
+ }
330
+ }
331
+ else if (overlay?.kind === "unsafe") {
332
+ observations.push({ key: "decision_satisfaction:overlay", artifact: "decisions", boundary: "decision_satisfaction", path: overlay.relative, provenance: "overlay", record: null, detail: "corrupt", relationships: [], message: unsafeSourceMessage(overlay.relative) });
333
+ }
334
+ const revisions = files.find((source) => source.relative === ".agentera/revisions/decisions.yaml");
335
+ if (revisions?.kind === "file") {
336
+ try {
337
+ const document = parseYaml(revisions);
338
+ const contract = decisionRevisionContract(sourceRoot);
339
+ for (const [identity, value] of Object.entries(document).sort(([left], [right]) => left.localeCompare(right))) {
340
+ const target = new RegExp(`^${contract.identityPrefix}:[1-9][0-9]*$`).test(identity) ? identity : null;
341
+ if (!Array.isArray(value)) {
342
+ observations.push({ key: `decision_revision:${identity}`, artifact: "decisions", boundary: "decision_revision", path: revisions.relative, provenance: "revision", record: null, detail: "corrupt", relationships: [{ field: "decision", target }], message: `${identity} must be an ordered list of revision records` });
343
+ continue;
344
+ }
345
+ value.forEach((candidate, index) => {
346
+ const record = mapping(candidate);
347
+ const violations = decisionRevisionViolations({ [identity]: [candidate] }, contract);
348
+ observations.push({ key: `decision_revision:${identity}:${index}`, artifact: "decisions", boundary: "decision_revision", path: revisions.relative, provenance: "revision", record, detail: record && violations.length === 0 ? "full" : "corrupt", relationships: [{ field: "decision", target }], message: violations.length === 0 ? undefined : violations.join("; ") });
349
+ });
350
+ }
351
+ }
352
+ catch (error) {
353
+ observations.push({ key: "decision_revision:document", artifact: "decisions", boundary: "decision_revision", path: revisions.relative, provenance: "revision", record: null, detail: "corrupt", relationships: [{ field: "decision", target: null }], message: error.message });
354
+ }
355
+ }
356
+ else if (revisions?.kind === "unsafe") {
357
+ observations.push({ key: "decision_revision:document", artifact: "decisions", boundary: "decision_revision", path: revisions.relative, provenance: "revision", record: null, detail: "corrupt", relationships: [], message: unsafeSourceMessage(revisions.relative) });
358
+ }
359
+ }
360
+ function planObservations(root, files, observations) {
361
+ const active = path.join(root, ".agentera", "plan.yaml");
362
+ const activeSource = files.find((source) => source.relative === ".agentera/plan.yaml");
363
+ const archiveBytes = new Map(files.flatMap((source) => source.kind === "file" && PLAN_ARCHIVE_SOURCE.test(source.relative)
364
+ ? [[path.join(root, source.relative), source.bytes]]
365
+ : []));
366
+ const discovery = discoverPlanArtifacts(active, {
367
+ activeBytes: activeSource?.kind === "file" ? activeSource.bytes : null,
368
+ archiveBytes,
369
+ });
370
+ const seen = new Set();
371
+ if (activeSource?.kind === "unsafe") {
372
+ observations.push({ key: "plan:document", artifact: "plan", boundary: "plan", path: activeSource.relative, provenance: "current_canonical", record: null, detail: "corrupt", relationships: [], message: unsafeSourceMessage(activeSource.relative) });
373
+ }
374
+ for (const identity of discovery.identities) {
375
+ const marker = `${identity.stableId}\0${identity.artifact.path}`;
376
+ if (seen.has(marker))
377
+ continue;
378
+ seen.add(marker);
379
+ const sourcePath = relative(root, identity.artifact.path);
380
+ const archived = identity.artifact.path !== active;
381
+ const source = files.find((candidate) => candidate.relative === sourcePath);
382
+ let sourceStatus = String((mapping(identity.artifact.data.header) ?? {}).status ?? "");
383
+ if (source?.kind === "file") {
384
+ const sourceDocument = parseYaml(source);
385
+ sourceStatus = String((mapping(sourceDocument.header) ?? {}).status ?? "");
386
+ }
387
+ const planRecord = structuredClone(identity.artifact.data);
388
+ const migratedHeader = mapping(planRecord.header);
389
+ if (archived && migratedHeader)
390
+ migratedHeader.status = "archived";
391
+ const migrationProvenance = archived ? {
392
+ ...identity.artifact.migrationProvenance,
393
+ source_path: sourcePath,
394
+ source_lifecycle: "verified_plan_archive",
395
+ source_status: sourceStatus,
396
+ target_status: "archived",
397
+ } : identity.artifact.migrationProvenance ? { ...identity.artifact.migrationProvenance, source_path: sourcePath } : undefined;
398
+ const classificationDetail = identity.ambiguous ? "corrupt" : "full";
399
+ observations.push({ key: identity.stableId, artifact: "plan", boundary: "plan", path: sourcePath, provenance: archived ? "verified_plan_archive" : "current_canonical", record: planRecord, detail: classificationDetail, relationships: [], message: identity.ambiguous ? "plan identity resolves to conflicting documents" : undefined, ...(migrationProvenance ? { migrationProvenance } : {}) });
400
+ const parts = planDocumentParts(identity.artifact.data);
401
+ parts.tasks.forEach((task, index) => {
402
+ const number = task.number;
403
+ const taskKey = typeof number === "number" && Number.isSafeInteger(number) && number > 0 ? `${identity.stableId}/task:${number}` : `${identity.stableId}/task:index:${index}`;
404
+ const depends = Array.isArray(task.depends_on) ? task.depends_on : [];
405
+ observations.push({
406
+ key: taskKey,
407
+ artifact: "plan",
408
+ boundary: "plan_task",
409
+ path: sourcePath,
410
+ provenance: identity.artifact.path === active ? "current_canonical" : "verified_plan_archive",
411
+ record: task,
412
+ detail: typeof number === "number" ? classificationDetail : "corrupt",
413
+ relationships: [
414
+ { field: "plan", target: identity.stableId },
415
+ ...depends.map((dependency) => { const normalized = /^Task ([1-9][0-9]*)$/.exec(String(dependency))?.[1] ?? String(dependency); return { field: "depends_on", target: /^[1-9][0-9]*$/.test(normalized) ? `${identity.stableId}/task:${normalized}` : null }; }),
416
+ ],
417
+ message: typeof number === "number" ? undefined : "plan task has no positive structured number",
418
+ ...(identity.artifact.migrationProvenance ? { migrationProvenance: { ...identity.artifact.migrationProvenance, source_path: sourcePath, source_task_index: index } } : {}),
419
+ });
420
+ });
421
+ }
422
+ for (const diagnostic of discovery.diagnostics.filter((item) => !seen.has(`${item.path}\0diagnostic`))) {
423
+ if (discovery.identities.some((identity) => identity.artifact.path === diagnostic.path))
424
+ continue;
425
+ const sourcePath = relative(root, diagnostic.path);
426
+ observations.push({ key: `plan:corrupt:${sourcePath}`, artifact: "plan", boundary: "plan", path: sourcePath, provenance: "plan_candidate", record: null, detail: "corrupt", relationships: [], message: diagnostic.message });
427
+ }
428
+ for (const source of files.filter((candidate) => PLAN_ARCHIVE_SOURCE.test(candidate.relative))) {
429
+ if (!discovery.identities.some((identity) => relative(root, identity.artifact.path) === source.relative) && !observations.some((entry) => entry.path === source.relative)) {
430
+ observations.push({ key: `plan:corrupt:${source.relative}`, artifact: "plan", boundary: "plan", path: source.relative, provenance: "plan_candidate", record: null, detail: "corrupt", relationships: [], message: source.kind === "unsafe" ? unsafeSourceMessage(source.relative) : "plan archive could not be validated" });
431
+ }
432
+ }
433
+ }
434
+ function objectiveObservations(root, files, observations) {
435
+ const sourceBytes = new Map(files.flatMap((source) => source.kind === "file" && /^\.agentera\/(optimize|optimera)\/.+\/(objective|experiments)\.yaml$/.test(source.relative)
436
+ ? [[path.join(root, source.relative), source.bytes]]
437
+ : []));
438
+ const discovery = discoverObjectiveArtifacts(root, sourceBytes);
439
+ for (const objective of discovery.objectives) {
440
+ for (const objectivePath of objective.paths) {
441
+ const sourcePath = relative(root, objectivePath);
442
+ const source = files.find((candidate) => candidate.relative === sourcePath);
443
+ let document = null;
444
+ try {
445
+ if (source?.kind === "file")
446
+ document = parseYaml(source);
447
+ }
448
+ catch { /* discovery diagnostic accounts for it */ }
449
+ observations.push({ key: objective.stableId, artifact: "objective", boundary: "objective", path: sourcePath, provenance: sourcePath.startsWith(".agentera/optimize/") ? "current_canonical" : "legacy_objective_root", record: document, detail: objective.ambiguous || !document ? "corrupt" : "full", relationships: [], message: objective.ambiguous ? "objective identity is ambiguous" : undefined });
450
+ }
451
+ if (objective.ambiguous)
452
+ continue;
453
+ const objectivePath = objective.paths[0];
454
+ const experimentsRelative = relative(root, path.join(path.dirname(objectivePath), "experiments.yaml"));
455
+ const experiments = files.find((source) => source.relative === experimentsRelative);
456
+ if (experiments?.kind === "file") {
457
+ try {
458
+ const document = parseYaml(experiments);
459
+ for (const experiment of inspectExperimentIdentities(objective.stableId, document).entries) {
460
+ const key = experiment.stableId ?? `${objective.stableId}/experiment:${experiment.provenance.collection}[${experiment.provenance.index}]`;
461
+ observations.push({ key, artifact: "experiments", boundary: "experiment", path: experiments.relative, provenance: "experiment_projection", record: experiment.data, detail: experiment.addressable ? "full" : experiment.compatibility === "legacy_missing_identity" ? "summary" : "corrupt", relationships: [{ field: "objective", target: objective.stableId }], message: experiment.caveats.join("; ") || undefined });
462
+ }
463
+ }
464
+ catch (error) {
465
+ observations.push({ key: `${objective.stableId}/experiments`, artifact: "experiments", boundary: "experiment", path: experiments.relative, provenance: "experiment_projection", record: null, detail: "corrupt", relationships: [{ field: "objective", target: objective.stableId }], message: error.message });
466
+ }
467
+ }
468
+ else if (experiments?.kind === "unsafe") {
469
+ observations.push({ key: `${objective.stableId}/experiments`, artifact: "experiments", boundary: "experiment", path: experiments.relative, provenance: "experiment_projection", record: null, detail: "corrupt", relationships: [{ field: "objective", target: objective.stableId }], message: unsafeSourceMessage(experiments.relative) });
470
+ }
471
+ }
472
+ for (const diagnostic of discovery.diagnostics) {
473
+ for (const candidate of diagnostic.candidate_paths) {
474
+ if (observations.some((entry) => entry.path === relative(root, candidate)))
475
+ continue;
476
+ observations.push({ key: `objective:corrupt:${relative(root, candidate)}`, artifact: "objective", boundary: "objective", path: relative(root, candidate), provenance: "objective_candidate", record: null, detail: "corrupt", relationships: [], message: diagnostic.message });
477
+ }
478
+ }
479
+ for (const source of files.filter((candidate) => candidate.kind === "unsafe" && /\/(objective|experiments)\.yaml$/.test(candidate.relative))) {
480
+ if (observations.some((entry) => entry.path === source.relative))
481
+ continue;
482
+ const artifact = source.relative.endsWith("/objective.yaml") ? "objective" : "experiments";
483
+ observations.push({ key: `${artifact}:corrupt:${source.relative}`, artifact, boundary: artifact === "objective" ? "objective" : "experiment", path: source.relative, provenance: artifact === "objective" ? "objective_candidate" : "experiment_projection", record: null, detail: "corrupt", relationships: [], message: unsafeSourceMessage(source.relative) });
484
+ }
485
+ }
486
+ function todoAndDocs(root, sourceRoot, todoPath, files, observations) {
487
+ observations.push(...todoMigrationObservations(root, sourceRoot, todoPath, files));
488
+ const docs = files.find((source) => source.relative === ".agentera/docs.yaml");
489
+ if (docs?.kind === "file") {
490
+ try {
491
+ const document = parseYaml(docs);
492
+ if (document.index !== undefined && !Array.isArray(document.index))
493
+ throw new Error("docs index must be a list");
494
+ (Array.isArray(document.index) ? document.index : []).forEach((value, index) => {
495
+ const sourceRecord = mapping(value);
496
+ const originalStatus = sourceRecord?.status;
497
+ const normalizedStatus = originalStatus === "draft" ? "intent" : originalStatus === "archived" ? "stale" : originalStatus;
498
+ const record = sourceRecord ? { ...structuredClone(sourceRecord), ...(normalizedStatus !== originalStatus ? { status: normalizedStatus } : {}) } : null;
499
+ const identity = typeof record?.path === "string" ? `docs:path:${record.path}` : `docs:index:${index}`;
500
+ const violations = record ? todoDocsRecordViolations("documentation_inventory_entry", record) : ["documentation inventory entry must be a mapping"];
501
+ observations.push({ key: identity, artifact: "docs", boundary: "documentation_inventory_entry", path: docs.relative, provenance: "current_canonical", record, detail: violations.length ? "corrupt" : "full", relationships: [], message: violations.length ? violations.join("; ") : undefined, ...(normalizedStatus !== originalStatus ? { migrationProvenance: { kind: "legacy_docs_status_normalization", source_path: docs.relative, index, ...(sourceRecord?.path !== undefined ? { original_path: sourceRecord.path } : {}), ...(originalStatus !== undefined ? { original_status: originalStatus } : {}), ...(normalizedStatus !== undefined ? { normalized_status: normalizedStatus } : {}) } } : {}) });
502
+ });
503
+ }
504
+ catch (error) {
505
+ observations.push({ key: "docs:document", artifact: "docs", boundary: "documentation_inventory_entry", path: docs.relative, provenance: "current_canonical", record: null, detail: "corrupt", relationships: [], message: error.message });
506
+ }
507
+ }
508
+ else if (docs?.kind === "unsafe") {
509
+ observations.push({ key: "docs:document", artifact: "docs", boundary: "documentation_inventory_entry", path: docs.relative, provenance: "current_canonical", record: null, detail: "corrupt", relationships: [], message: unsafeSourceMessage(docs.relative) });
510
+ }
511
+ }
512
+ function preservedSingletons(files) {
513
+ const declarations = [
514
+ { boundary: "vision", source_path: ".agentera/vision.yaml" },
515
+ { boundary: "design", source_path: "DESIGN.md" },
516
+ { boundary: "changelog", source_path: "CHANGELOG.md" },
517
+ { boundary: "docs_mapping", source_path: ".agentera/docs.yaml", preserved_sections: ["last_audit", "conventions", "mapping", "coverage", "audit_log"] },
518
+ { boundary: "profile", source_path: "$AGENTERA_PROFILE_DIR/PROFILE.md" },
519
+ { boundary: "runtime_local_session_state", source_path: "runtime-local" },
520
+ ];
521
+ return declarations.map((declaration) => {
522
+ const source = files.find((candidate) => candidate.relative === declaration.source_path);
523
+ return { ...declaration, presence: source?.kind ?? "missing", content_sha256: source?.bytes ? hash(source.bytes) : null };
524
+ });
525
+ }
526
+ function summaryBoundary(artifact, fallback) {
527
+ return { progress: "progress_summary", decisions: "decision_summary", health: "health_summary" }[artifact] ?? fallback;
528
+ }
529
+ function canonicalSummaryBodies(group, forbiddenAliases) {
530
+ return new Set(group.flatMap((item) => item.record
531
+ ? [canonicalRecordJson(canonicalMigrationRecord(summaryBoundary(item.artifact, item.boundary), item.record, forbiddenAliases))]
532
+ : []));
533
+ }
534
+ function classify(group, forbiddenAliases) {
535
+ if (group.some((item) => item.provenance === "historical_projection_residue"))
536
+ return "historical_projection_residue";
537
+ if (group.some((item) => item.key.startsWith("conflict:")))
538
+ return "conflict";
539
+ if (group.some((item) => item.key.startsWith("unsupported:")))
540
+ return "unsupported";
541
+ if (group.some((item) => item.detail === "corrupt"))
542
+ return "corrupt";
543
+ if (group.every((item) => item.detail === "summary")) {
544
+ if (!COMPACTED_SUMMARY_ARTIFACTS.has(group[0]?.artifact ?? ""))
545
+ return "corrupt";
546
+ return canonicalSummaryBodies(group, forbiddenAliases).size === 1 ? "valid_compacted_summary" : "conflict";
547
+ }
548
+ const full = group.filter((item) => item.detail === "full" && item.record);
549
+ const bodies = new Set(full.map((item) => canonicalRecordJson(item.record)));
550
+ if (bodies.size > 1)
551
+ return "duplicate";
552
+ const archive = group.find((item) => item.provenance === "verified_archive" && item.record);
553
+ const summaries = group.filter((item) => item.detail === "summary" && item.record);
554
+ if (full.length && summaries.length) {
555
+ const selected = archive ?? full[0];
556
+ const recovery = selected.migrationProvenance;
557
+ const recorded = mapping(recovery?.current_projection)?.record_sha256;
558
+ if (!summaries.every((item) => exactProjectionMirror(item.artifact, selected.record, item.record, recorded)))
559
+ return "conflict";
560
+ }
561
+ if (archive || group.some((item) => item.provenance === "verified_plan_archive"))
562
+ return "verified_full";
563
+ if (group.every((item) => item.provenance === "current_projection" || item.provenance === "experiment_projection"))
564
+ return "recoverable_degraded_full_projection";
565
+ return "verified_full";
566
+ }
567
+ function exactProjectionMirror(artifact, full, summary, recorded) {
568
+ if (recorded === hash(canonicalRecordJson(summary)))
569
+ return true;
570
+ if (artifact === "health" && typeof summary.summary === "string" && typeof full.number === "number" && typeof full.date === "string" && typeof full.trajectory === "string") {
571
+ if (summary.summary === `Audit ${full.number} · ${full.date} (${truncateWords(full.trajectory, 10)})`)
572
+ return true;
573
+ }
574
+ if (artifact !== "progress" && artifact !== "decisions" && artifact !== "health")
575
+ return false;
576
+ return canonicalRecordJson(yamlArchiveEntry(artifact, full)) === canonicalRecordJson(summary);
577
+ }
578
+ function buildEntries(project, sourceRoot, fingerprint, observations, forbiddenAliases) {
579
+ const groups = new Map();
580
+ for (const observation of observations)
581
+ groups.set(observation.key, [...(groups.get(observation.key) ?? []), observation]);
582
+ const ids = new Map();
583
+ for (const key of [...groups.keys()].sort()) {
584
+ const group = groups.get(key);
585
+ const canonicalSummaries = group.every((item) => item.detail === "summary") && COMPACTED_SUMMARY_ARTIFACTS.has(group[0]?.artifact ?? "")
586
+ ? [...canonicalSummaryBodies(group, forbiddenAliases)].sort()
587
+ : [];
588
+ const identityBinding = canonicalSummaries.length === 1 ? hash(canonicalRecordJson(canonicalSummaries)) : fingerprint;
589
+ const explicitIds = [...new Set(group.map((item) => item.explicitId).filter((id) => id !== undefined))];
590
+ ids.set(key, explicitIds.length === 1 ? explicitIds[0] : entityMigrationId(identityBinding, key));
591
+ }
592
+ const collisions = new Set();
593
+ const idOwners = new Map();
594
+ for (const [key, id] of ids) {
595
+ const owner = idOwners.get(id);
596
+ if (owner) {
597
+ collisions.add(owner);
598
+ collisions.add(key);
599
+ }
600
+ else
601
+ idOwners.set(id, key);
602
+ }
603
+ const entries = [...groups.entries()].map(([key, unsortedGroup]) => {
604
+ const group = [...unsortedGroup].sort((left, right) => `${left.path}\0${left.provenance}\0${canonicalRecordJson(left.record)}\0${left.sourceRecordSha256 ?? ""}`.localeCompare(`${right.path}\0${right.provenance}\0${canonicalRecordJson(right.record)}\0${right.sourceRecordSha256 ?? ""}`));
605
+ let classification = classify(group, forbiddenAliases);
606
+ if (collisions.has(key))
607
+ classification = "conflict";
608
+ const primary = group[0];
609
+ const contentObservation = group.find((item) => item.provenance === "verified_archive" && item.detail === "full" && item.record)
610
+ ?? group.find((item) => item.detail === "full" && item.record)
611
+ ?? group.find((item) => item.detail === "summary" && item.record);
612
+ const content = contentObservation?.record ?? null;
613
+ const contentSha256s = [...new Set(group.flatMap((item) => item.record ? [hash(canonicalRecordJson(item.record))] : []))].sort();
614
+ const mirrored = contentSha256s.length === 1 && group.filter((item) => item.record).length > 1;
615
+ const id = ids.get(key);
616
+ const relationshipSources = new Map(group.flatMap((item) => item.relationships).map((relationship) => [`${relationship.field}\0${relationship.target ?? ""}`, relationship])).values();
617
+ const relationships = [...relationshipSources].map((relationship) => ({
618
+ field: relationship.field,
619
+ target_source_identity: relationship.target,
620
+ target_id: relationship.target ? ids.get(relationship.target) ?? null : null,
621
+ status: relationship.target && groups.has(relationship.target) ? "resolved" : "unresolved",
622
+ }));
623
+ const summary = classification === "valid_compacted_summary";
624
+ const boundary = summary ? summaryBoundary(primary.artifact, primary.boundary) : contentObservation?.boundary ?? primary.boundary;
625
+ const record = content ? canonicalMigrationRecord(boundary, content, forbiddenAliases, summary ? [] : relationships) : {};
626
+ if (summary && contentObservation && content) {
627
+ record.migration_provenance = {
628
+ source_path: contentObservation.path,
629
+ source_record_sha256: contentObservation.sourceRecordSha256 ?? hash(canonicalRecordJson(content)),
630
+ };
631
+ }
632
+ const residue = classification === "historical_projection_residue";
633
+ const blocked = BLOCKING.has(classification) || relationships.some((relationship) => relationship.status === "unresolved");
634
+ return {
635
+ source_identity: key,
636
+ source_paths: [...new Set(group.map((item) => item.path))].sort(),
637
+ artifact: primary.artifact,
638
+ boundary,
639
+ classification,
640
+ detail_availability: summary ? "summary" : content ? "full" : "unavailable",
641
+ compatibility: summary ? "degraded" : "current",
642
+ provenance: [...new Set([...group.map((item) => item.provenance), ...(mirrored ? ["mirrored"] : [])])].sort(),
643
+ content_sha256: contentSha256s.length === 1 ? contentSha256s[0] : null,
644
+ content_sha256s: contentSha256s,
645
+ physical_record_count: group.length,
646
+ proposed_target: blocked || residue ? null : { id, path: `.agentera/entities/${primary.artifact}/${boundary}/${id}.yaml` },
647
+ target_sha256: null,
648
+ relationships,
649
+ record,
650
+ recovery: blocked ? recovery(project, primary.path) : "none",
651
+ ...(contentObservation?.inheritedConfidenceProvenance ? { canonical_migration_provenance: contentObservation.inheritedConfidenceProvenance } : {}),
652
+ ...(group.some((item) => item.migrationProvenance) ? { migration_provenance: group.flatMap((item) => item.migrationProvenance ? [item.migrationProvenance] : []) } : {}),
653
+ };
654
+ }).sort((a, b) => `${a.artifact}\0${a.boundary}\0${a.source_identity}\0${a.source_paths[0]}`.localeCompare(`${b.artifact}\0${b.boundary}\0${b.source_identity}\0${b.source_paths[0]}`));
655
+ const decisions = new Map(entries.filter(({ boundary, proposed_target }) => boundary === "decision" && proposed_target).map((entry) => [entry.proposed_target.id, entry.record]));
656
+ const legacyDecisions = new Map(entries.filter(({ boundary, proposed_target }) => boundary === "decision" && proposed_target).flatMap((entry) => {
657
+ const group = groups.get(entry.source_identity) ?? [];
658
+ const source = group.find((item) => item.provenance === "verified_archive" && item.detail === "full" && item.record)
659
+ ?? group.find((item) => item.detail === "full" && item.record);
660
+ return source?.record ? [[entry.proposed_target.id, source.record]] : [];
661
+ }));
662
+ migrateDecisionRevisionEntries(entries, decisions, legacyDecisions, sourceRoot, forbiddenAliases, fingerprint);
663
+ return entries;
664
+ }
665
+ export function validateEntityMigrationTargets(project, entries, sourceRoot) {
666
+ const targets = entries.flatMap((entry) => entry.proposed_target && entry.artifact && entry.boundary ? [{ sourceIdentity: entry.source_identity, path: entry.proposed_target.path, id: entry.proposed_target.id, artifact: entry.artifact, boundary: entry.boundary, record: entry.record, migrationProvenance: entry.canonical_migration_provenance }] : []);
667
+ const diagnostics = validateCanonicalEntityTargets(project, targets, sourceRoot);
668
+ for (const entry of entries) {
669
+ if (!entry.proposed_target || !entry.artifact)
670
+ continue;
671
+ const actual = hash(canonicalEntityEnvelopeBytes({ id: entry.proposed_target.id, artifact: entry.artifact, record: entry.record, migrationProvenance: entry.canonical_migration_provenance }));
672
+ if (entry.target_sha256 !== actual)
673
+ diagnostics.push({ sourceIdentity: entry.source_identity, path: entry.proposed_target.path, message: `canonical target bytes have SHA-256 '${actual}', not manifest binding '${entry.target_sha256 ?? "missing"}'` });
674
+ }
675
+ return diagnostics;
676
+ }
677
+ function migrationInventory(projectRoot, sourceRoot, resolveDescriptorPath) {
678
+ const project = path.resolve(projectRoot);
679
+ const validatedProject = validateRealProjectRoot(project);
680
+ const authority = authorityBinding(sourceRoot);
681
+ const todoRecord = loadArtifactRecord("todo");
682
+ if (!todoRecord)
683
+ throw new Error("artifact registry is missing the canonical 'todo' record");
684
+ const docsSnapshot = { relative: ".agentera/docs.yaml", ...readProjectFileSnapshot(validatedProject, ".agentera/docs.yaml", resolveDescriptorPath) };
685
+ const overrides = docsSnapshot.kind === "file" ? docsPathOverridesFromBytes(docsSnapshot.bytes) : {};
686
+ const todoAbsolute = todoRecord.displayName in overrides ? resolveArtifactPath(todoRecord, project, { docsPathOverrides: overrides }) : path.join(project, todoRecord.defaultPath);
687
+ const todoPath = relative(project, todoAbsolute);
688
+ if (todoPath !== todoRecord.defaultPath)
689
+ assertRealpathBoundary(project, todoAbsolute, todoRecord.artifactId);
690
+ const files = collectSources(project, validatedProject, todoPath, docsSnapshot, resolveDescriptorPath);
691
+ const fingerprint = sourceFingerprint(files);
692
+ const observations = [];
693
+ inventoryFailureObservations(files, observations);
694
+ numberedObservations(project, sourceRoot, files, observations, entityPreservedAggregateCollections(sourceRoot));
695
+ decisionEvidence(sourceRoot, files, observations);
696
+ planObservations(project, files, observations);
697
+ objectiveObservations(project, files, observations);
698
+ todoAndDocs(project, sourceRoot, todoPath, files, observations);
699
+ const preserved = preservedSingletons(files);
700
+ const completeInventory = buildEntries(project, sourceRoot, fingerprint, observations, entityForbiddenCanonicalAliases(sourceRoot));
701
+ const preservedResidues = completeInventory.filter((entry) => entry.classification === "historical_projection_residue");
702
+ const completeEntries = completeInventory.filter((entry) => entry.classification !== "historical_projection_residue");
703
+ const todoReconciliation = todoReconciliationMigrationPlan(todoPath, files, completeEntries);
704
+ for (const entry of completeEntries) {
705
+ if (entry.proposed_target && entry.artifact)
706
+ entry.target_sha256 = hash(canonicalEntityEnvelopeBytes({ id: entry.proposed_target.id, artifact: entry.artifact, record: entry.record, migrationProvenance: entry.canonical_migration_provenance }));
707
+ }
708
+ let causal = applyCausalBlockers(completeEntries, (sourcePath) => recovery(project, sourcePath));
709
+ const targetDiagnostics = validateEntityMigrationTargets(project, completeEntries, sourceRoot);
710
+ for (const diagnostic of targetDiagnostics) {
711
+ const entry = completeEntries.find((candidate) => candidate.source_identity === diagnostic.sourceIdentity);
712
+ if (!entry)
713
+ continue;
714
+ entry.classification = "corrupt";
715
+ entry.proposed_target = null;
716
+ entry.target_sha256 = null;
717
+ if (entry.recovery === "none")
718
+ entry.recovery = recovery(project, entry.source_paths[0]);
719
+ causal.rootReasons.set(entry.source_identity, `target_invalid: ${diagnostic.message}`);
720
+ }
721
+ causal = applyCausalBlockers(completeEntries, (sourcePath) => recovery(project, sourcePath), causal.rootReasons);
722
+ const classes = ["verified_full", "recoverable_degraded_full_projection", "valid_compacted_summary", "duplicate", "conflict", "corrupt", "unsupported", "historical_projection_residue"];
723
+ const counts = Object.fromEntries(classes.map((classification) => [classification, completeInventory.filter((entry) => entry.classification === classification).length]));
724
+ counts.total = completeInventory.length;
725
+ counts.publishable_entities = completeEntries.filter(({ proposed_target }) => proposed_target !== null).length;
726
+ counts.logical_identities = completeInventory.length;
727
+ counts.physical_records = observations.length;
728
+ counts.mirrors = completeInventory.reduce((total, entry) => total + (entry.provenance.includes("mirrored") ? entry.physical_record_count - 1 : 0), 0);
729
+ counts.duplicates = completeInventory.reduce((total, entry) => total + (entry.classification === "duplicate" ? entry.physical_record_count - 1 : 0), 0);
730
+ counts.conflicts = counts.duplicate + counts.conflict;
731
+ counts.relationships = completeEntries.reduce((total, entry) => total + entry.relationships.length, 0);
732
+ counts.unresolved_relationships = completeEntries.reduce((total, entry) => total + entry.relationships.filter((relationship) => relationship.status === "unresolved").length, 0);
733
+ const rootDiagnostics = completeEntries
734
+ .filter((entry) => causal.rootReasons.has(entry.source_identity))
735
+ .map((entry) => {
736
+ const unresolved = entry.relationships.find((relationship) => relationship.status === "unresolved");
737
+ const reason = causal.rootReasons.get(entry.source_identity) ?? `${entry.classification} source requires explicit recovery`;
738
+ const observationMessage = observations.find((item) => item.key === entry.source_identity)?.message;
739
+ return {
740
+ classification: entry.classification,
741
+ path: entry.source_paths[0],
742
+ source_identity: entry.source_identity,
743
+ ...(unresolved ? { relationship_field: unresolved.field, target_source_identity: unresolved.target_source_identity } : {}),
744
+ message: reason === `${entry.classification} source requires explicit recovery` && observationMessage ? observationMessage : reason,
745
+ recovery: entry.recovery,
746
+ };
747
+ });
748
+ const dependentDiagnostics = completeEntries.flatMap((entry) => {
749
+ if (causal.rootReasons.has(entry.source_identity))
750
+ return [];
751
+ return entry.relationships.flatMap((relationship) => {
752
+ if (relationship.status !== "resolved" || !relationship.target_source_identity)
753
+ return [];
754
+ return causal.rootsFor(relationship.target_source_identity).map((rootSourceIdentity) => ({
755
+ classification: "dependent_blocker",
756
+ path: entry.source_paths[0],
757
+ source_identity: entry.source_identity,
758
+ relationship_field: relationship.field,
759
+ target_source_identity: relationship.target_source_identity,
760
+ root_source_identity: rootSourceIdentity,
761
+ message: `source '${entry.source_identity}' relationship '${relationship.field}' is blocked by root source '${rootSourceIdentity}'`,
762
+ recovery: recovery(project, entry.source_paths[0]),
763
+ }));
764
+ });
765
+ });
766
+ const diagnostics = [...rootDiagnostics, ...dependentDiagnostics].sort((left, right) => `${left.source_identity}\0${left.classification}\0${left.relationship_field ?? ""}\0${left.target_source_identity ?? ""}\0${left.root_source_identity ?? ""}`.localeCompare(`${right.source_identity}\0${right.classification}\0${right.relationship_field ?? ""}\0${right.target_source_identity ?? ""}\0${right.root_source_identity ?? ""}`));
767
+ counts.root_blockers = rootDiagnostics.length;
768
+ counts.dependent_blockers = dependentDiagnostics.length;
769
+ counts.blockers = counts.root_blockers + counts.dependent_blockers;
770
+ const digestEntries = completeEntries.map(({ record: _record, ...entry }) => entry);
771
+ const digestResidues = preservedResidues.map(({ record: _record, ...entry }) => entry);
772
+ const digestBody = { source_fingerprint: fingerprint, authority, selectors: { project, filter: INVENTORY_FILTER, order: INVENTORY_ORDER }, entries: digestEntries, preserved_residues: digestResidues, preserved_singletons: preserved, counts, diagnostics, todo_reconciliation: todoReconciliation ?? null };
773
+ const previewDigest = hash(canonicalRecordJson(digestBody));
774
+ const sources = files.map((file) => {
775
+ return { path: file.relative, presence: file.kind === "file" ? "file" : "missing", size: file.bytes?.byteLength ?? 0, sha256: file.bytes ? hash(file.bytes) : null, mode: file.kind === "file" ? file.mode : null, dev: file.kind === "file" ? String(file.dev) : null, ino: file.kind === "file" ? String(file.ino) : null, type: file.kind === "file" ? file.type : null, bytes_base64: file.bytes?.toString("base64") ?? null };
776
+ });
777
+ return { project, source_fingerprint: fingerprint, preview_digest: previewDigest, ...authority, preserved_singletons: preserved, entries: completeEntries, preserved_residues: preservedResidues, sources, counts, diagnostics, ...(todoReconciliation ? { todo_reconciliation: todoReconciliation } : {}) };
778
+ }
779
+ export function planEntityMigration(projectRoot, sourceRoot, options = {}) {
780
+ return migrationInventory(projectRoot, sourceRoot, options.resolveDescriptorPath ?? resolveProjectDescriptorPath);
781
+ }
782
+ export function previewEntityMigration(projectRoot, sourceRoot, options = {}) {
783
+ const inventory = migrationInventory(projectRoot, sourceRoot, options.resolveDescriptorPath ?? resolveProjectDescriptorPath);
784
+ const { project, source_fingerprint: fingerprint, preview_digest: previewDigest, preserved_singletons: preserved, counts, diagnostics } = inventory;
785
+ const authority = { authority_schema_version: inventory.authority_schema_version, authority_sha256: inventory.authority_sha256 };
786
+ const completeEntries = inventory.entries.map(({ record: _record, ...entry }) => entry);
787
+ const preservedResidues = inventory.preserved_residues.map(({ record: _record, ...entry }) => entry);
788
+ const requestedLimit = Math.max(1, Math.min(options.limit ?? DEFAULT_LIMIT, MAX_LIMIT));
789
+ const restartCommand = fullEntityUpgradePreviewCommand(project);
790
+ if (options.after !== undefined && (options.sourceFingerprint !== fingerprint || options.previewDigest !== previewDigest)) {
791
+ throw new EntityMigrationContinuationError(restartCommand);
792
+ }
793
+ const start = options.after === undefined ? 0 : completeEntries.findIndex((entry) => entry.source_identity === options.after) + 1;
794
+ if (options.after !== undefined && start === 0)
795
+ throw new Error(`pagination cursor '${options.after}' is not a source identity in the bound inventory; restart without --after`);
796
+ let entries = completeEntries.slice(start, start + requestedLimit);
797
+ const diagnosticsForEntries = () => {
798
+ const identities = new Set(entries.map((entry) => entry.source_identity));
799
+ return diagnostics.filter((diagnostic) => identities.has(diagnostic.source_identity));
800
+ };
801
+ let omissionReason = start > 0 || start + entries.length < completeEntries.length ? "result_limit" : null;
802
+ const base = { schemaVersion: "agentera.entityMigrationPreview.v1", command: "upgrade", status: counts.blockers > 0 ? "blocked" : "ready", mode: "preview", project, read_only: true, mutation_intent: false, mutation_performed: false, source_fingerprint: fingerprint, preview_digest: previewDigest, preserved_singletons: preserved, preserved_residues: preservedResidues, counts, source_contract: { authority: AUTHORITY_PATH, ...authority, zero_write: true, scalar_truncation: "forbidden", apply_owner: "full development-channel upgrade --yes" } };
803
+ const serializedBytes = () => {
804
+ const pageDiagnostics = diagnosticsForEntries();
805
+ const nextAfter = start + entries.length < completeEntries.length ? entries.at(-1)?.source_identity ?? null : null;
806
+ const command = restartCommand;
807
+ const body = { ...base, entries, diagnostics: pageDiagnostics, omitted: start > 0 || entries.length < completeEntries.length, omitted_count: completeEntries.length - entries.length, diagnostics_omitted_count: diagnostics.length - pageDiagnostics.length, omission_reason: omissionReason, page_after: options.after ?? null, next_after: nextAfter, retrieval: { command } };
808
+ return Math.max(Buffer.byteLength(JSON.stringify(body, null, 2), "utf8"), Buffer.byteLength(YAML.stringify(body), "utf8"));
809
+ };
810
+ while (entries.length > 0 && serializedBytes() > ENTITY_MIGRATION_PREVIEW_MAX_OUTPUT_BYTES) {
811
+ entries = entries.slice(0, -1);
812
+ omissionReason = "output_byte_budget";
813
+ }
814
+ if (entries.length === 0 && start < completeEntries.length)
815
+ throw new Error(`the next whole migration entry exceeds the ${ENTITY_MIGRATION_PREVIEW_MAX_OUTPUT_BYTES}-byte output budget; repair that source before retrying`);
816
+ const outputDiagnostics = diagnosticsForEntries();
817
+ const nextAfter = start + entries.length < completeEntries.length ? entries.at(-1)?.source_identity ?? null : null;
818
+ const retrieval = { command: restartCommand };
819
+ return { ...base, status: base.status, mode: "preview", entries, diagnostics: outputDiagnostics, omitted: start > 0 || entries.length < completeEntries.length, omitted_count: completeEntries.length - entries.length, diagnostics_omitted_count: diagnostics.length - outputDiagnostics.length, omission_reason: omissionReason, page_after: options.after ?? null, next_after: nextAfter, retrieval };
820
+ }
821
+ export class EntityMigrationContinuationError extends Error {
822
+ restartCommand;
823
+ classification = "continuation_changed";
824
+ constructor(restartCommand) {
825
+ super(`entity migration continuation no longer matches its source, migration authority, selectors, or order; restart with ${restartCommand}`);
826
+ this.restartCommand = restartCommand;
827
+ this.name = "EntityMigrationContinuationError";
828
+ }
829
+ }
830
+ export class EntityMigrationBindingError extends Error {
831
+ current;
832
+ classification = "source_changed";
833
+ restartCommand;
834
+ constructor(current) {
835
+ const restartCommand = fullEntityUpgradePreviewCommand(current.project);
836
+ super(`entity migration source or migration authority changed after preview; rerun ${restartCommand}`);
837
+ this.current = current;
838
+ this.restartCommand = restartCommand;
839
+ this.name = "EntityMigrationBindingError";
840
+ }
841
+ }
842
+ export function assertEntityMigrationBinding(expectedSourceFingerprint, expectedPreviewDigest, current, effect) {
843
+ if (current.source_fingerprint !== expectedSourceFingerprint || current.preview_digest !== expectedPreviewDigest)
844
+ throw new EntityMigrationBindingError(current);
845
+ return effect();
846
+ }