@feltdb/core 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/dist/agent-state.d.ts +20 -0
  2. package/dist/agent-state.d.ts.map +1 -1
  3. package/dist/agent-state.js +36 -0
  4. package/dist/build-identity.json +12 -4
  5. package/dist/cli/commands.js +187 -4
  6. package/dist/cli/publish-engine.js +116 -16
  7. package/dist/collection.d.ts.map +1 -1
  8. package/dist/collection.js +3 -0
  9. package/dist/create/build-identity.json +12 -4
  10. package/dist/create/managed-account.js +93 -35
  11. package/dist/create/package-versions.js +1 -1
  12. package/dist/create/server-source/Cargo.lock +6 -509
  13. package/dist/create/server-source/Cargo.toml +2 -13
  14. package/dist/create/server-source/crates/feltdb-client/Cargo.toml +1 -1
  15. package/dist/create/server-source/crates/feltdb-server/Cargo.toml +1 -1
  16. package/dist/create/server-source/crates/feltdb-server/src/main.rs +255 -12
  17. package/dist/create/server-source/crates/feltdb-wasm/Cargo.toml +1 -1
  18. package/dist/db.d.ts +11 -1
  19. package/dist/db.d.ts.map +1 -1
  20. package/dist/db.js +15 -2
  21. package/dist/error-codes.d.ts +5 -0
  22. package/dist/error-codes.d.ts.map +1 -1
  23. package/dist/error-codes.js +9 -1
  24. package/dist/http-db.d.ts +16 -0
  25. package/dist/http-db.d.ts.map +1 -1
  26. package/dist/http-db.js +36 -6
  27. package/dist/managed-recovery.d.ts +6 -0
  28. package/dist/managed-recovery.d.ts.map +1 -1
  29. package/dist/managed-recovery.js +9 -0
  30. package/dist/studio-app/assets/{feltdb_wasm-BjM1ylL3.js → feltdb_wasm-DtybUY0q.js} +1 -1
  31. package/dist/studio-app/assets/feltdb_wasm_bg-DsgIUwaB.wasm +0 -0
  32. package/dist/studio-app/assets/index-C4OffsZl.js +37 -0
  33. package/dist/studio-app/index.html +1 -1
  34. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  35. package/dist/wasm/package.json +1 -1
  36. package/dist/workload.d.ts +55 -3
  37. package/dist/workload.d.ts.map +1 -1
  38. package/dist/workload.js +23 -0
  39. package/dist/workspace/workspace-connection.d.ts.map +1 -1
  40. package/dist/workspace/workspace-connection.js +14 -3
  41. package/package.json +1 -1
  42. package/dist/create/server-source/crates/feltdb/Cargo.lock +0 -175
  43. package/dist/create/server-source/crates/feltdb/Cargo.toml +0 -102
  44. package/dist/create/server-source/crates/feltdb/LICENSE +0 -21
  45. package/dist/create/server-source/crates/feltdb/README.md +0 -75
  46. package/dist/create/server-source/crates/feltdb/benches/baselines/gate-13-redux.json +0 -370
  47. package/dist/create/server-source/crates/feltdb/benches/gate13_baseline.rs +0 -589
  48. package/dist/create/server-source/crates/feltdb/benches/gate13_phase_7_1_release_economics.rs +0 -247
  49. package/dist/create/server-source/crates/feltdb/benches/gate_13_redux.rs +0 -440
  50. package/dist/create/server-source/crates/feltdb/benches/gate_13_regression_runner.rs +0 -275
  51. package/dist/create/server-source/crates/feltdb/benches/gate_14a_concurrent_writer_scaling.rs +0 -381
  52. package/dist/create/server-source/crates/feltdb/benches/gate_14a_production_admission_revalidation.rs +0 -467
  53. package/dist/create/server-source/crates/feltdb/benches/gate_14a_rc2_admission_contract.rs +0 -489
  54. package/dist/create/server-source/crates/feltdb/benches/gate_14a_rc_root_cause.rs +0 -281
  55. package/dist/create/server-source/crates/feltdb/benches/gate_14a_sync1_queued_prototype.rs +0 -606
  56. package/dist/create/server-source/crates/feltdb/benches/gate_14a_sync_economics.rs +0 -531
  57. package/dist/create/server-source/crates/feltdb/benches/gate_14b_causal_backlog_scaling.rs +0 -462
  58. package/dist/create/server-source/crates/feltdb/benches/gate_14c_replication_contract_test.rs +0 -505
  59. package/dist/create/server-source/crates/feltdb/benches/gate_14c_replication_scaling.rs +0 -484
  60. package/dist/create/server-source/crates/feltdb/benches/gate_14d_combined_dimension_scaling.rs +0 -758
  61. package/dist/create/server-source/crates/feltdb/benches/phase_7_1_2_optimization_benchmark.rs +0 -421
  62. package/dist/create/server-source/crates/feltdb/benches/phase_7_1_3_crossover_analysis.rs +0 -329
  63. package/dist/create/server-source/crates/feltdb/src/acceptance_tests.rs +0 -1705
  64. package/dist/create/server-source/crates/feltdb/src/acquisition.rs +0 -286
  65. package/dist/create/server-source/crates/feltdb/src/admission.rs +0 -185
  66. package/dist/create/server-source/crates/feltdb/src/admission_contract_tests.rs +0 -507
  67. package/dist/create/server-source/crates/feltdb/src/adversarial_transport.rs +0 -539
  68. package/dist/create/server-source/crates/feltdb/src/agent_state.rs +0 -320
  69. package/dist/create/server-source/crates/feltdb/src/agent_transition_contract.rs +0 -1545
  70. package/dist/create/server-source/crates/feltdb/src/analytics.rs +0 -521
  71. package/dist/create/server-source/crates/feltdb/src/application.rs +0 -2674
  72. package/dist/create/server-source/crates/feltdb/src/application_runtime.rs +0 -1070
  73. package/dist/create/server-source/crates/feltdb/src/authority.rs +0 -479
  74. package/dist/create/server-source/crates/feltdb/src/authority_failover.rs +0 -847
  75. package/dist/create/server-source/crates/feltdb/src/authorization.rs +0 -1030
  76. package/dist/create/server-source/crates/feltdb/src/authorization_security_tests.rs +0 -1122
  77. package/dist/create/server-source/crates/feltdb/src/bin/feltdb-authority-client.rs +0 -32
  78. package/dist/create/server-source/crates/feltdb/src/bin/feltdb-authority.rs +0 -19
  79. package/dist/create/server-source/crates/feltdb/src/bin/feltdb_node.rs +0 -1474
  80. package/dist/create/server-source/crates/feltdb/src/capabilities/mod.rs +0 -8
  81. package/dist/create/server-source/crates/feltdb/src/capabilities/search.rs +0 -418
  82. package/dist/create/server-source/crates/feltdb/src/capabilities/vector.rs +0 -482
  83. package/dist/create/server-source/crates/feltdb/src/capability.rs +0 -903
  84. package/dist/create/server-source/crates/feltdb/src/cardinality_diagnostics.rs +0 -263
  85. package/dist/create/server-source/crates/feltdb/src/cardinality_endpoint.rs +0 -77
  86. package/dist/create/server-source/crates/feltdb/src/causal_backlog_bound.rs +0 -496
  87. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier.rs +0 -2574
  88. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier_phase_7_1.rs +0 -212
  89. package/dist/create/server-source/crates/feltdb/src/concurrency_fuzzing.rs +0 -422
  90. package/dist/create/server-source/crates/feltdb/src/consistency_contract.rs +0 -445
  91. package/dist/create/server-source/crates/feltdb/src/content_distribution.rs +0 -465
  92. package/dist/create/server-source/crates/feltdb/src/convergence.rs +0 -634
  93. package/dist/create/server-source/crates/feltdb/src/crash_atomic_boundary.rs +0 -427
  94. package/dist/create/server-source/crates/feltdb/src/crash_injection.rs +0 -376
  95. package/dist/create/server-source/crates/feltdb/src/crash_recovery_tests.rs +0 -365
  96. package/dist/create/server-source/crates/feltdb/src/cron.rs +0 -294
  97. package/dist/create/server-source/crates/feltdb/src/dedup_bound_investigation.rs +0 -483
  98. package/dist/create/server-source/crates/feltdb/src/distributed_indexing.rs +0 -477
  99. package/dist/create/server-source/crates/feltdb/src/distributed_tests.rs +0 -1003
  100. package/dist/create/server-source/crates/feltdb/src/distributed_transactions.rs +0 -1334
  101. package/dist/create/server-source/crates/feltdb/src/durability_guarantees.rs +0 -368
  102. package/dist/create/server-source/crates/feltdb/src/durable_dedup_set.rs +0 -231
  103. package/dist/create/server-source/crates/feltdb/src/durable_operation_identity.rs +0 -482
  104. package/dist/create/server-source/crates/feltdb/src/durable_operation_log.rs +0 -203
  105. package/dist/create/server-source/crates/feltdb/src/durable_sync.rs +0 -317
  106. package/dist/create/server-source/crates/feltdb/src/equality_index.rs +0 -595
  107. package/dist/create/server-source/crates/feltdb/src/execution.rs +0 -426
  108. package/dist/create/server-source/crates/feltdb/src/in_process_transport.rs +0 -214
  109. package/dist/create/server-source/crates/feltdb/src/indexing.rs +0 -776
  110. package/dist/create/server-source/crates/feltdb/src/lib.rs +0 -7365
  111. package/dist/create/server-source/crates/feltdb/src/managed_cas_tests.rs +0 -234
  112. package/dist/create/server-source/crates/feltdb/src/materialization.rs +0 -184
  113. package/dist/create/server-source/crates/feltdb/src/metrics.rs +0 -266
  114. package/dist/create/server-source/crates/feltdb/src/multi_node_convergence.rs +0 -310
  115. package/dist/create/server-source/crates/feltdb/src/multi_operation_transaction.rs +0 -736
  116. package/dist/create/server-source/crates/feltdb/src/observability.rs +0 -379
  117. package/dist/create/server-source/crates/feltdb/src/operation.rs +0 -290
  118. package/dist/create/server-source/crates/feltdb/src/operation_algebra.rs +0 -439
  119. package/dist/create/server-source/crates/feltdb/src/operation_log.rs +0 -349
  120. package/dist/create/server-source/crates/feltdb/src/p1_application_atomicity.rs +0 -332
  121. package/dist/create/server-source/crates/feltdb/src/p1_atomicity_acceptance.rs +0 -718
  122. package/dist/create/server-source/crates/feltdb/src/partition_reconciliation.rs +0 -487
  123. package/dist/create/server-source/crates/feltdb/src/peer_registry.rs +0 -166
  124. package/dist/create/server-source/crates/feltdb/src/permutation_scheduler.rs +0 -289
  125. package/dist/create/server-source/crates/feltdb/src/persistence_reality.rs +0 -566
  126. package/dist/create/server-source/crates/feltdb/src/phase1b_acceptance.rs +0 -3391
  127. package/dist/create/server-source/crates/feltdb/src/phase1c1_acceptance.rs +0 -203
  128. package/dist/create/server-source/crates/feltdb/src/phase1c2_acceptance.rs +0 -261
  129. package/dist/create/server-source/crates/feltdb/src/phase1c3_acceptance.rs +0 -502
  130. package/dist/create/server-source/crates/feltdb/src/phase1c_atomicity_proof.rs +0 -216
  131. package/dist/create/server-source/crates/feltdb/src/phase5_integration.rs +0 -303
  132. package/dist/create/server-source/crates/feltdb/src/phase5_scenarios.rs +0 -323
  133. package/dist/create/server-source/crates/feltdb/src/phase6_adversarial_scenarios.rs +0 -531
  134. package/dist/create/server-source/crates/feltdb/src/phase6_convergence_validator.rs +0 -406
  135. package/dist/create/server-source/crates/feltdb/src/phase6_persistence.rs +0 -436
  136. package/dist/create/server-source/crates/feltdb/src/phase_1c_real_tcp.rs +0 -387
  137. package/dist/create/server-source/crates/feltdb/src/phase_2a_failures.rs +0 -378
  138. package/dist/create/server-source/crates/feltdb/src/phase_2b_network.rs +0 -359
  139. package/dist/create/server-source/crates/feltdb/src/phase_2c_cascading.rs +0 -372
  140. package/dist/create/server-source/crates/feltdb/src/phase_3_durability.rs +0 -404
  141. package/dist/create/server-source/crates/feltdb/src/phase_4_baseline.rs +0 -376
  142. package/dist/create/server-source/crates/feltdb/src/phase_5_soak.rs +0 -461
  143. package/dist/create/server-source/crates/feltdb/src/policy_evaluation.rs +0 -2125
  144. package/dist/create/server-source/crates/feltdb/src/production_api.rs +0 -418
  145. package/dist/create/server-source/crates/feltdb/src/provenance.rs +0 -207
  146. package/dist/create/server-source/crates/feltdb/src/query_execution_diagnostics.rs +0 -126
  147. package/dist/create/server-source/crates/feltdb/src/query_performance.rs +0 -218
  148. package/dist/create/server-source/crates/feltdb/src/read_basis.rs +0 -257
  149. package/dist/create/server-source/crates/feltdb/src/references.rs +0 -404
  150. package/dist/create/server-source/crates/feltdb/src/replay_fuzzing.rs +0 -401
  151. package/dist/create/server-source/crates/feltdb/src/replica_acknowledgements.rs +0 -501
  152. package/dist/create/server-source/crates/feltdb/src/replica_membership.rs +0 -680
  153. package/dist/create/server-source/crates/feltdb/src/replication_manager.rs +0 -163
  154. package/dist/create/server-source/crates/feltdb/src/replication_protocol.rs +0 -133
  155. package/dist/create/server-source/crates/feltdb/src/routing.rs +0 -409
  156. package/dist/create/server-source/crates/feltdb/src/semantic_decision.rs +0 -2029
  157. package/dist/create/server-source/crates/feltdb/src/semantic_query.rs +0 -599
  158. package/dist/create/server-source/crates/feltdb/src/sharding.rs +0 -549
  159. package/dist/create/server-source/crates/feltdb/src/state_conflict_contract.rs +0 -516
  160. package/dist/create/server-source/crates/feltdb/src/state_contract.rs +0 -6003
  161. package/dist/create/server-source/crates/feltdb/src/state_diff_contract.rs +0 -222
  162. package/dist/create/server-source/crates/feltdb/src/state_facade.rs +0 -320
  163. package/dist/create/server-source/crates/feltdb/src/state_hash.rs +0 -291
  164. package/dist/create/server-source/crates/feltdb/src/state_model.rs +0 -4158
  165. package/dist/create/server-source/crates/feltdb/src/state_transition_store.rs +0 -379
  166. package/dist/create/server-source/crates/feltdb/src/state_trigger.rs +0 -673
  167. package/dist/create/server-source/crates/feltdb/src/storage.rs +0 -273
  168. package/dist/create/server-source/crates/feltdb/src/submission.rs +0 -471
  169. package/dist/create/server-source/crates/feltdb/src/sync.rs +0 -495
  170. package/dist/create/server-source/crates/feltdb/src/sync_contract.rs +0 -822
  171. package/dist/create/server-source/crates/feltdb/src/tcp_transport.rs +0 -433
  172. package/dist/create/server-source/crates/feltdb/src/transaction_api.rs +0 -462
  173. package/dist/create/server-source/crates/feltdb/src/transaction_invariants.rs +0 -965
  174. package/dist/create/server-source/crates/feltdb/src/transaction_preconditions.rs +0 -1120
  175. package/dist/create/server-source/crates/feltdb/src/transactions.rs +0 -643
  176. package/dist/create/server-source/crates/feltdb/src/trigger.rs +0 -390
  177. package/dist/create/server-source/crates/feltdb/src/trigger_contract.rs +0 -749
  178. package/dist/create/server-source/crates/feltdb/src/versioned_object_substrate.rs +0 -708
  179. package/dist/create/server-source/crates/feltdb/src/worker_mesh.rs +0 -1269
  180. package/dist/create/server-source/crates/feltdb/src/workflow.rs +0 -713
  181. package/dist/create/server-source/crates/feltdb/src/workflow_acceptance_tests.rs +0 -510
  182. package/dist/create/server-source/crates/feltdb/src/workflow_integration.rs +0 -354
  183. package/dist/create/server-source/crates/feltdb/src/workflow_runtime.rs +0 -594
  184. package/dist/create/server-source/crates/feltdb/src/workload.rs +0 -4222
  185. package/dist/create/server-source/crates/feltdb/src/workload_diagnostics.rs +0 -456
  186. package/dist/create/server-source/crates/feltdb/tests/agent_state_native.rs +0 -1188
  187. package/dist/create/server-source/crates/feltdb/tests/agent_transition_contract_conformance.rs +0 -2884
  188. package/dist/create/server-source/crates/feltdb/tests/authority_process.rs +0 -297
  189. package/dist/create/server-source/crates/feltdb/tests/authority_transaction_identity.rs +0 -534
  190. package/dist/create/server-source/crates/feltdb/tests/bounded_read_contract.rs +0 -132
  191. package/dist/create/server-source/crates/feltdb/tests/branching_evidence.rs +0 -299
  192. package/dist/create/server-source/crates/feltdb/tests/common/mod.rs +0 -96
  193. package/dist/create/server-source/crates/feltdb/tests/compaction_stall_contract.rs +0 -272
  194. package/dist/create/server-source/crates/feltdb/tests/crash_durability_contract.rs +0 -467
  195. package/dist/create/server-source/crates/feltdb/tests/current_revision_authority_evidence.rs +0 -309
  196. package/dist/create/server-source/crates/feltdb/tests/durable_backup_contract.rs +0 -445
  197. package/dist/create/server-source/crates/feltdb/tests/durable_corruption_contract.rs +0 -518
  198. package/dist/create/server-source/crates/feltdb/tests/durable_format_compatibility.rs +0 -392
  199. package/dist/create/server-source/crates/feltdb/tests/feltdb_state_boundary_tests.rs +0 -850
  200. package/dist/create/server-source/crates/feltdb/tests/fixtures/agent_transition_corpus.json +0 -23340
  201. package/dist/create/server-source/crates/feltdb/tests/fixtures/state_conflict_contract_corpus.json +0 -1916
  202. package/dist/create/server-source/crates/feltdb/tests/fixtures/state_diff_contract_corpus.json +0 -1878
  203. package/dist/create/server-source/crates/feltdb/tests/fixtures/trigger_contract_corpus.json +0 -1862
  204. package/dist/create/server-source/crates/feltdb/tests/generalized_version_control_evidence.rs +0 -123
  205. package/dist/create/server-source/crates/feltdb/tests/generalized_version_control_substrate_completion.rs +0 -299
  206. package/dist/create/server-source/crates/feltdb/tests/local_process_ownership.rs +0 -69
  207. package/dist/create/server-source/crates/feltdb/tests/managed_incident_regression.rs +0 -191
  208. package/dist/create/server-source/crates/feltdb/tests/operational_health_contract.rs +0 -278
  209. package/dist/create/server-source/crates/feltdb/tests/pr34_query_collection.rs +0 -234
  210. package/dist/create/server-source/crates/feltdb/tests/pr35_equality_index.rs +0 -947
  211. package/dist/create/server-source/crates/feltdb/tests/pr7_self_authorization_proof.rs +0 -404
  212. package/dist/create/server-source/crates/feltdb/tests/pr8_vocabulary_assessment.rs +0 -916
  213. package/dist/create/server-source/crates/feltdb/tests/pr9_phase2_boundary_tests.rs +0 -1045
  214. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3a_path_a_tests.rs +0 -347
  215. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_authorized_mutations.rs +0 -361
  216. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_role_based_authorization.rs +0 -330
  217. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_simple_auth_delete.rs +0 -93
  218. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_team_delete_role_authorization.rs +0 -622
  219. package/dist/create/server-source/crates/feltdb/tests/pr9_teams_role_based_access.rs +0 -517
  220. package/dist/create/server-source/crates/feltdb/tests/production_certification.rs +0 -1153
  221. package/dist/create/server-source/crates/feltdb/tests/production_contract.rs +0 -771
  222. package/dist/create/server-source/crates/feltdb/tests/production_readiness_contract.rs +0 -1383
  223. package/dist/create/server-source/crates/feltdb/tests/reconciliation_application.rs +0 -868
  224. package/dist/create/server-source/crates/feltdb/tests/reconciliation_wire_format_evidence.rs +0 -221
  225. package/dist/create/server-source/crates/feltdb/tests/replicated_history_contract.rs +0 -417
  226. package/dist/create/server-source/crates/feltdb/tests/resource_scoped_revisions.rs +0 -338
  227. package/dist/create/server-source/crates/feltdb/tests/revision_identity_contract.rs +0 -1039
  228. package/dist/create/server-source/crates/feltdb/tests/revision_model_decision.rs +0 -739
  229. package/dist/create/server-source/crates/feltdb/tests/revision_retention_boundary_evidence.rs +0 -452
  230. package/dist/create/server-source/crates/feltdb/tests/saas_authorization_integration.rs +0 -81
  231. package/dist/create/server-source/crates/feltdb/tests/saas_invitation_lifecycle.rs +0 -438
  232. package/dist/create/server-source/crates/feltdb/tests/semantic_decision.rs +0 -1165
  233. package/dist/create/server-source/crates/feltdb/tests/semantic_query.rs +0 -767
  234. package/dist/create/server-source/crates/feltdb/tests/semantic_query_contract.rs +0 -363
  235. package/dist/create/server-source/crates/feltdb/tests/state_conflict_contract_conformance.rs +0 -1799
  236. package/dist/create/server-source/crates/feltdb/tests/state_diff_contract_conformance.rs +0 -1316
  237. package/dist/create/server-source/crates/feltdb/tests/state_model_integration.rs +0 -358
  238. package/dist/create/server-source/crates/feltdb/tests/state_persistence_integration.rs +0 -365
  239. package/dist/create/server-source/crates/feltdb/tests/state_ref_authority.rs +0 -918
  240. package/dist/create/server-source/crates/feltdb/tests/state_store_boundary_evidence.rs +0 -299
  241. package/dist/create/server-source/crates/feltdb/tests/storage_independent_versioned_object_substrate.rs +0 -328
  242. package/dist/create/server-source/crates/feltdb/tests/sync_divergence_evidence.rs +0 -255
  243. package/dist/create/server-source/crates/feltdb/tests/three_way_input_boundary_evidence.rs +0 -249
  244. package/dist/create/server-source/crates/feltdb/tests/trigger_contract_conformance.rs +0 -994
  245. package/dist/create/server-source/crates/feltdb/tests/workload_envelope_contract.rs +0 -484
  246. package/dist/studio-app/assets/feltdb_wasm_bg-TseJn2Ax.wasm +0 -0
  247. package/dist/studio-app/assets/index-1wd0uKua.js +0 -30
