File size: 8,530 Bytes
0a7312a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

# sovereign_control_plane_report.py
from __future__ import annotations

import json
import os
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional

from sovereign_control_plane_profile import generate_control_plane_profile


CONTROL_PLANE_OUTPUT_DIR = "sovereign_control_plane_outputs"


def _utc_now() -> str:
    return datetime.now(timezone.utc).isoformat()


def _ensure_dir(path: str) -> None:
    os.makedirs(path, exist_ok=True)


def _safe(v: Any, default: Any = "") -> Any:
    return v if v is not None else default


def _bool_text(v: Any) -> str:
    return "True" if bool(v) else "False"


def _render_header(bundle: Dict[str, Any]) -> str:
    profile = bundle.get("control_plane_profile", {}) if isinstance(bundle, dict) else {}

    return f"""# Sovereign Control Plane Report

Generated at: {_safe((profile or {}).get("generated_at"), _utc_now())}

## 1. Profile Identity
- Profile Type: {_safe(profile.get("profile_type"), "Sovereign Control Plane Profile")}
- Domain: {_safe(profile.get("domain"), "banking_and_financial_institutions")}
"""


def _render_summary(bundle: Dict[str, Any]) -> str:
    profile = bundle.get("control_plane_profile", {}) if isinstance(bundle, dict) else {}
    summary = profile.get("summary", {}) if isinstance(profile, dict) else {}

    return f"""## 2. Executive Summary
- Total Actions: {_safe(summary.get("total_actions"), 0)}
- Supported Actions: {_safe(summary.get("supported_actions"), 0)}
- Forbidden Actions: {_safe(summary.get("forbidden_actions"), 0)}
- Dual-Control Actions: {_safe(summary.get("dual_control_actions"), 0)}
- Audit-Required Actions: {_safe(summary.get("audit_required_actions"), 0)}

### Practical Interpretation
- Sovereign distinguishes read-only visibility from state-changing administrative actions.
- High-impact actions are not treated as casual operator functions.
- Certain control-plane actions remain intentionally forbidden because they would collapse trust, auditability, or fail-safe posture.
- Dual control is expected for high-impact administrative mutations.
"""


def _render_actions(bundle: Dict[str, Any]) -> str:
    profile = bundle.get("control_plane_profile", {}) if isinstance(bundle, dict) else {}
    actions = profile.get("admin_actions", []) if isinstance(profile, dict) else []

    lines: List[str] = ["## 3. Administrative Action Inventory"]

    if not actions:
        lines.append("- No administrative actions recorded.")
        return "\n".join(lines)

    for item in actions:
        lines.append(f"### {item.get('action', 'unknown_action')}")
        lines.append(f"- Status: {_safe(item.get('status'))}")
        lines.append(f"- Sensitivity: {_safe(item.get('sensitivity'))}")
        lines.append(f"- Execution Class: {_safe(item.get('execution_class'))}")
        lines.append(f"- Human Approval Required: {_bool_text(item.get('human_approval_required'))}")
        lines.append(f"- Dual Control Required: {_bool_text(item.get('dual_control_required'))}")
        lines.append(f"- Audit Required: {_bool_text(item.get('audit_required'))}")
        lines.append(f"- Description: {_safe(item.get('description'))}")
        lines.append("")

    return "\n".join(lines).rstrip() + "\n"


def _render_principles(bundle: Dict[str, Any]) -> str:
    profile = bundle.get("control_plane_profile", {}) if isinstance(bundle, dict) else {}
    principles = profile.get("governance_principles", []) if isinstance(profile, dict) else []

    lines: List[str] = ["## 4. Governance Principles"]

    if not principles:
        lines.append("- No governance principles recorded.")
        return "\n".join(lines)

    for item in principles:
        lines.append(f"### {item.get('principle', 'unknown_principle')}")
        lines.append(f"- Status: {_safe(item.get('status'))}")
        lines.append(f"- Description: {_safe(item.get('description'))}")
        lines.append("")

    return "\n".join(lines).rstrip() + "\n"


