cfgit 0.4.1__tar.gz → 0.4.2__tar.gz

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 (88) hide show
  1. {cfgit-0.4.1 → cfgit-0.4.2}/PKG-INFO +17 -3
  2. {cfgit-0.4.1 → cfgit-0.4.2}/README.md +15 -1
  3. {cfgit-0.4.1 → cfgit-0.4.2}/docs/ADAPTERS.md +4 -0
  4. {cfgit-0.4.1 → cfgit-0.4.2}/docs/AGENTS.md +19 -0
  5. {cfgit-0.4.1 → cfgit-0.4.2}/docs/BRANCHING_PLAN.md +3 -3
  6. {cfgit-0.4.1 → cfgit-0.4.2}/docs/USAGE.md +3 -3
  7. cfgit-0.4.2/docs/screenshots/01-diff.png +0 -0
  8. cfgit-0.4.2/docs/screenshots/02-impact.png +0 -0
  9. cfgit-0.4.2/docs/screenshots/03-scoped-impact.png +0 -0
  10. cfgit-0.4.2/docs/screenshots/04-branches.png +0 -0
  11. cfgit-0.4.2/docs/screenshots/05-pull-request.png +0 -0
  12. {cfgit-0.4.1 → cfgit-0.4.2}/examples/cfgit-support-demo.toml +11 -2
  13. {cfgit-0.4.1 → cfgit-0.4.2}/plugins/cfg_impact/pyproject.toml +2 -2
  14. {cfgit-0.4.1 → cfgit-0.4.2}/pyproject.toml +4 -2
  15. {cfgit-0.4.1 → cfgit-0.4.2}/skills/cfgit/SKILL.md +2 -1
  16. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/adapters/__init__.py +2 -0
  17. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/adapters/base.py +21 -0
  18. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/adapters/mongo.py +163 -71
  19. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/adapters/postgres.py +160 -73
  20. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/core/engine.py +117 -66
  21. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/mcp/server.py +6 -0
  22. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/ui/server.py +721 -147
  23. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_engine_safety.py +78 -3
  24. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_mcp_identity.py +4 -2
  25. cfgit-0.4.1/docs/screenshots/01-diff.png +0 -0
  26. cfgit-0.4.1/docs/screenshots/02-impact.png +0 -0
  27. cfgit-0.4.1/docs/screenshots/03-scoped-impact.png +0 -0
  28. {cfgit-0.4.1 → cfgit-0.4.2}/.github/workflows/ci.yml +0 -0
  29. {cfgit-0.4.1 → cfgit-0.4.2}/.github/workflows/publish.yml +0 -0
  30. {cfgit-0.4.1 → cfgit-0.4.2}/.gitignore +0 -0
  31. {cfgit-0.4.1 → cfgit-0.4.2}/CONTRIBUTING.md +0 -0
  32. {cfgit-0.4.1 → cfgit-0.4.2}/CREDITS.md +0 -0
  33. {cfgit-0.4.1 → cfgit-0.4.2}/LICENSE +0 -0
  34. {cfgit-0.4.1 → cfgit-0.4.2}/NOTICE +0 -0
  35. {cfgit-0.4.1 → cfgit-0.4.2}/SECURITY.md +0 -0
  36. {cfgit-0.4.1 → cfgit-0.4.2}/docs/CONFIGURATION.md +0 -0
  37. {cfgit-0.4.1 → cfgit-0.4.2}/docs/IDENTITY_AND_ATTRIBUTION.md +0 -0
  38. {cfgit-0.4.1 → cfgit-0.4.2}/docs/PUBLISHING.md +0 -0
  39. {cfgit-0.4.1 → cfgit-0.4.2}/docs/README.md +0 -0
  40. {cfgit-0.4.1 → cfgit-0.4.2}/docs/SPEC.md +0 -0
  41. {cfgit-0.4.1 → cfgit-0.4.2}/docs/SPEC_CORE.md +0 -0
  42. {cfgit-0.4.1 → cfgit-0.4.2}/examples/.cfg.toml +0 -0
  43. {cfgit-0.4.1 → cfgit-0.4.2}/examples/seed_support_demo.py +0 -0
  44. {cfgit-0.4.1 → cfgit-0.4.2}/plugins/cfg_impact/README.md +0 -0
  45. {cfgit-0.4.1 → cfgit-0.4.2}/plugins/cfg_impact/cfg_impact/__init__.py +0 -0
  46. {cfgit-0.4.1 → cfgit-0.4.2}/plugins/cfg_impact/cfg_impact/overview.py +0 -0
  47. {cfgit-0.4.1 → cfgit-0.4.2}/plugins/cfg_impact/cfg_impact/providers/__init__.py +0 -0
  48. {cfgit-0.4.1 → cfgit-0.4.2}/plugins/cfg_impact/cfg_impact/providers/base.py +0 -0
  49. {cfgit-0.4.1 → cfgit-0.4.2}/plugins/cfg_impact/cfg_impact/providers/claude.py +0 -0
  50. {cfgit-0.4.1 → cfgit-0.4.2}/plugins/cfg_impact/cfg_impact/providers/factory.py +0 -0
  51. {cfgit-0.4.1 → cfgit-0.4.2}/plugins/cfg_impact/cfg_impact/providers/gemini.py +0 -0
  52. {cfgit-0.4.1 → cfgit-0.4.2}/plugins/cfg_impact/cfg_impact/providers/openai_provider.py +0 -0
  53. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/__init__.py +0 -0
  54. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/approval/__init__.py +0 -0
  55. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/approval/base.py +0 -0
  56. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/cli/__init__.py +0 -0
  57. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/cli/main.py +0 -0
  58. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/core/__init__.py +0 -0
  59. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/core/authz.py +0 -0
  60. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/core/config.py +0 -0
  61. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/core/diff.py +0 -0
  62. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/core/hashing.py +0 -0
  63. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/core/identity.py +0 -0
  64. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/core/remedy.py +0 -0
  65. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/interfaces/__init__.py +0 -0
  66. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/interfaces/actions.py +0 -0
  67. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/mcp/__init__.py +0 -0
  68. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/ui/__init__.py +0 -0
  69. {cfgit-0.4.1 → cfgit-0.4.2}/src/cfg/update.py +0 -0
  70. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_adapter_contract_live.py +0 -0
  71. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_authz.py +0 -0
  72. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_awareness.py +0 -0
  73. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_commit_dry_run.py +0 -0
  74. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_config.py +0 -0
  75. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_config_discovery.py +0 -0
  76. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_console_script.py +0 -0
  77. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_core_purity.py +0 -0
  78. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_export_import.py +0 -0
  79. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_hashing.py +0 -0
  80. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_identity.py +0 -0
  81. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_impact_boundary.py +0 -0
  82. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_mongo_history.py +0 -0
  83. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_output_mode.py +0 -0
  84. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_postgres_history.py +0 -0
  85. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_remedy.py +0 -0
  86. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_set_fields.py +0 -0
  87. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_ui_server.py +0 -0
  88. {cfgit-0.4.1 → cfgit-0.4.2}/tests/test_update_check.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cfgit
