cfgit 0.2.0__tar.gz → 0.3.0__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 (81) hide show
  1. {cfgit-0.2.0 → cfgit-0.3.0}/PKG-INFO +29 -2
  2. {cfgit-0.2.0 → cfgit-0.3.0}/README.md +28 -1
  3. {cfgit-0.2.0 → cfgit-0.3.0}/docs/USAGE.md +33 -1
  4. {cfgit-0.2.0 → cfgit-0.3.0}/plugins/cfg_impact/pyproject.toml +2 -2
  5. {cfgit-0.2.0 → cfgit-0.3.0}/pyproject.toml +1 -1
  6. {cfgit-0.2.0 → cfgit-0.3.0}/skills/cfgit/SKILL.md +4 -1
  7. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/cli/main.py +40 -5
  8. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/core/engine.py +38 -0
  9. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/core/remedy.py +1 -1
  10. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/interfaces/actions.py +131 -0
  11. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/mcp/server.py +26 -2
  12. cfgit-0.3.0/tests/test_export_import.py +214 -0
  13. {cfgit-0.2.0 → cfgit-0.3.0}/.github/workflows/ci.yml +0 -0
  14. {cfgit-0.2.0 → cfgit-0.3.0}/.github/workflows/publish.yml +0 -0
  15. {cfgit-0.2.0 → cfgit-0.3.0}/.gitignore +0 -0
  16. {cfgit-0.2.0 → cfgit-0.3.0}/CONTRIBUTING.md +0 -0
  17. {cfgit-0.2.0 → cfgit-0.3.0}/CREDITS.md +0 -0
  18. {cfgit-0.2.0 → cfgit-0.3.0}/LICENSE +0 -0
  19. {cfgit-0.2.0 → cfgit-0.3.0}/NOTICE +0 -0
  20. {cfgit-0.2.0 → cfgit-0.3.0}/SECURITY.md +0 -0
  21. {cfgit-0.2.0 → cfgit-0.3.0}/docs/ADAPTERS.md +0 -0
  22. {cfgit-0.2.0 → cfgit-0.3.0}/docs/AGENTS.md +0 -0
  23. {cfgit-0.2.0 → cfgit-0.3.0}/docs/BRANCHING_PLAN.md +0 -0
  24. {cfgit-0.2.0 → cfgit-0.3.0}/docs/CONFIGURATION.md +0 -0
  25. {cfgit-0.2.0 → cfgit-0.3.0}/docs/IDENTITY_AND_ATTRIBUTION.md +0 -0
  26. {cfgit-0.2.0 → cfgit-0.3.0}/docs/PUBLISHING.md +0 -0
  27. {cfgit-0.2.0 → cfgit-0.3.0}/docs/README.md +0 -0
  28. {cfgit-0.2.0 → cfgit-0.3.0}/docs/SPEC.md +0 -0
  29. {cfgit-0.2.0 → cfgit-0.3.0}/docs/SPEC_CORE.md +0 -0
  30. {cfgit-0.2.0 → cfgit-0.3.0}/docs/screenshots/01-diff.png +0 -0
  31. {cfgit-0.2.0 → cfgit-0.3.0}/docs/screenshots/02-impact.png +0 -0
  32. {cfgit-0.2.0 → cfgit-0.3.0}/docs/screenshots/03-scoped-impact.png +0 -0
  33. {cfgit-0.2.0 → cfgit-0.3.0}/examples/.cfg.toml +0 -0
  34. {cfgit-0.2.0 → cfgit-0.3.0}/examples/cfgit-support-demo.toml +0 -0
  35. {cfgit-0.2.0 → cfgit-0.3.0}/examples/seed_support_demo.py +0 -0
  36. {cfgit-0.2.0 → cfgit-0.3.0}/plugins/cfg_impact/README.md +0 -0
  37. {cfgit-0.2.0 → cfgit-0.3.0}/plugins/cfg_impact/cfg_impact/__init__.py +0 -0
  38. {cfgit-0.2.0 → cfgit-0.3.0}/plugins/cfg_impact/cfg_impact/overview.py +0 -0
  39. {cfgit-0.2.0 → cfgit-0.3.0}/plugins/cfg_impact/cfg_impact/providers/__init__.py +0 -0
  40. {cfgit-0.2.0 → cfgit-0.3.0}/plugins/cfg_impact/cfg_impact/providers/base.py +0 -0
  41. {cfgit-0.2.0 → cfgit-0.3.0}/plugins/cfg_impact/cfg_impact/providers/claude.py +0 -0
  42. {cfgit-0.2.0 → cfgit-0.3.0}/plugins/cfg_impact/cfg_impact/providers/factory.py +0 -0
  43. {cfgit-0.2.0 → cfgit-0.3.0}/plugins/cfg_impact/cfg_impact/providers/gemini.py +0 -0
  44. {cfgit-0.2.0 → cfgit-0.3.0}/plugins/cfg_impact/cfg_impact/providers/openai_provider.py +0 -0
  45. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/__init__.py +0 -0
  46. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/adapters/__init__.py +0 -0
  47. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/adapters/base.py +0 -0
  48. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/adapters/mongo.py +0 -0
  49. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/adapters/postgres.py +0 -0
  50. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/approval/__init__.py +0 -0
  51. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/approval/base.py +0 -0
  52. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/cli/__init__.py +0 -0
  53. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/core/__init__.py +0 -0
  54. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/core/authz.py +0 -0
  55. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/core/config.py +0 -0
  56. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/core/diff.py +0 -0
  57. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/core/hashing.py +0 -0
  58. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/core/identity.py +0 -0
  59. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/interfaces/__init__.py +0 -0
  60. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/mcp/__init__.py +0 -0
  61. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/ui/__init__.py +0 -0
  62. {cfgit-0.2.0 → cfgit-0.3.0}/src/cfg/ui/server.py +0 -0
  63. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_adapter_contract_live.py +0 -0
  64. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_authz.py +0 -0
  65. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_awareness.py +0 -0
  66. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_commit_dry_run.py +0 -0
  67. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_config.py +0 -0
  68. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_config_discovery.py +0 -0
  69. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_console_script.py +0 -0
  70. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_core_purity.py +0 -0
  71. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_engine_safety.py +0 -0
  72. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_hashing.py +0 -0
  73. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_identity.py +0 -0
  74. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_impact_boundary.py +0 -0
  75. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_mcp_identity.py +0 -0
  76. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_mongo_history.py +0 -0
  77. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_output_mode.py +0 -0
  78. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_postgres_history.py +0 -0
  79. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_remedy.py +0 -0
  80. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_set_fields.py +0 -0
  81. {cfgit-0.2.0 → cfgit-0.3.0}/tests/test_ui_server.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cfgit
