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
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
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
from __future__ import annotations

import hashlib
import json
import os
import shutil
import urllib.error
import urllib.request
import uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime
from enum import StrEnum
from pathlib import Path, PurePosixPath
from typing import Literal

import yaml  # type: ignore[import-untyped]
from pydantic import BaseModel, ConfigDict, Field, model_validator

from packages.core.files import atomic_write_text


class _StrictModel(BaseModel):
    model_config = ConfigDict(extra="forbid", validate_assignment=True)


class SourceAccess(StrEnum):
    OPEN = "open"
    GATED = "gated"
    MANUAL_AGREEMENT = "manual_agreement"
    LICENSE_REVIEW = "license_review"


class DownloadArtifact(_StrictModel):
    artifact_id: str = Field(pattern=r"^[a-z0-9][a-z0-9_.-]*$")
    url: str
    relative_path: str
    expected_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
    expected_md5: str | None = Field(default=None, pattern=r"^[0-9a-f]{32}$")
    expected_size_bytes: int | None = Field(default=None, gt=0)

    @model_validator(mode="after")
    def validate_relative_path(self) -> DownloadArtifact:
        path = PurePosixPath(self.relative_path)
        if path.is_absolute() or ".." in path.parts or not path.name:
            raise ValueError("artifact relative_path must stay inside its raw version directory")
        return self


class AssetSourceSpec(_StrictModel):
    source_id: str = Field(pattern=r"^[a-z0-9][a-z0-9_.-]*$")
    display_name: str
    descriptor_source_aliases: list[str] = Field(default_factory=list)
    version: str
    purpose: list[str] = Field(default_factory=list)
    ingestion_priority: int = Field(default=100, ge=1)
    license_id: str
    license_url: str
    access: SourceAccess
    registration_required: bool = False
    auto_download_allowed: bool = False
    download_method: str
    source_url: str
    official_size_bytes: int | None = Field(default=None, gt=0)
    current_local_path: str | None = None
    current_local_size_bytes: int | None = Field(default=None, ge=0)
    artifacts: list[DownloadArtifact] = Field(default_factory=list)
    notes: list[str] = Field(default_factory=list)

    @model_validator(mode="after")
    def validate_access_policy(self) -> AssetSourceSpec:
        if self.access != SourceAccess.OPEN and self.auto_download_allowed:
            raise ValueError("restricted sources cannot enable unattended download")
        if self.auto_download_allowed and not self.artifacts:
            raise ValueError("auto-download source requires explicit versioned artifacts")
        return self


class SourceRegistry(_StrictModel):
    schema_version: Literal["1.0"] = "1.0"
    generated_for: str = "RoboHouseGen"
    sources: list[AssetSourceSpec]

    @model_validator(mode="after")
    def validate_source_ids(self) -> SourceRegistry:
        ids = [source.source_id for source in self.sources]
        if len(ids) != len(set(ids)):
            raise ValueError("source registry IDs must be unique")
        return self

    @classmethod
    def from_yaml(cls, path: Path) -> SourceRegistry:
        return cls.model_validate(yaml.safe_load(path.read_text(encoding="utf-8")))

    def require(self, source_id: str) -> AssetSourceSpec:
        for source in self.sources:
            if source.source_id == source_id:
                return source
        raise KeyError(f"asset source is not registered: {source_id}")


class AssetStoreLayout(_StrictModel):
    root: Path
    raw: Path
    staged: Path
    certified: Path
    quarantine: Path
    manifests: Path

    @classmethod
    def for_root(cls, root: Path) -> AssetStoreLayout:
        resolved = root.resolve()
        if resolved == Path(resolved.anchor):
            raise ValueError("asset store root cannot be a filesystem root")
        return cls(
            root=resolved,
            raw=resolved / "raw",
            staged=resolved / "staged",
            certified=resolved / "certified",
            quarantine=resolved / "quarantine",
            manifests=resolved / "manifests",
        )

    def initialize(self) -> None:
        for path in (self.raw, self.staged, self.certified, self.quarantine, self.manifests):
            path.mkdir(parents=True, exist_ok=True)


class LicenseBlockedError(RuntimeError):
    pass


class ChecksumMismatchError(RuntimeError):
    pass


class ResumeNotSupportedError(RuntimeError):
    pass


class IngestArtifactResult(_StrictModel):
    artifact_id: str
    status: Literal["downloaded", "reused", "blocked", "failed", "staged", "duplicate"]
    raw_path: str | None = None
    staged_path: str | None = None
    bytes: int = Field(default=0, ge=0)
    sha256: str | None = None
    resumed_from_bytes: int = Field(default=0, ge=0)
    message: str = ""


class IngestRunManifest(_StrictModel):
    schema_version: Literal["1.0"] = "1.0"
    run_id: str
    source_id: str
    source_version: str
    source_license: str
    license_url: str
    authorization_record: str | None = None
    authorization_record_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
    started_at: datetime
    completed_at: datetime
    asset_store_root: str
    raw_immutable: Literal[True] = True
    results: list[IngestArtifactResult]


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def md5_file(path: Path) -> str:
    """Return a source checksum when an upstream catalog publishes only MD5.

    SHA-256 remains the content identity used by RoboHouseGen. MD5 is evaluated
    only as an additional exact-byte check against the publisher's manifest.
    """
    digest = hashlib.md5(usedforsecurity=False)
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


