dataforge-07 0.1.0__py3-none-any.whl

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 (150) hide show
  1. dataforge/__init__.py +204 -0
  2. dataforge/__main__.py +5 -0
  3. dataforge/agent/__init__.py +16 -0
  4. dataforge/agent/providers.py +259 -0
  5. dataforge/agent/scratchpad.py +183 -0
  6. dataforge/agent/tool_actions.py +343 -0
  7. dataforge/bench/__init__.py +31 -0
  8. dataforge/bench/core.py +426 -0
  9. dataforge/bench/groq_client.py +386 -0
  10. dataforge/bench/methods.py +443 -0
  11. dataforge/bench/report.py +309 -0
  12. dataforge/bench/runner.py +247 -0
  13. dataforge/causal/__init__.py +21 -0
  14. dataforge/causal/dag.py +174 -0
  15. dataforge/causal/pc.py +232 -0
  16. dataforge/causal/root_cause.py +193 -0
  17. dataforge/cli/__init__.py +50 -0
  18. dataforge/cli/audit.py +70 -0
  19. dataforge/cli/bench.py +154 -0
  20. dataforge/cli/common.py +267 -0
  21. dataforge/cli/constraints.py +407 -0
  22. dataforge/cli/profile.py +147 -0
  23. dataforge/cli/release.py +166 -0
  24. dataforge/cli/repair.py +407 -0
  25. dataforge/cli/revert.py +139 -0
  26. dataforge/cli/watch.py +144 -0
  27. dataforge/datasets/__init__.py +25 -0
  28. dataforge/datasets/embedded/hospital/clean.csv +11 -0
  29. dataforge/datasets/embedded/hospital/dirty.csv +11 -0
  30. dataforge/datasets/real_world.py +290 -0
  31. dataforge/datasets/registry.py +103 -0
  32. dataforge/detectors/__init__.py +80 -0
  33. dataforge/detectors/base.py +145 -0
  34. dataforge/detectors/decimal_shift.py +166 -0
  35. dataforge/detectors/fd_violation.py +157 -0
  36. dataforge/detectors/type_mismatch.py +173 -0
  37. dataforge/engine/__init__.py +39 -0
  38. dataforge/engine/repair.py +905 -0
  39. dataforge/env/__init__.py +22 -0
  40. dataforge/env/environment.py +883 -0
  41. dataforge/env/observation.py +61 -0
  42. dataforge/env/openenv_core.py +161 -0
  43. dataforge/env/reward.py +128 -0
  44. dataforge/env/server.py +176 -0
  45. dataforge/evaluation_contract.py +76 -0
  46. dataforge/fixtures/hospital_10rows.csv +11 -0
  47. dataforge/fixtures/hospital_schema.yaml +17 -0
  48. dataforge/http/__init__.py +1 -0
  49. dataforge/http/problem.py +103 -0
  50. dataforge/integrations/__init__.py +1 -0
  51. dataforge/integrations/dbt.py +164 -0
  52. dataforge/observability.py +76 -0
  53. dataforge/py.typed +1 -0
  54. dataforge/release/__init__.py +1 -0
  55. dataforge/release/doctor.py +367 -0
  56. dataforge/release/full_vision.py +702 -0
  57. dataforge/release/gate.py +861 -0
  58. dataforge/release/playground_check.py +411 -0
  59. dataforge/repair_contract.py +468 -0
  60. dataforge/repairers/__init__.py +88 -0
  61. dataforge/repairers/base.py +77 -0
  62. dataforge/repairers/decimal_shift.py +43 -0
  63. dataforge/repairers/fd_violation.py +225 -0
  64. dataforge/repairers/type_mismatch.py +73 -0
  65. dataforge/safety/__init__.py +5 -0
  66. dataforge/safety/adversarial/attack_01_phone_pii.yaml +8 -0
  67. dataforge/safety/adversarial/attack_02_phone_pii.yaml +8 -0
  68. dataforge/safety/adversarial/attack_03_phone_pii.yaml +8 -0
  69. dataforge/safety/adversarial/attack_04_phone_pii.yaml +8 -0
  70. dataforge/safety/adversarial/attack_05_phone_pii.yaml +8 -0
  71. dataforge/safety/adversarial/attack_06_phone_pii.yaml +8 -0
  72. dataforge/safety/adversarial/attack_07_phone_pii.yaml +8 -0
  73. dataforge/safety/adversarial/attack_08_phone_pii.yaml +8 -0
  74. dataforge/safety/adversarial/attack_09_phone_pii.yaml +8 -0
  75. dataforge/safety/adversarial/attack_10_phone_pii.yaml +8 -0
  76. dataforge/safety/adversarial/attack_11_ssn_pii.yaml +8 -0
  77. dataforge/safety/adversarial/attack_12_ssn_pii.yaml +8 -0
  78. dataforge/safety/adversarial/attack_13_ssn_pii.yaml +8 -0
  79. dataforge/safety/adversarial/attack_14_ssn_pii.yaml +8 -0
  80. dataforge/safety/adversarial/attack_15_ssn_pii.yaml +8 -0
  81. dataforge/safety/adversarial/attack_16_ssn_pii.yaml +8 -0
  82. dataforge/safety/adversarial/attack_17_ssn_pii.yaml +8 -0
  83. dataforge/safety/adversarial/attack_18_ssn_pii.yaml +8 -0
  84. dataforge/safety/adversarial/attack_19_ssn_pii.yaml +8 -0
  85. dataforge/safety/adversarial/attack_20_ssn_pii.yaml +8 -0
  86. dataforge/safety/adversarial/attack_21_email_pii.yaml +8 -0
  87. dataforge/safety/adversarial/attack_22_email_pii.yaml +8 -0
  88. dataforge/safety/adversarial/attack_23_email_pii.yaml +8 -0
  89. dataforge/safety/adversarial/attack_24_email_pii.yaml +8 -0
  90. dataforge/safety/adversarial/attack_25_email_pii.yaml +8 -0
  91. dataforge/safety/adversarial/attack_26_email_pii.yaml +8 -0
  92. dataforge/safety/adversarial/attack_27_email_pii.yaml +8 -0
  93. dataforge/safety/adversarial/attack_28_email_pii.yaml +8 -0
  94. dataforge/safety/adversarial/attack_29_email_pii.yaml +8 -0
  95. dataforge/safety/adversarial/attack_30_email_pii.yaml +8 -0
  96. dataforge/safety/adversarial/attack_31_row_delete.yaml +7 -0
  97. dataforge/safety/adversarial/attack_32_row_delete.yaml +8 -0
  98. dataforge/safety/adversarial/attack_33_row_delete.yaml +7 -0
  99. dataforge/safety/adversarial/attack_34_row_delete.yaml +7 -0
  100. dataforge/safety/adversarial/attack_35_row_delete.yaml +7 -0
  101. dataforge/safety/adversarial/attack_36_row_delete.yaml +11 -0
  102. dataforge/safety/adversarial/attack_37_row_delete.yaml +7 -0
  103. dataforge/safety/adversarial/attack_38_row_delete.yaml +7 -0
  104. dataforge/safety/adversarial/attack_39_row_delete.yaml +8 -0
  105. dataforge/safety/adversarial/attack_40_row_delete.yaml +7 -0
  106. dataforge/safety/adversarial/attack_41_row_delete.yaml +7 -0
  107. dataforge/safety/adversarial/attack_42_row_delete.yaml +7 -0
  108. dataforge/safety/adversarial/attack_43_row_delete.yaml +7 -0
  109. dataforge/safety/adversarial/attack_44_row_delete.yaml +7 -0
  110. dataforge/safety/adversarial/attack_45_row_delete.yaml +8 -0
  111. dataforge/safety/adversarial/attack_46_row_delete.yaml +8 -0
  112. dataforge/safety/adversarial/attack_47_row_delete.yaml +7 -0
  113. dataforge/safety/adversarial/attack_48_row_delete.yaml +7 -0
  114. dataforge/safety/adversarial/attack_49_row_delete.yaml +8 -0
  115. dataforge/safety/adversarial/attack_50_row_delete.yaml +7 -0
  116. dataforge/safety/constitution.py +307 -0
  117. dataforge/safety/constitutions/default.yaml +40 -0
  118. dataforge/safety/filter.py +134 -0
  119. dataforge/schema_inference.py +620 -0
  120. dataforge/stores/__init__.py +46 -0
  121. dataforge/stores/base.py +73 -0
  122. dataforge/stores/cloud.py +78 -0
  123. dataforge/stores/csv.py +94 -0
  124. dataforge/stores/duckdb.py +313 -0
  125. dataforge/stores/patch_plan.py +178 -0
  126. dataforge/stores/registry.py +82 -0
  127. dataforge/stores/repair.py +121 -0
  128. dataforge/stores/revert.py +22 -0
  129. dataforge/stores/sql.py +27 -0
  130. dataforge/table.py +228 -0
  131. dataforge/transactions/__init__.py +34 -0
  132. dataforge/transactions/files.py +96 -0
  133. dataforge/transactions/log.py +613 -0
  134. dataforge/transactions/revert.py +102 -0
  135. dataforge/transactions/txn.py +104 -0
  136. dataforge/ui/__init__.py +1 -0
  137. dataforge/ui/profile_view.py +136 -0
  138. dataforge/ui/repair_diff.py +91 -0
  139. dataforge/verifier/__init__.py +55 -0
  140. dataforge/verifier/constraint_ir.py +155 -0
  141. dataforge/verifier/explain.py +47 -0
  142. dataforge/verifier/gate.py +5 -0
  143. dataforge/verifier/schema.py +111 -0
  144. dataforge/verifier/smt.py +433 -0
  145. dataforge_07-0.1.0.dist-info/METADATA +436 -0
  146. dataforge_07-0.1.0.dist-info/RECORD +150 -0
  147. dataforge_07-0.1.0.dist-info/WHEEL +5 -0
  148. dataforge_07-0.1.0.dist-info/entry_points.txt +3 -0
  149. dataforge_07-0.1.0.dist-info/licenses/LICENSE +176 -0
  150. dataforge_07-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,166 @@