3
- Version: 0.4.1
3
+ Version: 0.4.2
4
4
  Summary: Git-style history, diff, drift detection, and rollback for live database records without migrating or owning your datastore
5
5
  Project-URL: Homepage, https://github.com/AusafMo/cfgit
6
6
  Project-URL: Repository, https://github.com/AusafMo/cfgit
@@ -224,7 +224,7 @@ Requires-Dist: pytest>=8.0; extra == 'dev'
224
224
  Requires-Dist: ruff; extra == 'dev'
225
225
  Provides-Extra: impact
226
226
  Provides-Extra: mcp
227
- Requires-Dist: mcp>=1.0; extra == 'mcp'
227
+ Requires-Dist: mcp<2,>=1.0; extra == 'mcp'
228
228
  Provides-Extra: mongo
229
229
  Requires-Dist: pymongo>=4.6; extra == 'mongo'
230
230
  Provides-Extra: postgres
@@ -252,6 +252,15 @@ the store, records what changed, and refuses to clobber changes it did not recor
252
252
  <sub>Production-shaped drift review &nbsp;·&nbsp; narrated whole-system impact &nbsp;·&nbsp; narrated impact scoped to selected policy, eval, and rollout records</sub>
253
253
  </p>
254
254
 
255
+ <p align="center">
256
+ <img src="docs/screenshots/04-branches.png" alt="Branches workspace with a default runtime branch, a draft branch, and a branch with an open cfgit PR, plus a compare-branches selector" width="48%" />
257
+ <img src="docs/screenshots/05-pull-request.png" alt="Open cfgit pull request reviewing a policy-rule change on a draft branch with a line-aligned diff and merge action" width="48%" />
258
+ </p>
259
+
260
+ <p align="center">
261
+ <sub>Branch workflow over live records &nbsp;·&nbsp; a cfgit pull request with a line-aligned diff, ready to merge as one runtime mutation</sub>
262
+ </p>
263
+
255
264
  ## Why cfgit exists