def _render_governance_interpretation(bundle: Dict[str, Any]) -> str:
    profile = bundle.get("control_plane_profile", {}) if isinstance(bundle, dict) else {}
    actions = profile.get("admin_actions", []) if isinstance(profile, dict) else []

    forbidden = [a.get("action") for a in actions if str(a.get("status")) == "forbidden"]
    dual = [a.get("action") for a in actions if bool(a.get("dual_control_required"))]
    read_only = [a.get("action") for a in actions if str(a.get("execution_class")) == "read_only"]

    lines = ["## 5. Governance Interpretation"]

    if forbidden:
        lines.append("- Forbidden Administrative Classes:")
        for action in forbidden:
            lines.append(f"  - {action}")
    else:
        lines.append("- No forbidden administrative classes recorded.")

    if dual:
        lines.append("- Dual-Control Administrative Actions:")
        for action in dual:
            lines.append(f"  - {action}")
    else:
        lines.append("- No dual-control administrative actions recorded.")

    if read_only:
        lines.append("- Read-Only Administrative Actions:")
        for action in read_only:
            lines.append(f"  - {action}")
    else:
        lines.append("- No read-only administrative actions recorded.")

    lines.append("- Sensitive control-plane mutations should remain approval-bound and auditable.")
    lines.append("- Administrative power is intentionally bounded rather than broad or implicit.")
    lines.append("- Disabling audit, fail-safe, or unconditional allow boundaries is intentionally forbidden.")

    return "\n".join(lines)


def _render_artifact_status(bundle: Dict[str, Any]) -> str:
    seal = bundle.get("crypto_seal", {}) if isinstance(bundle, dict) else {}

    return f"""## 6. Artifact Status
- Sealed: {bool(bundle.get("sealed", False))}
- Seal Digest: {_safe(seal.get("seal_digest"), "")}
- Seal Scheme: {_safe(seal.get("scheme"), "")}
- Seal Algorithm: {_safe(seal.get("algorithm"), "")}
- Signer Hint: {_safe(seal.get("signer_hint"), "")}
"""


def _render_verdict(bundle: Dict[str, Any]) -> str:
    profile = bundle.get("control_plane_profile", {}) if isinstance(bundle, dict) else {}
    notes = profile.get("notes", []) if isinstance(profile, dict) else []

    verdict = (
        "Sovereign currently expresses a bounded bank-grade control-plane posture: "
        "administrative actions are classified, sensitive mutations are approval-bound, "
        "and trust-collapsing action classes remain intentionally forbidden."
    )

    lines = [
        "## 7. Preliminary Bank-Facing Verdict",
        verdict,
        "",
        "## 8. Notes",
    ]

    if notes:
        for item in notes:
            lines.append(f"- {item}")
    else:
        lines.append("- No additional notes provided.")

    return "\n".join(lines)


def build_control_plane_markdown(bundle: Dict[str, Any]) -> str:
    parts = [
        _render_header(bundle),
        _render_summary(bundle),
        _render_actions(bundle),
        _render_principles(bundle),
        _render_governance_interpretation(bundle),
        _render_artifact_status(bundle),
        _render_verdict(bundle),
    ]
    return "\n\n".join(parts).strip() + "\n"


def save_control_plane_report(
    bundle: Dict[str, Any],
    output_dir: str = CONTROL_PLANE_OUTPUT_DIR,
    base_name: Optional[str] = None,
) -> Dict[str, str]:
    _ensure_dir(output_dir)

    ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    base = base_name or f"sovereign_control_plane_report_{ts}"

    json_path = os.path.join(output_dir, f"{base}.json")
    md_path = os.path.join(output_dir, f"{base}.md")

    with open(json_path, "w", encoding="utf-8") as f:
        json.dump(bundle, f, ensure_ascii=False, indent=2)

    markdown = build_control_plane_markdown(bundle)
    with open(md_path, "w", encoding="utf-8") as f:
        f.write(markdown)

    return {
        "json_report": json_path,
        "markdown_report": md_path,
    }


def generate_control_plane_report(
    output_dir: str = CONTROL_PLANE_OUTPUT_DIR,
    base_name: Optional[str] = None,
) -> Dict[str, Any]:
    bundle = generate_control_plane_profile()

    files = save_control_plane_report(
        bundle=bundle,
        output_dir=output_dir,
        base_name=base_name,
    )

    return {
        "ok": True,
        "generated_at": _utc_now(),
        "bundle": bundle,
        "files": files,
    }


if __name__ == "__main__":
    out = generate_control_plane_report()
    print(json.dumps(out, indent=2, ensure_ascii=False))