attestory 0.3.1__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.
- attestory/__init__.py +3 -0
- attestory/cli.py +623 -0
- attestory/engine.py +288 -0
- attestory/parsers/__init__.py +1 -0
- attestory/parsers/csv_extract.py +167 -0
- attestory/parsers/excel.py +86 -0
- attestory/parsers/html.py +218 -0
- attestory/parsers/pptx.py +154 -0
- attestory/rules.py +246 -0
- attestory/server.py +166 -0
- attestory/watcher.py +155 -0
- attestory-0.3.1.dist-info/METADATA +175 -0
- attestory-0.3.1.dist-info/RECORD +16 -0
- attestory-0.3.1.dist-info/WHEEL +4 -0
- attestory-0.3.1.dist-info/entry_points.txt +2 -0
- attestory-0.3.1.dist-info/licenses/LICENSE +201 -0
attestory/__init__.py
ADDED
attestory/cli.py
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from html import escape
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
from rich.console import Console
|
|
7
|
+
from rich.panel import Panel
|
|
8
|
+
from rich.table import Table
|
|
9
|
+
|
|
10
|
+
from attestory.engine import (
|
|
11
|
+
ATTESTORY_DIR,
|
|
12
|
+
commit_file,
|
|
13
|
+
diff_file_snapshots,
|
|
14
|
+
init_workspace,
|
|
15
|
+
workspace_status,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
app = typer.Typer(
|
|
19
|
+
help="Attestory — Local version control & deterministic math auditing for analytics."
|
|
20
|
+
)
|
|
21
|
+
console = Console()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@app.command()
|
|
25
|
+
def init():
|
|
26
|
+
"""Initialize a local .attestory/ audit folder in the current directory."""
|
|
27
|
+
meta_dir = init_workspace(Path.cwd())
|
|
28
|
+
console.print(
|
|
29
|
+
Panel.fit(
|
|
30
|
+
f"[bold green]Initialized Attestory workspace[/bold green] at [cyan]{meta_dir}[/cyan]\n"
|
|
31
|
+
"Created [bold]rules.yaml[/bold], [bold]changelog.md[/bold], and [bold]snapshots/[/bold].",
|
|
32
|
+
title="Attestory",
|
|
33
|
+
)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@app.command()
|
|
38
|
+
def status():
|
|
39
|
+
"""Show the latest audit status for every tracked file."""
|
|
40
|
+
entries = workspace_status(Path.cwd())
|
|
41
|
+
if not entries:
|
|
42
|
+
console.print(
|
|
43
|
+
"[yellow]No tracked files yet. Run 'attestory demo' or "
|
|
44
|
+
"'attestory commit <file>'[/yellow]"
|
|
45
|
+
)
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
table = Table(title="Attestory Workspace Status")
|
|
49
|
+
table.add_column("File")
|
|
50
|
+
table.add_column("Latest Version")
|
|
51
|
+
table.add_column("Last Updated (UTC)")
|
|
52
|
+
table.add_column("SHA-256 Prefix")
|
|
53
|
+
table.add_column("Open Errors / Rule Violations", justify="right")
|
|
54
|
+
table.add_column("Status")
|
|
55
|
+
for entry in entries:
|
|
56
|
+
status_style = "green" if entry["status"] == "VERIFIED" else "yellow"
|
|
57
|
+
table.add_row(
|
|
58
|
+
entry["file"],
|
|
59
|
+
f"v{entry['version']}",
|
|
60
|
+
entry["timestamp"],
|
|
61
|
+
entry["sha256"][:12],
|
|
62
|
+
str(entry["open_issues"]),
|
|
63
|
+
f"[{status_style}]{entry['status']}[/{status_style}]",
|
|
64
|
+
)
|
|
65
|
+
Console(width=140).print(table)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@app.command()
|
|
69
|
+
def commit(
|
|
70
|
+
file: Path = typer.Argument(
|
|
71
|
+
..., exists=True, help="Path to an .xlsx, .pptx, .html, or .csv file to audit."
|
|
72
|
+
),
|
|
73
|
+
message: str = typer.Option(
|
|
74
|
+
"", "-m", "--message", help="Optional note describing this update."
|
|
75
|
+
),
|
|
76
|
+
):
|
|
77
|
+
"""Audit and snapshot a supported local file."""
|
|
78
|
+
result = commit_file(Path.cwd(), file.resolve(), message=message)
|
|
79
|
+
rec = result["record"]
|
|
80
|
+
diff = result["diff"]
|
|
81
|
+
|
|
82
|
+
status_color = "green"
|
|
83
|
+
if (
|
|
84
|
+
rec["rule_violations"]
|
|
85
|
+
or (
|
|
86
|
+
file.suffix.lower() == ".xlsx"
|
|
87
|
+
and (rec["stats"]["errors"] or (diff and diff.get("hardcode_overrides")))
|
|
88
|
+
)
|
|
89
|
+
or (file.suffix.lower() == ".html" and rec["stats"]["external_references"])
|
|
90
|
+
):
|
|
91
|
+
status_color = "yellow"
|
|
92
|
+
|
|
93
|
+
summary_lines = [
|
|
94
|
+
f"[bold]File:[/bold] {rec['file']} | [bold]Version:[/bold] v{rec['version']}",
|
|
95
|
+
f"[bold]SHA-256:[/bold] {rec['sha256'][:20]}...",
|
|
96
|
+
]
|
|
97
|
+
extension = file.suffix.lower()
|
|
98
|
+
if extension == ".xlsx":
|
|
99
|
+
summary_lines.append(
|
|
100
|
+
f"[bold]Populated Cells:[/bold] {rec['stats']['populated_cells']} | "
|
|
101
|
+
f"[bold]Formula Errors:[/bold] {len(rec['stats']['errors'])}"
|
|
102
|
+
)
|
|
103
|
+
elif extension == ".pptx":
|
|
104
|
+
summary_lines.append(
|
|
105
|
+
f"[bold]Slides:[/bold] {rec['stats']['slides']} | "
|
|
106
|
+
f"[bold]Extracted Elements:[/bold] {rec['stats']['elements']}"
|
|
107
|
+
)
|
|
108
|
+
elif extension == ".html":
|
|
109
|
+
summary_lines.append(
|
|
110
|
+
f"[bold]HTML Elements:[/bold] {rec['stats']['elements']} | "
|
|
111
|
+
f"[bold]External References:[/bold] {rec['stats']['external_references']}"
|
|
112
|
+
)
|
|
113
|
+
else:
|
|
114
|
+
summary_lines.append(
|
|
115
|
+
f"[bold]CSV Rows:[/bold] {rec['stats']['rows']} | "
|
|
116
|
+
f"[bold]Columns:[/bold] {rec['stats']['columns']}"
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
if diff:
|
|
120
|
+
if "hardcode_overrides" in diff:
|
|
121
|
+
summary_lines.append(
|
|
122
|
+
f"[bold]Changes vs v{rec['version'] - 1}:[/bold] {diff['total_changes']} total "
|
|
123
|
+
f"([red]{len(diff['hardcode_overrides'])} hardcode overrides[/red], "
|
|
124
|
+
f"{len(diff['formula_changes'])} formula edits, {len(diff['value_changes'])} value updates)"
|
|
125
|
+
)
|
|
126
|
+
elif extension == ".pptx":
|
|
127
|
+
summary_lines.append(
|
|
128
|
+
f"[bold]Changes vs v{rec['version'] - 1}:[/bold] "
|
|
129
|
+
f"{diff['total_changes']} presentation changes"
|
|
130
|
+
)
|
|
131
|
+
else:
|
|
132
|
+
summary_lines.append(
|
|
133
|
+
f"[bold]Changes vs v{rec['version'] - 1}:[/bold] "
|
|
134
|
+
f"{diff['total_changes']} {extension[1:].upper()} changes"
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
console.print(
|
|
138
|
+
Panel(
|
|
139
|
+
"\n".join(summary_lines),
|
|
140
|
+
title="Attestory Receipt",
|
|
141
|
+
border_style=status_color,
|
|
142
|
+
)
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
if diff and diff.get("hardcode_overrides"):
|
|
146
|
+
table = Table(title="⚠️ HARDCODE OVERRIDE", style="red")
|
|
147
|
+
table.add_column("Location")
|
|
148
|
+
table.add_column("Previous Formula")
|
|
149
|
+
table.add_column("New Hardcoded Value")
|
|
150
|
+
for item in diff["hardcode_overrides"]:
|
|
151
|
+
table.add_row(
|
|
152
|
+
item["location"], item["old_formula"], item["new_hardcoded_val"]
|
|
153
|
+
)
|
|
154
|
+
console.print(table)
|
|
155
|
+
if rec["rule_violations"]:
|
|
156
|
+
table = Table(title="RULE VIOLATIONS", style="bold red")
|
|
157
|
+
table.add_column("Rule")
|
|
158
|
+
table.add_column("Location")
|
|
159
|
+
table.add_column("Expected")
|
|
160
|
+
table.add_column("Actual")
|
|
161
|
+
for violation in rec["rule_violations"]:
|
|
162
|
+
table.add_row(
|
|
163
|
+
violation["rule"],
|
|
164
|
+
violation["location"],
|
|
165
|
+
str(violation.get("expected", "")),
|
|
166
|
+
str(violation.get("actual", "")),
|
|
167
|
+
)
|
|
168
|
+
console.print(table)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@app.command()
|
|
172
|
+
def diff(
|
|
173
|
+
file: Path = typer.Argument(
|
|
174
|
+
..., help="Filename (.xlsx, .pptx, .html, or .csv) to compare snapshots."
|
|
175
|
+
),
|
|
176
|
+
):
|
|
177
|
+
"""Compare the latest two Parquet snapshots of a tracked file."""
|
|
178
|
+
root = Path.cwd()
|
|
179
|
+
manifest = root / ATTESTORY_DIR / "history.json"
|
|
180
|
+
if not manifest.exists():
|
|
181
|
+
console.print(
|
|
182
|
+
"[red]No .attestory/ history found. Run `attestory init` first.[/red]"
|
|
183
|
+
)
|
|
184
|
+
raise typer.Exit(1)
|
|
185
|
+
|
|
186
|
+
history = json.loads(manifest.read_text(encoding="utf-8"))
|
|
187
|
+
commits = [c for c in history["commits"] if c["file"] == file.name]
|
|
188
|
+
if len(commits) < 2:
|
|
189
|
+
console.print(
|
|
190
|
+
f"[yellow]Need at least 2 versions of {file.name} to diff.[/yellow]"
|
|
191
|
+
)
|
|
192
|
+
raise typer.Exit(0)
|
|
193
|
+
|
|
194
|
+
res = diff_file_snapshots(
|
|
195
|
+
root / commits[-2]["snapshot"],
|
|
196
|
+
root / commits[-1]["snapshot"],
|
|
197
|
+
file.name,
|
|
198
|
+
)
|
|
199
|
+
console.print(
|
|
200
|
+
f"[bold]Diff {file.name}: v{commits[-2]['version']} -> v{commits[-1]['version']}[/bold] "
|
|
201
|
+
f"({res['total_changes']} changes)"
|
|
202
|
+
)
|
|
203
|
+
if "hardcode_overrides" in res:
|
|
204
|
+
for item in res["hardcode_overrides"]:
|
|
205
|
+
console.print(
|
|
206
|
+
f" [red]HARDCODE[/red] {item['location']}: {item['old_formula']} -> {item['new_hardcoded_val']}"
|
|
207
|
+
)
|
|
208
|
+
for item in res["formula_changes"]:
|
|
209
|
+
console.print(
|
|
210
|
+
f" [yellow]FORMULA[/yellow] {item['location']}: {item['old_formula']} -> {item['new_formula']}"
|
|
211
|
+
)
|
|
212
|
+
for item in res["value_changes"][:20]:
|
|
213
|
+
console.print(
|
|
214
|
+
f" [cyan]VALUE[/cyan] {item['location']}: {item['old_val']} -> {item['new_val']}"
|
|
215
|
+
)
|
|
216
|
+
elif "changes" in res:
|
|
217
|
+
for item in res["changes"][:50]:
|
|
218
|
+
if "slide_num" in item:
|
|
219
|
+
description = (
|
|
220
|
+
f"SLIDE {item['slide_num']} {item['element_type'].upper()} "
|
|
221
|
+
f"{item['label'] or item['element_id']}"
|
|
222
|
+
)
|
|
223
|
+
elif "metric_type" in item:
|
|
224
|
+
description = (
|
|
225
|
+
f"{item['metric_type'].upper()} {item['column_name']} "
|
|
226
|
+
f"{item['label']}"
|
|
227
|
+
)
|
|
228
|
+
else:
|
|
229
|
+
description = (
|
|
230
|
+
f"{item['element_type'].upper()} "
|
|
231
|
+
f"{item['label'] or item['element_id']}"
|
|
232
|
+
)
|
|
233
|
+
console.print(
|
|
234
|
+
f" [cyan]{description}[/cyan]: {item['old_val']} -> {item['new_val']}"
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def generate_report(root: Path, filename: str) -> dict:
|
|
239
|
+
"""Create a self-contained HTML receipt for the latest snapshot."""
|
|
240
|
+
file = Path(filename)
|
|
241
|
+
history_path = root / ATTESTORY_DIR / "history.json"
|
|
242
|
+
if not history_path.exists():
|
|
243
|
+
raise FileNotFoundError(
|
|
244
|
+
"No .attestory/ history found. Run `attestory init` first."
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
history = json.loads(history_path.read_text(encoding="utf-8"))
|
|
248
|
+
commits = [entry for entry in history["commits"] if entry["file"] == file.name]
|
|
249
|
+
if not commits:
|
|
250
|
+
raise FileNotFoundError(f"No commits recorded for {file.name}.")
|
|
251
|
+
|
|
252
|
+
latest = commits[-1]
|
|
253
|
+
diff = (
|
|
254
|
+
diff_file_snapshots(
|
|
255
|
+
root / commits[-2]["snapshot"],
|
|
256
|
+
root / latest["snapshot"],
|
|
257
|
+
file.name,
|
|
258
|
+
)
|
|
259
|
+
if len(commits) > 1
|
|
260
|
+
else None
|
|
261
|
+
)
|
|
262
|
+
hardcodes = len(diff.get("hardcode_overrides", [])) if diff else 0
|
|
263
|
+
formulas = len(diff.get("formula_changes", [])) if diff else 0
|
|
264
|
+
violations = latest.get("rule_violations", [])
|
|
265
|
+
review_needed = bool(
|
|
266
|
+
latest.get("stats", {}).get("errors")
|
|
267
|
+
or hardcodes
|
|
268
|
+
or violations
|
|
269
|
+
or latest.get("stats", {}).get("external_references")
|
|
270
|
+
)
|
|
271
|
+
status = "NEEDS REVIEW" if review_needed else "VERIFIED"
|
|
272
|
+
total_changes = diff["total_changes"] if diff else 0
|
|
273
|
+
|
|
274
|
+
if diff is None:
|
|
275
|
+
rows = []
|
|
276
|
+
elif "changes" in diff:
|
|
277
|
+
rows = []
|
|
278
|
+
for change in diff["changes"]:
|
|
279
|
+
if "slide_num" in change:
|
|
280
|
+
label = (
|
|
281
|
+
f"Slide {change['slide_num']} · {change['element_type']} · "
|
|
282
|
+
f"{change['label'] or change['element_id']}"
|
|
283
|
+
)
|
|
284
|
+
elif "metric_type" in change:
|
|
285
|
+
label = (
|
|
286
|
+
f"{change['metric_type']} · {change['column_name']} · "
|
|
287
|
+
f"{change['label']}"
|
|
288
|
+
)
|
|
289
|
+
else:
|
|
290
|
+
label = (
|
|
291
|
+
f"{change['element_type']} · "
|
|
292
|
+
f"{change['label'] or change['element_id']}"
|
|
293
|
+
)
|
|
294
|
+
rows.append(
|
|
295
|
+
(
|
|
296
|
+
label,
|
|
297
|
+
change["old_val"],
|
|
298
|
+
change["new_val"],
|
|
299
|
+
change.get("numeric_delta"),
|
|
300
|
+
change.get("element_type", change.get("metric_type", "change")),
|
|
301
|
+
)
|
|
302
|
+
)
|
|
303
|
+
else:
|
|
304
|
+
rows = []
|
|
305
|
+
for category, entries in (
|
|
306
|
+
("Hardcode override", diff["hardcode_overrides"]),
|
|
307
|
+
("Formula edit", diff["formula_changes"]),
|
|
308
|
+
("Value update", diff["value_changes"]),
|
|
309
|
+
):
|
|
310
|
+
for change in entries:
|
|
311
|
+
rows.append(
|
|
312
|
+
(
|
|
313
|
+
change["location"],
|
|
314
|
+
change.get("old_val", change.get("old_formula", "")),
|
|
315
|
+
change.get(
|
|
316
|
+
"new_val",
|
|
317
|
+
change.get(
|
|
318
|
+
"new_hardcoded_val", change.get("new_formula", "")
|
|
319
|
+
),
|
|
320
|
+
),
|
|
321
|
+
"",
|
|
322
|
+
category,
|
|
323
|
+
)
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
def render_diff_row(row):
|
|
327
|
+
label, old, new, delta, category = row
|
|
328
|
+
category_class = {
|
|
329
|
+
"hardcode override": "hardcode",
|
|
330
|
+
"formula edit": "formula",
|
|
331
|
+
"value update": "value",
|
|
332
|
+
"text": "text",
|
|
333
|
+
"table": "table",
|
|
334
|
+
"chart": "chart",
|
|
335
|
+
}.get(str(category).lower(), "other")
|
|
336
|
+
return (
|
|
337
|
+
f'<tr class="change-{category_class}">'
|
|
338
|
+
f"<td>{escape(str(label))}</td><td>{escape(str(old or '—'))}</td>"
|
|
339
|
+
f"<td>{escape(str(new or '—'))}</td>"
|
|
340
|
+
f"<td>{escape(str(delta if delta is not None else ''))}</td>"
|
|
341
|
+
f"<td>{escape(str(category))}</td></tr>"
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
row_html = "".join(render_diff_row(row) for row in rows) or (
|
|
345
|
+
'<tr><td colspan="5" class="empty">No changes in this snapshot.</td></tr>'
|
|
346
|
+
)
|
|
347
|
+
violation_html = "".join(
|
|
348
|
+
f"<li><strong>{escape(item['rule'])}</strong> — {escape(item['location'])}: "
|
|
349
|
+
f"{escape(str(item.get('description') or item.get('expected', 'Assertion failed')))}</li>"
|
|
350
|
+
for item in violations
|
|
351
|
+
)
|
|
352
|
+
html = f"""<!doctype html>
|
|
353
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
354
|
+
<title>Attestory Receipt — {escape(latest["file"])} v{latest["version"]}</title>
|
|
355
|
+
<style>
|
|
356
|
+
:root{{color-scheme:light dark;--bg:#f4f6fa;--card:#fff;--ink:#172033;--muted:#667085;--line:#dce2eb;--accent:#2563eb;}}
|
|
357
|
+
@media(prefers-color-scheme:dark){{:root{{--bg:#111827;--card:#1f2937;--ink:#f3f4f6;--muted:#aab4c4;--line:#374151;--accent:#60a5fa;}}}}
|
|
358
|
+
*{{box-sizing:border-box}}body{{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,Segoe UI,sans-serif}}
|
|
359
|
+
main{{max-width:1100px;margin:40px auto;padding:0 24px}}header,.card,.diff{{background:var(--card);border:1px solid var(--line);border-radius:14px}}
|
|
360
|
+
header{{padding:26px;margin-bottom:18px}}h1{{margin:0 0 8px;font-size:25px}}p,.muted{{color:var(--muted)}}.badge{{display:inline-block;padding:6px 12px;border-radius:20px;font-weight:750;background:{"#b42318" if review_needed else "#067647"};color:white}}
|
|
361
|
+
.meta{{display:flex;flex-wrap:wrap;gap:12px 24px;margin-top:18px}}.cards{{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin:18px 0}}
|
|
362
|
+
.card{{padding:18px}}.card span{{display:block;color:var(--muted);font-size:13px}}.card strong{{font-size:26px}}
|
|
363
|
+
.diff{{overflow:hidden}}table{{border-collapse:collapse;width:100%;font-size:14px}}th,td{{padding:12px 14px;text-align:left;border-bottom:1px solid var(--line);overflow-wrap:anywhere}}
|
|
364
|
+
th{{background:color-mix(in srgb,var(--accent) 10%,var(--card));color:var(--ink)}}tbody tr:nth-child(even){{background:color-mix(in srgb,var(--accent) 4%,var(--card))}}.change-hardcode td:last-child{{color:#b42318;font-weight:700}}.change-formula td:last-child{{color:#b54708;font-weight:700}}.change-value td:last-child,.change-chart td:last-child{{color:#067647;font-weight:700}}.change-text td:last-child,.change-table td:last-child{{color:var(--accent);font-weight:700}}.empty{{text-align:center;color:var(--muted);padding:30px}}.violations{{color:#b42318}}
|
|
365
|
+
@media print{{:root{{color-scheme:light}}body{{background:white}}main{{margin:0 auto}}}}
|
|
366
|
+
</style></head><body><main>
|
|
367
|
+
<header><span class="badge">{status}</span><h1>Attestory Receipt</h1><div>{escape(latest["file"])} · Version {latest["version"]}</div>
|
|
368
|
+
<div class="meta"><span><strong>SHA-256</strong> {escape(latest["sha256"])}</span>
|
|
369
|
+
<span><strong>Timestamp</strong> {escape(latest["timestamp"])}</span>
|
|
370
|
+
<span><strong>Commit note</strong> {escape(latest["message"])}</span></div></header>
|
|
371
|
+
<section class="cards"><div class="card"><span>Total Changes</span><strong>{total_changes}</strong></div>
|
|
372
|
+
<div class="card"><span>Hardcode Overrides</span><strong>{hardcodes}</strong></div>
|
|
373
|
+
<div class="card"><span>Formula Edits</span><strong>{formulas}</strong></div>
|
|
374
|
+
<div class="card"><span>Rule Violations</span><strong>{len(violations)}</strong></div>
|
|
375
|
+
<div class="card"><span>External References</span><strong>{latest.get("stats", {}).get("external_references", 0)}</strong></div></section>
|
|
376
|
+
{"<section class='card violations'><strong>Rule violations</strong><ul>" + violation_html + "</ul></section>" if violations else ""}
|
|
377
|
+
<section class="diff"><table><thead><tr><th>Element</th><th>Previous</th><th>Current</th><th>Numeric delta</th><th>Change type</th></tr></thead>
|
|
378
|
+
<tbody>{row_html}</tbody></table></section>
|
|
379
|
+
</main></body></html>"""
|
|
380
|
+
reports_dir = root / ATTESTORY_DIR / "reports"
|
|
381
|
+
reports_dir.mkdir(parents=True, exist_ok=True)
|
|
382
|
+
report_stem = Path(latest["file"]).stem.replace(" ", "_")
|
|
383
|
+
report_path = reports_dir / f"{report_stem}_v{latest['version']}_receipt.html"
|
|
384
|
+
report_path.write_text(html, encoding="utf-8")
|
|
385
|
+
return {
|
|
386
|
+
"path": str(report_path.relative_to(root)),
|
|
387
|
+
"status": status,
|
|
388
|
+
"summary": {
|
|
389
|
+
"file": latest["file"],
|
|
390
|
+
"version": latest["version"],
|
|
391
|
+
"total_changes": total_changes,
|
|
392
|
+
"hardcode_overrides": hardcodes,
|
|
393
|
+
"formula_changes": formulas,
|
|
394
|
+
"rule_violations": len(violations),
|
|
395
|
+
"external_references": latest.get("stats", {}).get(
|
|
396
|
+
"external_references", 0
|
|
397
|
+
),
|
|
398
|
+
},
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
@app.command()
|
|
403
|
+
def report(
|
|
404
|
+
file: Path = typer.Argument(
|
|
405
|
+
..., help="Tracked .xlsx, .pptx, .html, or .csv file to report on."
|
|
406
|
+
),
|
|
407
|
+
):
|
|
408
|
+
"""Generate a standalone HTML audit receipt for the latest snapshot."""
|
|
409
|
+
try:
|
|
410
|
+
result = generate_report(Path.cwd(), file.name)
|
|
411
|
+
except FileNotFoundError as error:
|
|
412
|
+
console.print(f"[red]{error}[/red]")
|
|
413
|
+
raise typer.Exit(1) from error
|
|
414
|
+
console.print(f"[green]HTML audit receipt written to {result['path']}[/green]")
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
@app.command()
|
|
418
|
+
def watch(
|
|
419
|
+
recursive: bool = typer.Option(
|
|
420
|
+
False, "--recursive", help="Watch subdirectories recursively."
|
|
421
|
+
),
|
|
422
|
+
debounce: float = typer.Option(
|
|
423
|
+
2.0, "--debounce", help="Seconds to wait after a save before snapshotting."
|
|
424
|
+
),
|
|
425
|
+
):
|
|
426
|
+
"""Automatically snapshot supported files after they are saved."""
|
|
427
|
+
if debounce <= 0:
|
|
428
|
+
raise typer.BadParameter("--debounce must be greater than zero.")
|
|
429
|
+
|
|
430
|
+
from attestory.watcher import run_watcher
|
|
431
|
+
|
|
432
|
+
console.print(
|
|
433
|
+
f"Watching {Path.cwd()} ({'recursive' if recursive else 'non-recursive'}); "
|
|
434
|
+
f"debounce {debounce:g}s. Press Ctrl+C to stop."
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
def on_commit(result):
|
|
438
|
+
record = result["record"]
|
|
439
|
+
console.print(
|
|
440
|
+
f"[green]Auto-snapshot[/green] {record['file']} v{record['version']} "
|
|
441
|
+
f"— SHA-256 {record['sha256'][:12]}"
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
def on_error(path, error):
|
|
445
|
+
console.print(f"[red]Could not snapshot {path}: {error}[/red]")
|
|
446
|
+
|
|
447
|
+
try:
|
|
448
|
+
run_watcher(
|
|
449
|
+
Path.cwd(),
|
|
450
|
+
recursive=recursive,
|
|
451
|
+
debounce=debounce,
|
|
452
|
+
on_commit=on_commit,
|
|
453
|
+
on_error=on_error,
|
|
454
|
+
)
|
|
455
|
+
except KeyboardInterrupt:
|
|
456
|
+
console.print("\n[yellow]Stopped watching.[/yellow]")
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
@app.command()
|
|
460
|
+
def log(
|
|
461
|
+
file: Path = typer.Argument(
|
|
462
|
+
..., help="Filename (e.g. Q4_Forecast.xlsx) to display commit history."
|
|
463
|
+
),
|
|
464
|
+
):
|
|
465
|
+
"""Display the Attestory version history for a tracked workbook."""
|
|
466
|
+
root = Path.cwd()
|
|
467
|
+
manifest = root / ATTESTORY_DIR / "history.json"
|
|
468
|
+
if not manifest.exists():
|
|
469
|
+
console.print(
|
|
470
|
+
"[red]No .attestory/ history found. Run `attestory init` first.[/red]"
|
|
471
|
+
)
|
|
472
|
+
raise typer.Exit(1)
|
|
473
|
+
|
|
474
|
+
history = json.loads(manifest.read_text(encoding="utf-8"))
|
|
475
|
+
commits = [c for c in history["commits"] if c["file"] == file.name]
|
|
476
|
+
if not commits:
|
|
477
|
+
console.print(f"[yellow]No commits recorded yet for {file.name}.[/yellow]")
|
|
478
|
+
raise typer.Exit(0)
|
|
479
|
+
|
|
480
|
+
table = Table(title=f"Attestory History — {file.name}")
|
|
481
|
+
table.add_column("Version")
|
|
482
|
+
table.add_column("Timestamp (UTC)")
|
|
483
|
+
table.add_column("SHA-256")
|
|
484
|
+
table.add_column("Changes")
|
|
485
|
+
table.add_column("Hardcode Overrides")
|
|
486
|
+
table.add_column("Message")
|
|
487
|
+
|
|
488
|
+
for c in commits:
|
|
489
|
+
table.add_row(
|
|
490
|
+
f"v{c['version']}",
|
|
491
|
+
c["timestamp"][:19],
|
|
492
|
+
c["sha256"][:12] + "...",
|
|
493
|
+
str(c["diff_summary"]["total_changes"]),
|
|
494
|
+
str(c["diff_summary"]["hardcode_overrides"]),
|
|
495
|
+
c["message"],
|
|
496
|
+
)
|
|
497
|
+
console.print(table)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
@app.command()
|
|
501
|
+
def demo(
|
|
502
|
+
directory: Path = typer.Option(
|
|
503
|
+
Path("./attestory-demo"),
|
|
504
|
+
"--dir",
|
|
505
|
+
help="Directory to create the self-contained demonstration workspace in.",
|
|
506
|
+
),
|
|
507
|
+
):
|
|
508
|
+
"""Create and run a five-second example of Attestory's audit workflow."""
|
|
509
|
+
target = directory.expanduser().resolve()
|
|
510
|
+
if target.exists() and any(target.iterdir()):
|
|
511
|
+
console.print(
|
|
512
|
+
f"[red]Demo directory is not empty: {target}. Choose an empty directory.[/red]"
|
|
513
|
+
)
|
|
514
|
+
raise typer.Exit(1)
|
|
515
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
516
|
+
meta_dir = init_workspace(target)
|
|
517
|
+
rules = {
|
|
518
|
+
"version": 1,
|
|
519
|
+
"guardrails": {
|
|
520
|
+
"flag_hardcoded_formula_overrides": True,
|
|
521
|
+
"flag_excel_errors": True,
|
|
522
|
+
},
|
|
523
|
+
"must_be_formula": ["Revenue!B4"],
|
|
524
|
+
"assertions": [],
|
|
525
|
+
"cross_file_checks": [
|
|
526
|
+
{
|
|
527
|
+
"pptx_file": "Board_Deck.pptx",
|
|
528
|
+
"xlsx_file": "Q4_Forecast.xlsx",
|
|
529
|
+
"slide_num": 2,
|
|
530
|
+
"element_type": "text",
|
|
531
|
+
"label": "ARR",
|
|
532
|
+
"location": "Revenue!B4",
|
|
533
|
+
"tolerance": 0.01,
|
|
534
|
+
"description": "Slide 2 ARR must match the forecast total.",
|
|
535
|
+
}
|
|
536
|
+
],
|
|
537
|
+
"business_rules": [],
|
|
538
|
+
}
|
|
539
|
+
import yaml
|
|
540
|
+
|
|
541
|
+
(meta_dir / "rules.yaml").write_text(
|
|
542
|
+
yaml.safe_dump(rules, sort_keys=False), encoding="utf-8"
|
|
543
|
+
)
|
|
544
|
+
|
|
545
|
+
import openpyxl
|
|
546
|
+
from pptx import Presentation
|
|
547
|
+
from pptx.util import Inches
|
|
548
|
+
|
|
549
|
+
workbook_path = target / "Q4_Forecast.xlsx"
|
|
550
|
+
|
|
551
|
+
def save_workbook(hardcoded: bool) -> None:
|
|
552
|
+
workbook = openpyxl.Workbook()
|
|
553
|
+
sheet = workbook.active
|
|
554
|
+
sheet.title = "Revenue"
|
|
555
|
+
sheet["A1"] = "Segment"
|
|
556
|
+
sheet["B1"] = "ARR"
|
|
557
|
+
sheet["A2"] = "Enterprise"
|
|
558
|
+
sheet["B2"] = 250000
|
|
559
|
+
sheet["A3"] = "Mid-Market"
|
|
560
|
+
sheet["B3"] = 162000
|
|
561
|
+
sheet["A4"] = "Total"
|
|
562
|
+
sheet["B4"] = 428000 if hardcoded else "=SUM(B2:B3)"
|
|
563
|
+
workbook.save(workbook_path)
|
|
564
|
+
|
|
565
|
+
save_workbook(hardcoded=False)
|
|
566
|
+
commit_file(target, workbook_path, "Clean formula baseline")
|
|
567
|
+
save_workbook(hardcoded=True)
|
|
568
|
+
workbook_result = commit_file(target, workbook_path, "Simulated AI hardcode edit")
|
|
569
|
+
overrides = workbook_result["diff"]["hardcode_overrides"]
|
|
570
|
+
for override in overrides:
|
|
571
|
+
console.print(
|
|
572
|
+
f"[bold yellow]HARDCODE OVERRIDE[/bold yellow] at "
|
|
573
|
+
f"{override['location']}: {override['old_formula']} -> "
|
|
574
|
+
f"{override['new_hardcoded_val']}"
|
|
575
|
+
)
|
|
576
|
+
|
|
577
|
+
presentation = Presentation()
|
|
578
|
+
presentation.slides.add_slide(presentation.slide_layouts[6])
|
|
579
|
+
slide = presentation.slides.add_slide(presentation.slide_layouts[6])
|
|
580
|
+
shape = slide.shapes.add_textbox(Inches(1), Inches(1), Inches(6), Inches(1))
|
|
581
|
+
shape.name = "ARR"
|
|
582
|
+
shape.text_frame.text = "ARR $412,000"
|
|
583
|
+
deck_path = target / "Board_Deck.pptx"
|
|
584
|
+
presentation.save(deck_path)
|
|
585
|
+
deck_result = commit_file(target, deck_path, "Board deck ARR figure")
|
|
586
|
+
for violation in deck_result["record"]["rule_violations"]:
|
|
587
|
+
console.print(
|
|
588
|
+
f"[bold red]RULE VIOLATION[/bold red] "
|
|
589
|
+
f"{violation['description']}: expected {violation['expected']}, "
|
|
590
|
+
f"actual {violation['actual']}"
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
report_result = generate_report(target, "Q4_Forecast.xlsx")
|
|
594
|
+
console.print(
|
|
595
|
+
Panel.fit(
|
|
596
|
+
f"[bold green]Demo workspace ready[/bold green] at [cyan]{target}[/cyan]\n"
|
|
597
|
+
f"Inspect the receipt: [bold]{target / report_result['path']}[/bold]\n"
|
|
598
|
+
f"Inspect the audit trail: [bold]{target / ATTESTORY_DIR / 'changelog.md'}[/bold]",
|
|
599
|
+
title="Attestory Demo",
|
|
600
|
+
)
|
|
601
|
+
)
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
@app.command()
|
|
605
|
+
def serve(
|
|
606
|
+
host: str = typer.Option("127.0.0.1", "--host", help="Interface to bind to."),
|
|
607
|
+
port: int = typer.Option(8765, "--port", help="Port to listen on."),
|
|
608
|
+
):
|
|
609
|
+
"""Start the local FastAPI bridge for ChatGPT Actions and integrations."""
|
|
610
|
+
try:
|
|
611
|
+
import uvicorn
|
|
612
|
+
|
|
613
|
+
from attestory.server import create_app
|
|
614
|
+
except ImportError as error:
|
|
615
|
+
console.print(
|
|
616
|
+
'[yellow]Install server extras with: pip install "attestory[server]"[/yellow]'
|
|
617
|
+
)
|
|
618
|
+
raise typer.Exit(1) from error
|
|
619
|
+
uvicorn.run(create_app(Path.cwd()), host=host, port=port)
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
if __name__ == "__main__":
|
|
623
|
+
app()
|