ski-audit-ledger 3.0.3__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.
@@ -0,0 +1,581 @@
1
+ Metadata-Version: 2.4
2
+ Name: ski-audit-ledger
3
+ Version: 3.0.3
4
+ Summary: Audit ledger management tool for the SKI Framework.
5
+ Author-email: KpiFinity <hello@kpifinity.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/kpifinity/ski-framework
8
+ Project-URL: Documentation, https://kpifinity.github.io/ski-framework/
9
+ Project-URL: Issues, https://github.com/kpifinity/ski-framework/issues
10
+ Keywords: ski-framework,audit,compliance,ledger
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ Requires-Dist: psycopg[binary]<4,>=3.1.18
21
+ Requires-Dist: sqlalchemy<3,>=2.0.27
22
+ Requires-Dist: click<9,>=8.1.7
23
+ Requires-Dist: pydantic<3,>=2.13.4
24
+ Requires-Dist: python-dotenv<2,>=1.2.2
25
+ Requires-Dist: jinja2<4,>=3.1.6
26
+ Requires-Dist: pyyaml<7,>=6.0.1
27
+ Requires-Dist: httpx<0.29,>=0.27
28
+ Requires-Dist: tabulate<1,>=0.9
29
+
30
+ # audit-ledger
31
+
32
+ > Install from PyPI: `pip install ski-audit-ledger` (publishing starts with the first release after June 2026).
33
+
34
+ > **⚠ STATUS: EARLY ALPHA (v0.1.0a0).** Alpha-quality tooling. See the
35
+ > repo root `README.md` for the project-wide status.
36
+
37
+ Manage and verify the immutable audit ledger for SKI Framework compliance monitoring.
38
+
39
+ ## v2.1 highlights
40
+
41
+ - **Real `verify_integrity()`.** Recomputes every entry's hash from the
42
+ documented canonical serialization. Catches in-place tampering, not
43
+ just chain-linkage breakage.
44
+ - **Real `backup`.** Invokes `pg_dump` and verifies the dump with
45
+ `pg_restore --list`. No more stub.
46
+ - **Five-verdict taxonomy.** `--verdict-filter` now accepts
47
+ `NULL_UNMAPPED` and `NULL_STALE` (the pre-v2.1 `NULL` is gone).
48
+ - **No `confidence_level`.** Removed entirely from the data model.
49
+ - **Append-only enforcement** lives at the database layer
50
+ (`reference-implementation/src/ledger/append_only.sql`). UPDATE,
51
+ DELETE, and TRUNCATE on `ledger_entries` are refused by triggers.
52
+
53
+ ## Overview
54
+
55
+ The audit ledger is a hash-chained, immutable record of all compliance
56
+ verdicts generated by the SKI Model runtime. This tool provides
57
+ utilities for:
58
+
59
+ - **Verification** — Verify ledger integrity and detect tampering
60
+ - **Backup** — Create secure backups with cryptographic verification
61
+ - **Export** — Extract ledger data for analysis and reporting
62
+ - **Reporting** — Generate compliance reports and summaries
63
+
64
+ ## Features
65
+
66
+ ### Ledger Integrity Verification
67
+
68
+ Verify the complete hash chain of ledger entries to ensure no records have been tampered with:
69
+
70
+ ```bash
71
+ audit-ledger verify --ledger-db postgresql://user:pass@localhost/ledger
72
+ ```
73
+
74
+ Output:
75
+ ```
76
+ Ledger Integrity Verification
77
+ ├── Total entries: 4,327
78
+ ├── Chain integrity: ✓ VERIFIED
79
+ ├── Hash verification: ✓ 4,327/4,327 valid
80
+ ├── Timestamp order: ✓ VALID
81
+ └── Last verified: 2026-05-21T15:30:00Z
82
+ ```
83
+
84
+ ### Secure Backup
85
+
86
+ Create verified backups with integrity checking:
87
+
88
+ ```bash
89
+ audit-ledger backup \
90
+ --source postgresql://user:pass@localhost/ledger \
91
+ --output ./ledger-backup-2026-05-21.sql \
92
+ --verify
93
+ ```
94
+
95
+ ### Data Export
96
+
97
+ Export ledger entries for analysis and reporting:
98
+
99
+ ```bash
100
+ # Export to JSON
101
+ audit-ledger export \
102
+ --source postgresql://user:pass@localhost/ledger \
103
+ --output ledger-data.json \
104
+ --format json
105
+
106
+ # Export to CSV
107
+ audit-ledger export \
108
+ --source postgresql://user:pass@localhost/ledger \
109
+ --output ledger-data.csv \
110
+ --format csv \
111
+ --fields "id,timestamp,verdict,rule_id,telemetry_id"
112
+ ```
113
+
114
+ ### Compliance Reporting
115
+
116
+ Generate formatted compliance reports:
117
+
118
+ ```bash
119
+ audit-ledger report \
120
+ --source postgresql://user:pass@localhost/ledger \
121
+ --start-date 2026-01-01 \
122
+ --end-date 2026-05-31 \
123
+ --output compliance-report.html
124
+ ```
125
+
126
+ ## Installation
127
+
128
+ ### From Source
129
+
130
+ ```bash
131
+ cd tools/audit-ledger
132
+ pip install -e .
133
+ ```
134
+
135
+ ### Requirements
136
+
137
+ - Python 3.8+
138
+ - PostgreSQL 12+ (for ledger database)
139
+ - psycopg2 (PostgreSQL adapter)
140
+ - sqlalchemy (ORM)
141
+
142
+ ## Quick Start
143
+
144
+ ### 1. Verify Ledger Integrity
145
+
146
+ After running compliance monitoring for a period, verify the ledger has not been tampered with:
147
+
148
+ ```bash
149
+ audit-ledger verify \
150
+ --ledger-db postgresql://compliance:securepass@localhost:5432/ski_ledger \
151
+ --verbose
152
+ ```
153
+
154
+ ### 2. Create a Backup
155
+
156
+ Before major system changes, create a verified backup:
157
+
158
+ ```bash
159
+ audit-ledger backup \
160
+ --source postgresql://compliance:securepass@localhost:5432/ski_ledger \
161
+ --output ./backups/ledger-$(date +%Y%m%d).sql.gz \
162
+ --compress \
163
+ --verify
164
+ ```
165
+
166
+ ### 3. Generate Monthly Report
167
+
168
+ At month-end, generate a compliance summary:
169
+
170
+ ```bash
171
+ audit-ledger report \
172
+ --source postgresql://compliance:securepass@localhost:5432/ski_ledger \
173
+ --start-date 2026-05-01 \
174
+ --end-date 2026-05-31 \
175
+ --output monthly-report-2026-05.html \
176
+ --include-verdicts \
177
+ --include-violations
178
+ ```
179
+
180
+ ### 4. Export for Audit
181
+
182
+ Export ledger data for external audit:
183
+
184
+ ```bash
185
+ audit-ledger export \
186
+ --source postgresql://compliance:securepass@localhost:5432/ski_ledger \
187
+ --output audit-export.json \
188
+ --format json \
189
+ --date-range 2026-01-01,2026-05-31
190
+ ```
191
+
192
+ ## Command Reference
193
+
194
+ ### verify
195
+
196
+ Verify ledger integrity and hash chain validity.
197
+
198
+ ```bash
199
+ audit-ledger verify [OPTIONS]
200
+
201
+ Options:
202
+ --ledger-db TEXT PostgreSQL connection string [required]
203
+ --verbose Show detailed verification output
204
+ --check-timestamps Verify timestamp ordering
205
+ --repair Attempt to repair minor issues (use with caution)
206
+ --output TEXT Write results to file
207
+ --help Show help message
208
+ ```
209
+
210
+ ### backup
211
+
212
+ Create a backup of the ledger database.
213
+
214
+ ```bash
215
+ audit-ledger backup [OPTIONS]
216
+
217
+ Options:
218
+ --source TEXT PostgreSQL connection string [required]
219
+ --output TEXT Output file path [required]
220
+ --compress Gzip compress the backup
221
+ --verify Verify backup integrity after creation
222
+ --encryption-key TEXT Encrypt backup (optional)
223
+ --help Show help message
224
+ ```
225
+
226
+ ### export
227
+
228
+ Export ledger entries for analysis.
229
+
230
+ ```bash
231
+ audit-ledger export [OPTIONS]
232
+
233
+ Options:
234
+ --source TEXT PostgreSQL connection string [required]
235
+ --output TEXT Output file path [required]
236
+ --format TEXT json|csv|jsonl (default: json)
237
+ --fields TEXT Comma-separated field names to include
238
+ --date-range TEXT Start,end dates (YYYY-MM-DD,YYYY-MM-DD)
239
+ --verdict-filter TEXT Filter by verdict (CLEAR|FLAG|NULL|DISCRETIONARY)
240
+ --rule-id TEXT Filter by rule ID
241
+ --limit INTEGER Maximum entries to export
242
+ --help Show help message
243
+ ```
244
+
245
+ ### report
246
+
247
+ Generate a compliance report from ledger data.
248
+
249
+ ```bash
250
+ audit-ledger report [OPTIONS]
251
+
252
+ Options:
253
+ --source TEXT PostgreSQL connection string [required]
254
+ --output TEXT Output HTML file path
255
+ --start-date TEXT Report start date (YYYY-MM-DD)
256
+ --end-date TEXT Report end date (YYYY-MM-DD)
257
+ --include-verdicts Include verdict summary statistics
258
+ --include-violations Include violation details
259
+ --include-timeline Include timeline visualization
260
+ --include-audit-trail Include audit trail verification
261
+ --title TEXT Report title
262
+ --organization TEXT Organization name for report
263
+ --help Show help message
264
+ ```
265
+
266
+ ## Ledger Structure
267
+
268
+ The audit ledger stores compliance verdicts in a hash-chained format:
269
+
270
+ ```sql
271
+ CREATE TABLE ledger_entries (
272
+ id BIGSERIAL PRIMARY KEY,
273
+ sequence_number BIGINT UNIQUE NOT NULL,
274
+ previous_hash CHAR(64) NOT NULL,
275
+ entry_hash CHAR(64) NOT NULL UNIQUE,
276
+ timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
277
+ verdict TEXT NOT NULL CHECK (verdict IN (
278
+ 'CLEAR','FLAG','NULL_UNMAPPED','NULL_STALE','DISCRETIONARY'
279
+ )),
280
+ telemetry_id TEXT NOT NULL,
281
+ telemetry_hash CHAR(64) NOT NULL,
282
+ rule_id TEXT,
283
+ knowledge_graph_version TEXT,
284
+ ski_model_version TEXT NOT NULL,
285
+ reasoning TEXT,
286
+ track TEXT CHECK (track IS NULL OR track IN ('symbolic','llm')),
287
+ escalation_status TEXT,
288
+ escalation_notes TEXT,
289
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
290
+ );
291
+ ```
292
+
293
+ > **v2.1 schema notes.** `milm_version` is renamed to `ski_model_version`.
294
+ > `confidence_level` has been removed entirely — B3.1 prohibits confidence
295
+ > scores in the ledger. The verdict CHECK constraint enforces the
296
+ > five-verdict taxonomy.
297
+
298
+ Each entry's `entry_hash` is `SHA-256` of the canonical serialization
299
+ documented in
300
+ [`src/audit_ledger/canonical.py`](./src/audit_ledger/canonical.py). The
301
+ canonical payload includes `sequence_number`, `previous_hash`, `timestamp`,
302
+ `verdict`, `telemetry_id`, `telemetry_hash`, `rule_id`, `kg_version`,
303
+ `ski_model_version`, `reasoning`, and `track`. Modifying any one of
304
+ these fields invalidates that entry's `entry_hash`.
305
+
306
+ Append-only enforcement is in
307
+ [`reference-implementation/src/ledger/append_only.sql`](../../reference-implementation/src/ledger/append_only.sql)
308
+ — `BEFORE UPDATE`, `BEFORE DELETE`, and `BEFORE TRUNCATE` triggers
309
+ refuse any modification at the database layer.
310
+
311
+ ## Integrity verification process
312
+
313
+ The `verify` command checks, for every row:
314
+
315
+ 1. **Chain linkage** — each row's `previous_hash` equals the prior row's `entry_hash`.
316
+ 2. **Entry-hash recomputation** — re-derive `entry_hash` from the
317
+ canonical payload and compare with what's stored. Catches in-place
318
+ tampering that chain-linkage-only checks miss.
319
+ 3. **Sequence continuity** — `sequence_number` has no gaps.
320
+ 4. **Timestamp ordering** — timestamps are monotonic.
321
+
322
+ Example verification output:
323
+
324
+ ```
325
+ Ledger Integrity Verification Report
326
+ ====================================
327
+
328
+ Database: postgresql://localhost/ski_ledger
329
+ Verification Date: 2026-05-21T15:30:00Z
330
+
331
+ Chain Analysis:
332
+ Total Entries: 4,327
333
+ Sequence Range: 1 - 4,327
334
+ Time Range: 2026-01-01 to 2026-05-21
335
+
336
+ Integrity Checks:
337
+ ✓ Chain continuity: All 4,327 entries form valid chain
338
+ ✓ Hash verification: 4,327/4,327 entries (100%)
339
+ ✓ Timestamp ordering: All timestamps chronologically valid
340
+ ✓ Data consistency: All references valid
341
+
342
+ Verdict Distribution:
343
+ CLEAR: 3,821 (88.3%)
344
+ FLAG: 412 (9.5%)
345
+ DISCRETIONARY: 94 (2.2%)
346
+ NULL: 0 (0.0%)
347
+
348
+ Risk Assessment:
349
+ ✓ No signs of tampering
350
+ ✓ No missing entries
351
+ ✓ No invalid references
352
+ Status: VERIFIED
353
+
354
+ Recommendation: Ledger integrity confirmed. Safe for regulatory reporting.
355
+ ```
356
+
357
+ ## Backup & Recovery
358
+
359
+ ### Creating a Backup
360
+
361
+ ```bash
362
+ # Standard backup
363
+ audit-ledger backup \
364
+ --source postgresql://compliance:pass@localhost/ski_ledger \
365
+ --output ./ledger-backup-2026-05-21.sql
366
+
367
+ # Compressed with verification
368
+ audit-ledger backup \
369
+ --source postgresql://compliance:pass@localhost/ski_ledger \
370
+ --output ./ledger-backup-2026-05-21.sql.gz \
371
+ --compress \
372
+ --verify
373
+ ```
374
+
375
+ ### Verifying a Backup
376
+
377
+ ```bash
378
+ # Restore to test database
379
+ psql test_ledger < ledger-backup-2026-05-21.sql
380
+
381
+ # Verify the restored ledger
382
+ audit-ledger verify \
383
+ --ledger-db postgresql://user:pass@localhost/test_ledger
384
+ ```
385
+
386
+ ## Export Examples
387
+
388
+ ### Export All Violations
389
+
390
+ ```bash
391
+ audit-ledger export \
392
+ --source postgresql://user:pass@localhost/ski_ledger \
393
+ --output violations.json \
394
+ --format json \
395
+ --verdict-filter FLAG
396
+ ```
397
+
398
+ Output:
399
+ ```json
400
+ {
401
+ "export_date": "2026-05-21T15:30:00Z",
402
+ "entry_count": 412,
403
+ "entries": [
404
+ {
405
+ "id": 1543,
406
+ "timestamp": "2026-05-15T10:30:00Z",
407
+ "verdict": "FLAG",
408
+ "rule_id": "e001",
409
+ "telemetry_id": "TEL_2026_05_001",
410
+ "reasoning": "SO2 emissions 125 ppm exceeds limit of 100 ppm"
411
+ },
412
+ ...
413
+ ]
414
+ }
415
+ ```
416
+
417
+ ### Export Monthly Audit Trail
418
+
419
+ ```bash
420
+ audit-ledger export \
421
+ --source postgresql://user:pass@localhost/ski_ledger \
422
+ --output may-2026-audit.csv \
423
+ --format csv \
424
+ --date-range 2026-05-01,2026-05-31 \
425
+ --fields "timestamp,verdict,rule_id,reasoning,escalation_status"
426
+ ```
427
+
428
+ ## Reporting
429
+
430
+ ### Generate Monthly Compliance Report
431
+
432
+ ```bash
433
+ audit-ledger report \
434
+ --source postgresql://user:pass@localhost/ski_ledger \
435
+ --start-date 2026-05-01 \
436
+ --end-date 2026-05-31 \
437
+ --output may-2026-compliance.html \
438
+ --include-verdicts \
439
+ --include-violations \
440
+ --include-timeline \
441
+ --organization "Acme Energy Corp"
442
+ ```
443
+
444
+ Report includes:
445
+ - Executive summary of compliance status
446
+ - Verdict distribution charts
447
+ - Violations identified and status
448
+ - Remediation actions taken
449
+ - Timeline of escalations
450
+ - Audit trail verification status
451
+ - Regulatory filing readiness
452
+
453
+ ## Security Considerations
454
+
455
+ ### Database Security
456
+
457
+ The PostgreSQL ledger database should be:
458
+ - Behind a firewall (not internet-accessible)
459
+ - Using strong authentication (not default credentials)
460
+ - Requiring SSL/TLS for all connections
461
+ - Backed up regularly
462
+ - Monitored for unauthorized access
463
+
464
+ ### Backup Security
465
+
466
+ Backups should be:
467
+ - Encrypted if stored off-site
468
+ - Stored securely (not in version control)
469
+ - Verified before relying on them
470
+ - Tested for recovery capability
471
+
472
+ ### Access Control
473
+
474
+ Ledger access should be restricted to:
475
+ - Compliance officers
476
+ - System administrators
477
+ - Authorized auditors
478
+
479
+ ## Troubleshooting
480
+
481
+ ### Ledger Verification Fails
482
+
483
+ If verification reports issues:
484
+
485
+ ```bash
486
+ # Get detailed diagnostic output
487
+ audit-ledger verify \
488
+ --ledger-db postgresql://user:pass@localhost/ski_ledger \
489
+ --verbose
490
+
491
+ # Attempt automatic repair (use with caution)
492
+ audit-ledger verify \
493
+ --ledger-db postgresql://user:pass@localhost/ski_ledger \
494
+ --repair
495
+ ```
496
+
497
+ ### Export Takes Too Long
498
+
499
+ For large ledgers, use filters:
500
+
501
+ ```bash
502
+ # Export only recent violations
503
+ audit-ledger export \
504
+ --source postgresql://user:pass@localhost/ski_ledger \
505
+ --output recent-flags.json \
506
+ --verdict-filter FLAG \
507
+ --date-range 2026-05-01,2026-05-31
508
+ ```
509
+
510
+ ### Backup Verification Fails
511
+
512
+ Restore to a test database and verify:
513
+
514
+ ```bash
515
+ # Create test database
516
+ createdb test_ledger
517
+
518
+ # Restore backup
519
+ psql test_ledger < backup.sql
520
+
521
+ # Verify restoration
522
+ audit-ledger verify --ledger-db postgresql://user:pass@localhost/test_ledger
523
+ ```
524
+
525
+ ## API Usage
526
+
527
+ ### Python API
528
+
529
+ ```python
530
+ from audit_ledger import Ledger
531
+
532
+ # Connect to ledger
533
+ ledger = Ledger("postgresql://user:pass@localhost/ski_ledger")
534
+
535
+ # Verify integrity
536
+ result = ledger.verify_integrity()
537
+ print(f"Ledger valid: {result.is_valid}")
538
+ print(f"Total entries: {result.total_entries}")
539
+
540
+ # Export entries
541
+ entries = ledger.export_entries(
542
+ start_date="2026-05-01",
543
+ end_date="2026-05-31",
544
+ verdict_filter="FLAG"
545
+ )
546
+
547
+ # Generate report
548
+ report = ledger.generate_report(
549
+ start_date="2026-05-01",
550
+ end_date="2026-05-31",
551
+ include_verdicts=True,
552
+ include_violations=True
553
+ )
554
+ ledger.save_report(report, "compliance-report.html")
555
+ ```
556
+
557
+ ## Production Checklist
558
+
559
+ - [ ] Configure PostgreSQL with strong authentication
560
+ - [ ] Enable SSL/TLS for database connections
561
+ - [ ] Set up automated backup schedule
562
+ - [ ] Verify backup recovery procedures
563
+ - [ ] Document ledger access controls
564
+ - [ ] Train staff on ledger commands
565
+ - [ ] Set up monitoring for ledger database
566
+ - [ ] Plan audit trail retention policy
567
+ - [ ] Test export/reporting workflows
568
+ - [ ] Schedule regular integrity verification
569
+ - [ ] Document escalation procedures for verification failures
570
+
571
+ ## Support
572
+
573
+ For issues or questions:
574
+ - Check individual command help: `audit-ledger COMMAND --help`
575
+ - Review ledger structure documentation
576
+ - Open an issue on GitHub
577
+ - Contact your compliance team
578
+
579
+ ---
580
+
581
+ **Note:** The audit ledger is critical for regulatory compliance. All operations should be performed by authorized personnel only. Always verify backups and test recovery procedures before relying on them.