grantstamp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. grantstamp/__init__.py +12 -0
  2. grantstamp/brand.py +46 -0
  3. grantstamp/cli.py +578 -0
  4. grantstamp/client.py +201 -0
  5. grantstamp/crypto.py +157 -0
  6. grantstamp/fingerprint/__init__.py +7 -0
  7. grantstamp/fingerprint/background.py +116 -0
  8. grantstamp/fingerprint/background_chunks_v1.u64 +0 -0
  9. grantstamp/fingerprint/background_strings_v1.u64 +0 -0
  10. grantstamp/fingerprint/bundle.py +340 -0
  11. grantstamp/fingerprint/cdc.py +138 -0
  12. grantstamp/fingerprint/filetypes.py +56 -0
  13. grantstamp/fingerprint/image.py +47 -0
  14. grantstamp/fingerprint/sampling.py +48 -0
  15. grantstamp/fingerprint/strings.py +104 -0
  16. grantstamp/fingerprint/winnow.py +63 -0
  17. grantstamp/hook.py +186 -0
  18. grantstamp/httpsig.py +242 -0
  19. grantstamp/manifest.py +76 -0
  20. grantstamp/markers.py +84 -0
  21. grantstamp/mcp_server.py +149 -0
  22. grantstamp/policy.py +144 -0
  23. grantstamp/pow.py +66 -0
  24. grantstamp/site/assets/check-page.js +85 -0
  25. grantstamp/site/assets/config.js +7 -0
  26. grantstamp/site/assets/favicon.svg +5 -0
  27. grantstamp/site/assets/fonts/OFL-LibreCaslonText.txt +93 -0
  28. grantstamp/site/assets/fonts/OFL-PublicSans.txt +93 -0
  29. grantstamp/site/assets/fonts/libre-caslon-text-latin-400-italic.woff2 +0 -0
  30. grantstamp/site/assets/fonts/libre-caslon-text-latin-400-normal.woff2 +0 -0
  31. grantstamp/site/assets/fonts/libre-caslon-text-latin-700-normal.woff2 +0 -0
  32. grantstamp/site/assets/fonts/public-sans-latin-400-normal.woff2 +0 -0
  33. grantstamp/site/assets/fonts/public-sans-latin-600-normal.woff2 +0 -0
  34. grantstamp/site/assets/fonts/public-sans-latin-700-normal.woff2 +0 -0
  35. grantstamp/site/assets/grantstamp-check.js +224 -0
  36. grantstamp/site/assets/style.css +135 -0
  37. grantstamp/site/check.html +48 -0
  38. grantstamp/site/index.html +165 -0
  39. grantstamp/site/spec.html +31 -0
  40. grantstamp/tokens.py +87 -0
  41. grantstamp/util.py +115 -0
  42. grantstamp-0.1.0.dist-info/METADATA +141 -0
  43. grantstamp-0.1.0.dist-info/RECORD +47 -0
  44. grantstamp-0.1.0.dist-info/WHEEL +4 -0
  45. grantstamp-0.1.0.dist-info/entry_points.txt +4 -0
  46. grantstamp-0.1.0.dist-info/licenses/LICENSE +177 -0
  47. grantstamp-0.1.0.dist-info/licenses/NOTICE +23 -0
