glosslayer 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.
glosslayer/cli.py ADDED
@@ -0,0 +1,560 @@
1
+ """Command line interface.
2
+
3
+ gloss init
4
+ gloss import ossie model.yaml [--accept]
5
+ gloss sync file:catalog.yaml
6
+ gloss pending [--dataset sales.orders] [--source ai:]
7
+ gloss accept <id>... | --all --dataset sales.orders
8
+ gloss rename dataset:sales.orders dataset:sales.order_lines
9
+ gloss show field:sales.orders/amount
10
+ gloss history field:sales.orders/amount
11
+ gloss progress
12
+ gloss export ossie -o model.yaml [--validate]
13
+ gloss viz [--html report.html]
14
+ gloss serve | gloss mcp
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import getpass
21
+ import json
22
+ import os
23
+ import sys
24
+ from typing import Any
25
+
26
+ from . import plugins
27
+ from .ledger import Gloss
28
+ from .ledger import open as open_gloss
29
+ from .model import OPEN_STATUSES, Status
30
+ from .policy import MODES, DefaultPolicy
31
+ from .store import Query
32
+
33
+ DEFAULT_DB = "sqlite:///gloss.db"
34
+
35
+
36
+ def _default_actor() -> str:
37
+ return os.environ.get("GLOSS_ACTOR") or f"human:{getpass.getuser()}"
38
+
39
+
40
+ def _short(aid: str) -> str:
41
+ return aid[:8]
42
+
43
+
44
+ def _fmt_value(v: Any, width: int = 60) -> str:
45
+ s = v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)
46
+ return s if len(s) <= width else s[: width - 1] + "…"
47
+
48
+
49
+ def _print_assertions(rows: list[Any], as_json: bool) -> None:
50
+ if as_json:
51
+ print(json.dumps([a.to_dict() for a in rows], indent=2, default=str))
52
+ return
53
+ if not rows:
54
+ print("nothing found")
55
+ return
56
+ for a in rows:
57
+ conf = f" {a.confidence:.2f}" if a.confidence is not None else ""
58
+ print(
59
+ f"{_short(a.id)} {a.status.value:<10} {a.subject} {a.attribute} = {_fmt_value(a.value)}"
60
+ f" [{a.source}{conf}]"
61
+ )
62
+
63
+
64
+ def _query_from(args: argparse.Namespace, statuses: list[Status] | None) -> Query:
65
+ return Query(
66
+ subject=getattr(args, "subject", None),
67
+ dataset=getattr(args, "dataset", None),
68
+ namespace=getattr(args, "namespace", None),
69
+ kind=getattr(args, "kind", None),
70
+ attribute=getattr(args, "attribute", None),
71
+ source_prefix=getattr(args, "source", None),
72
+ group=getattr(args, "group", None),
73
+ statuses=statuses,
74
+ limit=getattr(args, "limit", None),
75
+ )
76
+
77
+
78
+ # ---------------------------------------------------------------------------- commands
79
+ def cmd_init(g: Gloss, args: argparse.Namespace) -> int:
80
+ """``gloss init``: report the schema version; opening the ledger in ``main`` has created it."""
81
+ from . import schema
82
+
83
+ print(f"Gloss ledger ready at {args.db} (schema version {schema.current_version(g.store.engine)})")
84
+ return 0
85
+
86
+
87
+ def cmd_import(g: Gloss, args: argparse.Namespace) -> int:
88
+ """``gloss import``: propose every fact from a source plugin; ``--accept`` accepts them as ``--actor``."""
89
+ kwargs = {"key_by": args.key_by, "namespace": args.namespace} if args.plugin == "ossie" else {}
90
+ src = plugins.instantiate("source", f"{args.plugin}:{args.target}" if args.target else args.plugin, **kwargs)
91
+ results = g.propose_many(
92
+ src.proposals(g), source=src.source_id, actor=args.actor, accept=args.accept,
93
+ comment=f"bulk accepted on import by {args.actor}" if args.accept else None,
94
+ )
95
+ counts: dict[str, int] = {}
96
+ for r in results:
97
+ counts[r.outcome] = counts.get(r.outcome, 0) + 1
98
+ print(f"{len(results)} facts from {src.source_id}: " + ", ".join(f"{v} {k}" for k, v in sorted(counts.items())))
99
+ if args.accept:
100
+ print(f"accepted {len({r.assertion.id for r in results if r.accepted})} facts as {args.actor}")
101
+ return 0
102
+
103
+
104
+ def cmd_sync(g: Gloss, args: argparse.Namespace) -> int:
105
+ """``gloss sync``: sync with a catalog plugin and print what was new, changed, moved or gone."""
106
+ from .sync import sync
107
+
108
+ catalog = plugins.instantiate("catalog", args.catalog)
109
+ rep = sync(g, catalog, auto_accept_structure=not args.no_auto_accept, detect_removed=not args.keep_removed)
110
+ moved = f"{len(rep.moved)} moved, " if rep.moved else ""
111
+ print(
112
+ f"catalog {rep.catalog}: {len(rep.new)} new, {len(rep.changed)} changed, {moved}{len(rep.gone)} gone, "
113
+ f"{rep.unchanged} unchanged | {rep.proposed} proposed, {rep.accepted} accepted, {rep.staled} marked stale"
114
+ )
115
+ for note in rep.notes:
116
+ print(f" - {note}")
117
+ return 0
118
+
119
+
120
+ def cmd_propose(g: Gloss, args: argparse.Namespace) -> int:
121
+ """``gloss propose``: propose one fact; the value is read as JSON when it parses, else as text."""
122
+ try:
123
+ value = json.loads(args.value)
124
+ except json.JSONDecodeError:
125
+ value = args.value
126
+ a = g.propose(
127
+ args.subject,
128
+ args.attribute,
129
+ value,
130
+ source=args.source_as or args.actor,
131
+ actor=args.actor,
132
+ confidence=args.confidence,
133
+ comment=args.comment,
134
+ )
135
+ _print_assertions([a], args.json)
136
+ return 0
137
+
138
+
139
+ def cmd_list(g: Gloss, args: argparse.Namespace) -> int:
140
+ """``gloss list`` and ``gloss pending``: print facts matching the filters (pending: open ones)."""
141
+ statuses = [Status(s) for s in args.status] if args.status else None
142
+ if args.command == "pending" and statuses is None:
143
+ statuses = list(OPEN_STATUSES)
144
+ _print_assertions(g.store.find(_query_from(args, statuses)), args.json)
145
+ return 0
146
+
147
+
148
+ def cmd_action(g: Gloss, args: argparse.Namespace) -> int:
149
+ """``gloss accept`` and the other review actions: on the given ids, or with ``--all`` on every match."""
150
+ action = args.command
151
+ if args.all:
152
+ statuses = [Status(s) for s in args.status] if args.status else list(OPEN_STATUSES)
153
+ q = _query_from(args, statuses)
154
+ if not any([q.subject, q.dataset, q.namespace, q.kind, q.attribute, q.source_prefix, q.group]) \
155
+ and not args.yes:
156
+ print("Refusing to act on everything without a filter. Add --dataset/--source/... or --yes.")
157
+ return 2
158
+ done, errors = g.bulk(action, q, actor=args.actor, comment=args.comment)
159
+ print(f"{action}: {len(done)} changed, {len(errors)} failed")
160
+ for aid, err in errors[:20]:
161
+ print(f" {_short(aid)}: {err}")
162
+ return 1 if errors else 0
163
+ if not args.ids:
164
+ print("Give assertion ids or use --all with filters.")
165
+ return 2
166
+ fn = getattr(g, action)
167
+ seen: set[str] = set()
168
+ for aid in args.ids:
169
+ full = g.get(aid).id
170
+ if full in seen: # already decided with its group
171
+ continue
172
+ before = g.store.last_seq()
173
+ a = fn(full, actor=args.actor, comment=args.comment)
174
+ print(f"{_short(a.id)} -> {a.status.value}")
175
+ if action in ("accept", "reject"):
176
+ for e in g.log(after_seq=before):
177
+ if e.type.value == a.status.value and e.assertion_id != a.id:
178
+ seen.add(e.assertion_id)
179
+ print(f"{_short(e.assertion_id)} -> {a.status.value} (same group)")
180
+ return 0
181
+
182
+
183
+ def cmd_rename(g: Gloss, args: argparse.Namespace) -> int:
184
+ """``gloss rename``: re-key a subject, or a whole path with ``--namespace``, so its facts follow."""
185
+ fn = g.rekey_namespace if args.namespace else g.rekey
186
+ res = fn(args.old, args.new, actor=args.actor, comment=args.comment)
187
+ print(
188
+ f"{len(res.subjects)} subject(s) re-keyed: {res.moved} facts moved, {res.rewritten} references rewritten, "
189
+ f"{res.superseded} superseded, {res.staled} marked stale"
190
+ )
191
+ return 0
192
+
193
+
194
+ def cmd_show(g: Gloss, args: argparse.Namespace) -> int:
195
+ """``gloss show``: a subject's accepted values, then its facts that are not accepted."""
196
+ current = g.current(args.subject)
197
+ rows = g.find(subject=str(args.subject))
198
+ if args.json:
199
+ print(json.dumps({"current": current, "assertions": [a.to_dict() for a in rows]}, indent=2, default=str))
200
+ return 0
201
+ print(args.subject)
202
+ for k, v in current.items():
203
+ print(f" {k:<16} {_fmt_value(v, 80)}")
204
+ other = [a for a in rows if a.status is not Status.ACCEPTED]
205
+ if other:
206
+ print(" not accepted:")
207
+ for a in other:
208
+ print(f" {_short(a.id)} {a.status.value:<10} {a.attribute} = {_fmt_value(a.value)} [{a.source}]")
209
+ return 0
210
+
211
+
212
+ def cmd_history(g: Gloss, args: argparse.Namespace) -> int:
213
+ """``gloss history``: the events of one subject, or the whole log after ``--after``."""
214
+ events = g.history(args.subject) if args.subject else g.log(after_seq=args.after, limit=args.limit)
215
+ if args.json:
216
+ print(json.dumps([e.to_dict() for e in events], indent=2, default=str))
217
+ return 0
218
+ for e in events:
219
+ detail = ""
220
+ if e.type.value == "proposed":
221
+ detail = f"{e.data['subject']} {e.data['attribute']} = {_fmt_value(e.data['value'], 50)}"
222
+ elif e.type.value == "corroborated":
223
+ detail = f"also stated by {e.data.get('source')}"
224
+ elif e.type.value == "rekeyed":
225
+ detail = f"was {e.data['from_subject']}" if e.data.get("from_subject") else "a subject it names moved"
226
+ elif e.data.get("comment"):
227
+ detail = e.data["comment"]
228
+ elif e.data.get("auto"):
229
+ detail = f"by rule: {e.data.get('rule')}"
230
+ if e.via:
231
+ detail = f"{detail} (via {e.via})".strip()
232
+ print(f"#{e.seq:<6} {e.ts:%Y-%m-%d %H:%M:%S} {e.type.value:<13} {_short(e.assertion_id)} {e.actor:<22} {detail}")
233
+ return 0
234
+
235
+
236
+ def cmd_progress(g: Gloss, args: argparse.Namespace) -> int:
237
+ """``gloss progress``: review progress per dataset, as a table or JSON."""
238
+ from .viz import progress_table
239
+
240
+ if args.json:
241
+ print(json.dumps(g.progress(args.dataset), indent=2))
242
+ else:
243
+ print(progress_table(g, args.dataset))
244
+ return 0
245
+
246
+
247
+ def cmd_export(g: Gloss, args: argparse.Namespace) -> int:
248
+ """``gloss export``: write the model as Ossie YAML or publish it through a sink plugin."""
249
+ opts: dict[str, Any] = {"include_pending": args.include_pending, "annotate": not args.no_annotate}
250
+ if args.name:
251
+ opts["name"] = args.name
252
+ if args.dataset:
253
+ opts["dataset_prefix"] = args.dataset
254
+ if args.plugin == "ossie" and not args.target:
255
+ from .ossie import to_ossie
256
+
257
+ result = to_ossie(g, **opts)
258
+ if args.output:
259
+ with open(args.output, "w") as fh:
260
+ fh.write(result.to_yaml())
261
+ else:
262
+ sys.stdout.write(result.to_yaml())
263
+ else:
264
+ sink = plugins.instantiate("sink", f"{args.plugin}:{args.target}" if args.target else args.plugin)
265
+ if args.output:
266
+ opts["path"] = args.output
267
+ result = sink.publish(g, **opts)
268
+ for w in getattr(result, "warnings", []):
269
+ print(f"warning: {w}", file=sys.stderr)
270
+ if args.validate and args.plugin in ("ossie", "git"):
271
+ from .ossie import validate
272
+
273
+ errors = validate(result.document)
274
+ for err in errors:
275
+ print(f"invalid: {err}", file=sys.stderr)
276
+ if errors:
277
+ return 1
278
+ print("valid Ossie document", file=sys.stderr)
279
+ return 0
280
+
281
+
282
+ def cmd_viz(g: Gloss, args: argparse.Namespace) -> int:
283
+ """``gloss viz``: print a Mermaid ER diagram, or write an HTML report with ``--html``."""
284
+ from .viz import html_report, mermaid_er
285
+
286
+ if args.html:
287
+ with open(args.html, "w") as fh:
288
+ fh.write(html_report(g))
289
+ print(f"wrote {args.html}")
290
+ else:
291
+ print(mermaid_er(g, include_pending=not args.accepted_only, dataset_prefix=args.dataset))
292
+ return 0
293
+
294
+
295
+ def cmd_types(g: Gloss, args: argparse.Namespace) -> int:
296
+ """``gloss types``: accepted semantic types and the fields that use them."""
297
+ from .checks import Check
298
+
299
+ state = g.snapshot([Status.ACCEPTED])
300
+ if args.json:
301
+ print(json.dumps({n: {**t.attrs, "used_by": [str(s) for s in state.usages(n)]}
302
+ for n, t in state.types.items()}, indent=2, default=str))
303
+ return 0
304
+ if not state.types:
305
+ print("no accepted semantic types")
306
+ return 0
307
+ for name, t in sorted(state.types.items()):
308
+ used = state.usages(name)
309
+ a = t.attrs
310
+ dtype = a.get("physical_type") or a.get("datatype") or "?"
311
+ conf = f" [{a['confidentiality']}]" if a.get("confidentiality") else ""
312
+ print(f"{name} {dtype}{conf} used by {len(used)} field(s)")
313
+ if a.get("description"):
314
+ print(f" {a['description']}")
315
+ for c in a.get("checks") or []:
316
+ print(f" check: {Check.from_dict(c).describe()}")
317
+ for s in used[: args.show]:
318
+ print(f" - {s}")
319
+ if len(used) > args.show:
320
+ print(f" … and {len(used) - args.show} more")
321
+ return 0
322
+
323
+
324
+ def cmd_check(g: Gloss, args: argparse.Namespace) -> int:
325
+ """``gloss check``: run a dataset's checks on a Parquet or CSV file (exit 1 if any fail), or print SQL."""
326
+ from . import checks
327
+
328
+ if args.sql:
329
+ for subj, chk, query in checks.to_sql(g, args.dataset, dialect=args.dialect):
330
+ print(f"-- {subj}: {checks.Check.from_dict(chk).describe()}\n{query};")
331
+ return 0
332
+ if not args.data:
333
+ print("Give --data <file.parquet|.csv> to run the checks, or --sql to print them as SQL.")
334
+ return 2
335
+ import polars as pl
336
+
337
+ df = pl.read_parquet(args.data) if args.data.endswith(".parquet") else pl.read_csv(args.data)
338
+ results = checks.run_polars(g, args.dataset, df)
339
+ for r in results:
340
+ print(r)
341
+ if r.sample:
342
+ print(f" e.g. {r.sample}")
343
+ if args.record:
344
+ run = g.record_check_results(results, runner=args.actor, run_id=args.run_id)
345
+ print(f"recorded run {run[:8]}")
346
+ return 0 if all(r.passed for r in results) else 1
347
+
348
+
349
+ def cmd_search(g: Gloss, args: argparse.Namespace) -> int:
350
+ """``gloss search``: search accepted knowledge; ``--as-ai`` applies the AI visibility limit."""
351
+ hits = g.search(" ".join(args.text), kinds=args.kind, dataset_prefix=args.dataset, limit=args.limit,
352
+ for_ai=bool(args.as_ai))
353
+ if args.json:
354
+ print(json.dumps(hits, indent=2))
355
+ return 0
356
+ if not hits:
357
+ print("nothing found")
358
+ for h in hits:
359
+ extra = " [redacted]" if h.get("redacted") else (f" {_fmt_value(h['description'], 70)}" if h.get("description") else "")
360
+ st = f" <{h['semantic_type']}>" if h.get("semantic_type") else ""
361
+ print(f"{h['subject']}{st}{extra}")
362
+ return 0
363
+
364
+
365
+ def cmd_reindex(g: Gloss, args: argparse.Namespace) -> int:
366
+ """``gloss reindex``: rebuild the search index."""
367
+ print(f"indexed {g.rebuild_search_index()} subjects")
368
+ return 0
369
+
370
+
371
+ def cmd_rebuild(g: Gloss, args: argparse.Namespace) -> int:
372
+ """``gloss rebuild``: recompute every assertion's state from the event log."""
373
+ n = g.rebuild_projection()
374
+ print(f"rebuilt {n} assertions from the event log")
375
+ return 0
376
+
377
+
378
+ def cmd_plugins(g: Gloss | None, args: argparse.Namespace) -> int:
379
+ """``gloss plugins``: list the installed plugins by kind (needs no ledger)."""
380
+ for kind in plugins.GROUPS:
381
+ for name, target in sorted(plugins.available(kind).items()):
382
+ print(f"{kind:<8} {name:<20} {target}")
383
+ return 0
384
+
385
+
386
+ def cmd_serve(g: Gloss, args: argparse.Namespace) -> int:
387
+ """``gloss serve``: run the REST API with uvicorn; the actor comes from the ``X-Gloss-Actor`` header."""
388
+ import uvicorn
389
+
390
+ from .server import create_app
391
+
392
+ uvicorn.run(create_app(g), host=args.host, port=args.port)
393
+ return 0
394
+
395
+
396
+ def cmd_mcp(g: Gloss, args: argparse.Namespace) -> int:
397
+ """``gloss mcp``: run the MCP server, proposing as ``ai:<agent>``."""
398
+ from .mcp_server import run
399
+
400
+ run(g, agent=args.agent, transport=args.transport)
401
+ return 0
402
+
403
+
404
+ # ---------------------------------------------------------------------------- parser
405
+ def build_parser() -> argparse.ArgumentParser:
406
+ """The ``gloss`` argument parser; each subcommand sets ``fn`` to its ``cmd_*`` function."""
407
+ p = argparse.ArgumentParser(prog="gloss", description="Track, review and serve semantic metadata.")
408
+ p.add_argument("--db", default=os.environ.get("GLOSS_DB", DEFAULT_DB), help="SQLAlchemy URL (env GLOSS_DB)")
409
+ p.add_argument("--actor", default=_default_actor(), help="who is acting, e.g. human:alice (env GLOSS_ACTOR)")
410
+ p.add_argument("--mode", default=os.environ.get("GLOSS_MODE", "team"), choices=sorted(MODES),
411
+ help="review mode: solo accepts your own edits at once (env GLOSS_MODE)")
412
+ p.add_argument("--json", action="store_true", help="machine-readable output")
413
+ sub = p.add_subparsers(dest="command", required=True)
414
+
415
+ def filters(sp: argparse.ArgumentParser) -> None:
416
+ sp.add_argument("--subject")
417
+ sp.add_argument("--dataset")
418
+ sp.add_argument("--namespace", help="dotted path: everything at or under it")
419
+ sp.add_argument("--kind", choices=["model", "dataset", "field", "relationship", "metric", "type"])
420
+ sp.add_argument("--attribute")
421
+ sp.add_argument("--source", help="source prefix, e.g. ai: or import:ossie")
422
+ sp.add_argument("--group", help="a proposal group id")
423
+ sp.add_argument("--status", action="append", choices=[s.value for s in Status])
424
+ sp.add_argument("--limit", type=int)
425
+
426
+ sub.add_parser("init", help="create the ledger").set_defaults(fn=cmd_init)
427
+
428
+ sp = sub.add_parser("import", help="import proposals from a source plugin")
429
+ sp.add_argument("plugin", help="source plugin, e.g. ossie")
430
+ sp.add_argument("target", nargs="?", help="plugin argument, e.g. a file path")
431
+ sp.add_argument("--accept", action="store_true", help="accept everything imported, as --actor")
432
+ sp.add_argument("--key-by", default="name", choices=["name", "source"], help="(ossie) dataset key")
433
+ sp.add_argument("--namespace", help="(ossie) namespace for the file's relationships and model-level metrics")
434
+ sp.set_defaults(fn=cmd_import)
435
+
436
+ sp = sub.add_parser("sync", help="sync with a catalog plugin and detect drift")
437
+ sp.add_argument("catalog", help="catalog spec, e.g. file:catalog.yaml")
438
+ sp.add_argument("--no-auto-accept", action="store_true", help="propose structural facts instead of accepting")
439
+ sp.add_argument("--keep-removed", action="store_true", help="do not mark facts of missing assets stale")
440
+ sp.set_defaults(fn=cmd_sync)
441
+
442
+ sp = sub.add_parser("propose", help="propose one fact")
443
+ sp.add_argument("subject")
444
+ sp.add_argument("attribute")
445
+ sp.add_argument("value", help="string or JSON")
446
+ sp.add_argument("--confidence", type=float)
447
+ sp.add_argument("--comment")
448
+ sp.add_argument("--source-as", help="record a different source than the actor, e.g. ai:claude")
449
+ sp.set_defaults(fn=cmd_propose)
450
+
451
+ for name, helptext in (("pending", "facts awaiting review"), ("list", "query facts")):
452
+ sp = sub.add_parser(name, help=helptext)
453
+ filters(sp)
454
+ sp.set_defaults(fn=cmd_list)
455
+
456
+ for name in ("review", "accept", "reject", "retract", "reopen", "restore"):
457
+ sp = sub.add_parser(name, help=f"{name} facts")
458
+ sp.add_argument("ids", nargs="*", help="assertion ids (unique prefixes are fine)")
459
+ sp.add_argument("--all", action="store_true", help="apply to all facts matching the filters")
460
+ sp.add_argument("--yes", action="store_true", help="allow --all without filters")
461
+ sp.add_argument("--comment")
462
+ filters(sp)
463
+ sp.set_defaults(fn=cmd_action)
464
+
465
+ sp = sub.add_parser("rename", help="record that a subject was renamed or moved; its facts follow")
466
+ sp.add_argument("old", help="subject, e.g. dataset:sales.orders (or a path with --namespace)")
467
+ sp.add_argument("new")
468
+ sp.add_argument("--namespace", action="store_true", help="old and new are paths: move everything under old")
469
+ sp.add_argument("--comment")
470
+ sp.set_defaults(fn=cmd_rename)
471
+
472
+ sp = sub.add_parser("show", help="current state of one subject")
473
+ sp.add_argument("subject")
474
+ sp.set_defaults(fn=cmd_show)
475
+
476
+ sp = sub.add_parser("history", help="event log, for one subject or everything")
477
+ sp.add_argument("subject", nargs="?")
478
+ sp.add_argument("--after", type=int, default=0)
479
+ sp.add_argument("--limit", type=int, default=200)
480
+ sp.set_defaults(fn=cmd_history)
481
+
482
+ sp = sub.add_parser("progress", help="review progress per dataset")
483
+ sp.add_argument("--dataset", help="dataset key prefix")
484
+ sp.set_defaults(fn=cmd_progress)
485
+
486
+ sp = sub.add_parser("export", help="publish through a sink plugin")
487
+ sp.add_argument("plugin", nargs="?", default="ossie", help="sink plugin: ossie (default) or git")
488
+ sp.add_argument("target", nargs="?", help="plugin argument, e.g. repo path for git")
489
+ sp.add_argument("-o", "--output")
490
+ sp.add_argument("--name")
491
+ sp.add_argument("--dataset", help="only datasets with this key prefix")
492
+ sp.add_argument("--include-pending", action="store_true")
493
+ sp.add_argument("--no-annotate", action="store_true", help="omit gloss review annotations")
494
+ sp.add_argument("--validate", action="store_true", help="validate against the Ossie JSON Schema")
495
+ sp.set_defaults(fn=cmd_export)
496
+
497
+ sp = sub.add_parser("viz", help="Mermaid ER diagram or an HTML report")
498
+ sp.add_argument("--html", help="write an HTML report to this path")
499
+ sp.add_argument("--accepted-only", action="store_true")
500
+ sp.add_argument("--dataset")
501
+ sp.set_defaults(fn=cmd_viz)
502
+
503
+ sp = sub.add_parser("types", help="semantic types and where they are used")
504
+ sp.add_argument("--show", type=int, default=5, help="how many usages to list per type")
505
+ sp.set_defaults(fn=cmd_types)
506
+
507
+ sp = sub.add_parser("check", help="run data quality checks for a dataset")
508
+ sp.add_argument("dataset")
509
+ sp.add_argument("--data", help="Parquet or CSV file with the data (needs polars)")
510
+ sp.add_argument("--record", action="store_true", help="log the results")
511
+ sp.add_argument("--run-id", help="record under this run id (default: a new one)")
512
+ sp.add_argument("--sql", action="store_true", help="print the checks as SQL instead of running them")
513
+ sp.add_argument("--dialect", default="ansi", choices=["ansi", "postgres", "duckdb", "snowflake", "bigquery"])
514
+ sp.set_defaults(fn=cmd_check)
515
+
516
+ sp = sub.add_parser("search", help="search accepted knowledge (names, descriptions, synonyms)")
517
+ sp.add_argument("text", nargs="+")
518
+ sp.add_argument("--kind", action="append", choices=["model", "dataset", "field", "relationship", "metric", "type"])
519
+ sp.add_argument("--dataset", help="dataset key prefix")
520
+ sp.add_argument("--limit", type=int, default=20)
521
+ sp.add_argument("--as-ai", action="store_true", help="apply the AI visibility limit")
522
+ sp.set_defaults(fn=cmd_search)
523
+
524
+ sub.add_parser("reindex", help="rebuild the search index").set_defaults(fn=cmd_reindex)
525
+ sub.add_parser("rebuild", help="rebuild current state from the event log").set_defaults(fn=cmd_rebuild)
526
+ sub.add_parser("plugins", help="list installed plugins").set_defaults(fn=cmd_plugins, no_db=True)
527
+
528
+ sp = sub.add_parser("serve", help="run the REST API")
529
+ sp.add_argument("--host", default="127.0.0.1")
530
+ sp.add_argument("--port", type=int, default=8765)
531
+ sp.set_defaults(fn=cmd_serve)
532
+
533
+ sp = sub.add_parser("mcp", help="run the MCP server for AI agents")
534
+ sp.add_argument("--agent", default="assistant", help="recorded as source ai:<agent>")
535
+ sp.add_argument("--transport", default="stdio", choices=["stdio", "sse", "streamable-http"])
536
+ sp.set_defaults(fn=cmd_mcp)
537
+ return p
538
+
539
+
540
+ def main(argv: list[str] | None = None) -> int:
541
+ """Run ``gloss`` with ``argv`` and return the exit code (2, with a one-line message, on a known error)."""
542
+ from .model import InvalidTransition
543
+ from .policy import PermissionDenied
544
+
545
+ args = build_parser().parse_args(argv)
546
+ if getattr(args, "no_db", False):
547
+ return args.fn(None, args)
548
+ g = open_gloss(args.db, policy=DefaultPolicy(mode=args.mode))
549
+ try:
550
+ return args.fn(g, args)
551
+ except (PermissionDenied, InvalidTransition, KeyError, ValueError, LookupError, RuntimeError) as exc:
552
+ msg = exc.args[0] if isinstance(exc, KeyError) and exc.args else exc
553
+ print(f"error: {msg}", file=sys.stderr)
554
+ return 2
555
+ finally:
556
+ g.close()
557
+
558
+
559
+ if __name__ == "__main__":
560
+ raise SystemExit(main())