256
265
 
257
266
  Many teams keep runtime behavior in live database records: model routing, agent
@@ -521,7 +530,9 @@ cfg pr merge <pr-id>
521
530
  Branching is opt-in with `[branches] enabled = true`. `branch`, branch commits,
522
531
  branch diff, and PR creation write only cfgit draft/review refs. The only branch
523
532
  command that mutates runtime is `cfg pr merge`, and it refuses stale main heads
524
- or un-adopted live drift.
533
+ or un-adopted live drift. Multi-record PR merges require adapter batch atomicity:
534
+ all runtime records, canonical history/head updates, and PR closure commit
535
+ together or roll back together.
525
536
 
526
537
  `commit`, `import`, and `adopt` scan the would-be-stored document for secret-like
527
538
  field names and values from `[secrets]`. Fields listed in `secret_fields` are
@@ -757,6 +768,9 @@ Tools include:
757
768
  A portable skill lives at `skills/cfgit/SKILL.md`.
758
769
  `cfg_impact` accepts the same `against` list/string as the CLI `--against` flag,
759
770
  so MCP clients can request scoped narration without shelling out.
771
+ `cfg_pr_merge` has the same runtime semantics as the CLI: it is the only branch
772
+ or PR MCP tool that mutates runtime, and multi-record PRs are merged as one
773
+ adapter-atomic batch when the backend supports that guarantee.
760
774
 
761
775
  If `cfg_log` or `cfg_show` returns `bad_config` with a message saying history
762
776
  exists under another env, the same database has been addressed with two
@@ -19,6 +19,15 @@ the store, records what changed, and refuses to clobber changes it did not recor
19
19
  <sub>Production-shaped drift review &nbsp;·&nbsp; narrated whole-system impact &nbsp;·&nbsp; narrated impact scoped to selected policy, eval, and rollout records</sub>
20
20
  </p>
21
21
 
22
+ <p align="center">
23
+ <img src="docs/screenshots/04-branches.png" alt="Branches workspace with a default runtime branch, a draft branch, and a branch with an open cfgit PR, plus a compare-branches selector" width="48%" />
24
+ <img src="docs/screenshots/05-pull-request.png" alt="Open cfgit pull request reviewing a policy-rule change on a draft branch with a line-aligned diff and merge action" width="48%" />
25
+ </p>
26
+
27
+ <p align="center">
28
+ <sub>Branch workflow over live records &nbsp;·&nbsp; a cfgit pull request with a line-aligned diff, ready to merge as one runtime mutation</sub>
29
+ </p>
30
+
22
31
  ## Why cfgit exists
23
32
 
24
33
  Many teams keep runtime behavior in live database records: model routing, agent
@@ -288,7 +297,9 @@ cfg pr merge <pr-id>
288
297
  Branching is opt-in with `[branches] enabled = true`. `branch`, branch commits,
289
298
  branch diff, and PR creation write only cfgit draft/review refs. The only branch
290
299
  command that mutates runtime is `cfg pr merge`, and it refuses stale main heads
291
- or un-adopted live drift.
300
+ or un-adopted live drift. Multi-record PR merges require adapter batch atomicity:
301
+ all runtime records, canonical history/head updates, and PR closure commit
302
+ together or roll back together.
292
303
 
293
304
  `commit`, `import`, and `adopt` scan the would-be-stored document for secret-like
294
305
  field names and values from `[secrets]`. Fields listed in `secret_fields` are
@@ -524,6 +535,9 @@ Tools include:
524
535
  A portable skill lives at `skills/cfgit/SKILL.md`.
525
536
  `cfg_impact` accepts the same `against` list/string as the CLI `--against` flag,
526
537
  so MCP clients can request scoped narration without shelling out.
538
+ `cfg_pr_merge` has the same runtime semantics as the CLI: it is the only branch
539
+ or PR MCP tool that mutates runtime, and multi-record PRs are merged as one
540
+ adapter-atomic batch when the backend supports that guarantee.
527
541
 
528
542
  If `cfg_log` or `cfg_show` returns `bad_config` with a message saying history
529
543
  exists under another env, the same database has been addressed with two
@@ -103,3 +103,7 @@ The important contract is `apply(...)`, which atomically:
103
103
 