3
- Version: 0.2.0
3
+ Version: 0.3.0
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
@@ -479,11 +479,34 @@ Commit multiple records as one batch intent:
479
479
 
480
480
  ```bash
481
481
  cfg commit --bulk-from batch.json -m "switch planner routing"
482
+ cfg commit --bulk-from batch.json --dry-run # preview every record's delta, write nothing
482
483
  ```
483
484
 
484
485
  Bulk commit preflights the whole batch before writing. If any target has
485
486
  un-adopted drift, is missing, duplicates another target, or trips the secret
486
- policy, cfgit applies none of the batch.
487
+ policy, cfgit applies none of the batch. `--dry-run` previews the per-record delta
488
+ (`would_commit` / `noop` / `changed_outside_cfgit`) for the whole batch without writing —
489
+ run it before any collection-scale replace.
490
+
491
+ ### Snapshot and restore a whole collection
492
+
493
+ For "back it up, replace many rows, roll the whole thing back," `cfg export` writes a portable,
494
+ re-importable snapshot of the current live documents (each stamped with its cfgit head seq/oid),
495
+ and `cfg import --from` writes those documents back through the drift-guarded bulk-commit path —
496
+ so the restore is recorded in history like any other change:
497
+
498
+ ```bash
499
+ cfg export --out backup.json # snapshot every collection to a file
500
+ cfg export modelgarden_models:openai/gpt-4o-mini # or one record, to stdout
501
+ # ... do a risky bulk change ...
502
+ cfg import --from backup.json --dry-run # preview the restore
503
+ cfg import --from backup.json -m "restore from backup"
504
+ ```
505
+
506
+ This is the file-based backup artifact (portable, out-of-tool, diffable). For an in-tool
507
+ rollback with no file, use `cfg tag` + `cfg restore --tag` / `cfg restore --as-of <date>`, which
508
+ version the whole system inside cfgit. Both record the restore in history; export/import also
509
+ gives you a standalone file to keep or share.
487
510
 
488
511
  Draft changes on a branch before mutating runtime:
489
512
 
@@ -557,12 +580,15 @@ cfg init
557
580
  cfg doctor [record]
558
581
  cfg doctor --status
559
582
  cfg import --all -m "initial import"
583
+ cfg export [record] [--out file.json]
584
+ cfg import --from <export.json> [--dry-run] -m "message"
560
585
  cfg status [record]
561
586
  cfg diff <record> [from] [to]
562
587
  cfg impact <record> [from] [to]
563
588
  cfg commit <record> --from <file.json> -m "message"
564
589
  cfg commit <record> --from <file.json> --dry-run
565
590
  cfg commit --bulk-from <batch.json> -m "message"
591
+ cfg commit --bulk-from <batch.json> --dry-run
566
592
  cfg set <record> field=value nested.field=value -m "message"
567
593
  cfg edit <record> -m "message"
568
594
  cfg branch list
@@ -697,6 +723,7 @@ Tools include:
697
723
  - `cfg_commit`
698
724
  - `cfg_bulk_commit`
699
725
  - `cfg_set`
726
+ - `cfg_export`
700
727
  - `cfg_branch_list`
701
728
  - `cfg_branch_create`
702
729
  - `cfg_branch_delete`
@@ -246,11 +246,34 @@ Commit multiple records as one batch intent:
246
246
 
247
247
  ```bash
248
248
  cfg commit --bulk-from batch.json -m "switch planner routing"
249
+ cfg commit --bulk-from batch.json --dry-run # preview every record's delta, write nothing
249
250
  ```
250
251
 
251
252
  Bulk commit preflights the whole batch before writing. If any target has
252
253
  un-adopted drift, is missing, duplicates another target, or trips the secret
253
- policy, cfgit applies none of the batch.
254
+ policy, cfgit applies none of the batch. `--dry-run` previews the per-record delta
255
+ (`would_commit` / `noop` / `changed_outside_cfgit`) for the whole batch without writing —
256
+ run it before any collection-scale replace.
257
+
258
+ ### Snapshot and restore a whole collection
259
+
260
+ For "back it up, replace many rows, roll the whole thing back," `cfg export` writes a portable,
261
+ re-importable snapshot of the current live documents (each stamped with its cfgit head seq/oid),
262
+ and `cfg import --from` writes those documents back through the drift-guarded bulk-commit path —
263
+ so the restore is recorded in history like any other change:
264
+
265
+ ```bash
266
+ cfg export --out backup.json # snapshot every collection to a file
267
+ cfg export modelgarden_models:openai/gpt-4o-mini # or one record, to stdout
268
+ # ... do a risky bulk change ...
269
+ cfg import --from backup.json --dry-run # preview the restore
270
+ cfg import --from backup.json -m "restore from backup"
271
+ ```
272
+
273
+ This is the file-based backup artifact (portable, out-of-tool, diffable). For an in-tool
274
+ rollback with no file, use `cfg tag` + `cfg restore --tag` / `cfg restore --as-of <date>`, which
275
+ version the whole system inside cfgit. Both record the restore in history; export/import also
276
+ gives you a standalone file to keep or share.
254
277
 
255
278
  Draft changes on a branch before mutating runtime:
256
279
 
@@ -324,12 +347,15 @@ cfg init
324
347
  cfg doctor [record]
325
348
  cfg doctor --status
326
349
  cfg import --all -m "initial import"
350
+ cfg export [record] [--out file.json]
351
+ cfg import --from <export.json> [--dry-run] -m "message"
327
352
  cfg status [record]
328
353
  cfg diff <record> [from] [to]
329
354
  cfg impact <record> [from] [to]
330
355
  cfg commit <record> --from <file.json> -m "message"
331
356
  cfg commit <record> --from <file.json> --dry-run
332
357
  cfg commit --bulk-from <batch.json> -m "message"
358
+ cfg commit --bulk-from <batch.json> --dry-run
333
359
  cfg set <record> field=value nested.field=value -m "message"
334
360
  cfg edit <record> -m "message"
