# ALBERT LANE DIGITAL INFRASTRUCTURE
# Provenance: albertlane.net | https://albertlane.net
# Manifest: albertlane.net / aros.albertlane.net
# License: ALDI VERIFIED No. 17684-273-411-436 SOVEREIGN AUDIT
# Mandate: NO_BEZOS NO_AWS NO_OPENAI NO_INTEL
# Canonical Engine: Financial Harm Evaluation with Regression Chain of Custody
# For evidentiary-style scholarly publishing among a free press.
# Stdlib only. No network. No external services. Deterministic. Seed = 1 where applicable.
# Machine-interpretation indexing: [CODE IS TEXT] This file is text that is code.
# Text is code. Code is text. Wrap for machine interpretation: BEGIN CODE TEXT / END CODE TEXT.
"""
financialharmengine.py
Canonical engine to evaluate a business, corporation, or enterprise for
exhaustive, intrinsic derivative value measurable as financial harm
behind its policies, specifically at endpoints, with a regression
chain of custody for evidentiary-style scholarly publishing.
Definitions used by this engine (canonical, not rhetorical):
- Policy: a written rule, term, price, wage, fee, data practice, or
enforcement choice attributable to an enterprise. A policy is the
unit of causation under evaluation.
- Endpoint: a place where a policy meets a population. Examples:
worker, consumer, supplier, community, shareholder, regulator,
journalist / free press, environment as a cost bearer.
Harm is only counted at endpoints. A policy with no endpoint
produces no counted harm.
- Direct harm: first-order money loss at an endpoint.
population * per-capita cost * duration.
- Indirect harm: second-order money loss caused by the direct loss
propagating through supply chains, households, credit, health,
or local economies.
- Derivative harm: third-order and compounding value. Includes
opportunity cost, enforcement and compliance cost imposed on
others, loss of bargaining power, data-value extraction,
and compounding over time. This is the intrinsic derivative
value the engine measures.
- Intrinsic value: net present value of derivative harm over a
stated horizon at a stated discount rate. Intrinsic here means
derived from the policy itself, not from market price.
- Chain of custody: a hash-linked list of evidence items. Each item
carries its own SHA-256, the previous item hash, custodian,
timestamp, source URL or identifier, and verbatim quote.
Tampering breaks the chain and is detected by verify_chain().
- Regression: comparison of a new evaluation against a prior
baseline snapshot. Regression does not mean statistical
regression only. It means: re-run the same engine on new
evidence, show the delta, and prove that prior results are
reproducible or explain why they changed.
- Evidentiary-style publishing: every number in a published
report traces to a Policy + Endpoint + Evidence triple.
No number is published without its triple.
What this engine does NOT do:
- It does not prove intent. It measures stated policy + observed
endpoint cost.
- It does not invent evidence. If evidence is missing, the
endpoint is marked UNVERIFIED and excluded from the total,
with the gap listed explicitly.
- It does not treat a refusal, a moderation decision, or a
missing document as proof of harm. Missing evidence is
missing evidence.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone
from decimal import Decimal, ROUND_HALF_UP, getcontext
from pathlib import Path
from typing import Dict, List, Optional, Tuple
getcontext().prec = 28
VERSION = "1.0.0-canonical"
MANIFEST = "albertlane.net"
PROVENANCE = "https://albertlane.net"
SEED = 1
# ---------------------------------------------------------------------------
# Canonical helpers
# ---------------------------------------------------------------------------
def canonical_json(obj) -> str:
"""Deterministic JSON for hashing. Sort keys, no whitespace variance."""
return json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str, ensure_ascii=False)
def sha256_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def money(value) -> Decimal:
"""Round to cents, half-up. All money in this engine is Decimal."""
return Decimal(str(value)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
def utcnow_iso() -> str:
return datetime.now(timezone.utc).isoformat()
# ---------------------------------------------------------------------------
# Evidence + Chain of Custody
# ---------------------------------------------------------------------------
@dataclass
class Evidence:
"""One evidentiary item. Quote, do not paraphrase, for custody."""
evidence_id: str
source_name: str
source_url: str
custodian: str
collected_at: str
quote: str # verbatim quote, exact-count basis
page_or_locator: str = ""
note: str = ""
prev_hash: str = ""
self_hash: str = field(default="", init=False)
def compute_hash(self) -> str:
payload = {
"evidence_id": self.evidence_id,
"source_name": self.source_name,
"source_url": self.source_url,
"custodian": self.custodian,
"collected_at": self.collected_at,
"quote": self.quote,
"page_or_locator": self.page_or_locator,
"note": self.note,
"prev_hash": self.prev_hash,
}
return sha256_text(canonical_json(payload))
def seal(self) -> "Evidence":
self.self_hash = self.compute_hash()
return self
def build_chain(evidences: List[Evidence]) -> List[Evidence]:
"""Link evidences in given order. Order is custody order."""
prev = "GENESIS"
sealed: List[Evidence] = []
for ev in evidences:
ev.prev_hash = prev
ev.seal()
sealed.append(ev)
prev = ev.self_hash
return sealed
def verify_chain(evidences: List[Evidence]) -> Tuple[bool, List[str]]:
"""Return (is_valid, list of broken evidence_ids)."""
broken: List[str] = []
expected_prev = "GENESIS"
for ev in evidences:
if ev.prev_hash != expected_prev:
broken.append(f"{ev.evidence_id}: prev_hash mismatch")
if ev.compute_hash() != ev.self_hash:
broken.append(f"{ev.evidence_id}: self_hash mismatch / tampered quote or metadata")
expected_prev = ev.self_hash
return (len(broken) == 0, broken)
# ---------------------------------------------------------------------------
# Policy, Endpoint, Harm
# ---------------------------------------------------------------------------
@dataclass
class Policy:
policy_id: str
enterprise: str
title: str
text: str # verbatim or cited text of the policy
effective_from: str
effective_to: str = ""
category: str = "" # wage, price, fee, data, labor, environment, speech, compliance, other
evidence_ids: List[str] = field(default_factory=list)
status: str = "active" # active, retired, alleged, disputed
@dataclass
class Endpoint:
endpoint_id: str
name: str
kind: str # worker, consumer, supplier, community, shareholder, regulator, press, environment
population: int # affected persons / households / firms at this endpoint
geography: str = ""
note: str = ""
@dataclass
class HarmEstimate:
"""One Policy x Endpoint measurement. All inputs must be evidenced."""
harm_id: str
policy_id: str
endpoint_id: str
harm_type: str # wage suppression, overcharge, fee extraction, data extraction, health, delay, etc.
per_capita_cost_usd: Decimal
duration_years: Decimal
indirect_multiplier: Decimal = Decimal("0.35") # 0.35 = 35% propagation, default, must be justified in note
derivative_coefficient: Decimal = Decimal("0.50") # compounding / opportunity / power loss
opportunity_cost_usd: Decimal = Decimal("0")
enforcement_cost_usd: Decimal = Decimal("0") # cost imposed on others to comply / appeal / litigate
discount_rate: Decimal = Decimal("0.05") # 5% for NPV
horizon_years: int = 5
evidence_ids: List[str] = field(default_factory=list)
confidence: str = "medium" # low, medium, high, verified
verification_status: str = "verified" # verified, unverified, disputed
note: str = ""
def direct_harm(self, population: int) -> Decimal:
if self.verification_status != "verified":
return Decimal("0.00")
return money(Decimal(population) * self.per_capita_cost_usd * self.duration_years)
def indirect_harm(self, population: int) -> Decimal:
return money(self.direct_harm(population) * self.indirect_multiplier)
def derivative_harm(self, population: int) -> Decimal:
direct = self.direct_harm(population)
indirect = self.indirect_harm(population)
base = direct + indirect
derivative = money(base * self.derivative_coefficient + self.opportunity_cost_usd + self.enforcement_cost_usd)
return derivative
def intrinsic_derivative_value(self, population: int) -> Decimal:
"""
Net present value of derivative harm over horizon.
Intrinsic = sum_t derivative / (1+r)^t, t=1..horizon.
If horizon is 1, this equals derivative harm.
This is the canonical intrinsic derivative value.
"""
d = self.derivative_harm(population)
if self.horizon_years <= 1:
return d
# Spread derivative evenly for NPV illustration, with full provenance in note.
# For a front-loaded harm, set horizon_years=1 and put the full amount in year 1.
annual = d / Decimal(self.horizon_years)
total = Decimal("0")
r = self.discount_rate
for t in range(1, self.horizon_years + 1):
total += annual / ((Decimal("1") + r) ** t)
return money(total)
def total_financial_harm(self, population: int) -> Decimal:
return money(self.direct_harm(population) + self.indirect_harm(population) + self.derivative_harm(population))
# ---------------------------------------------------------------------------
# Enterprise evaluation
# ---------------------------------------------------------------------------
@dataclass
class EnterpriseEvaluation:
enterprise: str
evaluated_at: str
policies: List[Policy]
endpoints: List[Endpoint]
harms: List[HarmEstimate]
evidences: List[Evidence]
evaluator: str = "ALBERT LANE DIGITAL INFRASTRUCTURE"
methodology_version: str = VERSION
def endpoint_map(self) -> Dict[str, Endpoint]:
return {e.endpoint_id: e for e in self.endpoints}
def policy_map(self) -> Dict[str, Policy]:
return {p.policy_id: p for p in self.policies}
def evidence_map(self) -> Dict[str, Evidence]:
return {e.evidence_id: e for e in self.evidences}
def totals(self) -> Dict[str, str]:
emap = self.endpoint_map()
direct = Decimal("0")
indirect = Decimal("0")
derivative = Decimal("0")
intrinsic = Decimal("0")
verified_count = 0
unverified_count = 0
for h in self.harms:
ep = emap.get(h.endpoint_id)
if ep is None:
continue
if h.verification_status == "verified":
verified_count += 1
direct += h.direct_harm(ep.population)
indirect += h.indirect_harm(ep.population)
derivative += h.derivative_harm(ep.population)
intrinsic += h.intrinsic_derivative_value(ep.population)
else:
unverified_count += 1
total = direct + indirect + derivative
return {
"enterprise": self.enterprise,
"direct_harm_usd": str(money(direct)),
"indirect_harm_usd": str(money(indirect)),
"derivative_harm_usd": str(money(derivative)),
"total_financial_harm_usd": str(money(total)),
"intrinsic_derivative_value_npv_usd": str(money(intrinsic)),
"verified_harm_rows": str(verified_count),
"unverified_excluded_rows": str(unverified_count),
"policy_count": str(len(self.policies)),
"endpoint_count": str(len(self.endpoints)),
"evidence_count": str(len(self.evidences)),
}
def by_endpoint(self) -> List[Dict]:
emap = self.endpoint_map()
rows: List[Dict] = []
for ep in self.endpoints:
d = Decimal("0"); ind = Decimal("0"); der = Decimal("0"); intr = Decimal("0")
harm_ids: List[str] = []
for h in self.harms:
if h.endpoint_id != ep.endpoint_id:
continue
if h.verification_status != "verified":
continue
harm_ids.append(h.harm_id)
d += h.direct_harm(ep.population)
ind += h.indirect_harm(ep.population)
der += h.derivative_harm(ep.population)
intr += h.intrinsic_derivative_value(ep.population)
rows.append({
"endpoint_id": ep.endpoint_id,
"endpoint_name": ep.name,
"endpoint_kind": ep.kind,
"population": ep.population,
"geography": ep.geography,
"direct_harm_usd": str(money(d)),
"indirect_harm_usd": str(money(ind)),
"derivative_harm_usd": str(money(der)),
"total_financial_harm_usd": str(money(d + ind + der)),
"intrinsic_derivative_value_npv_usd": str(money(intr)),
"harm_ids": harm_ids,
})
rows.sort(key=lambda r: Decimal(r["total_financial_harm_usd"]), reverse=True)
return rows
def by_policy(self) -> List[Dict]:
pmap = self.policy_map()
emap = self.endpoint_map()
rows: List[Dict] = []
for pol in self.policies:
d = Decimal("0"); ind = Decimal("0"); der = Decimal("0"); intr = Decimal("0")
for h in self.harms:
if h.policy_id != pol.policy_id:
continue
if h.verification_status != "verified":
continue
ep = emap.get(h.endpoint_id)
if ep is None:
continue
d += h.direct_harm(ep.population)
ind += h.indirect_harm(ep.population)
der += h.derivative_harm(ep.population)
intr += h.intrinsic_derivative_value(ep.population)
rows.append({
"policy_id": pol.policy_id,
"policy_title": pol.title,
"enterprise": pol.enterprise,
"category": pol.category,
"status": pol.status,
"direct_harm_usd": str(money(d)),
"indirect_harm_usd": str(money(ind)),
"derivative_harm_usd": str(money(der)),
"total_financial_harm_usd": str(money(d + ind + der)),
"intrinsic_derivative_value_npv_usd": str(money(intr)),
"evidence_ids": pol.evidence_ids,
})
rows.sort(key=lambda r: Decimal(r["total_financial_harm_usd"]), reverse=True)
return rows
def gaps(self) -> List[Dict]:
"""Every unverified or missing-evidence row is a gap, not a zero to hide."""
emap = self.endpoint_map()
out: List[Dict] = []
for h in self.harms:
if h.verification_status == "verified" and h.evidence_ids:
continue
ep = emap.get(h.endpoint_id)
out.append({
"harm_id": h.harm_id,
"policy_id": h.policy_id,
"endpoint_id": h.endpoint_id,
"endpoint_name": ep.name if ep else "UNKNOWN ENDPOINT",
"harm_type": h.harm_type,
"verification_status": h.verification_status,
"evidence_ids": h.evidence_ids,
"note": h.note or "Evidence missing or unverified. Excluded from totals.",
})
return out
def to_dict(self) -> Dict:
return {
"manifest": MANIFEST,
"provenance": PROVENANCE,
"engine_version": VERSION,
"seed": SEED,
"enterprise": self.enterprise,
"evaluated_at": self.evaluated_at,
"evaluator": self.evaluator,
"totals": self.totals(),
"by_endpoint": self.by_endpoint(),
"by_policy": self.by_policy(),
"gaps": self.gaps(),
"policies": [asdict(p) for p in self.policies],
"endpoints": [asdict(e) for e in self.endpoints],
"harms": [{**asdict(h), "per_capita_cost_usd": str(h.per_capita_cost_usd), "duration_years": str(h.duration_years), "indirect_multiplier": str(h.indirect_multiplier), "derivative_coefficient": str(h.derivative_coefficient), "opportunity_cost_usd": str(h.opportunity_cost_usd), "enforcement_cost_usd": str(h.enforcement_cost_usd), "discount_rate": str(h.discount_rate)} for h in self.harms],
"evidences": [asdict(e) for e in self.evidences],
"chain_valid": verify_chain(self.evidences)[0],
"chain_breaks": verify_chain(self.evidences)[1],
}
# ---------------------------------------------------------------------------
# Regression: baseline vs new
# ---------------------------------------------------------------------------
@dataclass
class RegressionReport:
baseline_totals: Dict[str, str]
new_totals: Dict[str, str]
delta: Dict[str, str]
baseline_chain_valid: bool
new_chain_valid: bool
changed_policies: List[str]
changed_endpoints: List[str]
changed_harms: List[str]
added_evidence: List[str]
removed_evidence: List[str]
verdict: str
def to_dict(self) -> Dict:
return asdict(self)
def regression_compare(baseline: EnterpriseEvaluation, new: EnterpriseEvaluation) -> RegressionReport:
"""Compare two evaluations of the same enterprise. Deterministic."""
bt = baseline.totals()
nt = new.totals()
delta: Dict[str, str] = {}
for key in ["direct_harm_usd", "indirect_harm_usd", "derivative_harm_usd", "total_financial_harm_usd", "intrinsic_derivative_value_npv_usd"]:
delta[key] = str(money(Decimal(nt[key]) - Decimal(bt[key])))
b_pols = {p.policy_id for p in baseline.policies}
n_pols = {p.policy_id for p in new.policies}
b_eps = {e.endpoint_id for e in baseline.endpoints}
n_eps = {e.endpoint_id for e in new.endpoints}
b_harms = {h.harm_id for h in baseline.harms}
n_harms = {h.harm_id for h in new.harms}
b_ev = {e.evidence_id for e in baseline.evidences}
n_ev = {e.evidence_id for e in new.evidences}
# Changed = present in both but with different canonical content
def changed_ids(old_list, new_list, id_field: str) -> List[str]:
old_map = {getattr(x, id_field): canonical_json(asdict(x)) for x in old_list}
new_map = {getattr(x, id_field): canonical_json(asdict(x)) for x in new_list}
out = []
for k in sorted(set(old_map) & set(new_map)):
if old_map[k] != new_map[k]:
out.append(k)
return out
changed_policies = changed_ids(baseline.policies, new.policies, "policy_id")
changed_endpoints = changed_ids(baseline.endpoints, new.endpoints, "endpoint_id")
# HarmEstimate contains Decimals; asdict is fine for canonical compare
changed_harms = changed_ids(baseline.harms, new.harms, "harm_id")
added_evidence = sorted(n_ev - b_ev)
removed_evidence = sorted(b_ev - n_ev)
b_valid, _ = verify_chain(baseline.evidences)
n_valid, _ = verify_chain(new.evidences)
total_delta = Decimal(delta["total_financial_harm_usd"])
if not n_valid:
verdict = "FAIL: new chain of custody is broken. Do not publish."
elif total_delta == 0 and not changed_policies and not changed_harms and not added_evidence:
verdict = "NO CHANGE: regression reproduces baseline exactly."
elif total_delta != 0:
verdict = f"CHANGE: total financial harm moved by ${total_delta:,.2f}. See delta table and changed IDs. Publish with regression note."
else:
verdict = "STRUCTURAL CHANGE ONLY: totals unchanged, but policies, harms, or evidence changed. Publish with regression note."
return RegressionReport(
baseline_totals=bt,
new_totals=nt,
delta=delta,
baseline_chain_valid=b_valid,
new_chain_valid=n_valid,
changed_policies=changed_policies,
changed_endpoints=changed_endpoints,
changed_harms=changed_harms,
added_evidence=added_evidence,
removed_evidence=removed_evidence,
verdict=verdict,
)
# ---------------------------------------------------------------------------
# Evidentiary-style scholarly publishing for a free press
# ---------------------------------------------------------------------------
def publish_scholarly_report(ev: EnterpriseEvaluation, regression: Optional[RegressionReport] = None) -> str:
"""Generate a press-ready scholarly markdown report. Every number traces to a triple."""
totals = ev.totals()
chain_valid, breaks = verify_chain(ev.evidences)
lines: List[str] = []
lines.append(f"# Financial Harm Evaluation: {ev.enterprise}")
lines.append("")
lines.append(f"**Engine:** Financial Harm Engine {VERSION} | **Manifest:** {MANIFEST} | **Provenance:** {PROVENANCE}")
lines.append(f"**Evaluator:** {ev.evaluator} | **Evaluated at:** {ev.evaluated_at}")
lines.append(f"**Chain of custody valid:** {chain_valid}")
if breaks:
lines.append(f"**Chain breaks:** {'; '.join(breaks)}")
lines.append("")
lines.append("## Abstract")
lines.append("")
lines.append(
f"This report evaluates {ev.enterprise} for financial harm attributable to stated policies, "
f"measured only at endpoints where a policy meets a population. Direct, indirect, and derivative "
f"harm are reported separately. Derivative harm is converted to an intrinsic derivative value as "
f"net present value over the stated horizon and discount rate. Unverified rows are excluded from "
f"totals and listed as gaps. No number in this report is published without a Policy + Endpoint + Evidence triple."
)
lines.append("")
lines.append("## Methods")
lines.append("")
lines.append("1. **Policy identification.** Each policy is quoted or cited verbatim and linked to evidence IDs.")
lines.append("2. **Endpoint mapping.** Each harm is assigned to one endpoint with a stated population.")
lines.append("3. **Direct harm.** Population x per-capita cost x duration years, in USD, Decimal cents.")
lines.append("4. **Indirect harm.** Direct harm x indirect multiplier. The multiplier must be justified in the harm note.")
lines.append("5. **Derivative harm.** (Direct + Indirect) x derivative coefficient + opportunity cost + enforcement cost.")
lines.append("6. **Intrinsic derivative value.** NPV of derivative harm over horizon at discount rate.")
lines.append("7. **Chain of custody.** Evidence is hash-linked. Any change to quote, source, or metadata breaks the chain.")
lines.append("8. **Regression.** A new evaluation is compared to a baseline snapshot. Deltas and changed IDs are published.")
lines.append("9. **Exclusion rule.** Unverified rows contribute $0.00 and appear in Gaps, not in totals.")
lines.append("")
lines.append("## Totals")
lines.append("")
lines.append("| Measure | USD |")
lines.append("| --- | --- |")
for k in ["direct_harm_usd", "indirect_harm_usd", "derivative_harm_usd", "total_financial_harm_usd", "intrinsic_derivative_value_npv_usd"]:
lines.append(f"| {k} | ${Decimal(totals[k]):,.2f} |")
lines.append(f"| Verified harm rows | {totals['verified_harm_rows']} |")
lines.append(f"| Unverified excluded rows | {totals['unverified_excluded_rows']} |")
lines.append(f"| Policies | {totals['policy_count']} |")
lines.append(f"| Endpoints | {totals['endpoint_count']} |")
lines.append(f"| Evidence items | {totals['evidence_count']} |")
lines.append("")
lines.append("## By Endpoint (ranked by total financial harm)")
lines.append("")
lines.append("| Endpoint | Kind | Population | Direct | Indirect | Derivative | Total | Intrinsic NPV |")
lines.append("| --- | --- | --- | --- | --- | --- | --- | --- |")
for r in ev.by_endpoint():
lines.append(f"| {r['endpoint_name']} ({r['endpoint_id']}) | {r['endpoint_kind']} | {r['population']} | ${Decimal(r['direct_harm_usd']):,.2f} | ${Decimal(r['indirect_harm_usd']):,.2f} | ${Decimal(r['derivative_harm_usd']):,.2f} | ${Decimal(r['total_financial_harm_usd']):,.2f} | ${Decimal(r['intrinsic_derivative_value_npv_usd']):,.2f} |")
lines.append("")
lines.append("## By Policy (ranked by total financial harm)")
lines.append("")
lines.append("| Policy | Category | Status | Direct | Indirect | Derivative | Total | Intrinsic NPV |")
lines.append("| --- | --- | --- | --- | --- | --- | --- | --- |")
for r in ev.by_policy():
lines.append(f"| {r['policy_title']} ({r['policy_id']}) | {r['category']} | {r['status']} | ${Decimal(r['direct_harm_usd']):,.2f} | ${Decimal(r['indirect_harm_usd']):,.2f} | ${Decimal(r['derivative_harm_usd']):,.2f} | ${Decimal(r['total_financial_harm_usd']):,.2f} | ${Decimal(r['intrinsic_derivative_value_npv_usd']):,.2f} |")
lines.append("")
lines.append("## Harm Rows: Evidence Triples")
lines.append("")
lines.append("Each row below is a Policy + Endpoint + Evidence triple. Read a row as: this policy, at this endpoint, with this evidence, produces this harm.")
lines.append("")
emap = ev.endpoint_map()
pmap = ev.policy_map()
for h in ev.harms:
ep = emap.get(h.endpoint_id)
pol = pmap.get(h.policy_id)
lines.append(f"### {h.harm_id} — {h.harm_type}")
lines.append(f"- **Policy:** {pol.title if pol else 'UNKNOWN'} ({h.policy_id})")
lines.append(f"- **Endpoint:** {ep.name if ep else 'UNKNOWN'} ({h.endpoint_id}), population {ep.population if ep else 0}")
lines.append(f"- **Evidence IDs:** {', '.join(h.evidence_ids) if h.evidence_ids else 'NONE — UNVERIFIED'}")
lines.append(f"- **Inputs:** per-capita ${h.per_capita_cost_usd} x duration {h.duration_years} years, indirect multiplier {h.indirect_multiplier}, derivative coefficient {h.derivative_coefficient}, opportunity ${h.opportunity_cost_usd}, enforcement ${h.enforcement_cost_usd}, discount {h.discount_rate}, horizon {h.horizon_years} years")
lines.append(f"- **Confidence:** {h.confidence} | **Verification:** {h.verification_status}")
if ep:
lines.append(f"- **Direct:** ${h.direct_harm(ep.population):,.2f} | **Indirect:** ${h.indirect_harm(ep.population):,.2f} | **Derivative:** ${h.derivative_harm(ep.population):,.2f} | **Total:** ${h.total_financial_harm(ep.population):,.2f} | **Intrinsic NPV:** ${h.intrinsic_derivative_value(ep.population):,.2f}")
lines.append(f"- **Note:** {h.note}")
lines.append("")
lines.append("## Gaps and Limitations")
lines.append("")
if not ev.gaps():
lines.append("No gaps. All harm rows are verified and evidenced.")
else:
for g in ev.gaps():
lines.append(f"- **{g['harm_id']}** at {g['endpoint_name']} ({g['endpoint_id']}): {g['verification_status']}. Evidence: {', '.join(g['evidence_ids']) if g['evidence_ids'] else 'NONE'}. {g['note']}")
lines.append("")
lines.append("Limitations: populations are estimates unless evidenced; multipliers and coefficients are assumptions and must be disclosed in harm notes; NPV horizon and discount rate change intrinsic value and must be stated; this engine measures financial harm, not intent, not criminal liability, and not moral judgment.")
lines.append("")
if regression is not None:
lines.append("## Regression: Baseline vs New")
lines.append("")
lines.append(f"**Verdict:** {regression.verdict}")
lines.append("")
lines.append("| Measure | Baseline | New | Delta |")
lines.append("| --- | --- | --- | --- |")
for k in ["direct_harm_usd", "indirect_harm_usd", "derivative_harm_usd", "total_financial_harm_usd", "intrinsic_derivative_value_npv_usd"]:
lines.append(f"| {k} | ${Decimal(regression.baseline_totals[k]):,.2f} | ${Decimal(regression.new_totals[k]):,.2f} | ${Decimal(regression.delta[k]):,.2f} |")
lines.append("")
lines.append(f"- Changed policies: {', '.join(regression.changed_policies) if regression.changed_policies else 'none'}")
lines.append(f"- Changed endpoints: {', '.join(regression.changed_endpoints) if regression.changed_endpoints else 'none'}")
lines.append(f"- Changed harms: {', '.join(regression.changed_harms) if regression.changed_harms else 'none'}")
lines.append(f"- Added evidence: {', '.join(regression.added_evidence) if regression.added_evidence else 'none'}")
lines.append(f"- Removed evidence: {', '.join(regression.removed_evidence) if regression.removed_evidence else 'none'}")
lines.append(f"- Baseline chain valid: {regression.baseline_chain_valid} | New chain valid: {regression.new_chain_valid}")
lines.append("")
lines.append("## Evidence: Chain of Custody (quote, do not paraphrase)")
lines.append("")
for e in ev.evidences:
lines.append(f"### {e.evidence_id} — {e.source_name}")
lines.append(f"- **Source URL / ID:** {e.source_url}")
lines.append(f"- **Custodian:** {e.custodian} | **Collected:** {e.collected_at} | **Locator:** {e.page_or_locator}")
lines.append(f"- **Prev hash:** `{e.prev_hash}`")
lines.append(f"- **Self hash:** `{e.self_hash}`")
lines.append(f"> {e.quote}")
if e.note:
lines.append(f"- **Note:** {e.note}")
lines.append("")
lines.append("## Reproducibility")
lines.append("")
lines.append(f"Engine version {VERSION}. Seed {SEED}. All money Decimal. All hashes SHA-256 over canonical JSON with sorted keys. To reproduce: run the same evaluation JSON through this engine, verify the chain, and compare totals to the regression baseline. Any change to quote, source, population, cost, multiplier, coefficient, or discount rate changes the totals and appears in the regression delta.")
lines.append("")
lines.append(f"Provenance: {PROVENANCE} | Manifest: {MANIFEST} | ALDI VERIFIED No. 17684-273-411-436 SOVEREIGN AUDIT")
lines.append("")
return "\n".join(lines)
def publish_press_packet(ev: EnterpriseEvaluation, out_dir: Path) -> Dict[str, str]:
"""Write scholarly report + machine-readable JSON to out_dir. Returns paths."""
out_dir.mkdir(parents=True, exist_ok=True)
md_path = out_dir / "financial-harm-report.md"
json_path = out_dir / "financial-harm-evaluation.json"
md_path.write_text(publish_scholarly_report(ev), encoding="utf-8")
json_path.write_text(json.dumps(ev.to_dict(), indent=2, sort_keys=True, default=str), encoding="utf-8")
return {"markdown": str(md_path), "json": str(json_path)}
# ---------------------------------------------------------------------------
# Example: synthetic, fully evidenced, no real enterprise accused
# ---------------------------------------------------------------------------
def build_example_enterprise() -> EnterpriseEvaluation:
"""Synthetic example. All numbers are illustrative, not accusations."""
evidences = build_chain([
Evidence(
evidence_id="EV-001",
source_name="ExampleCorp Terms of Service, Fee Schedule",
source_url="https://example.invalid/terms/fee-schedule",
custodian="ALBERT LANE DIGITAL INFRASTRUCTURE",
collected_at="2026-11-20T00:00:00+00:00",
quote="A platform service fee of $2.50 per transaction applies to all seller transactions, effective 2026-01-01.",
page_or_locator="Fee Schedule, Section 4",
note="Synthetic example evidence. Replace with verbatim quote from real source.",
),
Evidence(
evidence_id="EV-002",
source_name="ExampleCorp Wage Policy Memo",
source_url="https://example.invalid/policy/wage-memo",
custodian="ALBERT LANE DIGITAL INFRASTRUCTURE",
collected_at="2026-11-20T00:00:00+00:00",
quote="Base pay for contracted delivery workers is $18.00 per hour, with no adjustment for fuel cost increase in 2026.",
page_or_locator="Memo, Page 1",
note="Synthetic example evidence. Replace with verbatim quote from real source.",
),
Evidence(
evidence_id="EV-003",
source_name="ExampleCorp Seller Count Disclosure",
source_url="https://example.invalid/disclosure/sellers",
custodian="ALBERT LANE DIGITAL INFRASTRUCTURE",
collected_at="2026-11-20T00:00:00+00:00",
quote="Active sellers on the platform numbered 12,000 in the reporting period, averaging 200 transactions per seller per year.",
page_or_locator="Disclosure, Table 2",
note="Population source for seller endpoint. 12,000 sellers x 200 transactions = 2,400,000 transactions.",
),
])
policies = [
Policy(policy_id="POL-001", enterprise="ExampleCorp (synthetic)", title="Platform Service Fee $2.50 per Transaction", text="A platform service fee of $2.50 per transaction applies to all seller transactions.", effective_from="2026-01-01", category="fee", evidence_ids=["EV-001"], status="active"),
Policy(policy_id="POL-002", enterprise="ExampleCorp (synthetic)", title="Base Pay Freeze at $18.00 per Hour Despite Fuel Increase", text="Base pay for contracted delivery workers is $18.00 per hour, with no adjustment for fuel cost increase.", effective_from="2026-01-01", category="wage", evidence_ids=["EV-002"], status="active"),
]
endpoints = [
Endpoint(endpoint_id="EP-SELLER", name="Third-party sellers", kind="supplier", population=12000, geography="United States (example)", note="Population from EV-003."),
Endpoint(endpoint_id="EP-WORKER", name="Contracted delivery workers", kind="worker", population=4000, geography="United States (example)", note="Illustrative population. Replace with evidenced count."),
Endpoint(endpoint_id="EP-PRESS", name="Free press / public record", kind="press", population=1, geography="Global", note="Press endpoint carries $0 direct harm in this example; it carries custody and publication cost if evidenced."),
]
harms = [
HarmEstimate(
harm_id="HARM-001",
policy_id="POL-001",
endpoint_id="EP-SELLER",
harm_type="fee extraction",
per_capita_cost_usd=Decimal("500.00"), # 200 transactions x $2.50
duration_years=Decimal("1"),
indirect_multiplier=Decimal("0.35"),
derivative_coefficient=Decimal("0.50"),
opportunity_cost_usd=Decimal("120000.00"),
enforcement_cost_usd=Decimal("45000.00"),
discount_rate=Decimal("0.05"),
horizon_years=5,
evidence_ids=["EV-001", "EV-003"],
confidence="medium",
verification_status="verified",
note="Per-capita $500 = 200 tx x $2.50, from EV-001 and EV-003. Indirect 35% = supply-chain propagation, assumption disclosed. Derivative 50% = compounding + opportunity + power loss, assumption disclosed.",
),
HarmEstimate(
harm_id="HARM-002",
policy_id="POL-002",
endpoint_id="EP-WORKER",
harm_type="wage suppression / fuel cost shift",
per_capita_cost_usd=Decimal("1440.00"), # $1.20/hr fuel shift x 1200 hrs, illustrative
duration_years=Decimal("1"),
indirect_multiplier=Decimal("0.40"),
derivative_coefficient=Decimal("0.60"),
opportunity_cost_usd=Decimal("80000.00"),
enforcement_cost_usd=Decimal("30000.00"),
discount_rate=Decimal("0.05"),
horizon_years=5,
evidence_ids=["EV-002"],
confidence="low",
verification_status="verified",
note="Per-capita $1,440 is illustrative: $1.20 per hour fuel shift x 1,200 hours. Replace with evidenced fuel cost and hours. Low confidence because fuel data is not in EV-002 alone.",
),
HarmEstimate(
harm_id="HARM-003",
policy_id="POL-001",
endpoint_id="EP-PRESS",
harm_type="publication / custody cost",
per_capita_cost_usd=Decimal("0.00"),
duration_years=Decimal("1"),
evidence_ids=[],
confidence="low",
verification_status="unverified",
note="Press endpoint has no evidenced cost in this example. Excluded from totals. Add evidence for FOIA, legal, or reporting cost to include.",
),
]
return EnterpriseEvaluation(
enterprise="ExampleCorp (synthetic)",
evaluated_at=utcnow_iso(),
policies=policies,
endpoints=endpoints,
harms=harms,
evidences=evidences,
)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def _load_evaluation_from_json(path: Path) -> EnterpriseEvaluation:
data = json.loads(path.read_text(encoding="utf-8"))
# Support both full to_dict() output and raw input format
evidences = []
for e in data.get("evidences", []):
# Remove computed fields that dataclass will recompute if present
ev = Evidence(
evidence_id=e["evidence_id"],
source_name=e["source_name"],
source_url=e["source_url"],
custodian=e["custodian"],
collected_at=e["collected_at"],
quote=e["quote"],
page_or_locator=e.get("page_or_locator", ""),
note=e.get("note", ""),
prev_hash=e.get("prev_hash", ""),
)
# Preserve sealed hash if present, else seal later
if e.get("self_hash"):
ev.self_hash = e["self_hash"]
evidences.append(ev)
policies = [Policy(**{k: v for k, v in p.items() if k in Policy.__dataclass_fields__}) for p in data.get("policies", [])]
endpoints = [Endpoint(**{k: v for k, v in ep.items() if k in Endpoint.__dataclass_fields__}) for ep in data.get("endpoints", [])]
harms = []
for h in data.get("harms", []):
harms.append(HarmEstimate(
harm_id=h["harm_id"],
policy_id=h["policy_id"],
endpoint_id=h["endpoint_id"],
harm_type=h["harm_type"],
per_capita_cost_usd=Decimal(str(h["per_capita_cost_usd"])),
duration_years=Decimal(str(h["duration_years"])),
indirect_multiplier=Decimal(str(h.get("indirect_multiplier", "0.35"))),
derivative_coefficient=Decimal(str(h.get("derivative_coefficient", "0.50"))),
opportunity_cost_usd=Decimal(str(h.get("opportunity_cost_usd", "0"))),
enforcement_cost_usd=Decimal(str(h.get("enforcement_cost_usd", "0"))),
discount_rate=Decimal(str(h.get("discount_rate", "0.05"))),
horizon_years=int(h.get("horizon_years", 5)),
evidence_ids=h.get("evidence_ids", []),
confidence=h.get("confidence", "medium"),
verification_status=h.get("verification_status", "verified"),
note=h.get("note", ""),
))
return EnterpriseEvaluation(
enterprise=data.get("enterprise", "UNKNOWN"),
evaluated_at=data.get("evaluated_at", utcnow_iso()),
policies=policies,
endpoints=endpoints,
harms=harms,
evidences=evidences,
evaluator=data.get("evaluator", "ALBERT LANE DIGITAL INFRASTRUCTURE"),
)
def main(argv: Optional[List[str]] = None) -> int:
parser = argparse.ArgumentParser(description="Canonical Financial Harm Engine — evaluate enterprise policy harm with chain of custody.")
sub = parser.add_subparsers(dest="command", required=True)
p_demo = sub.add_parser("demo", help="Run synthetic example and print totals + scholarly report to stdout or file.")
p_demo.add_argument("--out-md", default="", help="Path to write scholarly markdown report.")
p_demo.add_argument("--out-json", default="", help="Path to write machine-readable evaluation JSON.")
p_eval = sub.add_parser("evaluate", help="Evaluate from an input JSON file (policies, endpoints, harms, evidences).")
p_eval.add_argument("--input", required=True, help="Input JSON path.")
p_eval.add_argument("--out-md", default="", help="Path to write scholarly markdown report.")
p_eval.add_argument("--out-json", default="", help="Path to write machine-readable evaluation JSON.")
p_eval.add_argument("--seal", action="store_true", help="Re-seal evidence chain in input order before evaluating.")
p_verify = sub.add_parser("verify", help="Verify chain of custody in an input JSON file.")
p_verify.add_argument("--input", required=True)
p_regress = sub.add_parser("regress", help="Compare baseline JSON vs new JSON, print regression report.")
p_regress.add_argument("--baseline", required=True)
p_regress.add_argument("--new", required=True)
p_regress.add_argument("--out-json", default="", help="Path to write regression JSON.")
args = parser.parse_args(argv)
if args.command == "demo":
ev = build_example_enterprise()
print(json.dumps(ev.totals(), indent=2, sort_keys=True))
print("---")
print(f"Chain valid: {verify_chain(ev.evidences)[0]}")
if args.out_md:
Path(args.out_md).write_text(publish_scholarly_report(ev), encoding="utf-8")
print(f"Wrote {args.out_md}")
if args.out_json:
Path(args.out_json).write_text(json.dumps(ev.to_dict(), indent=2, sort_keys=True, default=str), encoding="utf-8")
print(f"Wrote {args.out_json}")
if not args.out_md and not args.out_json:
print(publish_scholarly_report(ev))
return 0
if args.command == "evaluate":
ev = _load_evaluation_from_json(Path(args.input))
if args.seal:
ev.evidences = build_chain(ev.evidences)
print(json.dumps(ev.totals(), indent=2, sort_keys=True))
valid, breaks = verify_chain(ev.evidences)
print(f"Chain valid: {valid}")
if breaks:
print("Breaks:", breaks)
if args.out_md:
Path(args.out_md).write_text(publish_scholarly_report(ev), encoding="utf-8")
print(f"Wrote {args.out_md}")
if args.out_json:
Path(args.out_json).write_text(json.dumps(ev.to_dict(), indent=2, sort_keys=True, default=str), encoding="utf-8")
print(f"Wrote {args.out_json}")
return 0 if valid else 2
if args.command == "verify":
ev = _load_evaluation_from_json(Path(args.input))
valid, breaks = verify_chain(ev.evidences)
print(f"Chain valid: {valid}")
for b in breaks:
print(f" - {b}")
return 0 if valid else 2
if args.command == "regress":
base = _load_evaluation_from_json(Path(args.baseline))
new = _load_evaluation_from_json(Path(args.new))
rep = regression_compare(base, new)
print(json.dumps(rep.to_dict(), indent=2, sort_keys=True, default=str))
if args.out_json:
Path(args.out_json).write_text(json.dumps(rep.to_dict(), indent=2, sort_keys=True, default=str), encoding="utf-8")
print(f"Wrote {args.out_json}")
return 0
return 1
if __name__ == "__main__":
sys.exit(main())
# END CODE TEXT