Skip to content

Commit dca1b4a

Browse files
authored
feat(schema): vaultctl schema sync drift detection (#40 phase 2) (#51)
## Summary Phase 2 of #40: \`vaultctl schema sync\` detects drift between the vault content and the \`.vaultctl/vault.cue\` baseline. Builds directly on the inference foundation that landed in #41/v1.2.0 — same walker, just compared against an existing baseline instead of written fresh. ## New Command \`\`\`bash vaultctl schema sync # diff-only, exit 1 on drift — CI-friendly vaultctl schema sync --apply # rewrite the baseline to match the vault \`\`\` Exit codes: - \`0\` — no drift, baseline matches. - \`1\` — drift detected, or fresh schema written with \`--apply\`. - \`2\` — no baseline exists; suggests \`vaultctl schema infer\` to create one. Sample output on drift: \`\`\`diff --- /home/.../vault.cue (current) +++ /home/.../vault.cue (inferred) @@ -2,5 +2,6 @@ #VaultFile: { existing_key: string + new_key: int } Drift detected. Run \`vaultctl schema sync --apply\` to update /home/.../vault.cue. \`\`\` ## Implementation - \`compute_schema_drift()\` — pure-Python helper that re-infers the schema from the current vault, strips both sides' auto-generated header comments (so wording changes in the header don't trigger false positives), and returns \`(drifted, current_text, fresh_text)\`. - \`render_schema_diff()\` — thin wrapper over \`difflib.unified_diff\` with stable filename labels for readable output. - \`@schema_group.command(\"sync\")\` — orchestrates the three exit-code paths. \`vault.constraints.cue\` is **never** touched. CUE merges it back in at validation time, so hand-edited rules (regex constraints, value ranges) survive both \`infer\` and \`sync\`. ## Test Coverage 13 new tests: - 9 pure-Python unit tests (no cue binary required) covering missing baseline, key add/remove, type change, header-only differences ignored, \`_previous\` backup keys excluded from drift, diff rendering on add/identical. - 4 CLI integration tests covering: no-drift after \`schema infer\`, missing-baseline exit-2, drift detection from a stale baseline, \`--apply\` round-trip (drift → apply → no drift). Total tests: 360 → 373. Coverage stable at 88%. ## Followup Phase 3 of #40 — schema-aware \`set\` (interactive prompt to extend the baseline when \`set\` introduces a new structure). That's UX work on top of what's now in place; ships as a separate PR. Refs #40. Co-authored-by: Fred Thiele <8555720+f3rdy@users.noreply.github.com>
1 parent ea5d30b commit dca1b4a

6 files changed

Lines changed: 250 additions & 0 deletions

File tree

‎CLAUDE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ src/vaultctl/
135135
| `vaultctl check` | Check expiring/expired keys |
136136
| `vaultctl validate` | Validate config/metadata/content against CUE schemas |
137137
| `vaultctl schema infer` | Generate a CUE schema baseline from current vault content |
138+
| `vaultctl schema sync` | Detect drift between baseline and current vault |
138139

139140
## Technology Stack
140141

‎README.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ vaultctl check # which keys need attention?
7676
| `vaultctl detect-types` | Auto-detect entry types (`--apply`, `--ai`, `--show-redacted`) |
7777
| `vaultctl validate` | Validate config, metadata, and vault content against CUE schemas |
7878
| `vaultctl schema infer` | Generate a CUE schema baseline from current vault content |
79+
| `vaultctl schema sync` | Detect drift between baseline and current vault (`--apply` to update) |
7980
| `vaultctl self-update` | Update binary to latest release (standalone only) |
8081

8182
All mutating commands support `--force` to skip confirmation prompts.
@@ -150,6 +151,15 @@ vaultctl schema infer --force # overwrites an existing baseline
150151

151152
The generated baseline is a closed `#VaultFile` definition — adding a new key without re-running `infer` (or extending the schema by hand) makes `validate` fail. Hand-edited rules (regex constraints, value ranges, required descriptions) belong in a sibling `vault.constraints.cue` so subsequent `infer` runs don't trample them.
152153

154+
**Detect drift between vault and baseline:**
155+
156+
```bash
157+
vaultctl schema sync # diff-only, exit 1 on drift — CI-friendly
158+
vaultctl schema sync --apply # rewrite the baseline to match the vault
159+
```
160+
161+
`schema sync` re-derives the schema from the current vault content and compares it to `.vaultctl/vault.cue`. Without `--apply` it prints a unified diff and exits non-zero; with `--apply` it rewrites the baseline. `vault.constraints.cue` is never touched — CUE merges it back in at validation time.
162+
153163
**Without `cue` installed:** schema checks are skipped with a warning; the cross-consistency check still runs.
154164

155165
## Type Detection

‎src/vaultctl/cli.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,12 @@
2929
from .redact import redact_vault_data
3030
from .schema import (
3131
ValidationIssue,
32+
compute_schema_drift,
3233
cross_check_keys,
3334
cue_available,
3435
discover_user_schema,
3536
infer_vault_schema,
37+
render_schema_diff,
3638
validate_config_file,
3739
validate_keys_file,
3840
validate_vault_data,
@@ -1095,3 +1097,55 @@ def schema_infer(vctx: VaultContext, force: bool, output_path: str | None) -> No
10951097
f"Tip: add project-specific constraints to {target.parent / 'vault.constraints.cue'} "
10961098
"to keep them separate from the auto-generated baseline."
10971099
)
1100+
1101+
1102+
@schema_group.command("sync")
1103+
@click.option(
1104+
"--apply",
1105+
is_flag=True,
1106+
default=False,
1107+
help="Overwrite the baseline with the freshly inferred schema instead of just reporting drift.",
1108+
)
1109+
@pass_ctx
1110+
def schema_sync(vctx: VaultContext, apply: bool) -> None:
1111+
"""Detect drift between the vault content and the schema baseline.
1112+
1113+
Re-derives a schema from the current vault and compares it to
1114+
`.vaultctl/vault.cue`. Without `--apply`, prints a unified diff and exits
1115+
non-zero on drift — useful as a CI gate. With `--apply`, overwrites the
1116+
baseline with the fresh inference (existing hand-edited rules in
1117+
`vault.constraints.cue` are untouched, since CUE merges them at validation
1118+
time).
1119+
1120+
Exit codes:
1121+
0 — no drift, baseline matches vault.
1122+
1 — drift detected (or fresh schema written with --apply).
1123+
2 — no baseline exists yet; run `vaultctl schema infer` first.
1124+
"""
1125+
baseline = vctx.config.config_dir / ".vaultctl" / "vault.cue"
1126+
if not baseline.is_file():
1127+
click.echo(
1128+
f"Error: no baseline at {baseline}. Run `vaultctl schema infer` to create one.",
1129+
err=True,
1130+
)
1131+
sys.exit(2)
1132+
1133+
try:
1134+
vault_data = decrypt_vault(vctx.config.vault_file, vctx.password)
1135+
except VaultError as exc:
1136+
click.echo(f"Error: {exc}", err=True)
1137+
sys.exit(1)
1138+
1139+
drifted, current, fresh = compute_schema_drift(vault_data, baseline)
1140+
if not drifted:
1141+
click.echo(f"No drift. {baseline} matches the current vault.")
1142+
return
1143+
1144+
if apply:
1145+
baseline.write_text(fresh, encoding="utf-8")
1146+
click.echo(f"Updated {baseline} to match current vault.")
1147+
sys.exit(1)
1148+
1149+
click.echo(render_schema_diff(current, fresh, str(baseline)))
1150+
click.echo(f"\nDrift detected. Run `vaultctl schema sync --apply` to update {baseline}.", err=True)
1151+
sys.exit(1)

‎src/vaultctl/schema.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,44 @@ def infer_vault_schema(vault_data: dict[str, Any]) -> str:
225225
return f"{header}\n{package}\n{body}"
226226

227227

228+
def compute_schema_drift(vault_data: dict[str, Any], baseline_path: Path) -> tuple[bool, str, str]:
229+
"""Compare the inferred schema for `vault_data` against an existing baseline file.
230+
231+
Returns (drifted, current_baseline_text, fresh_schema_text).
232+
233+
The auto-generated header is stripped from both sides before comparison so
234+
timestamp / wording changes don't trigger false positives. The header is
235+
restored when the caller writes the fresh schema back.
236+
"""
237+
fresh = infer_vault_schema(vault_data)
238+
if not baseline_path.is_file():
239+
return True, "", fresh
240+
current = baseline_path.read_text(encoding="utf-8")
241+
242+
drifted = _strip_header(current).strip() != _strip_header(fresh).strip()
243+
return drifted, current, fresh
244+
245+
246+
def render_schema_diff(current: str, fresh: str, baseline_label: str) -> str:
247+
"""Render a unified diff between current baseline and a freshly inferred schema."""
248+
import difflib
249+
250+
diff_lines = difflib.unified_diff(
251+
current.splitlines(keepends=True),
252+
fresh.splitlines(keepends=True),
253+
fromfile=f"{baseline_label} (current)",
254+
tofile=f"{baseline_label} (inferred)",
255+
lineterm="",
256+
)
257+
return "".join(diff_lines)
258+
259+
260+
def _strip_header(text: str) -> str:
261+
"""Remove the auto-generated header comment block so it doesn't dominate diffs."""
262+
lines = text.splitlines()
263+
return "\n".join(line for line in lines if not line.startswith("//"))
264+
265+
228266
def cross_check_keys(vault_data: dict[str, Any], keys_meta: dict[str, Any]) -> list[ValidationIssue]:
229267
"""Check that every key in vault.yml has metadata in vault-keys.yml and vice versa.
230268

‎tests/test_cli.py‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -786,3 +786,72 @@ def test_schema_infer_overwrites_with_force(runner, cli_env, tmp_path):
786786
result = runner.invoke(main, ["schema", "infer", "--output", str(output), "--force"])
787787
assert result.exit_code == 0, result.output
788788
assert "AUTO-GENERATED" in output.read_text()
789+
790+
791+
# --- schema sync command ---
792+
793+
794+
def _write_baseline_for_cli_env(cli_env_path):
795+
"""Write a baseline matching the cli_env vault into .vaultctl/vault.cue."""
796+
from pathlib import Path as _Path
797+
798+
import yaml as _yaml
799+
800+
config_data = _yaml.safe_load(_Path(cli_env_path).read_text())
801+
# The cli_env config_file points at absolute paths for vault and keys.
802+
# config_dir for `.vaultctl/vault.cue` is the parent of the .vaultctl dir,
803+
# which is tmp_path.
804+
project_root = _Path(cli_env_path).parent.parent
805+
baseline_dir = project_root / ".vaultctl"
806+
baseline_dir.mkdir(parents=True, exist_ok=True)
807+
return baseline_dir / "vault.cue", project_root, config_data
808+
809+
810+
def test_schema_sync_no_drift_after_infer(runner, cli_env):
811+
"""Right after `schema infer`, sync should report no drift."""
812+
infer = runner.invoke(main, ["schema", "infer"])
813+
assert infer.exit_code == 0, infer.output
814+
result = runner.invoke(main, ["schema", "sync"])
815+
assert result.exit_code == 0, result.output
816+
assert "No drift" in result.output
817+
818+
819+
def test_schema_sync_missing_baseline_exits_2(runner, cli_env):
820+
"""Without a baseline, sync exits with code 2 and a clear hint."""
821+
result = runner.invoke(main, ["schema", "sync"])
822+
assert result.exit_code == 2
823+
assert "no baseline" in result.output.lower()
824+
assert "schema infer" in result.output
825+
826+
827+
def test_schema_sync_detects_drift_from_stale_baseline(runner, cli_env, tmp_path):
828+
"""A baseline missing a key should be detected as drift."""
829+
# Write an intentionally incomplete baseline
830+
project_root = tmp_path
831+
baseline_dir = project_root / ".vaultctl"
832+
baseline_dir.mkdir(exist_ok=True)
833+
baseline = baseline_dir / "vault.cue"
834+
baseline.write_text("package vaultctl\n\n#VaultFile: {\n\tonly_one_key: string\n}\n")
835+
836+
result = runner.invoke(main, ["schema", "sync"])
837+
assert result.exit_code == 1
838+
# The diff should mention the keys that are present in the vault fixture
839+
# but missing from the stale baseline.
840+
assert "test_key" in result.output or "db_creds" in result.output
841+
assert "Drift detected" in result.output
842+
843+
844+
def test_schema_sync_apply_updates_baseline(runner, cli_env, tmp_path):
845+
"""`--apply` rewrites the baseline to match the vault."""
846+
baseline = tmp_path / ".vaultctl" / "vault.cue"
847+
baseline.parent.mkdir(exist_ok=True)
848+
baseline.write_text("package vaultctl\n\n#VaultFile: {\n\tonly_one_key: string\n}\n")
849+
850+
result = runner.invoke(main, ["schema", "sync", "--apply"])
851+
assert result.exit_code == 1 # exit 1 even on apply, indicates drift was present
852+
assert "Updated" in result.output
853+
854+
# Re-running should now find no drift
855+
follow_up = runner.invoke(main, ["schema", "sync"])
856+
assert follow_up.exit_code == 0, follow_up.output
857+
assert "No drift" in follow_up.output

‎tests/test_schema.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,12 @@
88
import yaml
99
from vaultctl.schema import (
1010
bundled_schema,
11+
compute_schema_drift,
1112
cross_check_keys,
1213
cue_available,
1314
discover_user_schema,
1415
infer_vault_schema,
16+
render_schema_diff,
1517
validate_config_file,
1618
validate_keys_file,
1719
validate_vault_data,
@@ -303,3 +305,79 @@ def test_infer_merges_with_user_constraints_file(tmp_path):
303305
# in the same directory automatically when they share the package.
304306
issues = validate_vault_data(data, override=baseline)
305307
assert any("password" in i.message for i in issues), "expected merged constraint to reject the short password"
308+
309+
310+
# --- schema drift detection (pure Python, no cue required) ---
311+
312+
313+
def test_drift_detected_when_baseline_missing(tmp_path):
314+
drifted, current, fresh = compute_schema_drift({"a": "x"}, tmp_path / "missing.cue")
315+
assert drifted is True
316+
assert current == ""
317+
assert "a: string" in fresh
318+
319+
320+
def test_no_drift_when_baseline_matches(tmp_path):
321+
data = {"token": "secret", "creds": {"username": "u", "password": "p"}}
322+
baseline = tmp_path / "vault.cue"
323+
baseline.write_text(infer_vault_schema(data))
324+
drifted, _, _ = compute_schema_drift(data, baseline)
325+
assert drifted is False
326+
327+
328+
def test_drift_detected_when_key_added(tmp_path):
329+
baseline = tmp_path / "vault.cue"
330+
baseline.write_text(infer_vault_schema({"a": "x"}))
331+
drifted, _, fresh = compute_schema_drift({"a": "x", "new_key": 42}, baseline)
332+
assert drifted is True
333+
assert "new_key: int" in fresh
334+
335+
336+
def test_drift_detected_when_key_removed(tmp_path):
337+
baseline = tmp_path / "vault.cue"
338+
baseline.write_text(infer_vault_schema({"a": "x", "obsolete": "y"}))
339+
drifted, _, fresh = compute_schema_drift({"a": "x"}, baseline)
340+
assert drifted is True
341+
assert "obsolete" not in fresh
342+
343+
344+
def test_drift_detected_when_type_changes(tmp_path):
345+
baseline = tmp_path / "vault.cue"
346+
baseline.write_text(infer_vault_schema({"port": "5432"})) # was string
347+
drifted, _, fresh = compute_schema_drift({"port": 5432}, baseline) # now int
348+
assert drifted is True
349+
assert "port: int" in fresh
350+
351+
352+
def test_drift_ignores_header_changes(tmp_path):
353+
"""Comment-only differences in the header should not trigger drift."""
354+
baseline = tmp_path / "vault.cue"
355+
baseline.write_text(
356+
"// Some other auto-generation header text.\n"
357+
"// That differs from the current INFER_HEADER.\n"
358+
"\npackage vaultctl\n\n#VaultFile: {\n\ta: string\n}\n"
359+
)
360+
drifted, _, _ = compute_schema_drift({"a": "x"}, baseline)
361+
assert drifted is False
362+
363+
364+
def test_drift_ignores_previous_backup_keys(tmp_path):
365+
"""_previous keys aren't part of the schema, so they don't cause drift."""
366+
baseline = tmp_path / "vault.cue"
367+
baseline.write_text(infer_vault_schema({"live": "x"}))
368+
drifted, _, _ = compute_schema_drift({"live": "x", "live_previous": "old"}, baseline)
369+
assert drifted is False
370+
371+
372+
def test_render_schema_diff_produces_unified_diff():
373+
current = "package vaultctl\n\n#VaultFile: {\n\ta: string\n}\n"
374+
fresh = "package vaultctl\n\n#VaultFile: {\n\ta: string\n\tb: int\n}\n"
375+
diff = render_schema_diff(current, fresh, "vault.cue")
376+
assert "vault.cue (current)" in diff
377+
assert "vault.cue (inferred)" in diff
378+
assert "+\tb: int" in diff
379+
380+
381+
def test_render_schema_diff_empty_when_identical():
382+
text = "package vaultctl\n\n#VaultFile: {}\n"
383+
assert render_schema_diff(text, text, "vault.cue") == ""

0 commit comments

Comments
 (0)