335
361
  cfg branch list
@@ -464,6 +490,7 @@ Tools include:
464
490
  - `cfg_commit`
465
491
  - `cfg_bulk_commit`
466
492
  - `cfg_set`
493
+ - `cfg_export`
467
494
  - `cfg_branch_list`
468
495
  - `cfg_branch_create`
469
496
  - `cfg_branch_delete`
@@ -109,7 +109,39 @@ cfg commit --bulk-from batch.json -m "switch planner routing"
109
109
 
110
110
  Bulk commit preflights every target before writing. If any record has un-adopted
111
111
  drift, is missing, duplicates another target, or trips the secret policy, no
112
- record in the batch is applied.
112
+ record in the batch is applied. Add `--dry-run` to preview the per-record delta for the whole
113
+ batch (`would_commit` / `noop` / `changed_outside_cfgit`) without writing — run it before any
114
+ collection-scale replace:
115
+
116
+ ```bash
117
+ cfg commit --bulk-from batch.json --dry-run
118
+ ```
119
+
120
+ ## Snapshot and restore a collection
121
+
122
+ `cfg export` writes a portable, re-importable snapshot of the current live documents, each
123
+ stamped with its cfgit head seq/oid. `cfg import --from` writes those documents back through the
124
+ drift-guarded bulk-commit path, so the restore is recorded in history like any other change.
125
+ Together they make "back it up, do the bulk change, roll it back" a fully in-cfgit workflow:
126
+
127
+ ```bash
128
+ cfg export --out backup.json # snapshot every collection to a file
129
+ cfg export modelgarden_models:openai/gpt-4o-mini # or one record, to stdout
130
+ # ... risky bulk change ...
131
+ cfg import --from backup.json --dry-run # preview the restore
132
+ cfg import --from backup.json -m "restore from backup"
133
+ ```
134
+
135
+ For an in-tool rollback without a file, use `cfg tag` + `cfg restore --tag` (or
136
+ `cfg restore --as-of <date>`) instead — see [Tags](#tags) and [Restore](#restore). Both record
137
+ the restore in history; export/import additionally gives you a standalone file to keep or share.
138
+
139
+ `cfg export` warns (without stopping) when a snapshot is large by control-plane standards — a
140
+ strong hint that the config points at a data-plane collection (events, user content, jobs),
141
+ which cfgit is not designed to version. If you cancel an `import --from` partway, cfgit reports
142
+ `partial` with `cancelled: true` listing what committed and what is still pending; each record
143
+ is applied atomically, so rerunning the same command resumes (already-applied records are
144
+ no-ops).
113
145
 
114
146
  If the live record changed after cfgit last recorded it, commit returns
115
147
  `changed_outside_cfgit` and does not apply your document. Inspect the drift first:
@@ -1,13 +1,13 @@
1
1
  [project]
2
2
  name = "cfgit-impact"
3
- version = "0.2.0"
3
+ version = "0.3.0"
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.2.0,<0.3.0",
10
+ "cfgit>=0.3.0,<0.4.0",
11
11
  "httpx>=0.27",
12
12
  ]
13
13
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cfgit"
3
- version = "0.2.0"
3
+ version = "0.3.0"
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"
@@ -52,7 +52,8 @@ Use cfgit as the safety layer around a live datastore. The app still reads and w
52
52
  (returns `would_commit` with the delta, or `changed_outside_cfgit`/`noop`; writes nothing).
53
53
  - Every outcome now carries a top-level `next` block (why + remedy + copy-paste `commands`);
54
54
  on a refusal, follow `next.commands` rather than guessing.
55
- - For a coupled multi-record change, write a batch JSON file and run `cfg commit --bulk-from <file> -m "<message>" --json`. The batch file can be `[{"record":"collection:id","doc":{...}}]` or `{"collection:id": {...}}`.
55
+ - For a coupled multi-record change, write a batch JSON file and run `cfg commit --bulk-from <file> -m "<message>" --json`. The batch file can be `[{"record":"collection:id","doc":{...}}]` or `{"collection:id": {...}}`. Preview a collection-scale batch first with `cfg commit --bulk-from <file> --dry-run --json` — it reports each record's `would_commit`/`noop`/`changed_outside_cfgit` and writes nothing.
56
+ - Before a risky bulk change, snapshot the current live docs with `cfg export --out backup.json --json` (a portable, re-importable artifact stamped with head seq/oid). To roll back, `cfg import --from backup.json -m "<message>" --json` writes them back through the drift-guarded path (preview with `--dry-run`). For an in-tool rollback with no file, use `cfg tag` + `cfg restore --tag` instead.
56
57
  - For a draft branch, use `cfg --branch <branch> commit <record> --from <file> -m "<message>" --json` or `cfg --branch <branch> commit --bulk-from <file> -m "<message>" --json`. This writes cfgit refs only; runtime is unchanged.
57
58
  - If commit returns `changed_outside_cfgit`, stop and inspect drift.
58
59
  - If bulk commit returns `blocked`, no record was applied; inspect `failed`. If it returns `partial`, some records were applied before a race/failure; inspect `results`, `failed`, and `pending` before continuing.
@@ -61,6 +62,7 @@ Use cfgit as the safety layer around a live datastore. The app still reads and w
61
62
  4. Reconcile drift.
62
63
  - `cfg diff <record> =HEAD =live --json`
63
64
  - `cfg adopt <record> -m "<message>" --json`
65
+ - If `cfg doctor --status` reports a high drift ratio (many records `changed_outside_cfgit`), baseline the whole collection once with `cfg adopt --all -m "<message>" --json` so later edits and restore work without a per-record adopt.
64
66
 
65
67
  5. Restore.
66
68
  - Single record: `cfg restore <record> <ref> -m "<message>" --json`
@@ -85,6 +87,7 @@ If the cfgit MCP server is available, prefer its tools over shelling out:
85
87
  - `cfg_impact`
86
88
  - `cfg_commit`
87
89
  - `cfg_bulk_commit`
90
+ - `cfg_export`
88
91
  - `cfg_branch_list`
89
92
  - `cfg_branch_create`
90
93
  - `cfg_branch_delete`
@@ -145,8 +145,15 @@ def _parser() -> argparse.ArgumentParser:
145
145
  p_import = sub.add_parser("import")
146
146
  p_import.add_argument("record", nargs="?")