104
104
  If a datastore cannot guarantee that atomicity, the adapter should report limited
105
105
  capabilities and refuse unsafe operations rather than pretending they are safe.
106
+
107
+ Adapters that support branch PR merge also implement `apply_many(...)`, which
108
+ runs the same checks and writes for several records inside one transaction and
109
+ can persist sidecar refs, such as marking a PR merged, before commit.
@@ -25,6 +25,14 @@ or secret-policy failure blocks the whole batch before any record is written.
25
25
  If it returns `blocked`, nothing was applied. If it returns `partial`, inspect
26
26
  `results`, `failed`, and `pending` before continuing.
27
27
 
28
+ For branch review flows, remember that branch commits and PR creation write only
29
+ cfgit refs. `cfg_pr_merge` is the runtime mutation. For multi-record PRs it
30
+ preflights every touched record, requires adapter batch atomicity, and commits or
31
+ rolls back all runtime records, canonical heads/history, and the PR status
32
+ together. If the MCP envelope returns `stale`, `changed_outside_cfgit`, or
33
+ `atomicity_unavailable`, stop and inspect the reported drift, main-head movement,
34
+ or adapter capability before retrying.
35
+
28
36
  ## Agent Identity
29
37
 
30
38
  In `authenticated` or `enforced` environments, run the agent process with its own
@@ -84,6 +92,17 @@ Tool list:
84
92
  - `cfg_impact`
85
93
  - `cfg_commit`
86
94
  - `cfg_bulk_commit`
95
+ - `cfg_branch_list`
96
+ - `cfg_branch_create`
97
+ - `cfg_branch_delete`
98
+ - `cfg_branch_diff`
99
+ - `cfg_branch_log`
100
+ - `cfg_pr_create`
101
+ - `cfg_pr_list`
102
+ - `cfg_pr_show`
103
+ - `cfg_pr_close`
104
+ - `cfg_pr_merge`
105
+ - `cfg_recent_history`
87
106
  - `cfg_log`
88
107
  - `cfg_show`
89
108
  - `cfg_adopt`
@@ -200,9 +200,9 @@ To mutate runtime, use: cfg pr merge <pr>
200
200
  7. For each touched record, confirm canonical `main` HEAD still equals `base_oid`.
201
201
  8. For each touched record, confirm live runtime hash still equals `base_oid`.
202
202
  9. For multi-record PRs, require adapter atomicity.
203
- 10. Apply runtime docs and append canonical history entries in one transaction.
204
- 11. Move canonical heads.
205
- 12. Mark PR merged.
203
+ 10. Use the adapter batch apply path to write runtime docs, append canonical
204
+ history entries, move canonical heads, and mark the PR merged in one
205
+ transaction.
206
206
 
207
207
  If any check fails, runtime remains unchanged and the result includes
208
208
  `runtime_mutated = false`.
@@ -240,9 +240,9 @@ cfg pr merge <pr-id>
240
240
 
241
241
  `cfg pr merge` is the only branch/PR command that mutates runtime. It writes a
242
242
  normal canonical history entry with `op = "merge"` and source PR metadata. It
243
- refuses stale main heads and live drift. In this v1 slice, multi-record PR merge
244
- is blocked unless the adapter exposes true batch atomicity; split those changes
245
- into one-record PRs when you need a merge today.
243
+ refuses stale main heads and live drift. Multi-record PR merge requires adapter
244
+ batch atomicity: all runtime records, canonical history/head updates, and the PR
245
+ status update commit together or roll back together.
246
246
 
247
247
  `cfg switch <branch>` only writes local CLI state under `.cfgit/state.json`.
248
248
  It does not change runtime. Agents and scripts should prefer explicit
Binary file
@@ -83,8 +83,17 @@ from = "git"
83
83
 
84
84
  [connections]
85
85
  enabled = true
86
- share_with_ai = []
87
- ai_provider = "openai"
86
+ # Demo data is synthetic and safe (see examples/seed_support_demo.py). We opt these
87
+ # records into AI narration so `cfg impact --llm` can explain the refund_resolution
88
+ # change and its scoped blast radius (used for the README screenshots).
89
+ share_with_ai = [
90
+ "agent_configs:refund_resolution",
91
+ "policy_rules:refund_window_standard",
92
+ "eval_suites:refund_policy_regression",
93
+ "rollout_controls:refund_agent_june",
94
+ "routing_policies:global_support_router",
95
+ ]
96
+ ai_provider = "gemini"
88
97
  warn_level = "none"