grantstamp/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 The Grantstamp Authors
3
+ """Grantstamp: an open ownership registry and check protocol for AI agents.
4
+
5
+ Owners publish fingerprints and a policy for their content (never the content
6
+ itself). AI agents and tools check a file before they analyze, decompile, port,
7
+ modify or redistribute it, and get back the owner, the owner's policy, a
8
+ confidence band and a signed receipt.
9
+ """
10
+
11
+ __version__ = "0.1.0"
12
+ PROTOCOL_VERSION = "0.1"
grantstamp/brand.py ADDED
@@ -0,0 +1,46 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 The Grantstamp Authors
3
+ """Brand constants in one place, so a rename touches as little code as possible.
4
+
5
+ `scripts/rebrand.py` rewrites these and every other reference in the repository.
6
+ Feature-hash domains (see fingerprint/sampling.py) are protocol constants and
7
+ must NOT change after the first public registration, or old fingerprints stop
8
+ matching.
9
+ """
10
+
11
+ BRAND = "Grantstamp"
12
+ SLUG = "grantstamp"
13
+ TAGLINE = "Agents ask first."
14
+
15
+ SITE_URL = "https://grantstamp.io"
16
+ DEFAULT_REGISTRY = "https://registry.grantstamp.io"
17
+
18
+ # Environment variable prefix (GRANTSTAMP_REGISTRY, GRANTSTAMP_DB, ...)
19
+ ENV_PREFIX = "GRANTSTAMP_"
20
+
21
+ # Per-user config directory (~/.grantstamp)
22
+ HOME_DIRNAME = ".grantstamp"
23
+
24
+ # Identifier prefixes
25
+ ID_STAMP = "stamp"
26
+ ID_OWNER = "own"
27
+ ID_AGENT = "agt"
28
+ ID_DISPUTE = "dsp"
29
+ ID_ALERT = "alr"
30
+
31
+ # Embedded marker compiled into binaries / placed in files by owners
32
+ MARKER_TAG = "GRANTSTAMP"
33
+
34
+ # Sidecar manifest filename placed at a distribution's root
35
+ MANIFEST_FILENAME = "grantstamp.json"
36
+
37
+ # DNS / well-known names used for owner domain verification
38
+ DNS_LABEL = "_grantstamp"
39
+ WELL_KNOWN_VERIFY = "/.well-known/grantstamp-verify.txt"
40
+ WELL_KNOWN_REGISTRY = "/.well-known/grantstamp"
41
+
42
+ # Signature tag used in HTTP Message Signatures (RFC 9421) issued by clients
43
+ SIG_TAG = "grantstamp"
44
+
45
+ # HTTP headers
46
+ HEADER_POW = "Grantstamp-PoW"
grantstamp/cli.py ADDED
@@ -0,0 +1,578 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 The Grantstamp Authors
3
+ """Command-line interface: `grantstamp <command>`.
4
+
5
+ Owners: keygen, owner create|domain|verify|show|webhook, register, policy,
6
+ withdraw, alerts, token issue|revoke, marker, manifest
7
+ Agents: check, fingerprint, agent register, token verify
8
+ Anyone: stamp, log verify, dispute
9
+ Operate: serve, mcp, admin ...
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import sys
17
+ import time
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from . import __version__, brand
22
+ from .crypto import generate_key, load_private_key, save_private_key, thumbprint
23
+ from .util import default_registry, home_dir
24
+
25
+ EXIT_OK, EXIT_ERROR, EXIT_DENY, EXIT_ASK = 0, 1, 2, 3
26
+
27
+
28
+ # ---------------------------------------------------------------- config helpers
29
+ def config_path() -> Path:
30
+ return home_dir() / "config.json"
31
+
32
+
33
+ def load_config() -> dict[str, Any]:
34
+ p = config_path()
35
+ return json.loads(p.read_text()) if p.exists() else {}
36
+
37
+
38
+ def save_config(cfg: dict[str, Any]) -> None:
39
+ config_path().write_text(json.dumps(cfg, indent=2, sort_keys=True) + "\n")
40
+
41
+
42
+ def key_path(role: str) -> Path:
43
+ return home_dir() / f"{role}.key"
44
+
45
+
46
+ def load_key(role: str, required: bool = True):
47
+ p = key_path(role)
48
+ if not p.exists():
49
+ if required:
50
+ sys.exit(f"no {role} key at {p}; run `grantstamp keygen --role {role}` first")
51
+ return None
52
+ return load_private_key(p)
53
+
54
+
55
+ def registry_url(args: argparse.Namespace) -> str:
56
+ return (getattr(args, "registry", None) or load_config().get("registry") or default_registry()).rstrip("/")
57
+
58
+
59
+ def client(args: argparse.Namespace, role: str | None = None, required: bool = True):
60
+ from .client import Client
61
+
62
+ key = load_key(role, required) if role else None
63
+ agent_url = load_config().get("agent_url") if role == "agent" else None
64
+ return Client(registry_url(args), key, signature_agent=agent_url)
65
+
66
+
67
+ def out(obj: Any, as_json: bool) -> None:
68
+ if as_json:
69
+ print(json.dumps(obj, indent=2, sort_keys=True))
70
+
71
+
72
+ def owner_id(args: argparse.Namespace) -> str:
73
+ oid = getattr(args, "owner", None) or load_config().get("owner_id")
74
+ if not oid:
75
+ sys.exit("no owner id; run `grantstamp owner create` first or pass --owner")
76
+ return oid
77
+
78
+
79
+ def human_bytes(n: int) -> str:
80
+ for unit in ("B", "KB", "MB", "GB", "TB"):
81
+ if n < 1024 or unit == "TB":
82
+ return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
83
+ n /= 1024
84
+ return str(n)
85
+
86
+
87
+ # ---------------------------------------------------------------- commands
88
+ def cmd_keygen(args):
89
+ p = key_path(args.role)
90
+ if p.exists() and not args.force:
91
+ sys.exit(f"{p} already exists (use --force to replace it; you will lose access to anything it signed)")
92
+ key = generate_key()
93
+ save_private_key(key, p)
94
+ print(f"wrote {args.role} key {p}")
95
+ print(f"key id (RFC 7638 thumbprint): {thumbprint(key)}")
96
+ print("back this file up somewhere safe; it is your identity on the registry")
97
+
98
+
99
+ def cmd_fingerprint(args):
100
+ from .fingerprint import QUERY_CAP, REF_CAP, Options, fingerprint, summarize
101
+
102
+ opts = Options(cap=REF_CAP if args.full else QUERY_CAP)
103
+ t = time.time()
104
+ b = fingerprint(args.path, opts)
105
+ if args.out:
106
+ Path(args.out).write_text(json.dumps(b))
107
+ s = summarize(b)
108
+ if args.json and not args.out:
109
+ print(json.dumps(b))
110
+ return
111
+ print(f"{b['root']}: {s['files']} files, {human_bytes(s['bytes'])} in {time.time() - t:.1f}s")
112
+ print("features: " + ", ".join(f"{k} {v}" for k, v in s["features"].items()))
113
+ if args.out:
114
+ print(f"bundle written to {args.out} (digests only; no content)")
115
+
116
+
117
+ def _print_check(res: dict[str, Any]) -> None:
118
+ v = res["verdict"]
119
+ print(f"band: {v['band']} decision: {v['decision']} stamp: {v.get('stamp') or '-'} access: {res['access']}")
120
+ for m in res["matches"][:3]:
121
+ own = m["owner"]
122
+ ver = ("verified " + ", ".join(own["verified_domains"])) if own["verified"] else "unverified"
123
+ print(f" - {m['band']:>6} {m['stamp']['title']} {m['stamp'].get('version') or ''} "
124
+ f"owner: {own['name']} ({ver}) policy for this use: {m['decision']['action']}")
125
+ print()
126
+ print(v["guidance"])
127
+
128
+
129
+ def cmd_check(args):
130
+ from .fingerprint import fingerprint
131
+
132
+ b = fingerprint(args.path)
133
+ tokens = list(args.token or [])
134
+ tdir = home_dir() / "licenses"
135
+ if tdir.exists():
136
+ tokens += [p.read_text().strip() for p in sorted(tdir.glob("*.jws"))]
137
+ role = "agent" if key_path("agent").exists() and not args.anonymous else None
138
+ res = client(args, role, required=False).check(b, use=args.use, purpose=args.purpose, license_tokens=tokens)
139
+ if args.json:
140
+ out(res, True)
141
+ else:
142
+ _print_check(res)
143
+ if args.exit_code:
144
+ d = res["verdict"]["decision"]
145
+ sys.exit(EXIT_DENY if d == "deny" else EXIT_ASK if d == "ask" else EXIT_OK)
146
+
147
+
148
+ def cmd_owner_create(args):
149
+ c = client(args, "owner")
150
+ res = c.create_owner(args.name, args.contact, args.url)
151
+ cfg = load_config()
152
+ cfg.update({"owner_id": res["owner"]["id"], "registry": c.base})
153
+ save_config(cfg)
154
+ print(f"owner created: {res['owner']['id']} on {c.base}")
155
+ print("next: prove you control your domain with `grantstamp owner domain example.com`")
156
+
157
+
158
+ def cmd_owner_domain(args):
159
+ res = client(args, "owner").add_domain(owner_id(args), args.domain)
160
+ if res["verified"]:
161
+ print(f"{res['domain']} is already verified")
162
+ return
163
+ print(f"Prove control of {res['domain']} with ONE of these, then run `grantstamp owner verify {res['domain']}`:\n")
164
+ print(f" DNS TXT record name: {res['dns']['name']}")
165
+ print(f" value: {res['dns']['value']}\n")
166
+ print(f" HTTPS file url: {res['https']['url']}")
167
+ print(f" body: {res['https']['content']}")
168
+
169
+
170
+ def cmd_owner_verify(args):
171
+ from .client import RegistryError
172
+
173
+ try:
174
+ res = client(args, "owner").verify_domain(owner_id(args), args.domain)
175
+ print(f"{res['domain']} verified via {res['method']}")
176
+ except RegistryError as exc:
177
+ sys.exit(f"not verified yet: {exc.detail}")
178
+
179
+
180
+ def cmd_owner_show(args):
181
+ res = client(args).owner(args.id or owner_id(args))
182
+ if args.json:
183
+ return out(res, True)
184
+ print(f"{res['name']} ({res['id']}) verified domains: {', '.join(res['verified_domains']) or 'none'}")
185
+ for d in res.get("stamps", []):
186
+ print(f" {d['id']} {d['title']} {d.get('version') or ''} [{d['status']}]")
187
+
188
+
189
+ def cmd_owner_webhook(args):
190
+ url = None if args.url == "none" else args.url
191
+ res = client(args, "owner").set_webhook(owner_id(args), url, args.format)
192
+ print(f"webhook set to {res['webhook']} ({res['format']})")
193
+
194
+
195
+ def _load_policy(args) -> dict[str, Any]:
196
+ if getattr(args, "policy", None):
197
+ return json.loads(Path(args.policy).read_text())
198
+ pol: dict[str, Any] = {"preset": getattr(args, "preset", None) or "standard"}
199
+ for field in ("contact", "message", "license_url", "request_url"):
200
+ v = getattr(args, field, None)
201
+ if v:
202
+ pol[field] = v
203
+ return pol
204
+
205
+
206
+ def cmd_register(args):
207
+ from .fingerprint import REF_CAP, Options, fingerprint, summarize
208
+ from .fingerprint.bundle import DEFAULT_EXCLUDES
209
+
210
+ excludes = tuple(args.exclude or ()) + (() if args.no_default_excludes else DEFAULT_EXCLUDES)
211
+ opts = Options(cap=REF_CAP, exclude=excludes)
212
+ t = time.time()
213
+ b = fingerprint(args.path, opts)
214
+ s = summarize(b)
215
+ print(f"fingerprinted {s['files']} files ({human_bytes(s['bytes'])}) in {time.time() - t:.1f}s; "
216
+ f"excluded {b['stats']['excluded']} third-party files; content stays on this machine")
217
+ if args.dry_run:
218
+ print(json.dumps(s, indent=2))
219
+ return
220
+ c = client(args, "owner")
221
+ res = c.register(b, title=args.title, policy=_load_policy(args), version=args.version, kind=args.kind,
222
+ description=args.description)
223
+ stamp = res["stamp"]
224
+ cfg = load_config()
225
+ cfg.setdefault("stamps", {})[stamp["id"]] = {"title": stamp["title"], "version": stamp.get("version")}
226
+ save_config(cfg)
227
+ print(f"registered stamp {stamp['id']} ({res['stored']['files']} files, {res['stored']['features']} features)")
228
+ print(f"public page: {res['page']}")
229
+ if res["conflicts"]:
230
+ print("WARNING: this content overlaps another owner's stamp; it is marked as a conflict:")
231
+ for cf in res["conflicts"]:
232
+ print(f" {cf['stamp_id']} ({cf['band']})")
233
+ print(f"\nembed this marker in future builds: {res['marker']}")
234
+ print("get a source snippet with: grantstamp marker " + stamp["id"] + " --lang c")
235
+ if args.manifest and Path(args.path).is_dir():
236
+ _write_manifest(c, stamp["id"], args.title, args.version, Path(args.path))
237
+
238
+
239
+ def _write_manifest(c, sid: str, title: str, version: str | None, directory: Path) -> None:
240
+ from . import manifest
241
+
242
+ cfg = load_config()
243
+ owner = c.owner(cfg["owner_id"])
244
+ doc = manifest.build(load_key("owner"), stamp_id=sid, owner_id=owner["id"], owner_name=owner["name"],
245
+ registry=c.base, title=title, version=version)
246
+ p = manifest.write(doc, directory)
247
+ print(f"signed manifest written to {p}; ship it at the root of the distribution")
248
+
249
+
250
+ def cmd_manifest(args):
251
+ c = client(args, "owner")
252
+ stamp = c.stamp(args.stamp)
253
+ _write_manifest(c, args.stamp, stamp["title"], stamp.get("version"), Path(args.dir))
254
+
255
+
256
+ def cmd_policy(args):
257
+ res = client(args, "owner").set_policy(args.stamp, _load_policy(args))
258
+ print(json.dumps(res["stamp"]["policy"], indent=2))
259
+
260
+
261
+ def cmd_withdraw(args):
262
+ res = client(args, "owner").withdraw(args.stamp)
263
+ print(f"{args.stamp} is now {res['stamp']['status']}")
264
+
265
+
266
+ def cmd_alerts(args):
267
+ since = int(time.time()) - int(args.hours * 3600)
268
+ res = client(args, "owner").alerts(since)
269
+ if args.json:
270
+ return out(res, True)
271
+ if not res["alerts"]:
272
+ print("no alerts in this window")
273
+ for a in res["alerts"]:
274
+ d = a["detail"]
275
+ print(f"{time.strftime('%Y-%m-%d %H:%M', time.gmtime(a['ts']))} {a['kind']:<9} {a.get('stamp_id') or '-'} "
276
+ f"band={d.get('band')} use={d.get('use')} caller={d.get('ptype')}:{d.get('principal')}")
277
+ if res["summary"]:
278
+ print("\nchecks by stamp and band:")
279
+ for row in res["summary"]:
280
+ print(f" {row['stamp_id']} {row['band']:<6} {row['decision']:<5} x{row['n']}")
281
+
282
+
283
+ def cmd_token_issue(args):
284
+ from .tokens import issue_license
285
+
286
+ cfg = load_config()
287
+ tok = issue_license(load_key("owner"), owner_id=owner_id(args), subject=args.to, stamps=args.stamp,
288
+ uses=[u.strip() for u in args.uses.split(",") if u.strip()], days=args.days, note=args.note)
289
+ if args.out:
290
+ Path(args.out).write_text(tok + "\n")
291
+ print(f"token written to {args.out}; the licensee puts it in ~/{brand.HOME_DIRNAME}/licenses/")
292
+ else:
293
+ print(tok)
294
+ _ = cfg
295
+
296
+
297
+ def cmd_token_verify(args):
298
+ from .tokens import peek
299
+
300
+ res = client(args).verify_token(args.token, args.stamp)
301
+ if args.json:
302
+ return out(res, True)
303
+ if res["valid"]:
304
+ p = res["payload"]
305
+ print(f"valid: {p['sub']} may {', '.join(p['uses'])} on {', '.join(p['stamps'])} until "
306
+ f"{time.strftime('%Y-%m-%d', time.gmtime(p['exp']))} (owner {res['owner']['name']})")
307
+ else:
308
+ print(f"invalid: {res['reason']} (payload: {peek(args.token)})")
309
+
310
+
311
+ def cmd_token_revoke(args):
312
+ client(args, "owner").revoke(args.jti)
313
+ print(f"revoked {args.jti}")
314
+
315
+
316
+ def cmd_marker(args):
317
+ from .markers import snippet
318
+
319
+ c = client(args)
320
+ stamp = c.stamp(args.stamp)
321
+ print(snippet(args.stamp, c.base, args.lang, stamp["owner"]["name"]), end="")
322
+
323
+
324
+ def cmd_show(args):
325
+ res = client(args).stamp(args.stamp)
326
+ if args.json:
327
+ return out(res, True)
328
+ own = res["owner"]
329
+ print(f"{res['title']} {res.get('version') or ''} [{res['status']}] {res['files']} files")
330
+ print(f"owner: {own['name']} ({own['id']}) verified: {', '.join(own['verified_domains']) or 'no'}")
331
+ print("policy: " + ", ".join(f"{u}={a}" for u, a in res["policy"]["uses"].items()))
332
+
333
+
334
+ def cmd_agent_register(args):
335
+ c = client(args, "agent")
336
+ res = c.create_agent(args.name, args.url, args.contact)
337
+ cfg = load_config()
338
+ cfg.update({"agent_id": res["agent"]["id"], "registry": c.base})
339
+ if args.url:
340
+ cfg["agent_url"] = args.url
341
+ save_config(cfg)
342
+ print(f"agent registered: {res['agent']['id']} (trust: {res['agent']['trust']}); requests are now signed")
343
+
344
+
345
+ def cmd_log_verify(args):
346
+ res = client(args).verify_log()
347
+ print(f"transparency log OK: {res['entries']} entries, signed head {res['head'][:16]}... at seq {res['head_seq']}")
348
+
349
+
350
+ def cmd_dispute(args):
351
+ res = client(args).dispute(args.stamp, args.claimant, args.contact, args.reason, args.evidence)
352
+ print(f"dispute filed: {res['id']} ({res['status']})")
353
+
354
+
355
+ def _server_cli():
356
+ """The registry server is a separate, AGPL-3.0 package; load it only when asked to."""
357
+ try:
358
+ from grantstamp_server import cli as server_cli
359
+ except ImportError:
360
+ sys.exit("the registry server is a separate package: pip install grantstamp-server")
361
+ return server_cli
362
+
363
+
364
+ def cmd_serve(args):
365
+ _server_cli().serve(args)
366
+
367
+
368
+ def cmd_mcp(args):
369
+ from .mcp_server import main as mcp_main
370
+
371
+ mcp_main()
372
+
373
+
374
+ def cmd_admin(args):
375
+ _server_cli().admin(args)
376
+
377
+
378
+ # ---------------------------------------------------------------- parser
379
+ def build_parser() -> argparse.ArgumentParser:
380
+ from .policy import PRESETS, PURPOSES, USES
381
+
382
+ p = argparse.ArgumentParser(prog="grantstamp", description=f"{brand.BRAND}: ownership registry for AI agents. "
383
+ f"{brand.TAGLINE}")
384
+ p.add_argument("--version", action="version", version=f"grantstamp {__version__}")
385
+ p.add_argument("--registry", help=f"registry URL (default: config, $GRANTSTAMP_REGISTRY or {brand.DEFAULT_REGISTRY})")
386
+ sub = p.add_subparsers(dest="cmd", required=True)
387
+
388
+ k = sub.add_parser("keygen", help="create an Ed25519 key (owner or agent)")
389
+ k.add_argument("--role", choices=["owner", "agent"], default="owner")
390
+ k.add_argument("--force", action="store_true")
391
+ k.set_defaults(func=cmd_keygen)
392
+
393
+ f = sub.add_parser("fingerprint", help="fingerprint a file or folder locally (no network)")
394
+ f.add_argument("path")
395
+ f.add_argument("--out", help="write the bundle JSON here")
396
+ f.add_argument("--full", action="store_true", help="registration-size feature caps")
397
+ f.add_argument("--json", action="store_true")
398
+ f.set_defaults(func=cmd_fingerprint)
399
+
400
+ c = sub.add_parser("check", help="check a file or folder against the registry")
401
+ c.add_argument("path")
402
+ c.add_argument("--use", choices=USES, default="analyze")
403
+ c.add_argument("--purpose", choices=PURPOSES)
404
+ c.add_argument("--token", action="append", help="licence token (repeatable); ~/.grantstamp/licenses/*.jws is read too")
405
+ c.add_argument("--anonymous", action="store_true", help="do not sign even if an agent key exists")
406
+ c.add_argument("--exit-code", action="store_true", help="exit 2 on deny, 3 on ask")
407
+ c.add_argument("--json", action="store_true")
408
+ c.set_defaults(func=cmd_check)
409
+
410
+ o = sub.add_parser("owner", help="owner account").add_subparsers(dest="owner_cmd", required=True)
411
+ oc = o.add_parser("create")
412
+ oc.add_argument("--name", required=True)
413
+ oc.add_argument("--contact")
414
+ oc.add_argument("--url")
415
+ oc.set_defaults(func=cmd_owner_create)
416
+ od = o.add_parser("domain", help="get a domain verification challenge")
417
+ od.add_argument("domain")
418
+ od.add_argument("--owner")
419
+ od.set_defaults(func=cmd_owner_domain)
420
+ ov = o.add_parser("verify", help="ask the registry to check your DNS/.well-known challenge")
421
+ ov.add_argument("domain")
422
+ ov.add_argument("--owner")
423
+ ov.set_defaults(func=cmd_owner_verify)
424
+ osh = o.add_parser("show")
425
+ osh.add_argument("id", nargs="?")
426
+ osh.add_argument("--owner")
427
+ osh.add_argument("--json", action="store_true")
428
+ osh.set_defaults(func=cmd_owner_show)
429
+ ow = o.add_parser("webhook", help="send alerts to a URL (Slack/Discord incoming webhooks work)")
430
+ ow.add_argument("url", help="https URL, or 'none' to remove")
431
+ ow.add_argument("--format", choices=["json", "slack", "discord"], default="json")
432
+ ow.add_argument("--owner")
433
+ ow.set_defaults(func=cmd_owner_webhook)
434
+
435
+ r = sub.add_parser("register", help="fingerprint content and register a stamp")
436
+ r.add_argument("path")
437
+ r.add_argument("--title", required=True)
438
+ r.add_argument("--version")
439
+ r.add_argument("--kind", default="software", help="software, game, firmware, model, dataset, media, ...")
440
+ r.add_argument("--description")
441
+ r.add_argument("--preset", choices=sorted(PRESETS), default="standard")
442
+ r.add_argument("--policy", help="JSON policy file (overrides --preset)")
443
+ r.add_argument("--contact")
444
+ r.add_argument("--message")
445
+ r.add_argument("--license-url", dest="license_url")
446
+ r.add_argument("--request-url", dest="request_url")
447
+ r.add_argument("--exclude", action="append", help="glob of files to skip (repeatable)")
448
+ r.add_argument("--no-default-excludes", action="store_true", help="also register common third-party runtimes")
449
+ r.add_argument("--manifest", action="store_true", help="write a signed grantstamp.json into the folder")
450
+ r.add_argument("--dry-run", action="store_true")
451
+ r.set_defaults(func=cmd_register)
452
+
453
+ po = sub.add_parser("policy", help="replace a stamp's policy")
454
+ po.add_argument("stamp")
455
+ po.add_argument("--preset", choices=sorted(PRESETS))
456
+ po.add_argument("--policy")
457
+ po.add_argument("--contact")
458
+ po.add_argument("--message")
459
+ po.add_argument("--license-url", dest="license_url")
460
+ po.add_argument("--request-url", dest="request_url")
461
+ po.set_defaults(func=cmd_policy)
462
+
463
+ w = sub.add_parser("withdraw", help="withdraw a stamp")
464
+ w.add_argument("stamp")
465
+ w.set_defaults(func=cmd_withdraw)
466
+
467
+ a = sub.add_parser("alerts", help="matches and probing alerts for your stamps")
468
+ a.add_argument("--hours", type=float, default=24)
469
+ a.add_argument("--json", action="store_true")
470
+ a.set_defaults(func=cmd_alerts)
471
+
472
+ t = sub.add_parser("token", help="licence tokens").add_subparsers(dest="token_cmd", required=True)
473
+ ti = t.add_parser("issue")
474
+ ti.add_argument("--stamp", action="append", required=True, help="stamp id (repeatable) or '*'")
475
+ ti.add_argument("--to", required=True, help="licensee name or identifier")
476
+ ti.add_argument("--uses", required=True, help="comma list: " + ",".join(USES) + " or *")
477
+ ti.add_argument("--days", type=int, default=90)
478
+ ti.add_argument("--note")
479
+ ti.add_argument("--out")
480
+ ti.set_defaults(func=cmd_token_issue)
481
+ tv = t.add_parser("verify")
482
+ tv.add_argument("token")
483
+ tv.add_argument("--stamp")
484
+ tv.add_argument("--json", action="store_true")
485
+ tv.set_defaults(func=cmd_token_verify)
486
+ tr = t.add_parser("revoke")
487
+ tr.add_argument("jti")
488
+ tr.set_defaults(func=cmd_token_revoke)
489
+
490
+ m = sub.add_parser("marker", help="print a source snippet that embeds the ownership notice")
491
+ m.add_argument("stamp")
492
+ m.add_argument("--lang", default="c", help="c, cpp, csharp, rust, python, js, text")
493
+ m.set_defaults(func=cmd_marker)
494
+
495
+ mf = sub.add_parser("manifest", help="write a signed grantstamp.json into a folder")
496
+ mf.add_argument("stamp")
497
+ mf.add_argument("--dir", required=True)
498
+ mf.set_defaults(func=cmd_manifest)
499
+
500
+ d = sub.add_parser("show", help="show a stamp")
501
+ d.add_argument("stamp")
502
+ d.add_argument("--json", action="store_true")
503
+ d.set_defaults(func=cmd_show)
504
+
505
+ ag = sub.add_parser("agent", help="agent identity").add_subparsers(dest="agent_cmd", required=True)
506
+ agr = ag.add_parser("register")
507
+ agr.add_argument("--name", required=True)
508
+ agr.add_argument("--url", help="your origin; enables Web Bot Auth key-directory discovery")
509
+ agr.add_argument("--contact")
510
+ agr.set_defaults(func=cmd_agent_register)
511
+
512
+ lg = sub.add_parser("log", help="transparency log").add_subparsers(dest="log_cmd", required=True)
513
+ lv = lg.add_parser("verify")
514
+ lv.set_defaults(func=cmd_log_verify)
515
+
516
+ ds = sub.add_parser("dispute", help="dispute a stamp")
517
+ ds.add_argument("stamp")
518
+ ds.add_argument("--claimant", required=True)
519
+ ds.add_argument("--contact", required=True)
520
+ ds.add_argument("--reason", required=True)
521
+ ds.add_argument("--evidence", action="append")
522
+ ds.set_defaults(func=cmd_dispute)
523
+
524
+ sv = sub.add_parser("serve", help="run a registry server (needs: pip install grantstamp-server)")
525
+ sv.add_argument("--host", default="127.0.0.1")
526
+ sv.add_argument("--port", type=int, default=8000)
527
+ sv.add_argument("--db", help="sqlite:///path.db or postgresql://...")
528
+ sv.add_argument("--public-url")
529
+ sv.add_argument("--dev", action="store_true", help="allow http and private addresses (local testing only)")
530
+ sv.set_defaults(func=cmd_serve)
531
+
532
+ mc = sub.add_parser("mcp", help="run the MCP server (stdio) for AI agents")
533
+ mc.set_defaults(func=cmd_mcp)
534
+
535
+ ad = sub.add_parser("admin", help="registry operator commands (run on the server; needs grantstamp-server)")
536
+ ad.add_argument("--db")
537
+ asub = ad.add_subparsers(dest="admin_cmd", required=True)
538
+ x = asub.add_parser("verify-domain")
539
+ x.add_argument("owner")
540
+ x.add_argument("domain")
541
+ x.add_argument("--note", default="manual review")
542
+ x = asub.add_parser("trust-agent")
543
+ x.add_argument("agent")
544
+ x.add_argument("--level", default="trusted", choices=["registered", "trusted", "blocked"])
545
+ x = asub.add_parser("stamp-status")
546
+ x.add_argument("stamp")
547
+ x.add_argument("status", choices=["active", "conflict", "suspended", "withdrawn"])
548
+ x = asub.add_parser("owner-status")
549
+ x.add_argument("owner")
550
+ x.add_argument("status", choices=["active", "suspended"])
551
+ x = asub.add_parser("disputes")
552
+ x.add_argument("--status", default="open")
553
+ x = asub.add_parser("resolve")
554
+ x.add_argument("dispute")
555
+ x.add_argument("status", choices=["upheld", "rejected", "withdrawn"])
556
+ x.add_argument("--note", required=True)
557
+ asub.add_parser("stats")
558
+ ad.set_defaults(func=cmd_admin)
559
+ return p
560
+
561
+
562
+ def main(argv: list[str] | None = None) -> None:
563
+ parser = build_parser()
564
+ args = parser.parse_args(argv)
565
+ from .client import RegistryError
566
+
567
+ try:
568
+ args.func(args)
569
+ except RegistryError as exc:
570
+ sys.exit(f"registry error {exc.status}: {exc.detail}")
571
+ except FileNotFoundError as exc:
572
+ sys.exit(f"not found: {exc}")
573
+ except KeyboardInterrupt:
574
+ sys.exit(130)
575
+
576
+
577
+ if __name__ == "__main__":
578
+ main()