class AssetIngestor:
    def __init__(self, layout: AssetStoreLayout, *, timeout_s: int = 120) -> None:
        self.layout = layout
        self.timeout_s = timeout_s

    @staticmethod
    def _check_authorization(source: AssetSourceSpec, authorization_record: Path | None) -> None:
        if source.access == SourceAccess.OPEN and not source.auto_download_allowed:
            raise LicenseBlockedError(
                f"{source.source_id} is plan-only until its version-pinned artifact manifest "
                "is reviewed and auto_download_allowed is enabled"
            )
        if source.access == SourceAccess.OPEN:
            return
        if authorization_record is None or not authorization_record.is_file():
            raise LicenseBlockedError(
                f"{source.source_id} requires a local authorization record; "
                "RoboHouseGen will not accept terms or supply credentials automatically"
            )

    def _raw_destination(self, source: AssetSourceSpec, artifact: DownloadArtifact) -> Path:
        version_root = (self.layout.raw / source.source_id / source.version).resolve()
        destination = (version_root / Path(*PurePosixPath(artifact.relative_path).parts)).resolve()
        if version_root not in destination.parents:
            raise ValueError("raw destination escaped source version root")
        return destination

    def download(
        self,
        source: AssetSourceSpec,
        artifact: DownloadArtifact,
        *,
        authorization_record: Path | None = None,
    ) -> IngestArtifactResult:
        self._check_authorization(source, authorization_record)
        destination = self._raw_destination(source, artifact)
        partial = destination.with_suffix(destination.suffix + ".part")
        destination.parent.mkdir(parents=True, exist_ok=True)
        if destination.exists():
            digest = sha256_file(destination)
            if artifact.expected_sha256 and digest != artifact.expected_sha256:
                raise ChecksumMismatchError(
                    f"existing immutable raw file hash differs: {destination}"
                )
            if (
                artifact.expected_size_bytes
                and destination.stat().st_size != artifact.expected_size_bytes
            ):
                raise ChecksumMismatchError(
                    f"existing immutable raw file size differs: {destination}"
                )
            if artifact.expected_md5 and md5_file(destination) != artifact.expected_md5:
                raise ChecksumMismatchError(
                    f"existing immutable raw file publisher checksum differs: {destination}"
                )
            return IngestArtifactResult(
                artifact_id=artifact.artifact_id,
                status="reused",
                raw_path=str(destination),
                bytes=destination.stat().st_size,
                sha256=digest,
            )
        resume_from = partial.stat().st_size if partial.is_file() else 0
        request = urllib.request.Request(
            artifact.url,
            headers={
                "User-Agent": "RoboHouseGen-AssetIngest/1.0",
                **({"Range": f"bytes={resume_from}-"} if resume_from else {}),
            },
        )
        try:
            response = urllib.request.urlopen(request, timeout=self.timeout_s)  # noqa: S310
        except urllib.error.URLError as error:
            raise RuntimeError(f"asset download failed: {artifact.url}: {error}") from error
        status = getattr(response, "status", response.getcode())
        if resume_from and status != 206:
            response.close()
            raise ResumeNotSupportedError(
                f"server did not honor Range for {artifact.artifact_id}; "
                f"partial retained at {partial}"
            )
        mode = "ab" if resume_from else "xb"
        try:
            with partial.open(mode) as handle, response:
                shutil.copyfileobj(response, handle, length=4 * 1024 * 1024)
                handle.flush()
                os.fsync(handle.fileno())
        except FileExistsError as error:
            raise RuntimeError(f"concurrent partial download detected: {partial}") from error
        size = partial.stat().st_size
        if artifact.expected_size_bytes is not None and size != artifact.expected_size_bytes:
            raise ChecksumMismatchError(
                f"download size mismatch for {artifact.artifact_id}: {size} != "
                f"{artifact.expected_size_bytes}; partial retained"
            )
        digest = sha256_file(partial)
        if artifact.expected_md5 is not None and md5_file(partial) != artifact.expected_md5:
            raise ChecksumMismatchError(
                f"download publisher checksum mismatch for {artifact.artifact_id}; partial retained"
            )
        if artifact.expected_sha256 is not None and digest != artifact.expected_sha256:
            raise ChecksumMismatchError(
                f"download checksum mismatch for {artifact.artifact_id}; partial retained"
            )
        partial.replace(destination)
        destination.chmod(0o444)
        return IngestArtifactResult(
            artifact_id=artifact.artifact_id,
            status="downloaded",
            raw_path=str(destination),
            bytes=size,
            sha256=digest,
            resumed_from_bytes=resume_from,
        )

    def stage(
        self,
        source: AssetSourceSpec,
        artifact: DownloadArtifact,
        download: IngestArtifactResult,
    ) -> IngestArtifactResult:
        if not download.raw_path or not download.sha256:
            raise ValueError("only a verified raw artifact can be staged")
        raw = Path(download.raw_path).resolve()
        expected_raw_root = (self.layout.raw / source.source_id / source.version).resolve()
        if expected_raw_root not in raw.parents:
            raise ValueError("raw artifact does not belong to this source version")
        relative = raw.relative_to(expected_raw_root)
        staged = (self.layout.staged / source.source_id / source.version / relative).resolve()
        if staged.exists():
            if sha256_file(staged) != download.sha256:
                raise FileExistsError(f"refusing to overwrite staged artifact: {staged}")
            status: Literal["staged", "duplicate"] = "duplicate"
        else:
            staged.parent.mkdir(parents=True, exist_ok=True)
            # Never hard-link staged data to raw: a converter that writes in
            # place would otherwise mutate the supposedly immutable raw inode.
            shutil.copy2(raw, staged)
            staged.chmod(0o644)
            status = "staged"
        content_record = (
            self.layout.manifests / "content" / download.sha256[:2] / (download.sha256 + ".json")
        )
        if not content_record.exists():
            content_record.parent.mkdir(parents=True, exist_ok=True)
            atomic_write_text(
                content_record,
                json.dumps(
                    {
                        "schema_version": "1.0",
                        "sha256": download.sha256,
                        "first_raw_path": str(raw),
                        "source_id": source.source_id,
                        "source_version": source.version,
                    },
                    indent=2,
                    sort_keys=True,
                )
                + "\n",
            )
        return IngestArtifactResult(
            artifact_id=artifact.artifact_id,
            status=status,
            raw_path=str(raw),
            staged_path=str(staged),
            bytes=download.bytes,
            sha256=download.sha256,
            resumed_from_bytes=download.resumed_from_bytes,
        )

    def run(
        self,
        source: AssetSourceSpec,
        *,
        authorization_record: Path | None = None,
        stage: bool = True,
        workers: int = 1,
    ) -> IngestRunManifest:
        if not 1 <= workers <= 64:
            raise ValueError("ingestion workers must be between 1 and 64")
        self.layout.initialize()
        started = datetime.now(UTC)
        results: list[IngestArtifactResult] = []
        try:
            self._check_authorization(source, authorization_record)
        except LicenseBlockedError as error:
            results.append(
                IngestArtifactResult(
                    artifact_id="source-access",
                    status="blocked",
                    message=str(error),
                )
            )
        access_blocked = bool(results and results[0].artifact_id == "source-access")

        def download_one(artifact: DownloadArtifact) -> IngestArtifactResult:
            try:
                return self.download(source, artifact, authorization_record=authorization_record)
            except LicenseBlockedError as error:
                return IngestArtifactResult(
                    artifact_id=artifact.artifact_id,
                    status="blocked",
                    message=str(error),
                )
            except Exception as error:
                return IngestArtifactResult(
                    artifact_id=artifact.artifact_id,
                    status="failed",
                    message=f"{type(error).__name__}:{error}",
                )

        if not access_blocked:
            if workers == 1:
                downloads = [download_one(artifact) for artifact in source.artifacts]
            else:
                # Download distinct immutable destinations concurrently, then stage
                # in manifest order. Serial staging keeps the content-hash ledger
                # deterministic even if two URLs resolve to identical bytes.
                with ThreadPoolExecutor(
                    max_workers=workers,
                    thread_name_prefix=f"ingest-{source.source_id}",
                ) as executor:
                    downloads = list(executor.map(download_one, source.artifacts))
            for artifact, downloaded in zip(source.artifacts, downloads, strict=True):
                if stage and downloaded.status in {"downloaded", "reused"}:
                    try:
                        results.append(self.stage(source, artifact, downloaded))
                    except Exception as error:
                        results.append(
                            IngestArtifactResult(
                                artifact_id=artifact.artifact_id,
                                status="failed",
                                raw_path=downloaded.raw_path,
                                bytes=downloaded.bytes,
                                sha256=downloaded.sha256,
                                resumed_from_bytes=downloaded.resumed_from_bytes,
                                message=f"{type(error).__name__}:{error}",
                            )
                        )
                else:
                    results.append(downloaded)
        completed = datetime.now(UTC)
        run_id = completed.strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:8]
        manifest = IngestRunManifest(
            run_id=run_id,
            source_id=source.source_id,
            source_version=source.version,
            source_license=source.license_id,
            license_url=source.license_url,
            authorization_record=(
                str(authorization_record.resolve()) if authorization_record else None
            ),
            authorization_record_sha256=(
                sha256_file(authorization_record)
                if authorization_record is not None and authorization_record.is_file()
                else None
            ),
            started_at=started,
            completed_at=completed,
            asset_store_root=str(self.layout.root),
            results=results,
        )
        destination = self.layout.manifests / source.source_id / source.version / f"{run_id}.json"
        destination.parent.mkdir(parents=True, exist_ok=True)
        atomic_write_text(destination, manifest.model_dump_json(indent=2) + "\n")
        return manifest