@@ -1,2674 +0,0 @@
1
- use serde::{Deserialize, Serialize};
2
- use serde_json::Value;
3
- use sha2::{Digest, Sha256};
4
- use std::{
5
- collections::{BTreeMap, BTreeSet},
6
- fs,
7
- path::PathBuf,
8
- sync::{Arc, RwLock},
9
- time::{SystemTime, UNIX_EPOCH},
10
- };
11
-
12
- pub const MANIFEST_SCHEMA_VERSION: u32 = 1;
13
- fn default_state_schema_version() -> u64 {
14
- 1
15
- }
16
-
17
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
18
- pub struct ApplicationMetadata {
19
- pub name: String,
20
- #[serde(default)]
21
- pub description: String,
22
- #[serde(default)]
23
- pub labels: BTreeMap<String, String>,
24
- }
25
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26
- pub struct FieldDefinition {
27
- pub name: String,
28
- #[serde(rename = "type")]
29
- pub field_type: String,
30
- #[serde(default)]
31
- pub required: bool,
32
- #[serde(default)]
33
- pub nullable: bool,
34
- #[serde(default)]
35
- pub default: Option<Value>,
36
- #[serde(default)]
37
- pub enum_values: Vec<String>,
38
- #[serde(default)]
39
- pub reference: Option<String>,
40
- #[serde(default)]
41
- pub computed: Option<String>,
42
- }
43
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
44
- pub struct CollectionDefinition {
45
- pub name: String,
46
- #[serde(default)]
47
- pub fields: Vec<FieldDefinition>,
48
- }
49
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50
- pub struct IndexDefinition {
51
- pub name: String,
52
- pub collection: String,
53
- pub fields: Vec<String>,
54
- #[serde(default)]
55
- pub unique: bool,
56
- #[serde(default)]
57
- pub sparse: bool,
58
- #[serde(default = "default_index_version")]
59
- pub version: u32,
60
- }
61
- fn default_index_version() -> u32 {
62
- 1
63
- }
64
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
65
- pub struct ReferenceDefinition {
66
- pub name: String,
67
- pub from_collection: String,
68
- pub from_field: String,
69
- pub to_collection: String,
70
- pub to_field: String,
71
- }
72
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
73
- pub struct QueryDefinition {
74
- pub name: String,
75
- pub collection: String,
76
- #[serde(default)]
77
- pub filter: Value,
78
- #[serde(default)]
79
- pub fields: Vec<String>,
80
- }
81
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
82
- #[serde(rename_all = "snake_case")]
83
- pub enum ActionOperation {
84
- Create,
85
- Update,
86
- Delete,
87
- }
88
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
89
- pub struct ActionDefinition {
90
- pub name: String,
91
- pub operation: ActionOperation,
92
- pub collection: String,
93
- #[serde(default)]
94
- pub input_fields: Vec<String>,
95
- #[serde(default)]
96
- pub required_capabilities: Vec<String>,
97
- #[serde(default)]
98
- pub audit: bool,
99
- }
100
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
101
- pub struct WorkflowStepDefinition {
102
- pub name: String,
103
- #[serde(default)]
104
- pub capability: Option<String>,
105
- }
106
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
107
- pub struct WorkflowDefinition {
108
- pub name: String,
109
- #[serde(default)]
110
- pub steps: Vec<WorkflowStepDefinition>,
111
- }
112
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
113
- pub struct TriggerDefinition {
114
- pub name: String,
115
- pub event: String,
116
- pub workflow: String,
117
- }
118
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
119
- pub struct ScheduleDefinition {
120
- pub name: String,
121
- pub expression: String,
122
- pub workflow: String,
123
- }
124
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
125
- pub struct AgentDefinition {
126
- pub name: String,
127
- #[serde(default)]
128
- pub capabilities: Vec<String>,
129
- }
130
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
131
- pub struct CapabilityBinding {
132
- pub name: String,
133
- #[serde(default)]
134
- pub provider: Option<String>,
135
- #[serde(default = "public_capability_visibility")]
136
- pub visibility: String,
137
- }
138
- fn public_capability_visibility() -> String {
139
- "public".into()
140
- }
141
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
142
- pub struct SecretReference {
143
- pub binding: String,
144
- pub secret_id: String,
145
- }
146
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
147
- pub struct ConnectionBinding {
148
- pub name: String,
149
- pub connection_id: String,
150
- #[serde(default)]
151
- pub configuration: Value,
152
- #[serde(default)]
153
- pub secrets: Vec<SecretReference>,
154
- }
155
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
156
- pub struct PolicyDefinition {
157
- pub name: String,
158
- pub resource: String,
159
- #[serde(default)]
160
- pub read: Option<String>,
161
- #[serde(default)]
162
- pub write: Option<String>,
163
- #[serde(default)]
164
- pub capabilities: Vec<String>,
165
- }
166
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
167
- pub struct DataBinding {
168
- pub name: String,
169
- #[serde(default)]
170
- pub collection: Option<String>,
171
- #[serde(default)]
172
- pub query: Option<String>,
173
- #[serde(default)]
174
- pub fields: Vec<String>,
175
- }
176
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
177
- pub struct FormDefinition {
178
- pub name: String,
179
- pub collection: String,
180
- #[serde(default)]
181
- pub fields: Vec<String>,
182
- }
183
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
184
- pub struct DashboardDefinition {
185
- pub name: String,
186
- #[serde(default)]
187
- pub bindings: Vec<String>,
188
- }
189
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
190
- pub struct RouteDefinition {
191
- pub path: String,
192
- pub view: String,
193
- }
194
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
195
- pub struct UiApplicationModel {
196
- #[serde(default)]
197
- pub routes: Vec<RouteDefinition>,
198
- #[serde(default)]
199
- pub bindings: Vec<DataBinding>,
200
- #[serde(default)]
201
- pub forms: Vec<FormDefinition>,
202
- #[serde(default)]
203
- pub dashboards: Vec<DashboardDefinition>,
204
- }
205
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
206
- pub struct EnvironmentDefinition {
207
- pub name: String,
208
- #[serde(default)]
209
- pub configuration: BTreeMap<String, String>,
210
- }
211
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
212
- pub struct ArtifactReference {
213
- pub name: String,
214
- pub uri: String,
215
- pub media_type: String,
216
- /// Immutable source bytes used by trusted control-plane services. The URI
217
- /// remains the content identity; values are base64 and never interpreted by Rust.
218
- #[serde(default, skip_serializing_if = "Option::is_none")]
219
- pub content: Option<String>,
220
- }
221
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
222
- pub struct DeploymentIntent {
223
- #[serde(default)]
224
- pub environments: Vec<String>,
225
- #[serde(default)]
226
- pub placement: Option<String>,
227
- }
228
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
229
- pub struct RuntimeRequirement {
230
- #[serde(default = "runtime_contract_version")]
231
- pub contract: u32,
232
- #[serde(default = "minimum_engine_version")]
233
- pub minimum_engine: String,
234
- #[serde(default)]
235
- pub maximum_engine_exclusive: Option<String>,
236
- }
237
- impl Default for RuntimeRequirement {
238
- fn default() -> Self {
239
- Self {
240
- contract: runtime_contract_version(),
241
- minimum_engine: minimum_engine_version(),
242
- maximum_engine_exclusive: Some("2.0.0".into()),
243
- }
244
- }
245
- }
246
- fn runtime_contract_version() -> u32 {
247
- 1
248
- }
249
- fn minimum_engine_version() -> String {
250
- "0.2.0".into()
251
- }
252
-
253
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
254
- pub struct ApplicationManifest {
255
- pub application_id: String,
256
- pub tenant_id: String,
257
- pub schema: u32,
258
- #[serde(default = "default_state_schema_version")]
259
- pub state_schema_version: u64,
260
- pub metadata: ApplicationMetadata,
261
- #[serde(default)]
262
- pub collections: Vec<CollectionDefinition>,
263
- #[serde(default)]
264
- pub indexes: Vec<IndexDefinition>,
265
- #[serde(default)]
266
- pub references: Vec<ReferenceDefinition>,
267
- #[serde(default)]
268
- pub queries: Vec<QueryDefinition>,
269
- #[serde(default)]
270
- pub actions: Vec<ActionDefinition>,
271
- #[serde(default)]
272
- pub workflows: Vec<WorkflowDefinition>,
273
- #[serde(default)]
274
- pub triggers: Vec<TriggerDefinition>,
275
- #[serde(default)]
276
- pub schedules: Vec<ScheduleDefinition>,
277
- #[serde(default)]
278
- pub agents: Vec<AgentDefinition>,
279
- #[serde(default)]
280
- pub capabilities: Vec<CapabilityBinding>,
281
- /// Resolved, provider-neutral module semantic contracts. Secret values are forbidden.
282
- #[serde(default)]
283
- pub modules: Vec<serde_json::Value>,
284
- #[serde(default)]
285
- pub connections: Vec<ConnectionBinding>,
286
- #[serde(default)]
287
- pub policies: Vec<PolicyDefinition>,
288
- #[serde(default)]
289
- pub ui: UiApplicationModel,
290
- #[serde(default)]
291
- pub environments: Vec<EnvironmentDefinition>,
292
- #[serde(default)]
293
- pub artifacts: Vec<ArtifactReference>,
294
- #[serde(default)]
295
- pub deployment: DeploymentIntent,
296
- #[serde(default)]
297
- pub runtime: RuntimeRequirement,
298
- }
299
-
300
- impl ApplicationManifest {
301
- pub fn empty(
302
- tenant_id: impl Into<String>,
303
- application_id: impl Into<String>,
304
- name: impl Into<String>,
305
- ) -> Self {
306
- Self {
307
- application_id: application_id.into(),
308
- tenant_id: tenant_id.into(),
309
- schema: MANIFEST_SCHEMA_VERSION,
310
- state_schema_version: 1,
311
- metadata: ApplicationMetadata {
312
- name: name.into(),
313
- ..Default::default()
314
- },
315
- collections: vec![],
316
- indexes: vec![],
317
- references: vec![],
318
- queries: vec![],
319
- actions: vec![],
320
- workflows: vec![],
321
- triggers: vec![],
322
- schedules: vec![],
323
- agents: vec![],
324
- capabilities: vec![],
325
- modules: vec![],
326
- connections: vec![],
327
- policies: vec![],
328
- ui: UiApplicationModel::default(),
329
- environments: vec![
330
- EnvironmentDefinition {
331
- name: "development".into(),
332
- configuration: BTreeMap::new(),
333
- },
334
- EnvironmentDefinition {
335
- name: "preview".into(),
336
- configuration: BTreeMap::new(),
337
- },
338
- EnvironmentDefinition {
339
- name: "staging".into(),
340
- configuration: BTreeMap::new(),
341
- },
342
- EnvironmentDefinition {
343
- name: "production".into(),
344
- configuration: BTreeMap::new(),
345
- },
346
- ],
347
- artifacts: vec![],
348
- deployment: DeploymentIntent {
349
- environments: vec![
350
- "development".into(),
351
- "preview".into(),
352
- "staging".into(),
353
- "production".into(),
354
- ],
355
- placement: None,
356
- },
357
- runtime: RuntimeRequirement::default(),
358
- }
359
- }
360
- }
361
-
362
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
363
- #[serde(rename_all = "snake_case")]
364
- pub enum Compatibility {
365
- Compatible,
366
- RequiresMigration,
367
- Breaking,
368
- Invalid,
369
- }
370
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
371
- pub struct ValidationIssue {
372
- pub category: String,
373
- pub path: String,
374
- pub message: String,
375
- }
376
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
377
- pub struct ValidationReport {
378
- pub valid: bool,
379
- pub compatibility: Compatibility,
380
- pub issues: Vec<ValidationIssue>,
381
- }
382
-
383
- fn is_valid_policy_subject(subject: &str) -> bool {
384
- subject.split('|').map(str::trim).all(|term| {
385
- matches!(term, "authenticated" | "owner" | "member")
386
- || term
387
- .strip_prefix("self(")
388
- .and_then(|value| value.strip_suffix(')'))
389
- .is_some_and(|field| {
390
- let mut characters = field.chars();
391
- characters
392
- .next()
393
- .is_some_and(|value| value == '_' || value.is_ascii_alphabetic())
394
- && characters.all(|value| value == '_' || value.is_ascii_alphanumeric())
395
- })
396
- })
397
- }
398
-
399
- fn unique(
400
- issues: &mut Vec<ValidationIssue>,
401
- category: &str,
402
- values: impl IntoIterator<Item = String>,
403
- ) {
404
- let mut seen = BTreeSet::new();
405
- for value in values {
406
- if value.trim().is_empty() {
407
- issues.push(ValidationIssue {
408
- category: "structural".into(),
409
- path: category.into(),
410
- message: "name cannot be empty".into(),
411
- });
412
- } else if !seen.insert(value.clone()) {
413
- issues.push(ValidationIssue {
414
- category: "structural".into(),
415
- path: format!("{category}.{value}"),
416
- message: format!("duplicate {category} name"),
417
- });
418
- }
419
- }
420
- }
421
- fn contains_plaintext_secret(value: &Value) -> bool {
422
- match value {
423
- Value::Object(map) => map.iter().any(|(key, value)| {
424
- matches!(
425
- key.to_ascii_lowercase().as_str(),
426
- "password" | "secret" | "token" | "api_key" | "apikey" | "private_key"
427
- ) && value.as_str().is_some_and(|v| !v.is_empty())
428
- || contains_plaintext_secret(value)
429
- }),
430
- Value::Array(values) => values.iter().any(contains_plaintext_secret),
431
- _ => false,
432
- }
433
- }
434
-
435
- pub fn validate_manifest(
436
- manifest: &ApplicationManifest,
437
- expected_tenant: &str,
438
- expected_application: &str,
439
- previous: Option<&ApplicationManifest>,
440
- ) -> ValidationReport {
441
- let mut issues = vec![];
442
- if manifest.schema != MANIFEST_SCHEMA_VERSION {
443
- issues.push(ValidationIssue {
444
- category: "compatibility".into(),
445
- path: "schema".into(),
446
- message: format!("unsupported manifest schema {}", manifest.schema),
447
- });
448
- }
449
- if manifest.tenant_id != expected_tenant {
450
- issues.push(ValidationIssue {
451
- category: "security".into(),
452
- path: "tenant_id".into(),
453
- message: "cross-tenant manifest rejected".into(),
454
- });
455
- }
456
- if manifest.application_id != expected_application {
457
- issues.push(ValidationIssue {
458
- category: "security".into(),
459
- path: "application_id".into(),
460
- message: "cross-application manifest rejected".into(),
461
- });
462
- }
463
- unique(
464
- &mut issues,
465
- "collections",
466
- manifest.collections.iter().map(|v| v.name.clone()),
467
- );
468
- unique(
469
- &mut issues,
470
- "indexes",
471
- manifest.indexes.iter().map(|v| v.name.clone()),
472
- );
473
- unique(
474
- &mut issues,
475
- "workflows",
476
- manifest.workflows.iter().map(|v| v.name.clone()),
477
- );
478
- unique(
479
- &mut issues,
480
- "actions",
481
- manifest.actions.iter().map(|v| v.name.clone()),
482
- );
483
- unique(
484
- &mut issues,
485
- "capabilities",
486
- manifest.capabilities.iter().map(|v| v.name.clone()),
487
- );
488
- unique(
489
- &mut issues,
490
- "connections",
491
- manifest.connections.iter().map(|v| v.name.clone()),
492
- );
493
- unique(
494
- &mut issues,
495
- "routes",
496
- manifest.ui.routes.iter().map(|v| v.path.clone()),
497
- );
498
- unique(
499
- &mut issues,
500
- "artifacts",
501
- manifest.artifacts.iter().map(|v| v.name.clone()),
502
- );
503
- unique(
504
- &mut issues,
505
- "environments",
506
- manifest.environments.iter().map(|v| v.name.clone()),
507
- );
508
- let collections: BTreeMap<_, _> = manifest
509
- .collections
510
- .iter()
511
- .map(|v| (v.name.as_str(), v))
512
- .collect();
513
- for collection in &manifest.collections {
514
- unique(
515
- &mut issues,
516
- &format!("collections.{}.fields", collection.name),
517
- collection.fields.iter().map(|v| v.name.clone()),
518
- );
519
- for field in &collection.fields {
520
- if !crate::state_contract::valid_manifest_field_type(&field.field_type) {
521
- issues.push(issue(
522
- "state_schema",
523
- format!("collections.{}.fields.{}", collection.name, field.name),
524
- "unsupported field type",
525
- ));
526
- }
527
- }
528
- }
529
- let field_exists = |collection: &str, field: &str| {
530
- collections
531
- .get(collection)
532
- .is_some_and(|value| value.fields.iter().any(|candidate| candidate.name == field))
533
- };
534
- for index in &manifest.indexes {
535
- if !collections.contains_key(index.collection.as_str()) {
536
- issues.push(issue(
537
- "semantic",
538
- format!("indexes.{}", index.name),
539
- "collection does not exist",
540
- ));
541
- }
542
- for field in &index.fields {
543
- if !field_exists(&index.collection, field) {
544
- issues.push(issue(
545
- "semantic",
546
- format!("indexes.{}.fields.{field}", index.name),
547
- "field does not exist",
548
- ));
549
- }
550
- }
551
- }
552
- for reference in &manifest.references {
553
- if !field_exists(&reference.from_collection, &reference.from_field)
554
- || !field_exists(&reference.to_collection, &reference.to_field)
555
- {
556
- issues.push(issue(
557
- "semantic",
558
- format!("references.{}", reference.name),
559
- "referenced collection or field does not exist",
560
- ));
561
- }
562
- }
563
- let capabilities: BTreeSet<_> = manifest
564
- .capabilities
565
- .iter()
566
- .map(|v| v.name.as_str())
567
- .collect();
568
- for capability in &manifest.capabilities {
569
- if !matches!(
570
- capability.visibility.as_str(),
571
- "public" | "agent" | "workflow" | "internal"
572
- ) {
573
- issues.push(issue(
574
- "semantic",
575
- format!("capabilities.{}.visibility", capability.name),
576
- "visibility must be public, agent, workflow, or internal",
577
- ));
578
- }
579
- }
580
- let workflows: BTreeSet<_> = manifest.workflows.iter().map(|v| v.name.as_str()).collect();
581
- let queries: BTreeSet<_> = manifest.queries.iter().map(|v| v.name.as_str()).collect();
582
- let bindings: BTreeSet<_> = manifest
583
- .ui
584
- .bindings
585
- .iter()
586
- .map(|v| v.name.as_str())
587
- .collect();
588
- let connections: BTreeSet<_> = manifest
589
- .connections
590
- .iter()
591
- .map(|v| v.name.as_str())
592
- .collect();
593
- for workflow in &manifest.workflows {
594
- for step in &workflow.steps {
595
- if let Some(capability) = &step.capability {
596
- if !capabilities.contains(capability.as_str()) {
597
- issues.push(issue(
598
- "semantic",
599
- format!("workflows.{}.steps.{}", workflow.name, step.name),
600
- "capability does not exist",
601
- ));
602
- }
603
- }
604
- }
605
- }
606
- for agent in &manifest.agents {
607
- for capability in &agent.capabilities {
608
- if !capabilities.contains(capability.as_str()) {
609
- issues.push(issue(
610
- "security",
611
- format!("agents.{}.capabilities", agent.name),
612
- "agent capability is not application-bound",
613
- ));
614
- }
615
- }
616
- }
617
- for trigger in &manifest.triggers {
618
- if !workflows.contains(trigger.workflow.as_str()) {
619
- issues.push(issue(
620
- "semantic",
621
- format!("triggers.{}", trigger.name),
622
- "workflow does not exist",
623
- ));
624
- }
625
- }
626
- for schedule in &manifest.schedules {
627
- if !workflows.contains(schedule.workflow.as_str()) {
628
- issues.push(issue(
629
- "semantic",
630
- format!("schedules.{}", schedule.name),
631
- "workflow does not exist",
632
- ));
633
- }
634
- }
635
- for query in &manifest.queries {
636
- if !collections.contains_key(query.collection.as_str()) {
637
- issues.push(issue(
638
- "semantic",
639
- format!("queries.{}", query.name),
640
- "collection does not exist",
641
- ));
642
- }
643
- }
644
- for action in &manifest.actions {
645
- if !collections.contains_key(action.collection.as_str()) {
646
- issues.push(issue(
647
- "semantic",
648
- format!("actions.{}", action.name),
649
- "collection does not exist",
650
- ));
651
- }
652
- if action
653
- .input_fields
654
- .iter()
655
- .any(|field| !field_exists(&action.collection, field))
656
- {
657
- issues.push(issue(
658
- "semantic",
659
- format!("actions.{}.input_fields", action.name),
660
- "action field does not exist",
661
- ));
662
- }
663
- if action
664
- .required_capabilities
665
- .iter()
666
- .any(|capability| !capabilities.contains(capability.as_str()))
667
- {
668
- issues.push(issue(
669
- "security",
670
- format!("actions.{}.required_capabilities", action.name),
671
- "action capability is not application-bound",
672
- ));
673
- }
674
- }
675
- for binding in &manifest.ui.bindings {
676
- if binding
677
- .collection
678
- .as_deref()
679
- .is_some_and(|v| !collections.contains_key(v))
680
- || binding
681
- .query
682
- .as_deref()
683
- .is_some_and(|v| !queries.contains(v))
684
- {
685
- issues.push(issue(
686
- "semantic",
687
- format!("ui.bindings.{}", binding.name),
688
- "state or query binding does not exist",
689
- ));
690
- }
691
- }
692
- for form in &manifest.ui.forms {
693
- if !collections.contains_key(form.collection.as_str())
694
- || form
695
- .fields
696
- .iter()
697
- .any(|field| !field_exists(&form.collection, field))
698
- {
699
- issues.push(issue(
700
- "semantic",
701
- format!("ui.forms.{}", form.name),
702
- "form collection or field does not exist",
703
- ));
704
- }
705
- }
706
- for dashboard in &manifest.ui.dashboards {
707
- if dashboard
708
- .bindings
709
- .iter()
710
- .any(|v| !bindings.contains(v.as_str()))
711
- {
712
- issues.push(issue(
713
- "semantic",
714
- format!("ui.dashboards.{}", dashboard.name),
715
- "dashboard binding does not exist",
716
- ));
717
- }
718
- }
719
- for artifact in &manifest.artifacts {
720
- if !artifact.uri.starts_with("artifact://sha256:") {
721
- issues.push(issue(
722
- "structural",
723
- format!("artifacts.{}", artifact.name),
724
- "artifact URI must be content-addressed",
725
- ));
726
- }
727
- }
728
- if manifest.deployment.environments.iter().any(|v| {
729
- !manifest
730
- .environments
731
- .iter()
732
- .any(|candidate| &candidate.name == v)
733
- }) {
734
- issues.push(issue(
735
- "semantic",
736
- "deployment.environments",
737
- "deployment references an unknown environment",
738
- ));
739
- }
740
- for connection in &manifest.connections {
741
- if contains_plaintext_secret(&connection.configuration) {
742
- issues.push(issue(
743
- "security",
744
- format!("connections.{}.configuration", connection.name),
745
- "plaintext secrets are forbidden; use secret references",
746
- ));
747
- }
748
- for secret in &connection.secrets {
749
- if secret.secret_id.trim().is_empty() {
750
- issues.push(issue(
751
- "security",
752
- format!("connections.{}.secrets", connection.name),
753
- "secret reference is empty",
754
- ));
755
- }
756
- }
757
- }
758
- for (index, module) in manifest.modules.iter().enumerate() {
759
- if contains_plaintext_secret(module) || module.get("value").is_some() {
760
- issues.push(issue(
761
- "security",
762
- format!("modules.{index}"),
763
- "module contracts may declare secret requirements but never secret values",
764
- ));
765
- }
766
- }
767
- for environment in &manifest.environments {
768
- if environment.configuration.iter().any(|(key, value)| {
769
- matches!(
770
- key.to_ascii_lowercase().as_str(),
771
- "password" | "secret" | "token" | "api_key" | "apikey" | "private_key"
772
- ) && !value.is_empty()
773
- }) {
774
- issues.push(issue(
775
- "security",
776
- format!("environments.{}.configuration", environment.name),
777
- "plaintext environment secrets are forbidden; use connection secret references",
778
- ));
779
- }
780
- }
781
- for policy in &manifest.policies {
782
- if let Some(name) = policy.resource.strip_prefix("connection:") {
783
- if !connections.contains(name) {
784
- issues.push(issue(
785
- "semantic",
786
- format!("policies.{}", policy.name),
787
- "connection resource does not exist",
788
- ));
789
- }
790
- }
791
- if let Some(ref read_subject) = policy.read {
792
- if !is_valid_policy_subject(read_subject) {
793
- issues.push(issue(
794
- "semantic",
795
- format!("policies.{}.read", policy.name),
796
- &format!("invalid policy subject '{}'", read_subject),
797
- ));
798
- }
799
- }
800
- if let Some(ref write_subject) = policy.write {
801
- if !is_valid_policy_subject(write_subject) {
802
- issues.push(issue(
803
- "semantic",
804
- format!("policies.{}.write", policy.name),
805
- &format!("invalid policy subject '{}'", write_subject),
806
- ));
807
- }
808
- }
809
- }
810
- let state_schema = crate::state_contract::schema_from_manifest(manifest, "validation");
811
- let schema_validation = crate::state_contract::validate_schema(&state_schema);
812
- for schema_issue in schema_validation.issues {
813
- issues.push(issue(
814
- "state_schema",
815
- format!("state_schema.{}", schema_issue.path),
816
- &format!("{}: {}", schema_issue.code, schema_issue.message),
817
- ));
818
- }
819
- if let Some(previous) = previous {
820
- let before = crate::state_contract::schema_from_manifest(previous, "previous");
821
- let schema_changed = before.collections != state_schema.collections;
822
- if schema_changed && manifest.state_schema_version <= previous.state_schema_version {
823
- issues.push(issue(
824
- "compatibility",
825
- "state_schema_version",
826
- "state_schema_version must increase when state schema changes",
827
- ));
828
- }
829
- if manifest.state_schema_version < previous.state_schema_version {
830
- issues.push(issue(
831
- "compatibility",
832
- "state_schema_version",
833
- "state_schema_version cannot decrease",
834
- ));
835
- }
836
- }
837
- let compatibility = if !issues.is_empty() {
838
- Compatibility::Invalid
839
- } else if let Some(previous) = previous {
840
- compatibility(previous, manifest)
841
- } else {
842
- Compatibility::Compatible
843
- };
844
- ValidationReport {
845
- valid: issues.is_empty(),
846
- compatibility,
847
- issues,
848
- }
849
- }
850
- fn issue(category: &str, path: impl Into<String>, message: &str) -> ValidationIssue {
851
- ValidationIssue {
852
- category: category.into(),
853
- path: path.into(),
854
- message: message.into(),
855
- }
856
- }
857
- fn compatibility(before: &ApplicationManifest, after: &ApplicationManifest) -> Compatibility {
858
- for old in &before.collections {
859
- match after.collections.iter().find(|v| v.name == old.name) {
860
- None => return Compatibility::Breaking,
861
- Some(new) => {
862
- for field in &old.fields {
863
- match new.fields.iter().find(|v| v.name == field.name) {
864
- None => return Compatibility::Breaking,
865
- Some(value) if value.field_type != field.field_type => {
866
- return Compatibility::RequiresMigration
867
- }
868
- _ => {}
869
- }
870
- }
871
- }
872
- }
873
- }
874
- Compatibility::Compatible
875
- }
876
-
877
- fn sorted(mut manifest: ApplicationManifest) -> ApplicationManifest {
878
- macro_rules! sort_name {
879
- ($field:expr) => {
880
- $field.sort_by(|a, b| a.name.cmp(&b.name));
881
- };
882
- }
883
- sort_name!(manifest.collections);
884
- for collection in &mut manifest.collections {
885
- sort_name!(collection.fields);
886
- }
887
- sort_name!(manifest.indexes);
888
- sort_name!(manifest.references);
889
- sort_name!(manifest.queries);
890
- sort_name!(manifest.actions);
891
- sort_name!(manifest.workflows);
892
- for workflow in &mut manifest.workflows {
893
- sort_name!(workflow.steps);
894
- }
895
- sort_name!(manifest.triggers);
896
- sort_name!(manifest.schedules);
897
- sort_name!(manifest.agents);
898
- for agent in &mut manifest.agents {
899
- agent.capabilities.sort();
900
- }
901
- sort_name!(manifest.capabilities);
902
- manifest.modules.sort_by(|a, b| {
903
- a.get("id")
904
- .and_then(Value::as_str)
905
- .cmp(&b.get("id").and_then(Value::as_str))
906
- });
907
- sort_name!(manifest.connections);
908
- sort_name!(manifest.policies);
909
- sort_name!(manifest.ui.bindings);
910
- sort_name!(manifest.ui.forms);
911
- sort_name!(manifest.ui.dashboards);
912
- manifest.ui.routes.sort_by(|a, b| a.path.cmp(&b.path));
913
- sort_name!(manifest.environments);
914
- sort_name!(manifest.artifacts);
915
- manifest.deployment.environments.sort();
916
- manifest
917
- }
918
- pub fn canonical_bytes(manifest: &ApplicationManifest) -> Result<Vec<u8>, String> {
919
- serde_json::to_vec(&sorted(manifest.clone())).map_err(|e| e.to_string())
920
- }
921
- pub fn manifest_hash(manifest: &ApplicationManifest) -> Result<String, String> {
922
- Ok(format!(
923
- "sha256:{:x}",
924
- Sha256::digest(canonical_bytes(manifest)?)
925
- ))
926
- }
927
-
928
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
929
- #[serde(rename_all = "snake_case")]
930
- pub enum RevisionStatus {
931
- Committed,
932
- }
933
- #[derive(Debug, Clone, Serialize, Deserialize)]
934
- pub struct ApplicationDraft {
935
- pub draft_id: String,
936
- pub application_id: String,
937
- pub tenant_id: String,
938
- pub base_revision_id: Option<String>,
939
- pub manifest: ApplicationManifest,
940
- pub version: u64,
941
- pub updated_at: u64,
942
- pub updated_by: String,
943
- }
944
- #[derive(Debug, Clone, Serialize, Deserialize)]
945
- pub struct ApplicationRevision {
946
- pub revision_id: String,
947
- pub application_id: String,
948
- pub tenant_id: String,
949
- pub revision_number: u64,
950
- pub parent_revision_id: Option<String>,
951
- pub manifest_hash: String,
952
- pub manifest: ApplicationManifest,
953
- pub created_by: String,
954
- pub created_at: u64,
955
- pub status: RevisionStatus,
956
- }
957
- pub fn draft_as_revision(draft: &ApplicationDraft) -> Result<ApplicationRevision, String> {
958
- let hash = manifest_hash(&draft.manifest)?;
959
- Ok(ApplicationRevision {
960
- revision_id: format!(
961
- "appdraft://{}/{}/{}@{}",
962
- draft.tenant_id, draft.application_id, draft.draft_id, draft.version
963
- ),
964
- application_id: draft.application_id.clone(),
965
- tenant_id: draft.tenant_id.clone(),
966
- revision_number: 0,
967
- parent_revision_id: draft.base_revision_id.clone(),
968
- manifest_hash: hash,
969
- manifest: draft.manifest.clone(),
970
- created_by: draft.updated_by.clone(),
971
- created_at: draft.updated_at,
972
- status: RevisionStatus::Committed,
973
- })
974
- }
975
- #[derive(Debug, Clone, Serialize, Deserialize)]
976
- pub struct RevisionPromotion {
977
- pub application_id: String,
978
- pub from_revision: Option<String>,
979
- pub to_revision: String,
980
- pub environment: String,
981
- pub promoted_by: String,
982
- pub promoted_at: u64,
983
- pub reason: String,
984
- #[serde(default)]
985
- pub diff_hash: String,
986
- #[serde(default)]
987
- pub correlation_id: String,
988
- #[serde(default)]
989
- pub rollback: bool,
990
- }
991
- #[derive(Debug, Clone, Serialize, Deserialize)]
992
- pub struct RevisionAuditEvent {
993
- pub event: String,
994
- pub tenant_id: String,
995
- pub application_id: String,
996
- pub subject: String,
997
- pub revision_id: Option<String>,
998
- pub parent_revision_id: Option<String>,
999
- pub manifest_hash: Option<String>,
1000
- pub authorization_decision: bool,
1001
- pub timestamp: u64,
1002
- pub correlation_id: String,
1003
- #[serde(default)]
1004
- pub environment: Option<String>,
1005
- #[serde(default)]
1006
- pub from_revision: Option<String>,
1007
- #[serde(default)]
1008
- pub to_revision: Option<String>,
1009
- #[serde(default)]
1010
- pub diff_hash: Option<String>,
1011
- }
1012
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1013
- pub struct RevisionRecovery {
1014
- pub recovery_id: String,
1015
- pub application_id: String,
1016
- pub environment: String,
1017
- pub source_revision: String,
1018
- pub target_revision: String,
1019
- pub approved_by: String,
1020
- pub reason: String,
1021
- pub authorization_level: String,
1022
- pub recovered_at: u64,
1023
- }
1024
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1025
- #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
1026
- pub enum ChangeSafety {
1027
- Safe,
1028
- Additive,
1029
- Modified,
1030
- RequiresMigration,
1031
- Breaking,
1032
- SecuritySensitive,
1033
- RuntimeSensitive,
1034
- }
1035
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1036
- #[serde(rename_all = "snake_case")]
1037
- pub enum ChangeKind {
1038
- Added,
1039
- Removed,
1040
- Modified,
1041
- }
1042
- #[derive(Debug, Clone, Serialize, Deserialize)]
1043
- pub struct ManifestChange {
1044
- pub section: String,
1045
- pub name: String,
1046
- pub kind: ChangeKind,
1047
- pub safety: ChangeSafety,
1048
- #[serde(default)]
1049
- pub detail: Option<String>,
1050
- }
1051
- #[derive(Debug, Clone, Serialize, Deserialize)]
1052
- pub struct ManifestDiff {
1053
- pub from_revision: Option<String>,
1054
- pub to_revision: String,
1055
- pub changes: Vec<ManifestChange>,
1056
- pub compatibility: Compatibility,
1057
- }
1058
-
1059
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1060
- #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
1061
- pub enum DiffClassification {
1062
- Unchanged,
1063
- Additive,
1064
- Modified,
1065
- MigrationRequired,
1066
- Breaking,
1067
- SecuritySensitive,
1068
- RuntimeSensitive,
1069
- }
1070
- #[derive(Debug, Clone, Serialize, Deserialize)]
1071
- pub struct MigrationOperation {
1072
- pub section: String,
1073
- pub resource: String,
1074
- pub operation: String,
1075
- pub destructive: bool,
1076
- }
1077
- #[derive(Debug, Clone, Serialize, Deserialize)]
1078
- pub struct MigrationPlan {
1079
- pub from_revision: Option<String>,
1080
- pub to_revision: String,
1081
- pub operations: Vec<MigrationOperation>,
1082
- pub destructive_operations: Vec<MigrationOperation>,
1083
- pub reversible: bool,
1084
- }
1085
- #[derive(Debug, Clone, Serialize, Deserialize)]
1086
- pub struct SecurityChange {
1087
- pub section: String,
1088
- pub resource: String,
1089
- pub description: String,
1090
- }
1091
- #[derive(Debug, Clone, Serialize, Deserialize)]
1092
- pub struct ApplicationRevisionDiff {
1093
- pub application_id: String,
1094
- pub from_revision: Option<String>,
1095
- pub to_revision: String,
1096
- pub changes: Vec<ManifestChange>,
1097
- pub classification: DiffClassification,
1098
- pub migrations: Vec<MigrationOperation>,
1099
- pub security_changes: Vec<SecurityChange>,
1100
- pub compatibility: Compatibility,
1101
- pub migration_plan: MigrationPlan,
1102
- pub diff_hash: String,
1103
- #[serde(default)]
1104
- pub state_schema_compatibility: Option<crate::state_contract::SchemaCompatibilityReport>,
1105
- }
1106
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1107
- #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
1108
- pub enum PreviewDataMode {
1109
- Empty,
1110
- Snapshot,
1111
- Cloned,
1112
- SharedReadOnly,
1113
- }
1114
- impl Default for PreviewDataMode {
1115
- fn default() -> Self {
1116
- Self::Empty
1117
- }
1118
- }
1119
- #[derive(Debug, Clone, Serialize, Deserialize)]
1120
- pub struct PreviewPolicy {
1121
- #[serde(default)]
1122
- pub state: PreviewDataMode,
1123
- #[serde(default)]
1124
- pub artifacts: PreviewDataMode,
1125
- #[serde(default)]
1126
- pub connections: PreviewDataMode,
1127
- #[serde(default = "default_true")]
1128
- pub workflows_enabled: bool,
1129
- }
1130
- fn default_true() -> bool {
1131
- true
1132
- }
1133
- impl Default for PreviewPolicy {
1134
- fn default() -> Self {
1135
- Self {
1136
- state: PreviewDataMode::Empty,
1137
- artifacts: PreviewDataMode::SharedReadOnly,
1138
- connections: PreviewDataMode::Empty,
1139
- workflows_enabled: true,
1140
- }
1141
- }
1142
- }
1143
- #[derive(Debug, Clone, Serialize, Deserialize)]
1144
- pub struct ApplicationPreview {
1145
- pub preview_id: String,
1146
- pub application_id: String,
1147
- pub tenant_id: String,
1148
- pub revision_id: String,
1149
- pub environment: String,
1150
- pub based_on_revision: Option<String>,
1151
- pub policy: PreviewPolicy,
1152
- pub created_by: String,
1153
- pub created_at: u64,
1154
- }
1155
-
1156
- #[derive(Debug, Default, Serialize, Deserialize)]
1157
- struct RevisionRecords {
1158
- drafts: Vec<ApplicationDraft>,
1159
- revisions: Vec<ApplicationRevision>,
1160
- promotions: Vec<RevisionPromotion>,
1161
- #[serde(default)]
1162
- previews: Vec<ApplicationPreview>,
1163
- environment_pointers: BTreeMap<String, BTreeMap<String, String>>,
1164
- audit: Vec<RevisionAuditEvent>,
1165
- #[serde(default)]
1166
- untrusted_revisions: BTreeMap<String, BTreeMap<String, String>>,
1167
- #[serde(default)]
1168
- recoveries: Vec<RevisionRecovery>,
1169
- }
1170
- #[derive(Clone)]
1171
- pub struct ApplicationStore {
1172
- path: PathBuf,
1173
- records: Arc<RwLock<RevisionRecords>>,
1174
- }
1175
- fn now() -> u64 {
1176
- SystemTime::now()
1177
- .duration_since(UNIX_EPOCH)
1178
- .unwrap_or_default()
1179
- .as_secs()
1180
- }
1181
- fn opaque_id(prefix: &str, seed: &str) -> String {
1182
- let digest = Sha256::digest(format!("{}:{seed}", now()).as_bytes());
1183
- format!(
1184
- "{prefix}_{}",
1185
- digest[..12]
1186
- .iter()
1187
- .map(|byte| format!("{byte:02x}"))
1188
- .collect::<String>()
1189
- )
1190
- }
1191
-
1192
- impl ApplicationStore {
1193
- pub fn load(path: impl Into<PathBuf>) -> Result<Self, String> {
1194
- let path = path.into();
1195
- let records = if path.exists() {
1196
- serde_json::from_slice(&fs::read(&path).map_err(|e| e.to_string())?)
1197
- .map_err(|e| e.to_string())?
1198
- } else {
1199
- RevisionRecords::default()
1200
- };
1201
- Ok(Self {
1202
- path,
1203
- records: Arc::new(RwLock::new(records)),
1204
- })
1205
- }
1206
-
1207
- /// Return every tenant scope asserted by canonical application definition
1208
- /// records for one stable application identity. Callers must reject zero
1209
- /// or multiple distinct tenants; ordering is never ownership evidence.
1210
- pub fn tenant_ownership_candidates(&self, application_id: &str) -> Vec<String> {
1211
- let Ok(records) = self.records.read() else {
1212
- return Vec::new();
1213
- };
1214
- records
1215
- .revisions
1216
- .iter()
1217
- .map(|value| (&value.application_id, &value.tenant_id))
1218
- .filter(|(candidate, _)| candidate.as_str() == application_id)
1219
- .map(|(_, tenant)| tenant.clone())
1220
- .collect()
1221
- }
1222
- fn persist(&self, r: &RevisionRecords) -> Result<(), String> {
1223
- if let Some(parent) = self.path.parent() {
1224
- fs::create_dir_all(parent).map_err(|e| e.to_string())?;
1225
- }
1226
- let tmp = self.path.with_extension("tmp");
1227
- fs::write(
1228
- &tmp,
1229
- serde_json::to_vec_pretty(r).map_err(|e| e.to_string())?,
1230
- )
1231
- .map_err(|e| e.to_string())?;
1232
- fs::rename(tmp, &self.path).map_err(|e| e.to_string())
1233
- }
1234
-
1235
- /// Remove revision material for one application after its tenancy record
1236
- /// has passed the caller's guarded destruction policy. The append-only
1237
- /// state and global audit logs remain separate.
1238
- pub fn purge_application(&self, application_id: &str) -> Result<(), String> {
1239
- let mut r = self
1240
- .records
1241
- .write()
1242
- .map_err(|_| "application store lock poisoned")?;
1243
- r.drafts
1244
- .retain(|value| value.application_id != application_id);
1245
- r.revisions
1246
- .retain(|value| value.application_id != application_id);
1247
- r.promotions
1248
- .retain(|value| value.application_id != application_id);
1249
- r.previews
1250
- .retain(|value| value.application_id != application_id);
1251
- r.environment_pointers.remove(application_id);
1252
- r.audit
1253
- .retain(|value| value.application_id != application_id);
1254
- r.untrusted_revisions.remove(application_id);
1255
- r.recoveries
1256
- .retain(|value| value.application_id != application_id);
1257
- self.persist(&r)
1258
- }
1259
- fn event(
1260
- r: &mut RevisionRecords,
1261
- event: &str,
1262
- tenant: &str,
1263
- app: &str,
1264
- subject: &str,
1265
- revision: Option<&ApplicationRevision>,
1266
- parent: Option<String>,
1267
- ) {
1268
- r.audit.push(RevisionAuditEvent {
1269
- event: event.into(),
1270
- tenant_id: tenant.into(),
1271
- application_id: app.into(),
1272
- subject: subject.into(),
1273
- revision_id: revision.map(|v| v.revision_id.clone()),
1274
- parent_revision_id: revision
1275
- .and_then(|v| v.parent_revision_id.clone())
1276
- .or(parent),
1277
- manifest_hash: revision.map(|v| v.manifest_hash.clone()),
1278
- authorization_decision: true,
1279
- timestamp: now(),
1280
- correlation_id: opaque_id("corr", subject),
1281
- environment: None,
1282
- from_revision: None,
1283
- to_revision: None,
1284
- diff_hash: None,
1285
- });
1286
- }
1287
- pub fn create_draft(
1288
- &self,
1289
- tenant: &str,
1290
- app: &str,
1291
- name: &str,
1292
- actor: &str,
1293
- base: Option<&str>,
1294
- ) -> Result<ApplicationDraft, String> {
1295
- let mut r = self
1296
- .records
1297
- .write()
1298
- .map_err(|_| "application store lock poisoned")?;
1299
- let manifest = match base {
1300
- Some(id) => r
1301
- .revisions
1302
- .iter()
1303
- .find(|v| v.revision_id == id && v.application_id == app && v.tenant_id == tenant)
1304
- .ok_or("base revision not found")?
1305
- .manifest
1306
- .clone(),
1307
- None => ApplicationManifest::empty(tenant, app, name),
1308
- };
1309
- let draft = ApplicationDraft {
1310
- draft_id: opaque_id("draft", &format!("{app}:{actor}:{}", r.drafts.len())),
1311
- application_id: app.into(),
1312
- tenant_id: tenant.into(),
1313
- base_revision_id: base.map(str::to_string),
1314
- manifest,
1315
- version: 1,
1316
- updated_at: now(),
1317
- updated_by: actor.into(),
1318
- };
1319
- r.drafts.push(draft.clone());
1320
- Self::event(
1321
- &mut r,
1322
- "draft.created",
1323
- tenant,
1324
- app,
1325
- actor,
1326
- None,
1327
- base.map(str::to_string),
1328
- );
1329
- self.persist(&r)?;
1330
- Ok(draft)
1331
- }
1332
- pub fn get_draft(&self, tenant: &str, app: &str, id: &str) -> Option<ApplicationDraft> {
1333
- self.records
1334
- .read()
1335
- .ok()?
1336
- .drafts
1337
- .iter()
1338
- .find(|v| v.draft_id == id && v.application_id == app && v.tenant_id == tenant)
1339
- .cloned()
1340
- }
1341
- pub fn update_draft(
1342
- &self,
1343
- tenant: &str,
1344
- app: &str,
1345
- id: &str,
1346
- version: u64,
1347
- manifest: ApplicationManifest,
1348
- actor: &str,
1349
- ) -> Result<ApplicationDraft, String> {
1350
- let report = validate_manifest(&manifest, tenant, app, None);
1351
- if !report.valid {
1352
- return Err(format!(
1353
- "invalid manifest: {}",
1354
- serde_json::to_string(&report).unwrap_or_default()
1355
- ));
1356
- }
1357
- let mut r = self
1358
- .records
1359
- .write()
1360
- .map_err(|_| "application store lock poisoned")?;
1361
- let index = r
1362
- .drafts
1363
- .iter()
1364
- .position(|v| v.draft_id == id && v.application_id == app && v.tenant_id == tenant)
1365
- .ok_or("draft not found")?;
1366
- if r.drafts[index].version != version {
1367
- return Err(format!("version_conflict:{}", r.drafts[index].version));
1368
- }
1369
- r.drafts[index].manifest = manifest;
1370
- r.drafts[index].version += 1;
1371
- r.drafts[index].updated_at = now();
1372
- r.drafts[index].updated_by = actor.into();
1373
- let result = r.drafts[index].clone();
1374
- Self::event(
1375
- &mut r,
1376
- "draft.updated",
1377
- tenant,
1378
- app,
1379
- actor,
1380
- None,
1381
- result.base_revision_id.clone(),
1382
- );
1383
- self.persist(&r)?;
1384
- Ok(result)
1385
- }
1386
- pub fn validate_draft(
1387
- &self,
1388
- tenant: &str,
1389
- app: &str,
1390
- id: &str,
1391
- actor: &str,
1392
- ) -> Result<ValidationReport, String> {
1393
- let mut r = self
1394
- .records
1395
- .write()
1396
- .map_err(|_| "application store lock poisoned")?;
1397
- let draft = r
1398
- .drafts
1399
- .iter()
1400
- .find(|v| v.draft_id == id && v.application_id == app && v.tenant_id == tenant)
1401
- .ok_or("draft not found")?
1402
- .clone();
1403
- let previous = draft
1404
- .base_revision_id
1405
- .as_ref()
1406
- .and_then(|base| r.revisions.iter().find(|v| &v.revision_id == base))
1407
- .map(|v| &v.manifest);
1408
- let report = validate_manifest(&draft.manifest, tenant, app, previous);
1409
- Self::event(
1410
- &mut r,
1411
- if report.valid {
1412
- "draft.validated"
1413
- } else {
1414
- "revision.rejected"
1415
- },
1416
- tenant,
1417
- app,
1418
- actor,
1419
- None,
1420
- draft.base_revision_id,
1421
- );
1422
- self.persist(&r)?;
1423
- Ok(report)
1424
- }
1425
- pub fn commit(
1426
- &self,
1427
- tenant: &str,
1428
- app: &str,
1429
- id: &str,
1430
- actor: &str,
1431
- ) -> Result<ApplicationRevision, String> {
1432
- let mut r = self
1433
- .records
1434
- .write()
1435
- .map_err(|_| "application store lock poisoned")?;
1436
- let draft = r
1437
- .drafts
1438
- .iter()
1439
- .find(|v| v.draft_id == id && v.application_id == app && v.tenant_id == tenant)
1440
- .ok_or("draft not found")?
1441
- .clone();
1442
- let previous = draft
1443
- .base_revision_id
1444
- .as_ref()
1445
- .and_then(|base| r.revisions.iter().find(|v| &v.revision_id == base))
1446
- .map(|v| &v.manifest);
1447
- let report = validate_manifest(&draft.manifest, tenant, app, previous);
1448
- if !report.valid {
1449
- return Err(format!(
1450
- "invalid manifest: {}",
1451
- serde_json::to_string(&report).unwrap_or_default()
1452
- ));
1453
- }
1454
- let hash = manifest_hash(&draft.manifest)?;
1455
- let number = r
1456
- .revisions
1457
- .iter()
1458
- .filter(|v| v.application_id == app)
1459
- .map(|v| v.revision_number)
1460
- .max()
1461
- .unwrap_or(0)
1462
- + 1;
1463
- let identity = Sha256::digest(
1464
- format!(
1465
- "{tenant}\0{app}\0{}\0{hash}",
1466
- draft.base_revision_id.as_deref().unwrap_or("")
1467
- )
1468
- .as_bytes(),
1469
- );
1470
- let revision = ApplicationRevision {
1471
- revision_id: format!("apprev://{tenant}/{app}/sha256:{identity:x}"),
1472
- application_id: app.into(),
1473
- tenant_id: tenant.into(),
1474
- revision_number: number,
1475
- parent_revision_id: draft.base_revision_id.clone(),
1476
- manifest_hash: hash,
1477
- manifest: sorted(draft.manifest),
1478
- created_by: actor.into(),
1479
- created_at: now(),
1480
- status: RevisionStatus::Committed,
1481
- };
1482
- r.revisions.push(revision.clone());
1483
- r.drafts.retain(|v| v.draft_id != id);
1484
- Self::event(
1485
- &mut r,
1486
- "revision.created",
1487
- tenant,
1488
- app,
1489
- actor,
1490
- Some(&revision),
1491
- None,
1492
- );
1493
- self.persist(&r)?;
1494
- Ok(revision)
1495
- }
1496
- pub fn revisions(&self, tenant: &str, app: &str) -> Vec<ApplicationRevision> {
1497
- let mut values = self
1498
- .records
1499
- .read()
1500
- .map(|r| {
1501
- r.revisions
1502
- .iter()
1503
- .filter(|v| v.tenant_id == tenant && v.application_id == app)
1504
- .cloned()
1505
- .collect::<Vec<_>>()
1506
- })
1507
- .unwrap_or_default();
1508
- values.sort_by_key(|v| std::cmp::Reverse(v.revision_number));
1509
- values
1510
- }
1511
- pub fn revision(&self, tenant: &str, app: &str, id: &str) -> Option<ApplicationRevision> {
1512
- self.records
1513
- .read()
1514
- .ok()?
1515
- .revisions
1516
- .iter()
1517
- .find(|v| {
1518
- v.tenant_id == tenant
1519
- && v.application_id == app
1520
- && (v.revision_id == id || v.revision_number.to_string() == id)
1521
- })
1522
- .cloned()
1523
- }
1524
- pub fn promote(
1525
- &self,
1526
- tenant: &str,
1527
- app: &str,
1528
- id: &str,
1529
- environment: &str,
1530
- actor: &str,
1531
- reason: &str,
1532
- ) -> Result<RevisionPromotion, String> {
1533
- let expected = self.pointers(app).get(environment).cloned();
1534
- self.move_environment_pointer(
1535
- tenant,
1536
- app,
1537
- id,
1538
- environment,
1539
- expected.as_deref(),
1540
- actor,
1541
- reason,
1542
- true,
1543
- false,
1544
- )
1545
- }
1546
- #[allow(clippy::too_many_arguments)]
1547
- pub fn move_environment_pointer(
1548
- &self,
1549
- tenant: &str,
1550
- app: &str,
1551
- id: &str,
1552
- environment: &str,
1553
- expected_current_revision: Option<&str>,
1554
- actor: &str,
1555
- reason: &str,
1556
- approve_destructive_changes: bool,
1557
- rollback: bool,
1558
- ) -> Result<RevisionPromotion, String> {
1559
- let mut r = self
1560
- .records
1561
- .write()
1562
- .map_err(|_| "application store lock poisoned")?;
1563
- let revision = r
1564
- .revisions
1565
- .iter()
1566
- .find(|v| {
1567
- v.tenant_id == tenant
1568
- && v.application_id == app
1569
- && (v.revision_id == id || v.revision_number.to_string() == id)
1570
- })
1571
- .ok_or("revision not found")?
1572
- .clone();
1573
- if r.untrusted_revisions
1574
- .get(app)
1575
- .is_some_and(|values| values.contains_key(&revision.revision_id))
1576
- {
1577
- return Err("revision is permanently untrusted".into());
1578
- }
1579
- if manifest_hash(&revision.manifest)? != revision.manifest_hash {
1580
- return Err("revision integrity check failed".into());
1581
- }
1582
- if !revision
1583
- .manifest
1584
- .environments
1585
- .iter()
1586
- .any(|v| v.name == environment)
1587
- {
1588
- return Err("environment is not defined by the revision".into());
1589
- }
1590
- let from = r
1591
- .environment_pointers
1592
- .get(app)
1593
- .and_then(|v| v.get(environment))
1594
- .cloned();
1595
- if from.as_deref() != expected_current_revision {
1596
- return Err(format!(
1597
- "expected_revision_mismatch:{}",
1598
- from.unwrap_or_default()
1599
- ));
1600
- }
1601
- let before = from
1602
- .as_deref()
1603
- .and_then(|previous| r.revisions.iter().find(|v| v.revision_id == previous));
1604
- let diff = application_revision_diff(before, &revision)?;
1605
- if !approve_destructive_changes
1606
- && diff.migration_plan.operations.iter().any(|v| v.destructive)
1607
- {
1608
- return Err("destructive_changes_require_approval".into());
1609
- }
1610
- r.environment_pointers
1611
- .entry(app.into())
1612
- .or_default()
1613
- .insert(environment.into(), revision.revision_id.clone());
1614
- let promotion = RevisionPromotion {
1615
- application_id: app.into(),
1616
- from_revision: from.clone(),
1617
- to_revision: revision.revision_id.clone(),
1618
- environment: environment.into(),
1619
- promoted_by: actor.into(),
1620
- promoted_at: now(),
1621
- reason: reason.into(),
1622
- diff_hash: diff.diff_hash,
1623
- correlation_id: opaque_id("corr", &format!("{app}:{environment}:{actor}")),
1624
- rollback,
1625
- };
1626
- r.promotions.push(promotion.clone());
1627
- Self::event(
1628
- &mut r,
1629
- if rollback {
1630
- "revision.rollback"
1631
- } else {
1632
- "revision.promoted"
1633
- },
1634
- tenant,
1635
- app,
1636
- actor,
1637
- Some(&revision),
1638
- None,
1639
- );
1640
- if let Some(event) = r.audit.last_mut() {
1641
- event.event = if rollback {
1642
- "application.revision.rolled_back".into()
1643
- } else {
1644
- "application.revision.promoted".into()
1645
- };
1646
- event.environment = Some(environment.into());
1647
- event.from_revision = from;
1648
- event.to_revision = Some(revision.revision_id.clone());
1649
- event.diff_hash = Some(promotion.diff_hash.clone());
1650
- event.correlation_id = promotion.correlation_id.clone();
1651
- }
1652
- self.persist(&r)?;
1653
- Ok(promotion)
1654
- }
1655
-
1656
- #[allow(clippy::too_many_arguments)]
1657
- pub fn recover_environment_pointer(
1658
- &self,
1659
- tenant: &str,
1660
- app: &str,
1661
- environment: &str,
1662
- expected_current_revision: &str,
1663
- target_revision: &str,
1664
- actor: &str,
1665
- reason: &str,
1666
- authorization_level: &str,
1667
- recovery_id: &str,
1668
- ) -> Result<RevisionRecovery, String> {
1669
- let mut records = self
1670
- .records
1671
- .write()
1672
- .map_err(|_| "application store lock poisoned")?;
1673
- if let Some(existing) = records
1674
- .recoveries
1675
- .iter()
1676
- .find(|value| value.recovery_id == recovery_id)
1677
- {
1678
- if existing.application_id == app
1679
- && existing.environment == environment
1680
- && existing.source_revision == expected_current_revision
1681
- && existing.target_revision == target_revision
1682
- {
1683
- return Ok(existing.clone());
1684
- }
1685
- return Err("recovery_id_conflict".into());
1686
- }
1687
- let current = records
1688
- .environment_pointers
1689
- .get(app)
1690
- .and_then(|values| values.get(environment))
1691
- .cloned()
1692
- .unwrap_or_default();
1693
- if current != expected_current_revision {
1694
- return Err(format!("expected_revision_mismatch:{current}"));
1695
- }
1696
- let target = records
1697
- .revisions
1698
- .iter()
1699
- .find(|value| {
1700
- value.tenant_id == tenant
1701
- && value.application_id == app
1702
- && (value.revision_id == target_revision
1703
- || value.revision_number.to_string() == target_revision)
1704
- })
1705
- .ok_or("target revision not found")?
1706
- .clone();
1707
- if manifest_hash(&target.manifest)? != target.manifest_hash {
1708
- return Err("target revision integrity check failed".into());
1709
- }
1710
- if records
1711
- .untrusted_revisions
1712
- .get(app)
1713
- .is_some_and(|values| values.contains_key(&target.revision_id))
1714
- {
1715
- return Err("target revision is permanently untrusted".into());
1716
- }
1717
- let recovery = RevisionRecovery {
1718
- recovery_id: recovery_id.into(),
1719
- application_id: app.into(),
1720
- environment: environment.into(),
1721
- source_revision: expected_current_revision.into(),
1722
- target_revision: target.revision_id.clone(),
1723
- approved_by: actor.into(),
1724
- reason: reason.into(),
1725
- authorization_level: authorization_level.into(),
1726
- recovered_at: now(),
1727
- };
1728
- records
1729
- .untrusted_revisions
1730
- .entry(app.into())
1731
- .or_default()
1732
- .insert(expected_current_revision.into(), recovery_id.into());
1733
- records
1734
- .environment_pointers
1735
- .entry(app.into())
1736
- .or_default()
1737
- .insert(environment.into(), target.revision_id.clone());
1738
- records.recoveries.push(recovery.clone());
1739
- Self::event(
1740
- &mut records,
1741
- "application.revision.recovered",
1742
- tenant,
1743
- app,
1744
- actor,
1745
- Some(&target),
1746
- Some(expected_current_revision.into()),
1747
- );
1748
- if let Some(event) = records.audit.last_mut() {
1749
- event.environment = Some(environment.into());
1750
- event.from_revision = Some(expected_current_revision.into());
1751
- event.to_revision = Some(target.revision_id);
1752
- event.correlation_id = recovery_id.into();
1753
- }
1754
- self.persist(&records)?;
1755
- Ok(recovery)
1756
- }
1757
-
1758
- pub fn history(&self, tenant: &str, app: &str, environment: &str) -> Vec<RevisionPromotion> {
1759
- self.records
1760
- .read()
1761
- .map(|r| {
1762
- r.promotions
1763
- .iter()
1764
- .filter(|v| {
1765
- v.application_id == app
1766
- && v.environment == environment
1767
- && r.revisions.iter().any(|rev| {
1768
- rev.tenant_id == tenant && rev.revision_id == v.to_revision
1769
- })
1770
- })
1771
- .cloned()
1772
- .rev()
1773
- .collect()
1774
- })
1775
- .unwrap_or_default()
1776
- }
1777
-
1778
- pub fn create_preview(
1779
- &self,
1780
- tenant: &str,
1781
- app: &str,
1782
- id: &str,
1783
- actor: &str,
1784
- policy: PreviewPolicy,
1785
- ) -> Result<ApplicationPreview, String> {
1786
- let revision = self.revision(tenant, app, id).ok_or("revision not found")?;
1787
- if manifest_hash(&revision.manifest)? != revision.manifest_hash {
1788
- return Err("revision integrity check failed".into());
1789
- }
1790
- let mut r = self
1791
- .records
1792
- .write()
1793
- .map_err(|_| "application store lock poisoned")?;
1794
- let preview = ApplicationPreview {
1795
- preview_id: opaque_id(
1796
- "preview",
1797
- &format!("{app}:{}:{actor}", revision.revision_id),
1798
- ),
1799
- application_id: app.into(),
1800
- tenant_id: tenant.into(),
1801
- revision_id: revision.revision_id,
1802
- environment: format!("preview/{actor}"),
1803
- based_on_revision: r
1804
- .environment_pointers
1805
- .get(app)
1806
- .and_then(|v| v.get("production"))
1807
- .cloned(),
1808
- policy,
1809
- created_by: actor.into(),
1810
- created_at: now(),
1811
- };
1812
- r.previews.push(preview.clone());
1813
- self.persist(&r)?;
1814
- Ok(preview)
1815
- }
1816
- pub fn preview(&self, tenant: &str, app: &str, id: &str) -> Option<ApplicationPreview> {
1817
- self.records
1818
- .read()
1819
- .ok()?
1820
- .previews
1821
- .iter()
1822
- .find(|v| v.tenant_id == tenant && v.application_id == app && v.preview_id == id)
1823
- .cloned()
1824
- }
1825
- pub fn pointers(&self, app: &str) -> BTreeMap<String, String> {
1826
- self.records
1827
- .read()
1828
- .ok()
1829
- .and_then(|r| r.environment_pointers.get(app).cloned())
1830
- .unwrap_or_default()
1831
- }
1832
- pub fn diff(&self, tenant: &str, app: &str, id: &str) -> Result<ManifestDiff, String> {
1833
- let target = self.revision(tenant, app, id).ok_or("revision not found")?;
1834
- let before = target
1835
- .parent_revision_id
1836
- .as_deref()
1837
- .and_then(|parent| self.revision(tenant, app, parent));
1838
- Ok(diff_manifests(before.as_ref(), &target))
1839
- }
1840
- pub fn revision_diff(
1841
- &self,
1842
- tenant: &str,
1843
- app: &str,
1844
- from: Option<&str>,
1845
- to: &str,
1846
- ) -> Result<ApplicationRevisionDiff, String> {
1847
- let after = self.revision(tenant, app, to).ok_or("revision not found")?;
1848
- let before = match from {
1849
- Some(id) => Some(
1850
- self.revision(tenant, app, id)
1851
- .ok_or("from revision not found")?,
1852
- ),
1853
- None => after
1854
- .parent_revision_id
1855
- .as_deref()
1856
- .and_then(|id| self.revision(tenant, app, id)),
1857
- };
1858
- application_revision_diff(before.as_ref(), &after)
1859
- }
1860
- pub fn audit(&self, tenant: &str, app: &str) -> Vec<RevisionAuditEvent> {
1861
- self.records
1862
- .read()
1863
- .map(|r| {
1864
- r.audit
1865
- .iter()
1866
- .filter(|v| v.tenant_id == tenant && v.application_id == app)
1867
- .cloned()
1868
- .collect()
1869
- })
1870
- .unwrap_or_default()
1871
- }
1872
- pub fn export_revision(&self, tenant: &str, app: &str, id: &str) -> Result<Value, String> {
1873
- let revision = self.revision(tenant, app, id).ok_or("revision not found")?;
1874
- let manifest = canonical_bytes(&revision.manifest)?;
1875
- let checksum = format!("sha256:{:x}", Sha256::digest(&manifest));
1876
- Ok(
1877
- serde_json::json!({"format":"feltdb-app/v1","revision":revision,"files":{"manifest.json":String::from_utf8(manifest).map_err(|e|e.to_string())?},"checksums":{"manifest.json":checksum}}),
1878
- )
1879
- }
1880
- pub fn import_draft(
1881
- &self,
1882
- tenant: &str,
1883
- app: &str,
1884
- name: &str,
1885
- actor: &str,
1886
- bundle: &Value,
1887
- ) -> Result<ApplicationDraft, String> {
1888
- if bundle.get("format").and_then(Value::as_str) != Some("feltdb-app/v1") {
1889
- return Err("unsupported application bundle".into());
1890
- }
1891
- let text = bundle
1892
- .pointer("/files/manifest.json")
1893
- .and_then(Value::as_str)
1894
- .ok_or("bundle manifest is missing")?;
1895
- let expected = bundle
1896
- .pointer("/checksums/manifest.json")
1897
- .and_then(Value::as_str)
1898
- .ok_or("bundle checksum is missing")?;
1899
- let actual = format!("sha256:{:x}", Sha256::digest(text.as_bytes()));
1900
- if actual != expected {
1901
- return Err("bundle checksum mismatch".into());
1902
- }
1903
- let mut manifest: ApplicationManifest =
1904
- serde_json::from_str(text).map_err(|e| e.to_string())?;
1905
- manifest.tenant_id = tenant.into();
1906
- manifest.application_id = app.into();
1907
- let report = validate_manifest(&manifest, tenant, app, None);
1908
- if !report.valid {
1909
- return Err(format!(
1910
- "invalid manifest: {}",
1911
- serde_json::to_string(&report).unwrap_or_default()
1912
- ));
1913
- }
1914
- let mut draft = self.create_draft(tenant, app, name, actor, None)?;
1915
- draft = self.update_draft(tenant, app, &draft.draft_id, draft.version, manifest, actor)?;
1916
- Ok(draft)
1917
- }
1918
- }
1919
-
1920
- fn named_map<T: Serialize>(values: &[T]) -> BTreeMap<String, Value> {
1921
- values
1922
- .iter()
1923
- .filter_map(|v| {
1924
- let value = serde_json::to_value(v).ok()?;
1925
- Some((value.get("name")?.as_str()?.to_string(), value))
1926
- })
1927
- .collect()
1928
- }
1929
- fn section_changes<T: Serialize>(
1930
- changes: &mut Vec<ManifestChange>,
1931
- section: &str,
1932
- before: &[T],
1933
- after: &[T],
1934
- default: ChangeSafety,
1935
- ) {
1936
- let left = named_map(before);
1937
- let right = named_map(after);
1938
- for (name, value) in &right {
1939
- match left.get(name) {
1940
- None => changes.push(ManifestChange {
1941
- section: section.into(),
1942
- name: name.clone(),
1943
- kind: ChangeKind::Added,
1944
- safety: default.clone(),
1945
- detail: None,
1946
- }),
1947
- Some(old) if old != value => changes.push(ManifestChange {
1948
- section: section.into(),
1949
- name: name.clone(),
1950
- kind: ChangeKind::Modified,
1951
- safety: default.clone(),
1952
- detail: None,
1953
- }),
1954
- _ => {}
1955
- }
1956
- }
1957
- for name in left.keys().filter(|name| !right.contains_key(*name)) {
1958
- changes.push(ManifestChange {
1959
- section: section.into(),
1960
- name: name.clone(),
1961
- kind: ChangeKind::Removed,
1962
- safety: ChangeSafety::Breaking,
1963
- detail: Some("resource removal requires explicit destructive-change approval".into()),
1964
- });
1965
- }
1966
- }
1967
- pub fn diff_manifests(
1968
- before: Option<&ApplicationRevision>,
1969
- after: &ApplicationRevision,
1970
- ) -> ManifestDiff {
1971
- let empty = ApplicationManifest::empty(
1972
- &after.tenant_id,
1973
- &after.application_id,
1974
- &after.manifest.metadata.name,
1975
- );
1976
- let left = before.map(|v| &v.manifest).unwrap_or(&empty);
1977
- let mut changes = vec![];
1978
- section_changes(
1979
- &mut changes,
1980
- "collections",
1981
- &left.collections,
1982
- &after.manifest.collections,
1983
- ChangeSafety::RequiresMigration,
1984
- );
1985
- section_changes(
1986
- &mut changes,
1987
- "indexes",
1988
- &left.indexes,
1989
- &after.manifest.indexes,
1990
- ChangeSafety::Safe,
1991
- );
1992
- section_changes(
1993
- &mut changes,
1994
- "workflows",
1995
- &left.workflows,
1996
- &after.manifest.workflows,
1997
- ChangeSafety::Safe,
1998
- );
1999
- section_changes(
2000
- &mut changes,
2001
- "actions",
2002
- &left.actions,
2003
- &after.manifest.actions,
2004
- ChangeSafety::SecuritySensitive,
2005
- );
2006
- section_changes(
2007
- &mut changes,
2008
- "agents",
2009
- &left.agents,
2010
- &after.manifest.agents,
2011
- ChangeSafety::SecuritySensitive,
2012
- );
2013
- section_changes(
2014
- &mut changes,
2015
- "capabilities",
2016
- &left.capabilities,
2017
- &after.manifest.capabilities,
2018
- ChangeSafety::SecuritySensitive,
2019
- );
2020
- section_changes(
2021
- &mut changes,
2022
- "connections",
2023
- &left.connections,
2024
- &after.manifest.connections,
2025
- ChangeSafety::SecuritySensitive,
2026
- );
2027
- section_changes(
2028
- &mut changes,
2029
- "policies",
2030
- &left.policies,
2031
- &after.manifest.policies,
2032
- ChangeSafety::SecuritySensitive,
2033
- );
2034
- let left_routes: BTreeMap<_, _> = left
2035
- .ui
2036
- .routes
2037
- .iter()
2038
- .map(|v| (v.path.clone(), v.view.clone()))
2039
- .collect();
2040
- let right_routes: BTreeMap<_, _> = after
2041
- .manifest
2042
- .ui
2043
- .routes
2044
- .iter()
2045
- .map(|v| (v.path.clone(), v.view.clone()))
2046
- .collect();
2047
- for (path, view) in &right_routes {
2048
- changes.push(ManifestChange {
2049
- section: "routes".into(),
2050
- name: path.clone(),
2051
- kind: if left_routes.contains_key(path) {
2052
- if left_routes.get(path) == Some(view) {
2053
- continue;
2054
- } else {
2055
- ChangeKind::Modified
2056
- }
2057
- } else {
2058
- ChangeKind::Added
2059
- },
2060
- safety: ChangeSafety::Safe,
2061
- detail: None,
2062
- });
2063
- }
2064
- for path in left_routes
2065
- .keys()
2066
- .filter(|path| !right_routes.contains_key(*path))
2067
- {
2068
- changes.push(ManifestChange {
2069
- section: "routes".into(),
2070
- name: path.clone(),
2071
- kind: ChangeKind::Removed,
2072
- safety: ChangeSafety::Breaking,
2073
- detail: Some("route removal may break existing navigation".into()),
2074
- });
2075
- }
2076
- section_changes(
2077
- &mut changes,
2078
- "forms",
2079
- &left.ui.forms,
2080
- &after.manifest.ui.forms,
2081
- ChangeSafety::Safe,
2082
- );
2083
- section_changes(
2084
- &mut changes,
2085
- "dashboards",
2086
- &left.ui.dashboards,
2087
- &after.manifest.ui.dashboards,
2088
- ChangeSafety::Safe,
2089
- );
2090
- ManifestDiff {
2091
- from_revision: before.map(|v| v.revision_id.clone()),
2092
- to_revision: after.revision_id.clone(),
2093
- changes,
2094
- compatibility: compatibility(left, &after.manifest),
2095
- }
2096
- }
2097
-
2098
- pub fn application_revision_diff(
2099
- before: Option<&ApplicationRevision>,
2100
- after: &ApplicationRevision,
2101
- ) -> Result<ApplicationRevisionDiff, String> {
2102
- if manifest_hash(&after.manifest)? != after.manifest_hash {
2103
- return Err("revision integrity check failed".into());
2104
- }
2105
- if let Some(value) = before {
2106
- if value.application_id != after.application_id || value.tenant_id != after.tenant_id {
2107
- return Err("cross-application revision comparison is forbidden".into());
2108
- }
2109
- if manifest_hash(&value.manifest)? != value.manifest_hash {
2110
- return Err("from revision integrity check failed".into());
2111
- }
2112
- }
2113
- let legacy = diff_manifests(before, after);
2114
- let state_schema_compatibility = before.map(|before| {
2115
- crate::state_contract::compare_schemas(
2116
- &crate::state_contract::schema_from_revision(before),
2117
- &crate::state_contract::schema_from_revision(after),
2118
- )
2119
- });
2120
- let migrations = legacy
2121
- .changes
2122
- .iter()
2123
- .filter(|change| {
2124
- matches!(
2125
- change.safety,
2126
- ChangeSafety::RequiresMigration | ChangeSafety::Breaking
2127
- )
2128
- })
2129
- .map(|change| MigrationOperation {
2130
- section: change.section.clone(),
2131
- resource: change.name.clone(),
2132
- operation: match change.kind {
2133
- ChangeKind::Added => "add",
2134
- ChangeKind::Modified => "alter",
2135
- ChangeKind::Removed => "remove",
2136
- }
2137
- .into(),
2138
- destructive: matches!(change.kind, ChangeKind::Removed)
2139
- || matches!(change.safety, ChangeSafety::Breaking)
2140
- || (change.section == "collections"
2141
- && matches!(legacy.compatibility, Compatibility::Breaking)),
2142
- })
2143
- .collect::<Vec<_>>();
2144
- let security_changes = legacy
2145
- .changes
2146
- .iter()
2147
- .filter(|change| matches!(change.safety, ChangeSafety::SecuritySensitive))
2148
- .map(|change| SecurityChange {
2149
- section: change.section.clone(),
2150
- resource: change.name.clone(),
2151
- description: format!("{:?} security-sensitive resource", change.kind),
2152
- })
2153
- .collect::<Vec<_>>();
2154
- let schema_breaking = state_schema_compatibility.as_ref().is_some_and(|report| {
2155
- matches!(
2156
- report.classification,
2157
- crate::state_contract::SchemaCompatibility::Destructive
2158
- | crate::state_contract::SchemaCompatibility::Incompatible
2159
- )
2160
- });
2161
- let classification = if legacy.changes.is_empty() {
2162
- DiffClassification::Unchanged
2163
- } else if schema_breaking
2164
- || matches!(legacy.compatibility, Compatibility::Breaking)
2165
- || legacy
2166
- .changes
2167
- .iter()
2168
- .any(|v| matches!(v.safety, ChangeSafety::Breaking))
2169
- {
2170
- DiffClassification::Breaking
2171
- } else if !security_changes.is_empty() {
2172
- DiffClassification::SecuritySensitive
2173
- } else if !migrations.is_empty() {
2174
- DiffClassification::MigrationRequired
2175
- } else if legacy
2176
- .changes
2177
- .iter()
2178
- .any(|v| matches!(v.safety, ChangeSafety::RuntimeSensitive))
2179
- {
2180
- DiffClassification::RuntimeSensitive
2181
- } else if legacy
2182
- .changes
2183
- .iter()
2184
- .all(|v| matches!(v.kind, ChangeKind::Added))
2185
- {
2186
- DiffClassification::Additive
2187
- } else {
2188
- DiffClassification::Modified
2189
- };
2190
- let destructive_operations = migrations
2191
- .iter()
2192
- .filter(|v| v.destructive)
2193
- .cloned()
2194
- .collect::<Vec<_>>();
2195
- let migration_plan = MigrationPlan {
2196
- from_revision: legacy.from_revision.clone(),
2197
- to_revision: legacy.to_revision.clone(),
2198
- operations: migrations.clone(),
2199
- destructive_operations,
2200
- reversible: !migrations.iter().any(|v| v.destructive),
2201
- };
2202
- let hash_input = serde_json::json!({"application_id":after.application_id,"from_revision":legacy.from_revision,
2203
- "to_revision":legacy.to_revision,"changes":legacy.changes,"classification":classification,
2204
- "migrations":migrations,"security_changes":security_changes,"compatibility":legacy.compatibility,"migration_plan":migration_plan,"state_schema_compatibility":state_schema_compatibility});
2205
- let diff_hash = format!(
2206
- "sha256:{:x}",
2207
- Sha256::digest(serde_json::to_vec(&hash_input).map_err(|e| e.to_string())?)
2208
- );
2209
- Ok(ApplicationRevisionDiff {
2210
- application_id: after.application_id.clone(),
2211
- from_revision: legacy.from_revision,
2212
- to_revision: legacy.to_revision,
2213
- changes: legacy.changes,
2214
- classification,
2215
- migrations,
2216
- security_changes,
2217
- compatibility: legacy.compatibility,
2218
- migration_plan,
2219
- diff_hash,
2220
- state_schema_compatibility,
2221
- })
2222
- }
2223
-
2224
- #[cfg(test)]
2225
- mod tests {
2226
- use super::*;
2227
- fn store(name: &str) -> ApplicationStore {
2228
- ApplicationStore::load(
2229
- std::env::temp_dir().join(format!("feltdb-app-{name}-{}.json", now())),
2230
- )
2231
- .unwrap()
2232
- }
2233
- #[test]
2234
- fn canonical_hash_ignores_named_section_order() {
2235
- let mut a = ApplicationManifest::empty("t", "a", "App");
2236
- a.collections = vec![
2237
- CollectionDefinition {
2238
- name: "z".into(),
2239
- fields: vec![],
2240
- },
2241
- CollectionDefinition {
2242
- name: "a".into(),
2243
- fields: vec![],
2244
- },
2245
- ];
2246
- let mut b = a.clone();
2247
- b.collections.reverse();
2248
- assert_eq!(manifest_hash(&a).unwrap(), manifest_hash(&b).unwrap());
2249
- }
2250
- #[test]
2251
- fn revision_is_immutable_and_rollback_moves_pointer() {
2252
- let s = store("lifecycle");
2253
- let d = s.create_draft("t", "a", "App", "owner", None).unwrap();
2254
- let r1 = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2255
- s.promote("t", "a", &r1.revision_id, "production", "owner", "initial")
2256
- .unwrap();
2257
- let d = s
2258
- .create_draft("t", "a", "App", "owner", Some(&r1.revision_id))
2259
- .unwrap();
2260
- let r2 = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2261
- s.promote("t", "a", &r2.revision_id, "production", "owner", "upgrade")
2262
- .unwrap();
2263
- s.promote("t", "a", &r1.revision_id, "production", "owner", "rollback")
2264
- .unwrap();
2265
- assert_eq!(s.pointers("a")["production"], r1.revision_id);
2266
- assert_eq!(s.revisions("t", "a").len(), 2);
2267
- }
2268
- #[test]
2269
- fn stale_update_and_plaintext_secret_are_rejected() {
2270
- let s = store("conflict");
2271
- let d = s.create_draft("t", "a", "App", "owner", None).unwrap();
2272
- let mut manifest = d.manifest.clone();
2273
- manifest.connections.push(ConnectionBinding {
2274
- name: "db".into(),
2275
- connection_id: "c".into(),
2276
- configuration: serde_json::json!({"password":"bad"}),
2277
- secrets: vec![],
2278
- });
2279
- assert!(s
2280
- .update_draft("t", "a", &d.draft_id, d.version, manifest, "owner")
2281
- .is_err());
2282
- let updated = s
2283
- .update_draft(
2284
- "t",
2285
- "a",
2286
- &d.draft_id,
2287
- d.version,
2288
- d.manifest.clone(),
2289
- "owner",
2290
- )
2291
- .unwrap();
2292
- assert!(s
2293
- .update_draft("t", "a", &d.draft_id, d.version, updated.manifest, "owner")
2294
- .unwrap_err()
2295
- .starts_with("version_conflict:"));
2296
- }
2297
- #[test]
2298
- fn export_import_preserves_hash() {
2299
- let s = store("portable");
2300
- let d = s.create_draft("t", "a", "App", "owner", None).unwrap();
2301
- let r = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2302
- let bundle = s.export_revision("t", "a", &r.revision_id).unwrap();
2303
- let imported = s
2304
- .import_draft("t", "b", "Imported", "owner", &bundle)
2305
- .unwrap();
2306
- assert_eq!(
2307
- manifest_hash(&imported.manifest).unwrap(),
2308
- manifest_hash(&ApplicationManifest {
2309
- tenant_id: "t".into(),
2310
- application_id: "b".into(),
2311
- ..r.manifest
2312
- })
2313
- .unwrap()
2314
- );
2315
- }
2316
- #[test]
2317
- fn promotion_is_compare_and_swap_and_history_is_durable() {
2318
- let s = store("promotion-cas");
2319
- let d = s.create_draft("t", "a", "App", "owner", None).unwrap();
2320
- let r1 = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2321
- s.move_environment_pointer(
2322
- "t",
2323
- "a",
2324
- &r1.revision_id,
2325
- "production",
2326
- None,
2327
- "owner",
2328
- "initial",
2329
- true,
2330
- false,
2331
- )
2332
- .unwrap();
2333
- let d = s
2334
- .create_draft("t", "a", "App", "owner", Some(&r1.revision_id))
2335
- .unwrap();
2336
- let r2 = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2337
- let d = s
2338
- .create_draft("t", "a", "App", "owner", Some(&r1.revision_id))
2339
- .unwrap();
2340
- let r3 = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2341
- s.move_environment_pointer(
2342
- "t",
2343
- "a",
2344
- &r2.revision_id,
2345
- "production",
2346
- Some(&r1.revision_id),
2347
- "owner",
2348
- "A",
2349
- true,
2350
- false,
2351
- )
2352
- .unwrap();
2353
- let error = s
2354
- .move_environment_pointer(
2355
- "t",
2356
- "a",
2357
- &r3.revision_id,
2358
- "production",
2359
- Some(&r1.revision_id),
2360
- "owner",
2361
- "B",
2362
- true,
2363
- false,
2364
- )
2365
- .unwrap_err();
2366
- assert!(error.starts_with("expected_revision_mismatch:"));
2367
- assert_eq!(s.pointers("a")["production"], r2.revision_id);
2368
- assert_eq!(s.history("t", "a", "production").len(), 2);
2369
- }
2370
-
2371
- #[test]
2372
- fn recovery_is_atomic_idempotent_durable_and_permanently_untrusts_source() {
2373
- let s = store("revision-recovery");
2374
- let d = s.create_draft("t", "a", "App", "owner", None).unwrap();
2375
- let corrupt = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2376
- s.move_environment_pointer(
2377
- "t",
2378
- "a",
2379
- &corrupt.revision_id,
2380
- "staging",
2381
- None,
2382
- "owner",
2383
- "initial",
2384
- true,
2385
- false,
2386
- )
2387
- .unwrap();
2388
- let d = s
2389
- .create_draft("t", "a", "App", "owner", Some(&corrupt.revision_id))
2390
- .unwrap();
2391
- let clean = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2392
-
2393
- // Historical source corruption must not prevent recovery away from it.
2394
- {
2395
- let mut records = s.records.write().unwrap();
2396
- records
2397
- .revisions
2398
- .iter_mut()
2399
- .find(|value| value.revision_id == corrupt.revision_id)
2400
- .unwrap()
2401
- .manifest
2402
- .metadata
2403
- .name = "corrupted without updating its integrity hash".into();
2404
- s.persist(&records).unwrap();
2405
- }
2406
- let recovered = s
2407
- .recover_environment_pointer(
2408
- "t",
2409
- "a",
2410
- "staging",
2411
- &corrupt.revision_id,
2412
- &clean.revision_id,
2413
- "sherpa",
2414
- "Replace corrupt historical revision",
2415
- "ELEVATED",
2416
- "recovery-1",
2417
- )
2418
- .unwrap();
2419
- assert_eq!(recovered.target_revision, clean.revision_id);
2420
- assert_eq!(
2421
- s.recover_environment_pointer(
2422
- "t",
2423
- "a",
2424
- "staging",
2425
- &corrupt.revision_id,
2426
- &clean.revision_id,
2427
- "sherpa",
2428
- "Replace corrupt historical revision",
2429
- "ELEVATED",
2430
- "recovery-1"
2431
- )
2432
- .unwrap(),
2433
- recovered
2434
- );
2435
- assert!(s
2436
- .move_environment_pointer(
2437
- "t",
2438
- "a",
2439
- &corrupt.revision_id,
2440
- "staging",
2441
- Some(&clean.revision_id),
2442
- "owner",
2443
- "rollback",
2444
- true,
2445
- true
2446
- )
2447
- .unwrap_err()
2448
- .contains("untrusted"));
2449
-
2450
- let reloaded = ApplicationStore::load(s.path.clone()).unwrap();
2451
- assert_eq!(reloaded.pointers("a")["staging"], clean.revision_id);
2452
- let records = reloaded.records.read().unwrap();
2453
- assert_eq!(records.recoveries.len(), 1);
2454
- assert!(records.untrusted_revisions["a"].contains_key(&corrupt.revision_id));
2455
- }
2456
- #[test]
2457
- fn preview_remains_bound_when_production_moves() {
2458
- let s = store("preview-bound");
2459
- let d = s.create_draft("t", "a", "App", "owner", None).unwrap();
2460
- let r1 = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2461
- s.move_environment_pointer(
2462
- "t",
2463
- "a",
2464
- &r1.revision_id,
2465
- "production",
2466
- None,
2467
- "owner",
2468
- "initial",
2469
- true,
2470
- false,
2471
- )
2472
- .unwrap();
2473
- let preview = s
2474
- .create_preview(
2475
- "t",
2476
- "a",
2477
- &r1.revision_id,
2478
- "editor",
2479
- PreviewPolicy::default(),
2480
- )
2481
- .unwrap();
2482
- let d = s
2483
- .create_draft("t", "a", "App", "owner", Some(&r1.revision_id))
2484
- .unwrap();
2485
- let r2 = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2486
- s.move_environment_pointer(
2487
- "t",
2488
- "a",
2489
- &r2.revision_id,
2490
- "production",
2491
- Some(&r1.revision_id),
2492
- "owner",
2493
- "next",
2494
- true,
2495
- false,
2496
- )
2497
- .unwrap();
2498
- assert_eq!(
2499
- s.preview("t", "a", &preview.preview_id)
2500
- .unwrap()
2501
- .revision_id,
2502
- r1.revision_id
2503
- );
2504
- assert_eq!(s.pointers("a")["production"], r2.revision_id);
2505
- }
2506
- #[test]
2507
- fn destructive_change_requires_acknowledgement_and_audit_binds_diff() {
2508
- let s = store("destructive-gate");
2509
- let mut d = s.create_draft("t", "a", "App", "owner", None).unwrap();
2510
- d.manifest.collections.push(CollectionDefinition {
2511
- name: "records".into(),
2512
- fields: vec![],
2513
- });
2514
- d = s
2515
- .update_draft("t", "a", &d.draft_id, d.version, d.manifest, "owner")
2516
- .unwrap();
2517
- let r1 = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2518
- s.move_environment_pointer(
2519
- "t",
2520
- "a",
2521
- &r1.revision_id,
2522
- "production",
2523
- None,
2524
- "owner",
2525
- "initial",
2526
- true,
2527
- false,
2528
- )
2529
- .unwrap();
2530
- let mut d = s
2531
- .create_draft("t", "a", "App", "owner", Some(&r1.revision_id))
2532
- .unwrap();
2533
- d.manifest.collections.clear();
2534
- d.manifest.state_schema_version += 1;
2535
- d = s
2536
- .update_draft("t", "a", &d.draft_id, d.version, d.manifest, "owner")
2537
- .unwrap();
2538
- let r2 = s.commit("t", "a", &d.draft_id, "owner").unwrap();
2539
- assert_eq!(
2540
- s.move_environment_pointer(
2541
- "t",
2542
- "a",
2543
- &r2.revision_id,
2544
- "production",
2545
- Some(&r1.revision_id),
2546
- "owner",
2547
- "remove",
2548
- false,
2549
- false
2550
- )
2551
- .unwrap_err(),
2552
- "destructive_changes_require_approval"
2553
- );
2554
- let promotion = s
2555
- .move_environment_pointer(
2556
- "t",
2557
- "a",
2558
- &r2.revision_id,
2559
- "production",
2560
- Some(&r1.revision_id),
2561
- "owner",
2562
- "approved",
2563
- true,
2564
- false,
2565
- )
2566
- .unwrap();
2567
- let audit = s.audit("t", "a");
2568
- let event = audit.last().unwrap();
2569
- assert_eq!(event.event, "application.revision.promoted");
2570
- assert_eq!(
2571
- event.diff_hash.as_deref(),
2572
- Some(promotion.diff_hash.as_str())
2573
- );
2574
- }
2575
-
2576
- #[test]
2577
- fn policy_with_valid_authenticated_subject() {
2578
- let mut manifest = ApplicationManifest::empty("tenant", "app", "test");
2579
- manifest.policies.push(PolicyDefinition {
2580
- name: "TodoPolicy".into(),
2581
- resource: "Todo".into(),
2582
- read: Some("authenticated".into()),
2583
- write: Some("authenticated".into()),
2584
- capabilities: vec![],
2585
- });
2586
-
2587
- let report = validate_manifest(&manifest, "tenant", "app", None);
2588
- assert!(
2589
- report.valid,
2590
- "Policy with authenticated subject should be valid: {:?}",
2591
- report.issues
2592
- );
2593
- }
2594
-
2595
- #[test]
2596
- fn policy_with_valid_owner_subject() {
2597
- let mut manifest = ApplicationManifest::empty("tenant", "app", "test");
2598
- manifest.policies.push(PolicyDefinition {
2599
- name: "ProjectPolicy".into(),
2600
- resource: "Project".into(),
2601
- read: Some("authenticated".into()),
2602
- write: Some("owner".into()),
2603
- capabilities: vec![],
2604
- });
2605
-
2606
- let report = validate_manifest(&manifest, "tenant", "app", None);
2607
- assert!(
2608
- report.valid,
2609
- "Policy with owner subject should be valid: {:?}",
2610
- report.issues
2611
- );
2612
- }
2613
-
2614
- #[test]
2615
- fn policy_with_identity_and_membership_composition_is_valid() {
2616
- let mut manifest = ApplicationManifest::empty("tenant", "app", "test");
2617
- manifest.policies.push(PolicyDefinition {
2618
- name: "InvitationPolicy".into(),
2619
- resource: "Invitation".into(),
2620
- read: Some("self(user) | member".into()),
2621
- write: Some("member".into()),
2622
- capabilities: vec![],
2623
- });
2624
-
2625
- let report = validate_manifest(&manifest, "tenant", "app", None);
2626
- assert!(
2627
- report.valid,
2628
- "composed identity policy should be valid: {:?}",
2629
- report.issues
2630
- );
2631
- }
2632
-
2633
- #[test]
2634
- fn policy_with_invalid_subject_rejected() {
2635
- let mut manifest = ApplicationManifest::empty("tenant", "app", "test");
2636
- manifest.policies.push(PolicyDefinition {
2637
- name: "BadPolicy".into(),
2638
- resource: "BadCollection".into(),
2639
- read: Some("unknown_subject".into()),
2640
- write: None,
2641
- capabilities: vec![],
2642
- });
2643
-
2644
- let report = validate_manifest(&manifest, "tenant", "app", None);
2645
- assert!(
2646
- !report.valid,
2647
- "Policy with unknown subject should be invalid"
2648
- );
2649
- assert!(
2650
- report.issues.iter().any(|i| i.path.contains("BadPolicy")
2651
- && i.path.contains("read")
2652
- && i.message.contains("invalid policy subject")),
2653
- "Should have error about invalid policy subject"
2654
- );
2655
- }
2656
-
2657
- #[test]
2658
- fn policy_without_subjects_is_valid() {
2659
- let mut manifest = ApplicationManifest::empty("tenant", "app", "test");
2660
- manifest.policies.push(PolicyDefinition {
2661
- name: "LegacyPolicy".into(),
2662
- resource: "SomeCollection".into(),
2663
- read: None,
2664
- write: None,
2665
- capabilities: vec!["some:capability".into()],
2666
- });
2667
-
2668
- let report = validate_manifest(&manifest, "tenant", "app", None);
2669
- assert!(
2670
- report.valid,
2671
- "Policy without subjects should be valid (backward compatible)"
2672
- );
2673
- }
2674
- }