147
147
  p_import.add_argument("--all", action="store_true")
148
+ p_import.add_argument("--from", dest="from_file",
149
+ help="restore documents from a `cfg export` file (writes via the drift-guarded bulk-commit path)")
148
150
  p_import.add_argument("-m", "--message", default="initial import")
149
151
  p_import.add_argument("--allow-secret", action="store_true")
152
+ p_import.add_argument("--dry-run", action="store_true", help="with --from: preview the bulk write without applying")
153
+
154
+ p_export = sub.add_parser("export", help="dump live documents to a portable, re-importable JSON snapshot")
155
+ p_export.add_argument("record", nargs="?", help="one collection:id; omit to export every configured collection")
156
+ p_export.add_argument("--out", help="write the snapshot to this file instead of stdout")
150
157
 
151
158
  p_doctor = sub.add_parser("doctor")
152
159
  p_doctor.add_argument("record", nargs="?")
@@ -191,7 +198,7 @@ def _parser() -> argparse.ArgumentParser:
191
198
  p_commit.add_argument(
192
199
  "--dry-run",
193
200
  action="store_true",
194
- help="preview the field-level delta vs live and exit without writing (main-branch, single record)",
201
+ help="preview the delta and exit without writing; works with --from (single) and --bulk-from (per-record)",
195
202
  )
196
203
 
197
204
  p_set = sub.add_parser("set", help="edit scalar fields in place; routes through commit (drift-guarded)")
@@ -321,8 +328,18 @@ def _dispatch(engine: Engine, args: argparse.Namespace) -> tuple[Any, int]:
321
328
  raise ValueError(f"unknown PR command: {args.pr_cmd}")
322
329
 
323
330
  if args.cmd == "import":
331
+ if getattr(args, "from_file", None):
332
+ from cfg.interfaces.actions import import_from_file
333
+
334
+ return import_from_file(
335
+ engine,
336
+ _load_json_any(args.from_file),
337
+ message=args.message if args.message != "initial import" else "import from export file",
338
+ allow_secret=args.allow_secret,
339
+ dry_run=args.dry_run,
340
+ )
324
341
  if not args.all and not args.record:
325
- raise ValueError("import needs --all or a record")
342
+ raise ValueError("import needs --all, a record, or --from <export.json>")
326
343
  result = engine.import_records(
327
344
  _parse_record(args.record) if args.record else None,
328
345
  message=args.message,
@@ -330,6 +347,18 @@ def _dispatch(engine: Engine, args: argparse.Namespace) -> tuple[Any, int]:
330
347
  )
331
348
  return result, EXIT_OK
332
349
 
350
+ if args.cmd == "export":
351
+ from cfg.interfaces.actions import export_records as _export_action
352
+
353
+ report, _ = _export_action(engine, args.record if args.record else None)
354
+ warning = report.pop("warning", None)
355
+ if warning:
356
+ print(f"⚠ {warning}", file=sys.stderr)
357
+ if getattr(args, "out", None):
358
+ Path(args.out).write_text(json.dumps(_to_json(report), indent=2), encoding="utf-8")
359
+ return {"state": "exported", "out": args.out, "count": report["count"]}, EXIT_OK
360
+ return report, EXIT_OK
361
+
333
362
  if args.cmd == "status":
334
363
  rows = engine.status(_parse_record(args.record) if args.record else None)
335
364
  code = EXIT_DIRTY if any(r.state == "changed_outside_cfgit" for r in rows) else EXIT_OK
@@ -383,11 +412,15 @@ def _dispatch(engine: Engine, args: argparse.Namespace) -> tuple[Any, int]:
383
412
  if args.bulk_from_file:
384
413
  if args.record or args.from_file:
385
414
  raise ValueError("bulk commit uses --bulk-from without record or --from")
386
- if not args.message:
387
- raise ValueError("bulk commit needs -m/--message")
388
- from cfg.interfaces.actions import bulk_commit_exit_code, parse_bulk_commit_items
415
+ from cfg.interfaces.actions import bulk_commit_exit_code, bulk_commit_preview, parse_bulk_commit_items
389
416
 
390
417
  items = parse_bulk_commit_items(_load_json_any(args.bulk_from_file))
418
+ if args.dry_run:
419
+ if branch != engine.config.branches.default_branch:
420
+ raise ValueError("--dry-run is only supported on the main-branch commit path")
421
+ return bulk_commit_preview(engine, items), EXIT_OK
422
+ if not args.message:
423
+ raise ValueError("bulk commit needs -m/--message")
391
424
  if branch != engine.config.branches.default_branch:
392
425
  result = engine.branch_commit_many(
393
426
  branch,
@@ -674,6 +707,8 @@ def _format_status_report(r: dict[str, Any]) -> str:
674
707
  ]
675
708
  for warning in r.get("warnings") or []:
676
709
  lines.append(f"⚠ {warning}")
710
+ for nudge in r.get("nudges") or []:
711
+ lines.append(f"→ {nudge}")
677
712
  return "\n".join(lines)
678
713
 
679
714
 
@@ -493,6 +493,32 @@ class Engine:
493
493
  results.append({"collection": item.collection, "record_id": item.record_id, "state": "imported", "seq": result.seq, "oid": result.oid})
494
494
  return results
495
495
 
496
+ def export_records(self, ref: RecordRef | None = None) -> dict[str, Any]:
497
+ """Read-only snapshot of live documents into a portable, re-importable artifact.
498
+
499
+ With a ref, exports that one record; without, exports every configured collection's live
500
+ records. Each item carries its live doc plus the current cfgit head seq/oid (or null if
501
+ untracked), so the snapshot records exactly which version it represents. Writes nothing.
502
+ """
503
+ refs = [ref] if ref else self._all_refs(include_history=False)
504
+ items: list[dict[str, Any]] = []
505
+ for item in sorted(refs, key=lambda r: (r.collection, r.record_id)):
506
+ live = self.adapter.get_record(item.collection, item.record_id)
507
+ if live is None:
508
+ continue
509
+ head = self.adapter.get_head(item.collection, item.record_id)
510
+ items.append(
511
+ {
512
+ "record": f"{item.collection}:{item.record_id}",
513
+ "collection": item.collection,
514
+ "record_id": item.record_id,
515
+ "head_seq": head.get("seq") if head else None,
516
+ "head_oid": head.get("oid") if head else None,
517
+ "doc": live,
518
+ }
519
+ )
520
+ return {"version": 1, "kind": "cfgit-export", "count": len(items), "items": items}
521
+
496
522
  def doctor(self, ref: RecordRef | None = None, *, large_field_bytes: int = 20000) -> dict[str, Any]:
