okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
33.9 KiB556 linesraw
1#!/usr/bin/env python3
2"""The release-side tool for the update feed: keys, signed packages, archives, the signed feed.
3
4Nothing here runs on a user's PC. It runs on the owner's release machine, with the owner's private key, and writes files
5that are then uploaded (to a local folder or a local HTTP server while testing; to the real host only when the owner
6decides). Nothing is uploaded by this tool.
7
8Typical use (the owner's offline machine; replace ``KEYDIR`` with a folder that is NOT in a git checkout):
9
10    python packaging/feed_tool.py keygen --out KEYDIR                      # once: feed-key.json (SECRET) + feed-key.pub.json
11    python packaging/feed_tool.py sign-package <components>/engine/0.1.46-linux-x86_64-cuda --key KEYDIR/feed-key.json
12    python packaging/feed_tool.py pack-engine  <that folder> --out RELEASE/engine           # archive + <name>.entry.json
13    python packaging/feed_tool.py pack-control <control bundle folder> --version 0.1.46 --platform linux-x86_64 --out RELEASE/control
14    python packaging/feed_tool.py build-feed --out RELEASE --sequence 12 --key KEYDIR/feed-key.json \
15        --engine RELEASE/engine --control RELEASE/control [--app-json tauri-latest.json] [--channel stable] [--expires-days 365]
16    python packaging/feed_tool.py verify-feed RELEASE --pub KEYDIR/feed-key.pub.json
17
18A new model ships as a signed feed update with the optional `models` member (packaging/UPDATES.md): write one <id>.entry.json for each model in a folder
19(`model-files` prints the size and SHA-256 of the real files for it) and pass the folder as `build-feed --models FOLDER`; `verify-feed` lists the models and
20fails when Control would leave one out.
21
22``keygen`` never prints the secret and refuses to write inside a git checkout or over an existing file. The public file's
23entry goes into ``strata_control/update_keys.json`` (``keys``) once, in the commit that ships the first signed release.
24The Tauri updater key is a different key (minisign, made by ``tauri signer generate``); its public half goes in
25``tauri.conf.json`` and in ``update_keys.json`` as ``app_minisign_public``.
26"""
27
28from __future__ import annotations
29
30import argparse
31import datetime as dt
32import hashlib
33import json
34import os
35import shutil
36import stat
37import sys
38import tarfile
39import zipfile
40import zlib
41from concurrent.futures import ThreadPoolExecutor
42from pathlib import Path
43
44ROOT = Path(__file__).resolve().parents[1]
45sys.path.insert(0, str(ROOT))
46
47from strata_control import engine_component as ec, feed as feedmod, signing  # noqa: E402
48
49
50def _inside_git(path: Path) -> bool:
51    for parent in [path.resolve(), *path.resolve().parents]:
52        if (parent / ".git").exists():
53            return True
54    return False
55
56
57def _sha256(path: Path) -> str:
58    digest = hashlib.sha256()
59    with path.open("rb") as stream:
60        for block in iter(lambda: stream.read(1 << 20), b""):
61            digest.update(block)
62    return digest.hexdigest()
63
64
65def _load_key(path: Path) -> dict:
66    key = json.loads(path.read_text(encoding="utf-8"))
67    if key.get("alg") != signing.ALG or "seed" not in key:
68        raise SystemExit(f"{path} is not a secret key file made by `feed_tool.py keygen`")
69    return key
70
71
72def keygen(out: Path, *, allow_git: bool = False) -> dict:
73    out = Path(out)
74    if _inside_git(out) and not allow_git:
75        raise SystemExit(f"{out} is inside a git checkout; a private key must not be where it can be committed. Choose another folder.")
76    secret, public = out / "feed-key.json", out / "feed-key.pub.json"
77    if secret.exists() or public.exists():
78        raise SystemExit(f"{secret} or {public} already exists; refusing to overwrite a key")
79    out.mkdir(parents=True, exist_ok=True)
80    key = signing.generate_key()
81    fd = os.open(secret, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
82    with os.fdopen(fd, "w", encoding="utf-8") as stream:
83        json.dump(key, stream, indent=1)
84        stream.write("\n")
85    from strata_control import private_files
86    private_files.restrict_to_current_user(secret, directory=False)          # 0600, or a protected ACL on Windows
87    public.write_text(json.dumps({"keys": [signing.public_part(key)]}, indent=1) + "\n", encoding="utf-8")
88    return signing.public_part(key)
89
90
91def sign_package(folder: Path, key: dict) -> str:
92    """Put the signature into the package's manifest. Returns the manifest's SHA-256 afterwards (the feed names it)."""
93    path = Path(folder) / ec.MANIFEST
94    manifest = json.loads(path.read_text(encoding="utf-8-sig"))
95    manifest["signature"] = None
96    payload = ec.signing_payload(manifest)
97    manifest["signature"] = signing.sign_bytes(key, payload)
98    path.write_text(json.dumps(manifest, indent=1) + "\n", encoding="utf-8")
99    ec.read_manifest_any(Path(folder))                      # still a valid manifest
100    signing.verify_bytes({key["key_id"]: __import__("base64").b64decode(key["public"])}, payload, manifest["signature"])
101    return _sha256(path)
102
103
104_NATIVE_MAGIC = (b"\x7fELF", b"\xcf\xfa\xed\xfe", b"\xca\xfe\xba\xbe", b"\xfe\xed\xfa\xcf", b"#!")      # ELF, Mach-O (64-bit, fat), script
105
106
107def _is_native_executable(path: Path) -> bool:
108    try:
109        with path.open("rb") as stream:
110            head = stream.read(4)
111    except OSError:
112        return False
113    return any(head.startswith(m) for m in _NATIVE_MAGIC)
114
115
116def _mode(path: Path, rel: str, entrypoint: str | None) -> int:
117    if rel == entrypoint:
118        return 0o755
119    try:
120        if os.name == "nt":                       # a Linux / Mac package packed on Windows has no execute bits: take them from the file's own header
121            return 0o755 if _is_native_executable(path) else 0o644
122        return 0o755 if path.stat().st_mode & stat.S_IXUSR else 0o644
123    except OSError:
124        return 0o644
125
126
127GZIP_BLOCK = 4 << 20        # bytes of the tar per gzip member when several threads compress (_parallel_gzip)
128
129
130def gzip_threads() -> int:
131    """How many threads compress a tar.gz: 1 (the single-stream gzip, byte for byte as before) unless STRATA_PACK_THREADS asks for more. OPT-IN
132    (coordinator 11-10): a threaded archive is several gzip members, and every published client that unpacks a package must be shown to read
133    those before this may become the default."""
134    raw = os.environ.get("STRATA_PACK_THREADS", "").strip()
135    if raw.isdigit() and int(raw) >= 1:
136        return min(int(raw), 64)
137    return 1
138
139
140def _parallel_gzip(src: Path, dst: Path, threads: int, level: int = 9) -> None:
141    """`src` (a plain tar) gzipped into `dst` by `threads` threads: GZIP_BLOCK-sized pieces, each a complete gzip member (RFC 1952 allows several in one
142    file; Python's tarfile and gzip, GNU tar / gzip and bsdtar read them as one stream). zlib releases the GIL while it compresses, so the pieces run in
143    parallel. The header carries no file name and mtime 0, so the same tar always gives the same bytes."""
144    def one(block: bytes) -> bytes:
145        c = zlib.compressobj(level, zlib.DEFLATED, 31)       # wbits 31: a gzip member (header, deflate, crc32 + size trailer)
146        return c.compress(block) + c.flush()
147
148    def blocks():
149        with src.open("rb") as f:
150            while True:
151                block = f.read(GZIP_BLOCK)
152                if not block:
153                    return
154                yield block
155
156    with dst.open("wb") as out, ThreadPoolExecutor(max_workers=threads) as pool:
157        pending = []
158        for block in blocks():                               # at most 2 x threads blocks in memory
159            pending.append(pool.submit(one, block))
160            if len(pending) >= 2 * threads:
161                out.write(pending.pop(0).result())
162        for fut in pending:
163            out.write(fut.result())
164
165
166def _write_archive(files: list[tuple[str, Path]], archive: Path, fmt: str, entrypoint: str | None) -> None:
167    archive.parent.mkdir(parents=True, exist_ok=True)
168    if fmt == "zip":
169        with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as zf:
170            for rel, path in files:
171                zf.write(path, rel)
172        return
173    threads = gzip_threads() if fmt == "tar.gz" else 1
174    if threads > 1:                                          # the tar first (uncompressed, beside the archive), then the parallel gzip
175        plain = archive.with_name(archive.name + ".tar-part")
176        try:
177            _write_tar(files, plain, "w", entrypoint)
178            _parallel_gzip(plain, archive, threads)
179        finally:
180            plain.unlink(missing_ok=True)
181        return
182    _write_tar(files, archive, {"tar.gz": "w:gz", "tar.xz": "w:xz"}[fmt], entrypoint)
183
184
185def _write_tar(files: list[tuple[str, Path]], archive: Path, mode: str, entrypoint: str | None) -> None:
186    with tarfile.open(archive, mode) as tar:
187        for rel, path in files:
188            info = tar.gettarinfo(str(path), arcname=rel)
189            info.uid = info.gid = 0
190            info.uname = info.gname = ""
191            info.mtime = 0
192            if info.issym():                              # a Control bundle's Python has relative symlinks; engines have none
193                tar.addfile(info)
194                continue
195            info.mode = _mode(path, rel, entrypoint)
196            with path.open("rb") as stream:
197                tar.addfile(info, stream)
198
199
200def _tree(folder: Path, *, links: bool = False) -> list[tuple[str, Path]]:
201    """Regular files under `folder`; with `links` also the symbolic links, which must be relative and stay inside it."""
202    found = []
203    root = folder.resolve()
204    for path in sorted(folder.rglob("*")):
205        if path.is_symlink():
206            if not links:
207                continue
208            target = os.readlink(path)
209            if os.path.isabs(target) or not (path.parent / target).resolve().is_relative_to(root):
210                raise SystemExit(f"{path} is a symbolic link that leaves the package ({target}); a package may only link inside itself")
211            found.append((path.relative_to(folder).as_posix(), path))
212        elif path.is_file():
213            found.append((path.relative_to(folder).as_posix(), path))
214    return found
215
216
217def pack_engine(folder: Path, out: Path, fmt: str = "tar.gz", *, url_prefix: str = "engine/", prefix: str = "strata-engine") -> dict:
218    """Archive a (signed) engine package folder and return its feed entry. The archive holds the folder's files at its root. The package of a model shape (package_engine.py --shape)
219    gets its component's name as the archive prefix (strata-q4-lite-<version>-...) and its entry names the ``shape``: it goes into the feed member ``shape_engines``."""
220    folder = Path(folder)
221    component = ec.read_manifest_any(folder)
222    if component.shape and prefix == "strata-engine":
223        prefix = component.id
224    files = _tree(folder)
225    installed = sum(p.stat().st_size for _, p in files)
226    name = f"{prefix}-{folder.name}.{fmt}"
227    archive = Path(out) / name
228    _write_archive(files, archive, fmt, component.entrypoint)
229    entry = {"version": component.version, "platform": component.platform, "backend": component.backend,
230             "variant": component.variant, "archs": list(component.archs), "min_driver": dict(component.min_driver),
231             "min_runtime": component.min_runtime, "build_id": component.build_id, "format": fmt,
232             "url": f"{url_prefix}{name}", "size": archive.stat().st_size, "sha256": _sha256(archive),
233             "manifest_sha256": _sha256(folder / ec.MANIFEST), "installed_bytes": installed, "notes": component.notes}
234    if component.shape:
235        entry["shape"] = component.shape
236    (Path(out) / (name + ".entry.json")).write_text(json.dumps(entry, indent=1) + "\n", encoding="utf-8")
237    return entry
238
239
240def pack_control(folder: Path, out: Path, *, version: str, platform: str, fmt: str = "tar.gz",
241                 entry_file: str = "strata.py", url_prefix: str = "control/") -> dict:
242    folder = Path(folder)
243    files = _tree(folder, links=True)
244    installed = sum(p.stat().st_size for _, p in files if not p.is_symlink())
245    name = f"strata-control-{version}-{platform}.{fmt}"
246    archive = Path(out) / name
247    _write_archive(files, archive, fmt, entry_file)
248    entry = {"platform": platform, "format": fmt, "url": f"{url_prefix}{name}", "size": archive.stat().st_size,
249             "sha256": _sha256(archive), "installed_bytes": installed, "entry": entry_file, "version": version}
250    (Path(out) / (name + ".entry.json")).write_text(json.dumps(entry, indent=1) + "\n", encoding="utf-8")
251    return entry
252
253
254def pack_drafter(pack: Path, out: Path, *, version: str, backends: list[str], url_prefix: str = "", base: str = "", licence: str = "", notes: str = "") -> dict:
255    """Copy a DFlash2 drafter file into `out` (a flat release asset, as it is hosted) and write its feed entry (`<name>.entry.json`). The file is not an archive: the
256    client checks its size and SHA-256 against the signed feed AND against the pin in strata_control/drafting.py."""
257    pack = Path(pack)
258    Path(out).mkdir(parents=True, exist_ok=True)
259    target = Path(out) / pack.name
260    if pack.resolve() != target.resolve():
261        shutil.copy2(pack, target)
262    entry = {"name": pack.name, "version": version, "url": f"{url_prefix}{pack.name}", "size": target.stat().st_size, "sha256": _sha256(target),
263             "backends": list(backends), "base": base, "licence": licence, "notes": notes}
264    (Path(out) / (pack.name + ".entry.json")).write_text(json.dumps(entry, indent=1) + "\n", encoding="utf-8")
265    return entry
266
267
268def model_files(paths: list[Path], repo_dir: str = "") -> list[dict]:
269    """The `files` pins of a models entry from the real files: name, exact size, SHA-256 (and `path` when they sit in a folder of the repository)."""
270    out = []
271    for p in map(Path, paths):
272        item = {"name": p.name, "size": p.stat().st_size, "sha256": _sha256(p)}
273        if repo_dir:
274            item["path"] = f"{repo_dir.strip('/')}/{p.name}"
275        out.append(item)
276    return out
277
278
279DSV41_BASE_EXAMPLE = "https://github.com/Niko1221/Strata/releases/download/<DSV41-TAG>/"
280
281
282def carried_dsv41(previous_feed: Path, base: str) -> dict:
283    """The ``dsv41`` member of a published feed, frozen (owner 11-11, "Keep frozen"): Strata 0.2.13 and earlier read it to keep their DeepSeek
284    engine; this Strata never does.  Every entry is kept as it was, except a relative ``url`` (a flat release asset, resolved against the feed's
285    own release): it becomes ``base`` + url, the release that really holds the archive, because the new feed sits in a newer release that does
286    not.  Absolute https URLs are what those Controls accept (strata_control/transfer.py resolve_ref since 0.2.7).  ``base`` must be a real https
287    release folder: the placeholder in DSV41_BASE_EXAMPLE stops the build."""
288    if not isinstance(base, str) or not base.startswith("https://") or "<" in base or ">" in base or not base.endswith("/"):
289        raise SystemExit(f"--carry-dsv41-base must be the https folder of the release that holds the DeepSeek archives, ending in '/' "
290                         f"(like {DSV41_BASE_EXAMPLE} with the tag filled in), not {base!r}")
291    doc = json.loads(Path(previous_feed).read_text(encoding="utf-8"))
292    member = doc.get("dsv41") if isinstance(doc, dict) else None
293    if not isinstance(member, dict) or not isinstance(member.get("packages"), list) or not member["packages"]:
294        raise SystemExit(f"{previous_feed} has no dsv41 packages to carry over")
295    packages = []
296    for item in member["packages"]:
297        item = dict(item)
298        url = str(item.get("url") or "")
299        if not url or url.startswith(("http://", "file:")) or ".." in url.split("/"):
300            raise SystemExit(f"{previous_feed}: a dsv41 entry has an unusable url {url!r}")
301        if not url.startswith("https://"):
302            item["url"] = base + url.rsplit("/", 1)[-1]          # (a local test feed's "dsv41/<name>": the release asset is the bare name)
303        packages.append(item)
304    return {"packages": packages}
305
306
307def build_feed(out: Path, *, key: dict, sequence: int, channel: str = "stable", engine_dir: Path | None = None,
308               control_dir: Path | None = None, app_json: Path | None = None, expires_days: int | None = None,
309               now: dt.datetime | None = None, drafters_dir: Path | None = None, models_dir: Path | None = None,
310               shapes_dir: Path | None = None, dsv41_member: dict | None = None) -> dict:
311    now = now or dt.datetime.now(dt.timezone.utc)
312    install_manifest = ""
313    document: dict = {"schema_version": feedmod.SCHEMA_VERSION, "feed": "strata-updates", "channel": channel,
314                      "sequence": sequence, "generated_at": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
315                      "expires_at": (now + dt.timedelta(days=expires_days)).strftime("%Y-%m-%dT%H:%M:%SZ") if expires_days else None}
316    if engine_dir:
317        document["engine"] = {"packages": [json.loads(p.read_text(encoding="utf-8"))
318                                           for p in sorted(Path(engine_dir).glob("*.entry.json"))]}
319    if dsv41_member:                              # the frozen DeepSeek engine packages of Strata 0.2.13 and earlier (carried_dsv41)
320        document["dsv41"] = dsv41_member
321    if shapes_dir:                                # the engines of model shapes (feed member shape_engines): each entry must name a shape
322        entries = []
323        for p in sorted(Path(shapes_dir).glob("*.entry.json")):
324            item = json.loads(p.read_text(encoding="utf-8"))
325            if not item.get("shape"):
326                raise SystemExit(f"{p.name} names no shape: pack it from a package made with package_engine.py --shape")
327            entries.append(item)
328        document["shape_engines"] = {"packages": entries}
329    if drafters_dir:
330        document["drafters"] = {"packages": [json.loads(p.read_text(encoding="utf-8"))
331                                             for p in sorted(Path(drafters_dir).glob("*.entry.json"))]}
332    if models_dir:                                # the model list (feed member models): every entry must be one Control will keep, or the build stops
333        packages = []
334        for p in sorted(Path(models_dir).glob("*.entry.json")):
335            item = json.loads(p.read_text(encoding="utf-8"))
336            if "[FILL" in json.dumps(item):             # a placeholder from make_model_release.py that nobody filled in would reach people's screens
337                raise SystemExit(f"{p.name}: still has a [FILL: ...] value: fill it in first")
338            try:
339                feedmod._model_entry(item)
340            except feedmod.FeedError as exc:
341                raise SystemExit(f"{p.name}: {exc}")
342            packages.append(item)
343        if len({m["id"] for m in packages}) != len(packages):
344            raise SystemExit("two model entries have the same id")
345        document["models"] = {"packages": packages}
346    wanted = {m["family"][len("qwen4exp_"):] for m in (document.get("models") or {}).get("packages", []) if str(m.get("family", "")).startswith("qwen4exp_")}
347    have = {e["shape"] for e in (document.get("shape_engines") or {}).get("packages", [])}
348    if wanted - have:                             # a model of its own shape with no engine in the feed could be listed and never run
349        raise SystemExit("the feed lists a model for the shape " + ", ".join(sorted(wanted - have)) + " but no engine for it (build-feed --shapes FOLDER, with the .entry.json "
350                         "that pack-engine wrote for a package made with package_engine.py --shape)")
351    if control_dir:
352        entries = [json.loads(p.read_text(encoding="utf-8")) for p in sorted(Path(control_dir).glob("*.entry.json"))]
353        versions = {e["version"] for e in entries}
354        if len(versions) > 1:
355            raise SystemExit(f"the control packages are for different versions: {sorted(versions)}")
356        if entries:
357            document["control"] = {"version": versions.pop(), "packages": [{k: v for k, v in e.items() if k != "version"} for e in entries]}
358            for e in entries:     # install.sh unpacks with tar -xzf, install.ps1 with Expand-Archive: a pack in the other format cannot be installed that way
359                want = "zip" if e["platform"].startswith("windows") else "tar.gz"
360                if e.get("format") != want:
361                    print(f"note: the {e['platform']} control package is {e.get('format')}, so it is left out of install-manifest.txt "
362                          f"(the one-line installer needs {want}; pack-control --format {want})", file=sys.stderr)
363                    continue
364                install_manifest += f"{e['platform']} {e['version']} {e['url']} {e['sha256']} {e['size']}\n"
365    if app_json:
366        document["app"] = json.loads(Path(app_json).read_text(encoding="utf-8"))
367    payload = (json.dumps(document, indent=1, sort_keys=True) + "\n").encode("utf-8")
368    Path(out).mkdir(parents=True, exist_ok=True)
369    (Path(out) / feedmod.FEED_NAME).write_bytes(payload)
370    signature = signing.sign_bytes(key, payload)
371    (Path(out) / (feedmod.FEED_NAME + feedmod.SIGNATURE_SUFFIX)).write_text(json.dumps(signature) + "\n", encoding="utf-8")
372    if install_manifest:                        # what install.sh / install.ps1 read: platform version url sha256 size, one line per Terminal (Control) package
373        (Path(out) / "install-manifest.txt").write_text(install_manifest, encoding="utf-8", newline="\n")
374    if "app" in document:                       # the file the Tauri updater plugin reads
375        latest = Path(out) / "app" / "latest.json"
376        latest.parent.mkdir(parents=True, exist_ok=True)
377        latest.write_text(json.dumps({k: v for k, v in document["app"].items()}, indent=1) + "\n", encoding="utf-8")
378    # a parse of what was written is the last check: a feed this tool makes must be a feed Control accepts
379    checked = feedmod.verify_and_parse(payload, json.dumps(signature).encode(), source=str(Path(out) / feedmod.FEED_NAME),
380                                       trusted={key["key_id"]: __import__("base64").b64decode(key["public"])}, now=now)
381    if checked.models_dropped or len(checked.models) != len((document.get("models") or {}).get("packages", [])):
382        raise SystemExit("the feed was written, but Control would leave out a model: " + " ".join(checked.models_dropped))
383    return document
384
385
386TAURI_TARGET_NAMES = tuple(feedmod.TAURI_TARGETS.values())
387
388
389def _default_app_pubkey() -> str:
390    conf = Path(__file__).resolve().parents[1] / "apps" / "desktop" / "src-tauri" / "tauri.conf.json"
391    return json.loads(conf.read_text(encoding="utf-8"))["plugins"]["updater"]["pubkey"]
392
393
394def _check_mac_archive(archive: Path) -> None:
395    """A Mac updater archive is a gzip tar with exactly one top-level ``<Name>.app`` folder (what Tauri's bundler makes)."""
396    try:
397        with tarfile.open(archive, "r:gz") as tar:
398            tops = {m.name.lstrip("./").split("/", 1)[0] for m in tar.getmembers() if m.name.lstrip("./")}
399            names = set(tar.getnames())
400    except (tarfile.TarError, OSError) as exc:
401        raise SystemExit(f"{archive.name} is not a readable .tar.gz ({exc})")
402    if len(tops) != 1 or not next(iter(tops)).endswith(".app"):
403        raise SystemExit(f"{archive.name} must hold one <Name>.app folder at its root; found {sorted(tops)[:5]}")
404    app = next(iter(tops))
405    if not any(n.lstrip("./") == f"{app}/Contents/Info.plist" for n in names):
406        raise SystemExit(f"{archive.name} has no {app}/Contents/Info.plist")
407
408
409def set_app_platform(app_json: Path, *, target: str, archive: Path, signature_file: Path, url: str, version: str | None = None,
410                     notes: str | None = None, pub_date: str | None = None, pubkey: str | None = None,
411                     now: dt.datetime | None = None) -> dict:
412    """Add or replace one platform in the Tauri updater JSON (the file ``build-feed --app-json`` takes; it becomes ``latest.json``).
413
414    The ``.sig`` is made by ``npx tauri signer sign`` (or by ``tauri build`` for the Windows / Linux installers) and is only READ here;
415    this tool never touches the Tauri private key. It is checked against the public key in ``tauri.conf.json`` (or ``pubkey``) over the
416    exact archive bytes, so a signature of an older or unsigned file, or one from another key, is refused before it can be published.
417    ``sha256`` and ``size`` are taken from the archive."""
418    if target not in TAURI_TARGET_NAMES:
419        raise SystemExit(f"unknown target {target!r}; use one of {', '.join(TAURI_TARGET_NAMES)}")
420    archive, signature_file = Path(archive), Path(signature_file)
421    if target.startswith("darwin-"):
422        _check_mac_archive(archive)
423    signature = signature_file.read_text(encoding="utf-8").strip()
424    try:
425        with archive.open("rb") as stream:
426            signing.minisign_verify(pubkey or _default_app_pubkey(), signature, iter(lambda: stream.read(1 << 20), b""))
427    except signing.SignatureError as exc:
428        raise SystemExit(f"{signature_file.name} does not verify for {archive.name}: {exc}")
429    document: dict = {}
430    if Path(app_json).exists():
431        document = json.loads(Path(app_json).read_text(encoding="utf-8"))
432    if version:
433        if document.get("version") not in (None, version):
434            raise SystemExit(f"{app_json} is for version {document['version']}, not {version}")
435        document["version"] = version
436    if not document.get("version"):
437        raise SystemExit("a new app json needs --version")
438    document.setdefault("notes", notes or "")
439    if notes:
440        document["notes"] = notes
441    document["pub_date"] = pub_date or document.get("pub_date") or (now or dt.datetime.now(dt.timezone.utc)).strftime("%Y-%m-%dT%H:%M:%SZ")
442    document.setdefault("platforms", {})[target] = {"url": url, "signature": signature, "sha256": _sha256(archive),
443                                                    "size": archive.stat().st_size}
444    Path(app_json).write_text(json.dumps(document, indent=1) + "\n", encoding="utf-8")
445    return document["platforms"][target]
446
447
448def main(argv: list[str] | None = None) -> int:
449    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
450    sub = ap.add_subparsers(dest="cmd", required=True)
451    k = sub.add_parser("keygen")
452    k.add_argument("--out", type=Path, required=True)
453    sp = sub.add_parser("sign-package")
454    sp.add_argument("folder", type=Path)
455    sp.add_argument("--key", type=Path, required=True)
456    pe = sub.add_parser("pack-engine")
457    pe.add_argument("folder", type=Path)
458    pe.add_argument("--out", type=Path, required=True)
459    pe.add_argument("--format", choices=feedmod.FORMATS, default="tar.gz")
460    pe.add_argument("--url-prefix", default="engine/", help='where the archive sits relative to the feed ("" for flat GitHub release assets)')
461    pe.add_argument("--prefix", default="strata-engine", help="archive name prefix")
462    pd = sub.add_parser("pack-drafter", help="a DFlash2 drafter file as a feed entry (feed member drafters)")
463    pd.add_argument("pack", type=Path)
464    pd.add_argument("--out", type=Path, required=True)
465    pd.add_argument("--version", required=True)
466    pd.add_argument("--backends", required=True, help="comma-separated engine families it was measured on, e.g. metal")
467    pd.add_argument("--url-prefix", default="", help='"" for flat GitHub release assets')
468    pd.add_argument("--base", default="")
469    pd.add_argument("--licence", default="")
470    pm = sub.add_parser("model-files", help="print the size and SHA-256 of model files as the `files` list of a feed models entry")
471    pm.add_argument("files", type=Path, nargs="+")
472    pm.add_argument("--repo-dir", default="", help="the folder of the Hugging Face repository the files sit in (becomes each file's path); default: the top")
473    pc = sub.add_parser("pack-control")
474    pc.add_argument("folder", type=Path)
475    pc.add_argument("--out", type=Path, required=True)
476    pc.add_argument("--version", required=True)
477    pc.add_argument("--platform", required=True, choices=feedmod.PLATFORMS)
478    pc.add_argument("--format", choices=feedmod.FORMATS, default="tar.gz")
479    pc.add_argument("--url-prefix", default="control/")
480    bf = sub.add_parser("build-feed")
481    bf.add_argument("--out", type=Path, required=True)
482    bf.add_argument("--key", type=Path, required=True)
483    bf.add_argument("--sequence", type=int, required=True)
484    bf.add_argument("--channel", default="stable")
485    bf.add_argument("--engine", type=Path)
486    bf.add_argument("--carry-dsv41", type=Path, metavar="PREVIOUS-FEED",
487                    help="the last published strata-feed.json: its dsv41 member (the DeepSeek engine of Strata 0.2.13 and earlier) is carried over, frozen")
488    bf.add_argument("--carry-dsv41-base", metavar="URL", help="the https folder of the release that holds those archives, e.g. " + DSV41_BASE_EXAMPLE)
489    bf.add_argument("--no-dsv41-carry", action="store_true", help="build the feed without the frozen DeepSeek member (a test feed, or the owner's choice)")
490    bf.add_argument("--shapes", type=Path, help="folder of the model-shape engines' .entry.json files (feed member shape_engines; pack-engine writes them for a package made with package_engine.py --shape)")
491    bf.add_argument("--models", type=Path, help="folder of the models' <id>.entry.json files (feed member models: the model list setup and the screens show after the built-in ones)")
492    bf.add_argument("--drafters", type=Path, help="folder of the DFlash2 drafters' .entry.json files (feed member drafters; pack-drafter writes them)")
493    bf.add_argument("--control", type=Path)
494    bf.add_argument("--app-json", type=Path)
495    bf.add_argument("--expires-days", type=int)
496    sa = sub.add_parser("set-app-platform", help="add one signed app installer to the Tauri updater json")
497    sa.add_argument("--app-json", type=Path, required=True, help="the file to create or patch (what build-feed --app-json takes)")
498    sa.add_argument("--target", required=True, help="darwin-aarch64, darwin-x86_64, windows-x86_64 or linux-x86_64")
499    sa.add_argument("--archive", type=Path, required=True)
500    sa.add_argument("--sig", type=Path, required=True, help="the .sig file made by tauri signer sign")
501    sa.add_argument("--url", help="where the archive is published (default: the latest GitHub release)")
502    sa.add_argument("--version")
503    sa.add_argument("--notes")
504    sa.add_argument("--pub-date")
505    sa.add_argument("--pubkey", help="the Tauri public key (default: tauri.conf.json plugins.updater.pubkey)")
506    vf = sub.add_parser("verify-feed")
507    vf.add_argument("source")
508    vf.add_argument("--pub", type=Path, required=True)
509    a = ap.parse_args(argv)
510    if a.cmd == "keygen":
511        public = keygen(a.out)
512        print(f"wrote {a.out / 'feed-key.json'} (SECRET, keep it offline and backed up) and {a.out / 'feed-key.pub.json'}")
513        print(f"key_id {public['key_id']}")
514    elif a.cmd == "sign-package":
515        print("manifest sha256", sign_package(a.folder, _load_key(a.key)))
516    elif a.cmd == "pack-engine":
517        entry = pack_engine(a.folder, a.out, a.format, url_prefix=a.url_prefix, prefix=a.prefix)
518        print(json.dumps({k: entry[k] for k in ("version", "backend", "variant", "size", "sha256", "manifest_sha256")}, indent=1))
519    elif a.cmd == "pack-drafter":
520        entry = pack_drafter(a.pack, a.out, version=a.version, backends=[b for b in a.backends.split(",") if b], url_prefix=a.url_prefix, base=a.base, licence=a.licence)
521        print(json.dumps({k: entry[k] for k in ("name", "version", "size", "sha256", "backends")}, indent=1))
522    elif a.cmd == "model-files":
523        print(json.dumps(model_files(a.files, a.repo_dir), indent=1))
524    elif a.cmd == "pack-control":
525        entry = pack_control(a.folder, a.out, version=a.version, platform=a.platform, fmt=a.format, url_prefix=a.url_prefix)
526        print(json.dumps({k: entry[k] for k in ("version", "platform", "size", "sha256")}, indent=1))
527    elif a.cmd == "build-feed":
528        if bool(a.carry_dsv41) == bool(a.no_dsv41_carry):
529            raise SystemExit("build-feed: say what happens to the frozen DeepSeek member: --carry-dsv41 <the last strata-feed.json> --carry-dsv41-base "
530                             f"{DSV41_BASE_EXAMPLE} (with the tag of the release that holds the archives), or --no-dsv41-carry")
531        member = carried_dsv41(a.carry_dsv41, a.carry_dsv41_base) if a.carry_dsv41 else None
532        doc = build_feed(a.out, key=_load_key(a.key), sequence=a.sequence, channel=a.channel, engine_dir=a.engine,
533                         control_dir=a.control, app_json=a.app_json, expires_days=a.expires_days, drafters_dir=a.drafters, models_dir=a.models, shapes_dir=a.shapes,
534                         dsv41_member=member)
535        print(f"wrote {a.out / feedmod.FEED_NAME} (+ .sig); engines {len((doc.get('engine') or {}).get('packages', []))}, "
536              f"frozen deepseek engines {len((doc.get('dsv41') or {}).get('packages', []))}, shape engines {len((doc.get('shape_engines') or {}).get('packages', []))}, drafters {len((doc.get('drafters') or {}).get('packages', []))}, models {len((doc.get('models') or {}).get('packages', []))}, control {'yes' if 'control' in doc else 'no'}, app {'yes' if 'app' in doc else 'no'}")
537    elif a.cmd == "set-app-platform":
538        url = a.url or f"https://github.com/Niko1221/Strata/releases/latest/download/{a.archive.name}"
539        entry = set_app_platform(a.app_json, target=a.target, archive=a.archive, signature_file=a.sig, url=url, version=a.version,
540                                 notes=a.notes, pub_date=a.pub_date, pubkey=a.pubkey)
541        print(f"{a.app_json}: {a.target} -> {entry['url']} ({entry['size']} bytes, sha256 {entry['sha256'][:16]}..., signature verified)")
542    elif a.cmd == "verify-feed":
543        trusted = signing.load_trusted_keys(a.pub, environ={})
544        loaded = feedmod.fetch(a.source, trusted)
545        print(f"ok: sequence {loaded.sequence}, channel {loaded.channel}, signed by {loaded.key_id}, "
546              f"{len(loaded.engine)} engine packages, control {len(loaded.control)}, app {'yes' if loaded.app else 'no'}"
547              + (f", {len(loaded.shape_engines)} shape engines ({', '.join(sorted({p.shape for p in loaded.shape_engines}))})" if loaded.shape_engines else "")
548              + (f", {len(loaded.models)} models ({', '.join(m.id for m in loaded.models)})" if loaded.models else ""))
549        if loaded.models_dropped:                 # Control would skip these: a signed feed must not carry them
550            print(*loaded.models_dropped, sep=chr(10), file=sys.stderr)
551            return 3
552    return 0
553
554
555if __name__ == "__main__":
556    raise SystemExit(main())