89
98
  links = [
90
99
  { field = "agent", means = "agent identifier" },
@@ -1,13 +1,13 @@
1
1
  [project]
2
2
  name = "cfgit-impact"
3
- version = "0.4.1"
3
+ version = "0.4.2"
4
4
  description = "Optional cfgit plugin for deterministic system-impact summaries and opt-in LLM narration of database record diffs"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
7
7
  license = "Apache-2.0"
8
8
  authors = [{ name = "Mohammad Ausaf" }]
9
9
  dependencies = [
10
- "cfgit>=0.4.1,<0.5.0",
10
+ "cfgit>=0.4.2,<0.5.0",
11
11
  "httpx>=0.27",
12
12
  ]
13
13
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cfgit"
3
- version = "0.4.1"
3
+ version = "0.4.2"
4
4
  description = "Git-style history, diff, drift detection, and rollback for live database records without migrating or owning your datastore"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -31,7 +31,9 @@ dependencies = [
31
31
  mongo = ["pymongo>=4.6"]
32
32
  postgres = ["psycopg[binary]>=3.2"]
33
33
  cli = ["click>=8.1", "rich>=13.0"]
34
- mcp = ["mcp>=1.0"]
34
+ # mcp 2.0 relocated FastMCP off `mcp.server.fastmcp`, which cfg/mcp/server.py imports.
35
+ # Cap below 2.0 until the server is ported to the 2.x API.
36
+ mcp = ["mcp>=1.0,<2"]
35
37
  impact = [] # the cfgit-impact plugin declares its own model-client deps; never in core
36
38
  dev = ["pytest>=8.0", "pytest-asyncio", "ruff", "mypy", "httpx>=0.27"]
37
39
 
@@ -77,7 +77,7 @@ Use cfgit as the safety layer around a live datastore. The app still reads and w
77
77
  - `cfg --branch <name> commit <record> --from <file> -m "<message>" --json`
78
78
  - `cfg diff main..<name> --json`
79
79
  - `cfg pr create --base main --head <name> -m "<message>" --json`
80
- - `cfg pr merge <pr-id> --json` only after review. If merge returns `stale` or `changed_outside_cfgit`, do not retry blindly; inspect current main/live drift first.
80
+ - `cfg pr merge <pr-id> --json` only after review. If merge returns `stale`, `changed_outside_cfgit`, or `atomicity_unavailable`, do not retry blindly; inspect current main/live drift or adapter capability first.
81
81
 
82
82
  ## MCP Tools
83
83
 
@@ -116,4 +116,5 @@ If the cfgit MCP server is available, prefer its tools over shelling out:
116
116
 
117
117
  Every MCP tool returns the same envelope: `status`, `code`, `message`, `data`, plus top-level `state` and `next`. `state` echoes the outcome's terminal state (e.g. `changed_outside_cfgit`, `noop`, `blocked`, `would_commit`); `next` is a self-teaching remedy `{why, remedy, commands}` when the outcome needs one, else null. Branch on `state` and follow `next.commands` on a refusal instead of guessing.
118
118
  For MCP bulk commits, pass `items` as structured JSON (`[{record, doc}]`) when the client supports it; use a JSON string only when the client cannot send nested objects cleanly.
119
+ For MCP PR merges, `cfg_pr_merge` has the same semantics as `cfg pr merge`: it is the only branch/PR mutation path, multi-record merges are batch-atomic when supported, and `atomicity_unavailable` means no runtime records were changed.
119
120
  For MCP history/env mismatches, branch on `status="error"` and `code=6`; surface the `message` to the user and do not continue mutation.
@@ -2,6 +2,7 @@
2
2
  """StorageAdapter implementations (the DB seam, SPEC §2). Mongo is first."""
3
3
  from cfg.adapters.base import (
4
4
  AmbiguousConfig,
5
+ ApplyItem,
5
6
  ApplyResult,
6
7
  AtomicityReport,
7
8
  HistoryEnvMismatch,
@@ -14,6 +15,7 @@ from cfg.adapters.base import (
14
15
 
15
16
  __all__ = [
16
17
  "StorageAdapter",
18
+ "ApplyItem",
17
19
  "ApplyResult",
18
20
  "ReconcileReport",
19
21
  "AtomicityReport",
@@ -49,6 +49,18 @@ class ApplyResult:
49
49
  head_oid: str
50
50
 
51
51
 
52
+ @dataclass
53
+ class ApplyItem:
54
+ collection: str
55
+ record_id: str
56
+ new_doc: dict | None
57
+ entry: dict
58
+ expected_head_oid: str | None
59
+ expected_live_oid: str | None = None
60
+ make_head: bool = True
61
+ seed_missing: bool = False
62
+
63
+
52
64
  @dataclass
53
65
  class ReconcileReport:
54
66
  rolled_forward: list[str]
@@ -88,6 +100,14 @@ class StorageAdapter(Protocol):
88
100
  def seed_record(self, collection: str, record_id: str, doc: dict) -> None: ...
89
101
  def list_record_ids(self, collection: str) -> list[str]: ...
90
102
 
103
+ # OPTIONAL batch reads. Callers (e.g. Engine.status) feature-detect these and
104
+ # fall back to per-record get_record/get_head when an adapter does not provide
105
+ # them, so third-party adapters that omit them keep working. Implementing them
106
+ # collapses the per-record N+1 (2 round-trips per record) into ~2 queries per
107
+ # collection — the difference between a snappy and a stalling UI on a remote DB.
108
+ def get_records(self, collection: str, record_ids: list[str]) -> dict[str, dict]: ...
109
+ def get_heads(self, collection: str, record_ids: list[str]) -> dict[str, dict]: ...
110
+
91
111
  # history reads
92
112
  def get_head(self, collection: str, record_id: str) -> dict | None: ...
93
113
  def query_history(self, *, collection: str | None = None, record_id: str | None = None,
@@ -108,6 +128,7 @@ class StorageAdapter(Protocol):
108
128
  def apply(self, *, collection: str, record_id: str, new_doc: dict | None, entry: dict,
109
129
  expected_head_oid: str | None, expected_live_oid: str | None = None,
110
130
  make_head: bool = True, seed_missing: bool = False) -> ApplyResult: ...
131
+ def apply_many(self, *, items: list[ApplyItem], put_refs: list[dict] | None = None) -> list[ApplyResult]: ...
111
132
 
112
133
  # labels
113
134
  def add_tag(self, *, collection: str, record_id: str, seq: int, tag: str) -> None: ...
@@ -9,6 +9,7 @@ from urllib.parse import unquote, urlsplit
9
9
 
10
10
  from cfg.adapters.base import (
11
11
  AmbiguousConfig,
12
+ ApplyItem,
12
13
  ApplyResult,
13
14
  AtomicityUnavailable,
14
15
  AtomicityReport,
@@ -67,6 +68,53 @@ class MongoAdapter:
67
68
  values = self.db[collection].distinct(coll.id_field, coll.live_when)
68
69
  return sorted(str(v) for v in values if v is not None)
69
70
 
71
+ def get_records(self, collection: str, record_ids: list[str]) -> dict[str, dict]:
72
+ """Batch of get_record: one runtime query for many ids instead of one per id.
73
+
74
+ Raises AmbiguousConfig if any id resolves to more than one live doc, matching
75
+ get_record's single-doc guarantee. Ids with no live doc are simply absent.
76
+ """
77
+ if not record_ids:
78
+ return {}
79
+ coll = self.project.collection(collection)
80
+ query = {coll.id_field: {"$in": list(record_ids)}, **coll.live_when}
81
+ out: dict[str, dict] = {}
82
+ for doc in self.db[collection].find(query):
83
+ rid = str(doc.get(coll.id_field))
84
+ if rid in out:
85
+ raise AmbiguousConfig(f"{collection}:{rid}")
86
+ out[rid] = doc
87
+ return out
88
+
89
+ def get_heads(self, collection: str, record_ids: list[str]) -> dict[str, dict]:
90
+ """Batch of get_head: two history-store queries total (head pointers, then the
91
+ pointed-to history rows) instead of two per id."""
92
+ if not record_ids:
93
+ return {}
94
+ ids = list(record_ids)
95
+ ptrs = list(
96
+ self.heads.find(
97
+ {"env": self.env_name, "collection": collection, "record_id": {"$in": ids}}
98
+ )
99
+ )
100
+ if not ptrs:
101
+ return {}
102
+ want = {str(p["record_id"]): p["head_seq"] for p in ptrs}
103
+ rows = self.history.find(
104
+ {
105
+ "env": self.env_name,
106
+ "collection": collection,
107
+ "record_id": {"$in": list(want)},
108
+ "seq": {"$in": sorted(set(want.values()))},
109
+ }
110
+ )
111
+ out: dict[str, dict] = {}
112
+ for row in rows:
113
+ rid = str(row["record_id"])
114
+ if want.get(rid) == row["seq"]:
115
+ out[rid] = _history_row(row, with_doc=True)
116
+ return out
117
+
70
118
  def get_head(self, collection: str, record_id: str) -> dict | None:
71
119
  ptr = self.heads.find_one(self._head_query(collection, record_id))
72
120
  if not ptr:
@@ -138,6 +186,9 @@ class MongoAdapter:
138
186
  return [{"tag": row["_id"], "count": row["count"]} for row in self.history.aggregate(pipeline)]
139
187
 
140
188
  def put_ref(self, doc: dict) -> None:
189
+ self._put_ref(doc)
190
+
191
+ def _put_ref(self, doc: dict, *, session: ClientSession | None = None) -> None:
141
192
  stored = deepcopy(doc)
142
193
  stored["env"] = self.env_name
143
194
  ref_type = str(stored["type"])
@@ -146,6 +197,7 @@ class MongoAdapter:
146
197
  {"env": self.env_name, "type": ref_type, "id": ref_id},
147
198
  stored,
148
199
  upsert=True,
200
+ session=session,
149
201
  )
150
202
 
151
203
  def get_ref(self, ref_type: str, ref_id: str) -> dict | None:
@@ -193,6 +245,28 @@ class MongoAdapter:
193
245
  raise
194
246
  raise RuntimeError("unreachable")
195
247
 
248
+ def apply_many(self, *, items: list[ApplyItem], put_refs: list[dict] | None = None) -> list[ApplyResult]:
249
+ atomicity = self.check_atomicity_scope()
250
+ if not atomicity.atomic:
251
+ raise AtomicityUnavailable(atomicity.reason)
252
+ if not items:
253
+ return []
254
+ for attempt in range(3):
255
+ try:
256
+ return self._apply_many_once(items=items, put_refs=put_refs or [])
257
+ except OperationFailure as exc:
258
+ if attempt >= 2 or not _is_transient_transaction_error(exc):
259
+ raise
260
+ raise RuntimeError("unreachable")
261
+
262
+ def _apply_many_once(self, *, items: list[ApplyItem], put_refs: list[dict]) -> list[ApplyResult]:
263
+ with self.client.start_session() as session:
264
+ with session.start_transaction():
265
+ results = [self._apply_item(item, session=session) for item in items]
266
+ for doc in put_refs:
267
+ self._put_ref(doc, session=session)
268
+ return results
269
+
196
270
  def _apply_once(
197
271
  self,
198
272
  *,
@@ -205,82 +279,100 @@ class MongoAdapter:
205
279
  make_head: bool,
206
280
  seed_missing: bool,
207
281
  ) -> ApplyResult:
208
- coll_cfg = self.project.collection(collection)
209
282
  with self.client.start_session() as session:
210
283
  with session.start_transaction():
211
- ptr = self.heads.find_one(self._head_query(collection, record_id), session=session)
212
- current_head = ptr.get("head_oid") if ptr else None
213
- if current_head != expected_head_oid:
214
- raise StaleHead(current_head)
215
-
216
- if expected_live_oid is not None:
217
- live = self._get_record(collection, record_id, session=session)
218
- if live is None:
219
- raise NoSuchConfig(f"{collection}:{record_id}")
220
- live_oid = hash_doc(live, coll_cfg)
221
- if live_oid != expected_live_oid:
222
- raise StaleLive(live_oid)
223
-
224
- seq = int(ptr.get("head_seq", 0)) + 1 if ptr else 1
225
- entry = dict(entry)
226
- entry.update(
227
- {
284
+ result = self._apply_item(
285
+ ApplyItem(
286
+ collection=collection,
287
+ record_id=record_id,
288
+ new_doc=new_doc,
289
+ entry=entry,
290
+ expected_head_oid=expected_head_oid,
291
+ expected_live_oid=expected_live_oid,
292
+ make_head=make_head,
293
+ seed_missing=seed_missing,
294
+ ),
295
+ session=session,
296
+ )
297
+ return result
298
+
299
+ def _apply_item(self, item: ApplyItem, *, session: ClientSession) -> ApplyResult:
300
+ collection = item.collection
301
+ record_id = item.record_id
302
+ coll_cfg = self.project.collection(collection)
303
+ ptr = self.heads.find_one(self._head_query(collection, record_id), session=session)
304
+ current_head = ptr.get("head_oid") if ptr else None
305
+ if current_head != item.expected_head_oid:
306
+ raise StaleHead(current_head)
307
+
308
+ if item.expected_live_oid is not None:
309
+ live = self._get_record(collection, record_id, session=session)
310
+ if live is None:
311
+ raise NoSuchConfig(f"{collection}:{record_id}")
312
+ live_oid = hash_doc(live, coll_cfg)
313
+ if live_oid != item.expected_live_oid:
314
+ raise StaleLive(live_oid)
315
+
316
+ seq = int(ptr.get("head_seq", 0)) + 1 if ptr else 1
317
+ entry = dict(item.entry)
318
+ entry.update(
319
+ {
320
+ "env": self.env_name,
321
+ "collection": collection,
322
+ "record_id": record_id,
323
+ "seq": seq,
324
+ }
325
+ )
326
+ self.history.insert_one(entry, session=session)
327
+
328
+ if current_head:
329
+ self.history.update_one(
330
+ {
331
+ "env": self.env_name,
332
+ "collection": collection,
333
+ "record_id": record_id,
334
+ "seq": ptr["head_seq"],
335
+ "valid_to": None,
336
+ },
337
+ {"$set": {"valid_to": entry["valid_from"]}},
338
+ session=session,
339
+ )
340
+
341
+ if item.new_doc is not None:
342
+ if item.seed_missing:
343
+ if self._get_record(collection, record_id, session=session) is not None:
344
+ raise StaleLive(f"{collection}:{record_id} reappeared before restore")
345
+ self._seed_record(collection, record_id, item.new_doc, session=session)
346
+ else:
347
+ self._put_record(collection, record_id, item.new_doc, session=session)
348
+
349
+ if item.make_head:
350
+ head_filter = self._head_query(collection, record_id)
351
+ if ptr:
352
+ head_filter = {
353
+ **head_filter,
354
+ "head_oid": item.expected_head_oid,
355
+ "head_seq": ptr["head_seq"],
356
+ }
357
+ result = self.heads.update_one(
358
+ head_filter,
359
+ {
360
+ "$set": {
361
+ "head_oid": entry["oid"],
362
+ "head_seq": seq,
363
+ "updated_at": entry["recorded_at"],
364
+ },
365
+ "$setOnInsert": {
228
366
  "env": self.env_name,
229
367
  "collection": collection,
230
368
  "record_id": record_id,
231
- "seq": seq,
232
- }
233
- )
234
- self.history.insert_one(entry, session=session)
235
-
236
- if current_head:
237
- self.history.update_one(
238
- {
239
- "env": self.env_name,
240
- "collection": collection,
241
- "record_id": record_id,
242
- "seq": ptr["head_seq"],
243
- "valid_to": None,
244
- },
245
- {"$set": {"valid_to": entry["valid_from"]}},
246
- session=session,
247
- )
248
-
249
- if new_doc is not None:
250
- if seed_missing:
251
- if self._get_record(collection, record_id, session=session) is not None:
252
- raise StaleLive(f"{collection}:{record_id} reappeared before restore")
253
- self._seed_record(collection, record_id, new_doc, session=session)
254
- else:
255
- self._put_record(collection, record_id, new_doc, session=session)
256
-
257
- if make_head:
258
- head_filter = self._head_query(collection, record_id)
259
- if ptr:
260
- head_filter = {
261
- **head_filter,
262
- "head_oid": expected_head_oid,
263
- "head_seq": ptr["head_seq"],
264
- }
265
- result = self.heads.update_one(
266
- head_filter,
267
- {
268
- "$set": {
269
- "head_oid": entry["oid"],
270
- "head_seq": seq,
271
- "updated_at": entry["recorded_at"],
272
- },
273
- "$setOnInsert": {
274
- "env": self.env_name,
275
- "collection": collection,
276
- "record_id": record_id,
277
- },
278
- },
279
- upsert=not ptr,
280
- session=session,
281
- )
282
- if ptr and result.matched_count != 1:
283
- raise StaleHead(expected_head_oid)
369
+ },
370
+ },
371
+ upsert=not ptr,
372
+ session=session,
373
+ )
374
+ if ptr and result.matched_count != 1:
375
+ raise StaleHead(item.expected_head_oid)
284
376
 
285
377
  return ApplyResult(
286
378
  collection=collection,