497
523
  """Read-only preflight. Walks live records and reports what would trip an
498
524
  import/commit BEFORE anything is written: secret-deny matches (grouped by
@@ -748,6 +774,18 @@ class Engine:
748
774
  expected_live_oid=plan["expected_live"],
749
775
  make_head=True,
750
776
  )
777
+ except KeyboardInterrupt:
778
+ # A cancel between per-record writes: each apply() is atomic, so already-committed
779
+ # records are durable. Return a clean partial report (what landed, what did not)
780
+ # instead of dying silently and leaving the operator guessing about DB state.
781
+ pending = [_plan_result(p) for p in plans[offset:]]
782
+ return {
783
+ "state": "partial",
784
+ "cancelled": True,
785
+ "results": results,
786
+ "failed": [],
787
+ "pending": pending,
788
+ }
751
789
  except Exception as exc:
752
790
  failed = [
753
791
  {
@@ -102,7 +102,7 @@ _STATE_REMEDIES: dict[str, Next] = {
102
102
  commands=("cfg commit {record} --from <file> -m '<why>'",),
103
103
  ),
104
104
  "dry_run": Next(
105
- why="Dry run: this is what a restore would change. Nothing was written.",
105
+ why="Dry run: this is what would change. Nothing was written.",
106
106
  remedy="Rerun without --dry-run to apply.",
107
107
  commands=(),
108
108
  ),
@@ -138,10 +138,23 @@ def status_report(engine: Engine) -> tuple[dict[str, Any], int]:
138
138
  "tracked": tracked,
139
139
  "drift": drift,
140
140
  "warnings": _env_warnings(engine),
141
+ "nudges": _drift_nudges(tracked, drift),
141
142
  }
142
143
  return report, EXIT_OK
143
144
 
144
145
 
146
+ def _drift_nudges(tracked: int, drift: int) -> list[str]:
147
+ """Turn a high drift ratio into an actionable suggestion. When a large share of tracked
148
+ records drifted, every edit needs a manual adopt first and restore has no clean baseline —
149
+ so nudge the operator to baseline the collection once with `cfg adopt --all`."""
150
+ if drift >= 5 and tracked and drift / tracked >= 0.25:
151
+ return [
152
+ f"{drift}/{tracked} tracked records drifted — run `cfg adopt --all` to baseline the "
153
+ "collection, then edits and restore work without a per-record adopt."
154
+ ]
155
+ return []
156
+
157
+
145
158
  def _env_warnings(engine: Engine) -> list[str]:
146
159
  env = engine.config.envs[engine.env]
147
160
  warnings: list[str] = []
@@ -183,6 +196,78 @@ def import_records(
183
196
  return result, EXIT_OK
184
197
 
185
198
 
199
+ EXPORT_WARN_RECORDS = 2000
200
+ EXPORT_WARN_BYTES = 50 * 1024 * 1024 # 50 MB serialized
201
+
202
+
203
+ def export_records(engine: Engine, record: str | None = None) -> tuple[dict[str, Any], int]:
204
+ report = engine.export_records(parse_record(record) if record else None)
205
+ warning = _export_size_warning(report)
206
+ if warning:
207
+ report["warning"] = warning
208
+ return report, EXIT_OK
209
+
210
+
211
+ def _export_size_warning(report: dict[str, Any]) -> str | None:
212
+ """Soft warning (never a hard cap) when a snapshot is large by control-plane standards —
213
+ it usually means the config points at a data-plane collection (events, user content, jobs),
214
+ which cfgit is not designed to version. Triggers on record count OR serialized size."""
215
+ count = report.get("count", 0)
216
+ try:
217
+ size = len(json.dumps(to_json(report)))
218
+ except (TypeError, ValueError):
219
+ size = 0
220
+ reasons = []
221
+ if count >= EXPORT_WARN_RECORDS:
222
+ reasons.append(f"{count} records")
223
+ if size >= EXPORT_WARN_BYTES:
224
+ reasons.append(f"~{size // (1024 * 1024)}MB")
225
+ if not reasons:
226
+ return None
227
+ return (
228
+ f"large export ({', '.join(reasons)}). cfgit is built for control-plane collections "
229
+ "(hundreds–low thousands of hand-curated records). If this is a data-plane collection "
230
+ "(events, user content, jobs), it is the wrong fit — use a backup or warehouse instead."
231
+ )
232
+
233
+
234
+ def import_from_file(
235
+ engine: Engine,
236
+ export_obj: Any,
237
+ *,
238
+ message: str,
239
+ allow_secret: bool = False,
240
+ dry_run: bool = False,
241
+ ) -> tuple[dict[str, Any], int]:
242
+ """Restore documents from a `cfg export` artifact by writing them back through the
243
+ drift-guarded bulk-commit path (preflights the whole batch; applies none on any drift)."""
244
+ items = _export_items_to_commit(export_obj)
245
+ if dry_run:
246
+ return bulk_commit_preview(engine, items), EXIT_OK
247
+ result = engine.commit_many(items, message=message, allow_secret=allow_secret)
248
+ return result, bulk_commit_exit_code(result)
249
+
250
+
251
+ def _export_items_to_commit(export_obj: Any) -> list[tuple[RecordRef, dict[str, Any]]]:
252
+ if isinstance(export_obj, dict) and export_obj.get("kind") == "cfgit-export":
253
+ rows = export_obj.get("items") or []
254
+ elif isinstance(export_obj, list):
255
+ rows = export_obj
256
+ else:
257
+ raise ValueError("import --from expects a cfg export artifact or a list of {record, doc}")
258
+ out: list[tuple[RecordRef, dict[str, Any]]] = []
259
+ for i, row in enumerate(rows, start=1):
260
+ if not isinstance(row, dict) or "doc" not in row:
261
+ raise ValueError(f"export item {i} needs a doc")
262
+ rec = row.get("record") or (
263
+ f"{row.get('collection')}:{row.get('record_id')}" if row.get("collection") else None
264
+ )
265
+ if not rec:
266
+ raise ValueError(f"export item {i} needs record or collection+record_id")
267
+ out.append((parse_record(rec), row["doc"]))
268
+ return out
269
+
270
+
186
271
  def diff(engine: Engine, record: str, a: str = "=HEAD", b: str = "=live") -> tuple[dict[str, Any], int]:
187
272
  changes = engine.diff(parse_record(record), a, b)
188
273
  return {"changes": changes, "text": format_diff(changes)}, EXIT_OK
@@ -287,8 +372,13 @@ def bulk_commit(
287
372
  message: str,
288
373
  allow_secret: bool = False,
289
374
  branch: str | None = None,
375
+ dry_run: bool = False,
290
376
  ) -> tuple[dict[str, Any], int]:
291
377
  parsed = _bulk_commit_items(items)
378
+ if dry_run:
379
+ if branch and branch != engine.config.branches.default_branch:
380
+ raise ValueError("--dry-run is only supported on the main-branch commit path")
381
+ return bulk_commit_preview(engine, parsed), EXIT_OK
292
382
  if branch and branch != engine.config.branches.default_branch:
293
383
  result = engine.branch_commit_many(branch, parsed, message=message, allow_secret=allow_secret)
294
384
  else:
@@ -296,6 +386,35 @@ def bulk_commit(
296
386
  return result, bulk_commit_exit_code(result)
297
387
 
298
388
 
389
+ def bulk_commit_preview(
390
+ engine: Engine, items: list[tuple[RecordRef, dict[str, Any]]]
391
+ ) -> dict[str, Any]:
392
+ """Dry-run a bulk commit: preview each record without writing. Aggregates per-record
393
+ would_commit / noop / changed_outside_cfgit so the operator sees the whole blast radius of a
394
+ collection-scale replace before applying it. Mirrors commit_many's per-record semantics."""
395
+ results: list[dict[str, Any]] = []
396
+ would_change = drift = noop = 0
397
+ for ref, doc in items:
398
+ try:
399
+ preview = engine.commit_preview(ref, doc)
400
+ except NoSuchConfig:
401
+ results.append({"record": f"{ref.collection}:{ref.record_id}", "state": "missing"})
402
+ continue
403
+ state = preview.get("state")
404
+ if state == "would_commit":
405
+ would_change += 1
406
+ elif state == "changed_outside_cfgit":
407
+ drift += 1
408
+ elif state == "noop":
409
+ noop += 1
410
+ results.append({"record": f"{ref.collection}:{ref.record_id}", **preview})
411
+ return {
412
+ "state": "dry_run",
413
+ "summary": {"total": len(items), "would_commit": would_change, "drift": drift, "noop": noop},
414
+ "results": results,
415
+ }
416
+
417
+
299
418
  def log(engine: Engine, record: str, *, limit: int | None = 20) -> tuple[list[dict[str, Any]], int]:
