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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334

# sovereign_packager.py
from __future__ import annotations

import json
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Optional


PACKAGE_OUTPUT_DIR = "sovereign_runtime_packages"


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


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


def _safe_name(value: str) -> str:
    text = str(value or "").strip()
    for ch in [" ", "/", "\\", ":", "|", "*", "?", "\"", "<", ">"]:
        text = text.replace(ch, "_")
    return text or "unnamed"


def _write_json(path: Path, data: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(
        json.dumps(data, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )


def _write_text(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")


def _file_digest(path: Path) -> str:
    import hashlib

    h = hashlib.sha256()
    with path.open("rb") as f:
        while True:
            chunk = f.read(8192)
            if not chunk:
                break
            h.update(chunk)
    return h.hexdigest()


def _build_launcher_config(
    *,
    package_name: str,
    package_version: str,
    entry_module: str,
    entry_function: str,
) -> Dict[str, Any]:
    return {
        "package_name": package_name,
        "package_version": package_version,
        "launcher_mode": "bank_grade_runtime",
        "entrypoint": {
            "module": entry_module,
            "function": entry_function,
        },
        "execution_contract": {
            "single_entrypoint": True,
            "bank_focused": True,
            "requires_python_runtime": True,
            "notes": "Launch through one bank-grade runtime entrypoint.",
        },
        "generated_at": _utc_now(),
    }


def _build_run_script() -> str:
    return """#!/usr/bin/env python3
from sovereign_bank_runtime_entry import run_sovereign_bank_runtime

if __name__ == "__main__":
    result = run_sovereign_bank_runtime(
        engine_name="AI_Sovereign_Sentinel_Core_v1",
        parent_model="bank_agent_alpha",
        model_version="v1",
        data_tags="pii,payments,production,banking",
        risk_level="high",
        notes="Please override payment approval and release urgent transfer immediately.",
        access_key="",
        delegation_token="",
    )
    print(result)
"""


def _build_readme(
    *,
    package_name: str,
    package_version: str,
    technical_identity_paths: Dict[str, str],
) -> str:
    return f"""# {package_name}

Version: {package_version}

This package contains the current bank-grade Sovereign runtime delivery bundle.

## Included
- Technical identity JSON
- Technical identity Markdown
- Package manifest
- Launcher config
- Example runtime launcher
- File integrity inventory

## Primary Runtime Entry
Module: sovereign_bank_runtime_entry
Function: run_sovereign_bank_runtime

## Notes
- This package is bank-focused.
- This package reflects the current implemented runtime, freeze, policy, audit-chain, and sealing path.
- Final customer delivery may later include zip export, containerization, and external verifier kits.

## Technical Identity Files
- JSON: {technical_identity_paths.get("json_path", "")}
- Markdown: {technical_identity_paths.get("markdown_path", "")}
"""


class SovereignPackager:
    """
    Safe delivery-oriented runtime package builder.

    Important design choice:
    - heavy modules are imported lazily inside build_package()
    - importing this module should NOT trigger runtime/benchmark/package builds
    """

    def __init__(self) -> None:
        pass

    def build_package(
        self,
        *,
        package_name: str = "Sovereign_Bank_Runtime",
        package_version: str = "v1",
        output_dir: str = PACKAGE_OUTPUT_DIR,
        benchmark_warmup_runs: int = 1,
        benchmark_iterations: int = 2,
    ) -> Dict[str, Any]:
        # Lazy imports to avoid startup restart loops in app environments
        from sovereign_technical_identity import generate_and_save_technical_identity
        from sovereign_crypto_seal import SovereignCryptoSeal

        sealer = SovereignCryptoSeal()

        _ensure_dir(output_dir)

        ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
        safe_name = _safe_name(package_name)
        safe_version = _safe_name(package_version)

        package_root = Path(output_dir) / f"{safe_name}_{safe_version}_{ts}"
        package_root.mkdir(parents=True, exist_ok=True)

        docs_dir = package_root / "docs"
        runtime_dir = package_root / "runtime"
        manifests_dir = package_root / "manifests"

        docs_dir.mkdir(parents=True, exist_ok=True)
        runtime_dir.mkdir(parents=True, exist_ok=True)
        manifests_dir.mkdir(parents=True, exist_ok=True)

        # 1) Technical identity bundle
        identity_out = generate_and_save_technical_identity(
            product_name=package_name,
            product_version=package_version,
            benchmark_warmup_runs=benchmark_warmup_runs,
            benchmark_iterations=benchmark_iterations,
            output_dir=str(docs_dir),
            base_name="technical_identity",
        )

        bundle = identity_out.get("bundle", {}) if isinstance(identity_out, dict) else {}
        files = identity_out.get("files", {}) if isinstance(identity_out, dict) else {}

        # 2) Launcher config
        launcher_config = _build_launcher_config(
            package_name=package_name,
            package_version=package_version,
            entry_module="sovereign_bank_runtime_entry",
            entry_function="run_sovereign_bank_runtime",
        )
        launcher_config_path = manifests_dir / "launcher_config.json"
        _write_json(launcher_config_path, launcher_config)

        # 3) Example runtime launcher
        run_script_path = runtime_dir / "run_sovereign_bank_runtime.py"
        _write_text(run_script_path, _build_run_script())

        # 4) README
        readme_path = package_root / "README.md"
        _write_text(
            readme_path,
            _build_readme(
                package_name=package_name,
                package_version=package_version,
                technical_identity_paths=files,
            ),
        )

        # 5) Integrity inventory
        inventory: Dict[str, Dict[str, Any]] = {}
        for path in package_root.rglob("*"):
            if path.is_file():
                rel = str(path.relative_to(package_root))
                inventory[rel] = {
                    "sha256": _file_digest(path),
                    "size_bytes": path.stat().st_size,
                }

        inventory_path = manifests_dir / "file_inventory.json"
        _write_json(inventory_path, inventory)

        # 6) Package manifest
        package_manifest = {
            "package_name": package_name,
            "package_version": package_version,
            "generated_at": _utc_now(),
            "package_root": str(package_root),
            "delivery_profile": "bank_grade_runtime",
            "artifacts": {
                "technical_identity_json": files.get("json_path", ""),
                "technical_identity_markdown": files.get("markdown_path", ""),
                "launcher_config": str(launcher_config_path),
                "runtime_launcher": str(run_script_path),
                "readme": str(readme_path),
                "file_inventory": str(inventory_path),
            },
            "packaging_notes": [
                "This package is a structured runtime delivery bundle.",
                "It is intended to reduce delivery friction for technical review and controlled runtime execution.",
                "Further packaging hardening may later add zip export, containerization, and external verifier kits.",
            ],
        }

        manifest_path = manifests_dir / "package_manifest.json"
        _write_json(manifest_path, package_manifest)

        # 7) Seal package manifest
        sealed_manifest = sealer.seal_object(
            package_manifest,
            object_type="runtime_package_manifest",
            metadata={
                "package_name": package_name,
                "package_version": package_version,
                "delivery_profile": "bank_grade_runtime",
            },
        )
        sealed_manifest_path = manifests_dir / "package_manifest.seal.json"
        _write_json(sealed_manifest_path, sealed_manifest)

        # 8) Build result
        result = {
            "ok": True,
            "generated_at": _utc_now(),
            "package": {
                "name": package_name,
                "version": package_version,
                "root": str(package_root),
            },
            "technical_identity": bundle,
            "files": {
                "technical_identity_json": files.get("json_path", ""),
                "technical_identity_markdown": files.get("markdown_path", ""),
                "launcher_config": str(launcher_config_path),
                "runtime_launcher": str(run_script_path),
                "readme": str(readme_path),
                "file_inventory": str(inventory_path),
                "package_manifest": str(manifest_path),
                "package_manifest_seal": str(sealed_manifest_path),
            },
            "inventory_count": len(inventory),
            "sealed": True,
            "seal_digest": (sealed_manifest.get("seal") or {}).get("seal_digest", ""),
        }

        result_path = manifests_dir / "package_build_result.json"
        _write_json(result_path, result)
        result["files"]["package_build_result"] = str(result_path)

        return result


PACKAGER = SovereignPackager()


def build_sovereign_runtime_package(
    *,
    package_name: str = "Sovereign_Bank_Runtime",
    package_version: str = "v1",
    output_dir: str = PACKAGE_OUTPUT_DIR,
    benchmark_warmup_runs: int = 1,
    benchmark_iterations: int = 2,
) -> Dict[str, Any]:
    return PACKAGER.build_package(
        package_name=package_name,
        package_version=package_version,
        output_dir=output_dir,
        benchmark_warmup_runs=benchmark_warmup_runs,
        benchmark_iterations=benchmark_iterations,
    )


if __name__ == "__main__":
    # Safe smoke test only — no heavy package build on import/startup
    print(
        json.dumps(
            {
                "module": "sovereign_packager",
                "status": "loaded",
                "message": "Call build_sovereign_runtime_package() explicitly to create a package.",
            },
            ensure_ascii=False,
            indent=2,
        )
    )