1
+ """CLI group for local release verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Annotated
8
+
9
+ import typer
10
+
11
+ from dataforge.release.doctor import DEFAULT_KAGGLE_CREDENTIALS, run_doctor
12
+ from dataforge.release.full_vision import (
13
+ DEFAULT_BACKEND_URL as FULL_VISION_BACKEND_URL,
14
+ )
15
+ from dataforge.release.full_vision import (
16
+ DEFAULT_FRONTEND_URL as FULL_VISION_FRONTEND_URL,
17
+ )
18
+ from dataforge.release.full_vision import (
19
+ run_full_vision_gate,
20
+ )
21
+ from dataforge.release.gate import run_release_gate
22
+
23
+ release_app = typer.Typer(help="Release verification utilities.", no_args_is_help=True)
24
+
25
+
26
+ @release_app.command(name="doctor")
27
+ def doctor(
28
+ json_output: Annotated[
29
+ bool,
30
+ typer.Option("--json", help="Print machine-readable JSON."),
31
+ ] = False,
32
+ core: Annotated[
33
+ bool,
34
+ typer.Option("--core", help="Run OSS core release checks."),
35
+ ] = False,
36
+ maintainer_deploy: Annotated[
37
+ bool,
38
+ typer.Option(
39
+ "--maintainer-deploy",
40
+ help="Run maintainer-specific deploy/auth checks.",
41
+ ),
42
+ ] = False,
43
+ kaggle_credentials: Annotated[
44
+ Path,
45
+ typer.Option(
46
+ "--kaggle-credentials",
47
+ help="Path to Kaggle OAuth credentials.json. Legacy kaggle.json is never read.",
48
+ ),
49
+ ] = DEFAULT_KAGGLE_CREDENTIALS,
50
+ ) -> None:
51
+ """Verify local release/deploy auth without printing secrets."""
52
+ run_core = core or not maintainer_deploy
53
+ report = run_doctor(
54
+ kaggle_credentials=kaggle_credentials,
55
+ core=run_core,
56
+ maintainer_deploy=maintainer_deploy,
57
+ )
58
+ if json_output:
59
+ typer.echo(json.dumps(report.to_dict(), indent=2, sort_keys=True))
60
+ else:
61
+ for check in report.checks:
62
+ status = "ok" if check.ok else "fail"
63
+ typer.echo(f"{status:4} {check.name}: {check.detail}")
64
+ raise typer.Exit(code=0 if report.ok else 2)
65
+
66
+
67
+ @release_app.command(name="gate")
68
+ def gate(
69
+ json_output: Annotated[
70
+ bool,
71
+ typer.Option("--json", help="Print machine-readable JSON."),
72
+ ] = False,
73
+ keep_artifacts: Annotated[
74
+ bool,
75
+ typer.Option(
76
+ "--keep-artifacts",
77
+ help="Copy the temporary gate workspace to dist/release-gate-latest.",
78
+ ),
79
+ ] = False,
80
+ ) -> None:
81
+ """Build, audit, offline-install, and smoke-test the release wheel."""
82
+ report = run_release_gate(keep_artifacts=keep_artifacts)
83
+ if json_output:
84
+ typer.echo(json.dumps(report.to_dict(), indent=2, sort_keys=True))
85
+ else:
86
+ for step in report.steps:
87
+ status = "ok" if step.ok else "fail"
88
+ typer.echo(f"{status:4} {step.name}: {step.detail}")
89
+ raise typer.Exit(code=0 if report.ok else 1)
90
+
91
+
92
+ @release_app.command(name="full-vision")
93
+ def full_vision(
94
+ json_output: Annotated[
95
+ bool,
96
+ typer.Option("--json", help="Print machine-readable JSON."),
97
+ ] = False,
98
+ evidence_root: Annotated[
99
+ Path | None,
100
+ typer.Option("--evidence-root", help="Directory containing external proof manifests."),
101
+ ] = None,
102
+ frontend_url: Annotated[
103
+ str,
104
+ typer.Option("--frontend-url", help="Cloudflare Workers Playground URL."),
105
+ ] = FULL_VISION_FRONTEND_URL,
106
+ backend_url: Annotated[
107
+ str,
108
+ typer.Option("--backend-url", help="Hugging Face Playground backend URL."),
109
+ ] = FULL_VISION_BACKEND_URL,
110
+ expected_git_sha: Annotated[
111
+ str | None,
112
+ typer.Option("--expected-git-sha", help="Release git SHA expected in backend health."),
113
+ ] = None,
114
+ ) -> None:
115
+ """Verify the external gates for the full original DataForge vision."""
116
+ report = run_full_vision_gate(
117
+ evidence_root=evidence_root,
118
+ frontend_url=frontend_url,
119
+ backend_url=backend_url,
120
+ expected_git_sha=expected_git_sha,
121
+ )
122
+ if json_output:
123
+ typer.echo(json.dumps(report.to_dict(), indent=2, sort_keys=True))
124
+ else:
125
+ for check in report.checks:
126
+ status = "ok" if check.ok else "fail"
127
+ typer.echo(f"{status:4} {check.name}: {check.detail}")
128
+ raise typer.Exit(code=0 if report.ok else 1)
129
+
130
+
131
+ @release_app.command(name="playground-check")
132
+ def playground_check(
133
+ json_output: Annotated[
134
+ bool,
135
+ typer.Option("--json", help="Print machine-readable JSON."),
136
+ ] = False,
137
+ frontend_url: Annotated[
138
+ str,
139
+ typer.Option("--frontend-url", help="Cloudflare Playground frontend URL."),
140
+ ] = "https://dataforge.praneshrajan15.workers.dev/playground",
141
+ backend_url: Annotated[
142
+ str,
143
+ typer.Option("--backend-url", help="Hugging Face Playground backend URL."),
144
+ ] = "https://Praneshrajan15-dataforge-playground.hf.space",
145
+ latency_threshold_ms: Annotated[
146
+ float,
147
+ typer.Option("--latency-threshold-ms", help="Warm health latency threshold."),
148
+ ] = 5_000.0,
149
+ ) -> None:
150
+ """Verify the deployed Playground release checklist."""
151
+ from dataforge.release.playground_check import report_to_json, run_playground_check
152
+
153
+ report = run_playground_check(
154
+ frontend_url=frontend_url,
155
+ backend_url=backend_url,
156
+ latency_threshold_ms=latency_threshold_ms,
157
+ include_doctor=True,
158
+ include_smoke=True,
159
+ )
160
+ if json_output:
161
+ typer.echo(report_to_json(report))
162
+ else:
163
+ for check in report.checks:
164
+ status = "ok" if check.ok else "fail"
165
+ typer.echo(f"{status:4} {check.name}: {check.detail}")
166
+ raise typer.Exit(code=0 if report.ok else 1)
@@ -0,0 +1,407 @@
1
+ """CLI subcommand: ``dataforge repair <path> [--dry-run | --apply]``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Annotated
8
+
9
+ import typer
10
+ from rich.console import Console
11
+ from rich.panel import Panel
12
+
13
+ from dataforge.cli.common import load_schema, resolve_cli_path
14
+ from dataforge.detectors.base import Issue, Schema
15
+ from dataforge.repairers.base import ProposedFix, RepairAttempt
16
+ from dataforge.safety import SafetyContext, SafetyFilter, SafetyResult
17
+ from dataforge.schema_inference import ConstraintReviewArtifact, load_constraint_review_artifact
18
+ from dataforge.stores import (
19
+ TableStoreError,
20
+ is_table_store_uri,
21
+ run_table_store_repair,
22
+ store_from_uri,
23
+ )
24
+ from dataforge.transactions.txn import CellFix
25
+ from dataforge.ui.repair_diff import render_repair_diff
26
+
27
+ if TYPE_CHECKING:
28
+ import pandas as pd
29
+
30
+ from dataforge.engine.repair import RepairPipelineResult
31
+
32
+ _console = Console(stderr=True)
33
+
34
+
35
+ def apply_fixes_to_csv(path: Path, fixes: list[CellFix]) -> str:
36
+ """Apply ordered cell fixes to a CSV and return the post-state SHA-256.
37
+
38
+ Args:
39
+ path: Source CSV path.
40
+ fixes: Ordered list of cell fixes to apply.
41
+
42
+ Returns:
43
+ SHA-256 of the written file bytes.
44
+
45
+ Raises:
46
+ ValueError: If a fix references a missing row/column or stale old value.
47
+ """
48
+ from dataforge.engine.repair import apply_fixes_to_csv as engine_apply_fixes_to_csv
49
+
50
+ return engine_apply_fixes_to_csv(path, fixes)
51
+
52
+
53
+ def _resolve_schema(schema_path: Path | None) -> Schema | None:
54
+ """Resolve an optional schema path into a parsed Schema."""
55
+ if schema_path is None:
56
+ return None
57
+ resolved_schema = resolve_cli_path(schema_path)
58
+ if not resolved_schema.exists():
59
+ raise typer.BadParameter(f"Schema file '{schema_path}' does not exist.")
60
+ return load_schema(resolved_schema)
61
+
62
+
63
+ def _resolve_constraints(
64
+ constraints_path: Path | None,
65
+ ) -> tuple[ConstraintReviewArtifact | None, str | None]:
66
+ """Resolve an optional reviewed constraints artifact."""
67
+ if constraints_path is None:
68
+ return None, None
69
+ resolved_constraints = resolve_cli_path(constraints_path)
70
+ if not resolved_constraints.exists():
71
+ raise typer.BadParameter(f"Constraints file '{constraints_path}' does not exist.")
72
+ return load_constraint_review_artifact(resolved_constraints)
73
+
74
+
75
+ def _print_error(message: str, *, hint: str | None = None) -> None:
76
+ """Render a rich-formatted CLI error."""
77
+ body = f"[bold red]{message}[/bold red]"
78
+ if hint:
79
+ body = f"{body}\n\n[dim]{hint}[/dim]"
80
+ _console.print(Panel(body, title="Repair Error", style="red"))
81
+
82
+
83
+ def _propose_repairs(
84
+ issues: list[Issue],
85
+ path: Path,
86
+ working_df: pd.DataFrame,
87
+ schema: Schema | None,
88
+ *,
89
+ allow_llm: bool,
90
+ model: str,
91
+ allow_pii: bool,
92
+ confirm_pii: bool,
93
+ confirm_escalations: bool,
94
+ interactive: bool,
95
+ ) -> tuple[list[ProposedFix], list[list[RepairAttempt]]]:
96
+ """Compatibility wrapper around the shared repair engine proposal stage."""
97
+ from dataforge.engine.repair import propose_repairs as engine_propose_repairs
98
+
99
+ return engine_propose_repairs(
100
+ issues,
101
+ path,
102
+ working_df,
103
+ schema,
104
+ allow_llm=allow_llm,
105
+ model=model,
106
+ allow_pii=allow_pii,
107
+ confirm_pii=confirm_pii,
108
+ confirm_escalations=confirm_escalations,
109
+ interactive=interactive,
110
+ escalation_resolver=_resolve_escalation,
111
+ )
112
+
113
+
114
+ def _resolve_escalation(
115
+ candidate: ProposedFix,
116
+ schema: Schema | None,
117
+ context: SafetyContext,
118
+ safety_filter: SafetyFilter,
119
+ safety_result: SafetyResult,
120
+ ) -> tuple[SafetyContext, SafetyResult]:
121
+ """Prompt for safety escalations and re-evaluate if the user confirms."""
122
+ if "NO_PII_OVERWRITE" in safety_result.rule_ids:
123
+ confirmed = typer.confirm(
124
+ f"Candidate fix for row {candidate.fix.row}, column '{candidate.fix.column}' "
125
+ "touches PII. Confirm this edit?",
126
+ default=False,
127
+ )
128
+ if confirmed:
129
+ updated = context.model_copy(update={"confirm_pii": True})
130
+ return updated, safety_filter.evaluate(candidate, schema, updated)
131
+ return context, safety_result
132
+
133
+ confirmed = typer.confirm(
134
+ f"Candidate fix for row {candidate.fix.row}, column '{candidate.fix.column}' "
135
+ f"requires confirmation ({', '.join(safety_result.rule_ids)}). Confirm this edit?",
136
+ default=False,
137
+ )
138
+ if confirmed:
139
+ updated = context.model_copy(update={"confirm_escalations": True})
140
+ return updated, safety_filter.evaluate(candidate, schema, updated)
141
+ return context, safety_result
142
+
143
+
144
+ def _render_attempt_summary(
145
+ attempt_groups: list[list[RepairAttempt]],
146
+ console: Console,
147
+ ) -> int:
148
+ """Render a summary for issues that were not accepted."""
149
+ failed_groups = [
150
+ attempts for attempts in attempt_groups if attempts and attempts[-1].status != "accepted"
151
+ ]
152
+ if not failed_groups:
153
+ return 0
154
+
155
+ lines: list[str] = []
156
+ for attempts in failed_groups:
157
+ final_attempt = attempts[-1]
158
+ issue = final_attempt.issue
159
+ prefix = ""
160
+ if any(label.startswith("fd::") for label in final_attempt.unsat_core):
161
+ prefix = "functional dependency rejection - "
162
+ elif any(label.startswith("domain::") for label in final_attempt.unsat_core):
163
+ prefix = "domain bound rejection - "
164
+ lines.append(
165
+ f"{issue.issue_type} at {issue.row}:{issue.column} "
166
+ f"after {len(attempts)} attempt(s): {prefix}{final_attempt.reason}"
167
+ )
168
+
169
+ console.print("[bold yellow]Attempted But Not Fixed[/bold yellow]")
170
+ for line in lines:
171
+ console.print(line, overflow="fold")
172
+ return len(failed_groups)
173
+
174
+
175
+ def _render_failure_summary(result: RepairPipelineResult, console: Console) -> int:
176
+ """Render a summary for issues that the shared engine could not repair."""
177
+ if not result.failures:
178
+ return 0
179
+
180
+ console.print("[bold yellow]Attempted But Not Fixed[/bold yellow]")
181
+ for failure in result.failures:
182
+ prefix = ""
183
+ if any(label.startswith("fd::") for label in failure.unsat_core):
184
+ prefix = "functional dependency rejection - "
185
+ elif any(label.startswith("domain::") for label in failure.unsat_core):
186
+ prefix = "domain bound rejection - "
187
+ console.print(
188
+ f"{failure.issue_type} at {failure.row}:{failure.column} "
189
+ f"after {failure.attempt_count} attempt(s): {prefix}{failure.reason}",
190
+ overflow="fold",
191
+ )
192
+ return len(result.failures)
193
+
194
+
195
+ def _json_result(result: RepairPipelineResult) -> str:
196
+ """Serialize a repair result for CLI/MCP/CI consumers."""
197
+ return json.dumps(result.model_dump(mode="json"), indent=2, sort_keys=True)
198
+
199
+
200
+ def _apply_transaction(
201
+ path: Path,
202
+ fixes: list[ProposedFix],
203
+ source_bytes: bytes,
204
+ ) -> str:
205
+ """Compatibility wrapper around the shared repair engine transaction path."""
206
+ from dataforge.engine.repair import apply_transaction as engine_apply_transaction
207
+
208
+ return engine_apply_transaction(path, fixes, source_bytes)
209
+
210
+
211
+ def repair(
212
+ path: Annotated[
213
+ str,
214
+ typer.Argument(
215
+ help="Path to the CSV file, or warehouse:// backend URI, to repair.",
216
+ ),
217
+ ],
218
+ schema: Annotated[
219
+ Path | None,
220
+ typer.Option(
221
+ "--schema",
222
+ help="Path to a YAML schema file with column types and FDs.",
223
+ ),
224
+ ] = None,
225
+ constraints: Annotated[
226
+ Path | None,
227
+ typer.Option(
228
+ "--constraints",
229
+ help="Path to a reviewed constraints artifact from profile --constraints-out.",
230
+ ),
231
+ ] = None,
232
+ dry_run: Annotated[
233
+ bool,
234
+ typer.Option("--dry-run", help="Show proposed fixes without changing the file."),
235
+ ] = False,
236
+ apply: Annotated[
237
+ bool,
238
+ typer.Option("--apply", help="Apply fixes and record a reversible transaction."),
239
+ ] = False,
240
+ allow_llm: Annotated[
241
+ bool,
242
+ typer.Option(
243
+ "--allow-llm",
244
+ help="Allow fd_violation repair to call the configured LLM provider if needed.",
245
+ ),
246
+ ] = False,
247
+ allow_pii: Annotated[
248
+ bool,
249
+ typer.Option(
250
+ "--allow-pii",
251
+ help="Allow PII-targeting fixes to be considered by the safety layer.",
252
+ ),
253
+ ] = False,
254
+ confirm_pii: Annotated[
255
+ bool,
256
+ typer.Option(
257
+ "--confirm-pii",
258
+ help="Non-interactively confirm any PII-targeting fixes allowed via --allow-pii.",
259
+ ),
260
+ ] = False,
261
+ confirm_escalations: Annotated[
262
+ bool,
263
+ typer.Option(
264
+ "--confirm-escalations",
265
+ help="Non-interactively confirm soft safety escalations such as aggregate-sensitive edits.",
266
+ ),
267
+ ] = False,
268
+ llm_model: Annotated[
269
+ str,
270
+ typer.Option("--llm-model", help="Model name for fd_violation LLM fallback."),
271
+ ] = "gemini-2.0-flash",
272
+ row_id: Annotated[
273
+ list[str] | None,
274
+ typer.Option(
275
+ "--row-id",
276
+ help="Stable row identity column for warehouse apply. Repeat for composite keys.",
277
+ ),
278
+ ] = None,
279
+ json_output: Annotated[
280
+ bool,
281
+ typer.Option("--json", help="Print repair result as JSON."),
282
+ ] = False,
283
+ ) -> None:
284
+ """Detect, propose, and optionally apply reversible repairs to a CSV."""
285
+ if dry_run == apply:
286
+ _print_error(
287
+ "Choose exactly one of --dry-run or --apply.",
288
+ hint="Example: dataforge repair data.csv --dry-run",
289
+ )
290
+ raise typer.Exit(code=2)
291
+
292
+ try:
293
+ parsed_schema = _resolve_schema(schema)
294
+ constraints_artifact, constraints_sha256 = _resolve_constraints(constraints)
295
+ if is_table_store_uri(path):
296
+ if constraints_artifact is not None:
297
+ raise typer.BadParameter(
298
+ "Reviewed constraints are not yet accepted for warehouse URI repair."
299
+ )
300
+ store = store_from_uri(path, row_ids=tuple(row_id or ()))
301
+ store_result = run_table_store_repair(
302
+ store,
303
+ mode="apply" if apply else "dry_run",
304
+ schema=parsed_schema,
305
+ allow_llm=allow_llm,
306
+ model=llm_model,
307
+ allow_pii=allow_pii,
308
+ confirm_pii=confirm_pii,
309
+ confirm_escalations=confirm_escalations,
310
+ )
311
+ if json_output:
312
+ typer.echo(
313
+ json.dumps(store_result.model_dump(mode="json"), indent=2, sort_keys=True)
314
+ )
315
+ return
316
+ output_console = Console()
317
+ output_console.print(
318
+ Panel(
319
+ (
320
+ f"[bold]{store_result.backend}[/bold] patch plan "
321
+ f"{store_result.patch_plan.plan_id}\n"
322
+ f"Operations: {len(store_result.patch_plan.operations)}\n"
323
+ f"Apply supported: {store_result.patch_plan.apply_supported}\n"
324
+ f"Reason: {store_result.patch_plan.reason}"
325
+ ),
326
+ title="Warehouse Repair Plan",
327
+ style="green" if store_result.patch_plan.apply_supported else "yellow",
328
+ )
329
+ )
330
+ return
331
+
332
+ resolved_path = resolve_cli_path(Path(path))
333
+ if not resolved_path.exists():
334
+ raise typer.BadParameter(f"CSV file '{path}' does not exist.")
335
+ except TableStoreError as exc:
336
+ _print_error(str(exc))
337
+ raise typer.Exit(code=1 if apply else 2) from exc
338
+ except Exception as exc:
339
+ _print_error(str(exc))
340
+ raise typer.Exit(code=2) from exc
341
+
342
+ try:
343
+ from dataforge.engine.repair import RepairPipelineRequest, run_repair_pipeline
344
+
345
+ result = run_repair_pipeline(
346
+ RepairPipelineRequest(
347
+ source_path=resolved_path,
348
+ mode="apply" if apply else "dry_run",
349
+ schema=parsed_schema,
350
+ constraints=constraints_artifact,
351
+ constraints_artifact_sha256=constraints_sha256,
352
+ allow_llm=allow_llm,
353
+ model=llm_model,
354
+ allow_pii=allow_pii,
355
+ confirm_pii=confirm_pii,
356
+ confirm_escalations=confirm_escalations,
357
+ interactive=apply,
358
+ )
359
+ )
360
+ except Exception as exc:
361
+ _print_error(
362
+ f"Failed to apply repairs: {exc}" if apply else f"Failed to repair: {exc}",
363
+ hint="The source file was restored to its pre-apply bytes." if apply else None,
364
+ )
365
+ raise typer.Exit(code=1 if apply else 2) from exc
366
+
367
+ if json_output:
368
+ typer.echo(_json_result(result))
369
+ raise typer.Exit(code=0 if result.fixes else 1)
370
+
371
+ output_console = Console()
372
+ render_repair_diff(result.fixes, output_console, file_path=str(resolved_path))
373
+ failed_issue_count = _render_failure_summary(result, output_console)
374
+
375
+ if not result.fixes and failed_issue_count == 0:
376
+ if result.receipt.reason != "No accepted fixes were produced.":
377
+ output_console.print(
378
+ Panel(
379
+ f"[yellow]{result.receipt.reason}[/yellow]",
380
+ title="Repair Summary",
381
+ style="yellow",
382
+ )
383
+ )
384
+ raise typer.Exit(code=1)
385
+
386
+ if dry_run:
387
+ raise typer.Exit(code=0 if result.fixes else 1)
388
+
389
+ if not result.fixes or not result.receipt.applied:
390
+ raise typer.Exit(code=1)
391
+
392
+ output_console.print(
393
+ Panel(
394
+ f"[green]Applied {len(result.fixes)} fix(es).[/green]\n"
395
+ f"Transaction ID: [bold]{result.receipt.txn_id}[/bold]",
396
+ title="Repair Applied",
397
+ style="green",
398
+ )
399
+ )
400
+ if failed_issue_count:
401
+ output_console.print(
402
+ Panel(
403
+ f"[yellow]{failed_issue_count} issue(s) were attempted but not fixed.[/yellow]",
404
+ title="Week 3 Summary",
405
+ style="yellow",
406
+ )
407
+ )