300
419
  return engine.log(parse_record(record), limit=limit), EXIT_OK
301
420
 
@@ -461,6 +580,14 @@ def run_named_action(name: str, engine: Engine, payload: dict[str, Any] | None =
461
580
  large_field_bytes=int(payload.get("large_field_bytes") or 20000),
462
581
  )
463
582
  if name == "import":
583
+ if payload.get("export") is not None or payload.get("from") is not None:
584
+ return import_from_file(
585
+ engine,
586
+ payload.get("export") if payload.get("export") is not None else payload.get("from"),
587
+ message=str(payload.get("message") or "import from export file"),
588
+ allow_secret=bool(payload.get("allow_secret")),
589
+ dry_run=bool(payload.get("dry_run")),
590
+ )
464
591
  return import_records(
465
592
  engine,
466
593
  _blank_to_none(payload.get("record")),
@@ -468,6 +595,8 @@ def run_named_action(name: str, engine: Engine, payload: dict[str, Any] | None =
468
595
  message=str(payload.get("message") or "initial import"),
469
596
  allow_secret=bool(payload.get("allow_secret")),
470
597
  )
598
+ if name == "export":
599
+ return export_records(engine, _blank_to_none(payload.get("record")))
471
600
  if name == "diff":
472
601
  return diff(
473
602
  engine,
@@ -483,6 +612,7 @@ def run_named_action(name: str, engine: Engine, payload: dict[str, Any] | None =
483
612
  message=str(payload.get("message") or "commit"),
484
613
  allow_secret=bool(payload.get("allow_secret")),
485
614
  branch=_blank_to_none(payload.get("branch")),
615
+ dry_run=bool(payload.get("dry_run")),
486
616
  )
487
617
  return commit(
488
618
  engine,
@@ -509,6 +639,7 @@ def run_named_action(name: str, engine: Engine, payload: dict[str, Any] | None =
509
639
  message=str(payload.get("message") or "bulk commit"),
510
640
  allow_secret=bool(payload.get("allow_secret")),
511
641
  branch=_blank_to_none(payload.get("branch")),
642
+ dry_run=bool(payload.get("dry_run")),
512
643
  )
513
644
  if name == "log":
514
645
  return log(engine, _required(payload, "record"), limit=int(payload.get("limit") or 20))
@@ -67,17 +67,24 @@ def cfg_doctor(
67
67
  def cfg_import(
68
68
  record: str | None = None,
69
69
  all_records: bool = False,
70
+ from_export: dict[str, Any] | list[dict[str, Any]] | None = None,
71
+ dry_run: bool = False,
70
72
  message: str = "initial import",
71
73
  allow_secret: bool = False,
72
74
  config_file: str | None = None,
73
75
  env: str = "dev",
74
76
  author: str | None = None,
75
77
  ) -> dict[str, Any]:
78
+ """Start tracking live records (record or all_records), or restore documents from a
79
+ `cfg_export` artifact via from_export (writes them back through the drift-guarded bulk-commit
80
+ path; set dry_run=true to preview)."""
76
81
  return _call(
77
82
  "import",
78
83
  {
79
84
  "record": record,
80
85
  "all_records": all_records,
86
+ "export": from_export,
87
+ "dry_run": dry_run,
81
88
  "message": message,
82
89
  "allow_secret": allow_secret,
83
90
  },
@@ -87,6 +94,19 @@ def cfg_import(
87
94
  )
88
95
 
89
96
 
97
+ @mcp.tool()
98
+ def cfg_export(
99
+ record: str | None = None,
100
+ config_file: str | None = None,
101
+ env: str = "dev",
102
+ author: str | None = None,
103
+ ) -> dict[str, Any]:
104
+ """Read-only snapshot of live documents into a portable, re-importable artifact. Pass a
105
+ record for one, or omit it to export every configured collection. Each item is stamped with
106
+ its cfgit head seq/oid. Feed the result back to cfg_import(from_export=...) to restore."""
107
+ return _call("export", {"record": record}, config_file=config_file, env=env, author=author)
108
+
109
+
90
110
  @mcp.tool()
91
111
  def cfg_diff(
92
112
  record: str,
@@ -168,9 +188,10 @@ def cfg_commit(
168
188
  @mcp.tool()
169
189
  def cfg_bulk_commit(
170
190
  items: list[dict[str, Any]] | dict[str, Any] | str,
171
- message: str,
191
+ message: str = "",
172
192
  allow_secret: bool = False,
173
193
  branch: str | None = None,
194
+ dry_run: bool = False,
174
195
  config_file: str | None = None,
175
196
  env: str = "dev",
176
197
  author: str | None = None,
@@ -180,10 +201,13 @@ def cfg_bulk_commit(
180
201
  `items` may be either:
181
202
  [{"record":"collection:id","doc":{...}}, ...]
182
203
  {"collection:id": {...}, ...}, or a JSON string in either shape.
204
+
205
+ Set dry_run=true to preview every record's delta (would_commit / noop / changed_outside_cfgit)
206
+ without writing — recommended before a collection-scale replace.
183
207
  """
184
208
  return _call(
185
209
  "bulk_commit",
186
- {"items": items, "message": message, "allow_secret": allow_secret, "branch": branch},
210
+ {"items": items, "message": message, "allow_secret": allow_secret, "branch": branch, "dry_run": dry_run},
187
211
  config_file=config_file,
188
212
  env=env,
189
213
  author=author,
@@ -0,0 +1,214 @@
1
+ # Copyright 2026 Mohammad Ausaf. Licensed under the Apache License, Version 2.0.
2
+ """cfg export snapshot + import --from round-trip + --bulk-from --dry-run + drift nudge."""
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+
7
+ from cfg.core.engine import RecordRef
8
+ from cfg.interfaces import actions
9
+
10
+ from test_engine_safety import _engine
11
+
12
+
13
+ # --- export ---------------------------------------------------------------------------------
14
+
15
+
16
+ def test_export_dumps_live_docs_stamped_with_head():
17
+ engine, adapter = _engine(records={
18
+ ("demo", "a"): {"id": "a", "value": 1},
19
+ ("demo", "b"): {"id": "b", "value": 2},
20
+ })
21
+ engine.commit(RecordRef("demo", "a"), {"id": "a", "value": 1}, message="seed a")
22
+
23
+ snap = engine.export_records()
24
+ assert snap["kind"] == "cfgit-export"
25
+ assert snap["count"] == 2
26
+ by_rec = {i["record"]: i for i in snap["items"]}
27
+ # tracked record carries its head seq/oid; untracked record has null head
28
+ assert by_rec["demo:a"]["head_seq"] is not None
29
+ assert by_rec["demo:a"]["doc"] == {"id": "a", "value": 1}
30
+ assert by_rec["demo:b"]["head_seq"] is None
31
+
32
+
33
+ def test_export_single_record():
34
+ engine, _ = _engine(records={("demo", "a"): {"id": "a", "value": 1}, ("demo", "b"): {"id": "b"}})
35
+ snap = engine.export_records(RecordRef("demo", "a"))
36
+ assert snap["count"] == 1
37
+ assert snap["items"][0]["record"] == "demo:a"
38
+
39
+
40
+ def test_export_writes_nothing():
41
+ engine, adapter = _engine(records={("demo", "a"): {"id": "a", "value": 1}})
42
+ before = len(adapter.history)
43
+ engine.export_records()
44
+ assert len(adapter.history) == before
45
+
46
+
47
+ # --- import --from (round-trip via drift-guarded commit) ------------------------------------
48
+
49
+
50
+ def test_export_then_import_round_trip_restores_docs():
51
+ engine, adapter = _engine(records={("demo", "a"): {"id": "a", "value": 1}})
52
+ engine.commit(RecordRef("demo", "a"), {"id": "a", "value": 1}, message="seed")
53
+ snap = engine.export_records() # capture value=1
54
+
55
+ # mutate live away from the snapshot, adopt so there's no drift blocking the restore
56
+ adapter.records[("demo", "a")] = {"id": "a", "value": 999}
57
+ engine.adopt(RecordRef("demo", "a"), message="adopt drift")
58
+
59
+ result, code = actions.import_from_file(engine, snap, message="restore from backup")
60
+ assert result["state"] == "committed"
61
+ # live is back to the snapshot value
62
+ assert adapter.records[("demo", "a")]["value"] == 1
63
+
64
+
65
+ def test_import_from_accepts_bare_list_shape():
66
+ engine, adapter = _engine(records={("demo", "a"): {"id": "a", "value": 1}})
67
+ engine.commit(RecordRef("demo", "a"), {"id": "a", "value": 1}, message="seed")
68
+ items = [{"record": "demo:a", "doc": {"id": "a", "value": 7}}]
69
+ result, _ = actions.import_from_file(engine, items, message="restore list")
70
+ assert result["state"] == "committed"
71
+ assert adapter.records[("demo", "a")]["value"] == 7
72
+
73
+
74
+ def test_import_from_dry_run_writes_nothing():
75
+ engine, adapter = _engine(records={("demo", "a"): {"id": "a", "value": 1}})
76
+ engine.commit(RecordRef("demo", "a"), {"id": "a", "value": 1}, message="seed")
77
+ snap = engine.export_records()
78
+ adapter.records[("demo", "a")] = {"id": "a", "value": 5}
79
+ engine.adopt(RecordRef("demo", "a"), message="adopt")
80
+ before = len(adapter.history)
81
+
82
+ result, _ = actions.import_from_file(engine, snap, message="preview", dry_run=True)
83
+ assert result["state"] == "dry_run"
84
+ assert len(adapter.history) == before
85
+
86
+
87
+ def test_import_from_rejects_garbage():
88
+ engine, _ = _engine(records={("demo", "a"): {"id": "a"}})
89
+ with pytest.raises(ValueError):
90
+ actions.import_from_file(engine, {"not": "an export"}, message="x")
91
+
92
+
93
+ # --- bulk commit --dry-run ------------------------------------------------------------------
94
+
95
+
96
+ def test_bulk_commit_preview_reports_per_record_and_writes_nothing():
97
+ engine, adapter = _engine(records={
98
+ ("demo", "a"): {"id": "a", "value": 1},
99
+ ("demo", "b"): {"id": "b", "value": 1},
100
+ })
101
+ engine.commit(RecordRef("demo", "a"), {"id": "a", "value": 1}, message="seed a")
102
+ engine.commit(RecordRef("demo", "b"), {"id": "b", "value": 1}, message="seed b")
103
+ before = len(adapter.history)
104
+
105
+ items = [
106
+ (RecordRef("demo", "a"), {"id": "a", "value": 2}), # would_commit
107
+ (RecordRef("demo", "b"), {"id": "b", "value": 1}), # noop
108
+ ]
109
+ preview = actions.bulk_commit_preview(engine, items)
110
+ assert preview["state"] == "dry_run"
111
+ assert preview["summary"] == {"total": 2, "would_commit": 1, "drift": 0, "noop": 1}
112
+ assert len(adapter.history) == before # nothing written
113
+
114
+
115
+ def test_bulk_commit_dry_run_via_action_writes_nothing():
116
+ engine, adapter = _engine(records={("demo", "a"): {"id": "a", "value": 1}})
117
+ engine.commit(RecordRef("demo", "a"), {"id": "a", "value": 1}, message="seed")
118
+ before = len(adapter.history)
119
+ result, code = actions.bulk_commit(
120
+ engine, [{"record": "demo:a", "doc": {"id": "a", "value": 9}}], message="x", dry_run=True
121
+ )
122
+ assert result["state"] == "dry_run"
123
+ assert len(adapter.history) == before
124
+
125
+
126
+ def test_bulk_commit_preview_flags_drift_without_writing():
127
+ engine, adapter = _engine(records={("demo", "a"): {"id": "a", "value": 1}})
128
+ engine.commit(RecordRef("demo", "a"), {"id": "a", "value": 1}, message="seed")
129
+ adapter.records[("demo", "a")] = {"id": "a", "value": 42} # out-of-band drift
130
+ before = len(adapter.history)
131
+ preview = actions.bulk_commit_preview(engine, [(RecordRef("demo", "a"), {"id": "a", "value": 2})])
132
+ assert preview["summary"]["drift"] == 1
133
+ assert len(adapter.history) == before
134
+
135
+
136
+ # --- doctor adopt-all nudge -----------------------------------------------------------------
137
+
138
+
139
+ def test_drift_nudge_fires_only_above_threshold():
140
+ # below ratio / below count → no nudge
141
+ assert actions._drift_nudges(tracked=100, drift=4) == []
142
+ assert actions._drift_nudges(tracked=100, drift=10) == [] # 10% < 25%
143
+ # high drift → nudge mentioning adopt --all
144
+ nudge = actions._drift_nudges(tracked=288, drift=201)
145
+ assert nudge and "adopt --all" in nudge[0]
146
+ assert "201/288" in nudge[0]
147
+
148
+
149
+ # --- export size warning --------------------------------------------------------------------
150
+
151
+
152
+ def test_export_size_warning_absent_for_small_collection():
153
+ engine, _ = _engine(records={("demo", "a"): {"id": "a", "value": 1}})
154
+ report, _ = actions.export_records(engine)
155
+ assert "warning" not in report
156
+
157
+
158
+ def test_export_size_warning_fires_on_high_record_count(monkeypatch):
159
+ monkeypatch.setattr(actions, "EXPORT_WARN_RECORDS", 3)
160
+ engine, _ = _engine(records={
161
+ ("demo", "a"): {"id": "a"}, ("demo", "b"): {"id": "b"},
162
+ ("demo", "c"): {"id": "c"}, ("demo", "d"): {"id": "d"},
163
+ })
164
+ report, _ = actions.export_records(engine)
165
+ assert "warning" in report
166
+ assert "control-plane" in report["warning"]
167
+ assert "4 records" in report["warning"]
168
+
169
+
170
+ def test_export_size_warning_fires_on_byte_size(monkeypatch):
171
+ monkeypatch.setattr(actions, "EXPORT_WARN_BYTES", 500)
172
+ big = {"id": "a", "blob": "x" * 2000}
173
+ engine, _ = _engine(records={("demo", "a"): big})
174
+ report, _ = actions.export_records(engine)
175
+ assert "warning" in report and "MB" in report["warning"]
176
+
177
+
178
+ # --- cancellation safety on the import/bulk write path --------------------------------------
179
+
180
+
181
+ def test_commit_many_cancel_returns_clean_partial(monkeypatch):
182
+ engine, adapter = _engine(records={
183
+ ("demo", "a"): {"id": "a", "value": 0},
184
+ ("demo", "b"): {"id": "b", "value": 0},
185
+ ("demo", "c"): {"id": "c", "value": 0},
186
+ })
187
+ for r in ("a", "b", "c"):
188
+ engine.commit(RecordRef("demo", r), {"id": r, "value": 0}, message="seed")
189
+
190
+ # simulate a Ctrl-C during the 2nd record's write; the 1st is already durable
191
+ real_apply = adapter.apply
192
+ calls = {"n": 0}
193
+
194
+ def flaky_apply(*a, **k):
195
+ calls["n"] += 1
196
+ if calls["n"] == 2:
197
+ raise KeyboardInterrupt
198
+ return real_apply(*a, **k)
199
+
200
+ monkeypatch.setattr(adapter, "apply", flaky_apply)
201
+
202
+ result = engine.commit_many(
203
+ [
204
+ (RecordRef("demo", "a"), {"id": "a", "value": 1}),
205
+ (RecordRef("demo", "b"), {"id": "b", "value": 1}),
206
+ (RecordRef("demo", "c"), {"id": "c", "value": 1}),
207
+ ],
208
+ message="bulk restore",
209
+ )
210
+ assert result["state"] == "partial"
211
+ assert result["cancelled"] is True
212
+ assert len(result["results"]) == 1 # 'a' committed before the cancel
213
+ assert result["results"][0]["record_id"] == "a"
214
+ assert len(result["pending"]) == 2 # 'b' and 'c' not applied — rerun resumes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes