File size: 7,324 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""``explicit-resource`` — exact-revision resource fetch and verification.

Subcommands:

  list    Show every pinned resource with its role, revision, required approval
          gates, and current block status given an approval file.
  fetch   Download one or all resources at pinned revisions into the model/data
          roots, appending a ``resource_snapshot.jsonl`` row per success. A
          blocked gate skips the resource with a reason (never substitutes).
  verify  Offline-verify a previously fetched resource against its recorded
          snapshot row (recompute the file-tree manifest, detect LFS pointers,
          reject a resolved/requested-commit mismatch or content drift).

See ``docs/01_RESOURCE_CATALOG.md`` §7 and ``docs/07_IMPLEMENTATION_TASKS.md``
section 3.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path

from .. import __version__
from ..config import ConfigError, load_resources
from ..logging_setup import get_logger
from ..paths import repo_root
from ..resources import (
    ResourceError,
    block_reason,
    fetch_one,
    load_approval,
    plan,
    verify_one,
)

logger = get_logger("resource")


def _add_config(parser: argparse.ArgumentParser) -> None:
    parser.add_argument(
        "--resources",
        type=Path,
        default=repo_root() / "configs" / "resources.yaml",
    )


def _token() -> str | None:
    """Read ``HF_TOKEN`` from the environment (never logged)."""
    return os.environ.get("HF_TOKEN") or None


def cmd_list(args: argparse.Namespace) -> int:
    try:
        resources = load_resources(args.resources)
    except (ConfigError, FileNotFoundError) as exc:
        print(f"RESOURCE LIST FAILED: {exc}", file=sys.stderr)
        return 1
    approval = load_approval(args.approval)
    rows = []
    for ref in plan(resources):
        reason = block_reason(ref, approval)
        rows.append(
            {
                "logical_name": ref.logical_name,
                "kind": ref.kind,
                "role": ref.role,
                "repo_id": ref.repo_id,
                "revision": ref.revision,
                "local_path": str(ref.local_path),
                "required_gates": list(ref.required_gates),
                "blocked": reason is not None,
                "block_reason": reason,
            }
        )
    print(json.dumps({"resources": rows}, sort_keys=True))
    return 0


def _snapshot_path(args: argparse.Namespace) -> Path:
    return Path(args.snapshot)


def cmd_fetch(args: argparse.Namespace) -> int:
    try:
        resources = load_resources(args.resources)
    except (ConfigError, FileNotFoundError) as exc:
        print(f"RESOURCE FETCH FAILED: {exc}", file=sys.stderr)
        return 1
    approval = load_approval(args.approval)
    refs = plan(resources)
    if args.name:
        wanted = set(args.name)
        refs = [r for r in refs if r.logical_name in wanted]
        missing = wanted - {r.logical_name for r in refs}
        if missing:
            print(f"RESOURCE FETCH FAILED: unknown resource(s): {sorted(missing)}", file=sys.stderr)
            return 1
    allow = tuple(args.include) if args.include else None
    snapshot_path = _snapshot_path(args)
    snapshot_path.parent.mkdir(parents=True, exist_ok=True)

    results = []
    failures = 0
    for ref in refs:
        try:
            result = fetch_one(
                ref,
                approval,
                snapshot_path=snapshot_path,
                allow_patterns=allow,
                token=_token(),
            )
        except ResourceError as exc:
            # ResourceError messages must never carry the token; verify defensively.
            failures += 1
            logger.error("fetch %s failed: %s", ref.logical_name, exc)
            results.append(
                {"status": "failed", "logical_name": ref.logical_name, "error": str(exc)}
            )
            continue
        results.append(result)
        if result["status"] == "skipped":
            logger.info("skip %s: %s", ref.logical_name, result["reason"])
        else:
            logger.info("fetched %s (%d files)", ref.logical_name, result["row"]["file_count"])

    print(json.dumps({"results": results, "failures": failures}, sort_keys=True))
    return 1 if failures else 0


def cmd_verify(args: argparse.Namespace) -> int:
    try:
        resources = load_resources(args.resources)
    except (ConfigError, FileNotFoundError) as exc:
        print(f"RESOURCE VERIFY FAILED: {exc}", file=sys.stderr)
        return 1
    refs = plan(resources)
    if args.name:
        wanted = set(args.name)
        refs = [r for r in refs if r.logical_name in wanted]
        missing = wanted - {r.logical_name for r in refs}
        if missing:
            print(
                f"RESOURCE VERIFY FAILED: unknown resource(s): {sorted(missing)}", file=sys.stderr
            )
            return 1
    snapshot_path = _snapshot_path(args)
    results = []
    failures = 0
    for ref in refs:
        try:
            result = verify_one(ref, snapshot_path)
        except ResourceError as exc:
            failures += 1
            result = {"logical_name": ref.logical_name, "ok": False, "error": str(exc)}
        results.append(result)
    print(json.dumps({"results": results, "failures": failures}, sort_keys=True))
    return 1 if failures else 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="explicit-resource")
    parser.add_argument("--version", action="version", version=f"explicit-resource {__version__}")
    sub = parser.add_subparsers(dest="command", required=True)

    p_list = sub.add_parser("list", help="List pinned resources and their gate status.")
    _add_config(p_list)
    p_list.add_argument("--approval", type=Path, default=None, help="resource_approval.json path.")
    p_list.set_defaults(func=cmd_list)

    p_fetch = sub.add_parser("fetch", help="Download resources at pinned revisions.")
    _add_config(p_fetch)
    p_fetch.add_argument("--approval", type=Path, default=None)
    p_fetch.add_argument("--name", action="append", help="resource logical name (repeatable).")
    p_fetch.add_argument(
        "--include",
        action="append",
        help="glob allow-pattern forwarded to the downloader (repeatable, small-fetch fixture).",
    )
    p_fetch.add_argument(
        "--snapshot",
        type=Path,
        default=repo_root() / "resource_snapshot.jsonl",
        help="resource_snapshot.jsonl path to append rows to.",
    )
    p_fetch.set_defaults(func=cmd_fetch)

    p_verify = sub.add_parser(
        "verify", help="Offline-verify a fetched resource vs its snapshot row."
    )
    _add_config(p_verify)
    p_verify.add_argument("--name", action="append", help="resource logical name (repeatable).")
    p_verify.add_argument(
        "--snapshot",
        type=Path,
        default=repo_root() / "resource_snapshot.jsonl",
        help="resource_snapshot.jsonl path to verify against.",
    )
    p_verify.set_defaults(func=cmd_verify)

    return parser


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    return int(args.func(args))


if __name__ == "__main__":
    raise SystemExit(main())