textgraph-kg 3.2.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 (117) hide show
  1. textgraph/__init__.py +6 -0
  2. textgraph/cli.py +923 -0
  3. textgraph/console/__init__.py +10 -0
  4. textgraph/console/api.py +101 -0
  5. textgraph/console/chat.py +512 -0
  6. textgraph/console/ingest.py +124 -0
  7. textgraph/console/page.py +49 -0
  8. textgraph/console/renderer.py +592 -0
  9. textgraph/console/server.py +212 -0
  10. textgraph/core/__init__.py +27 -0
  11. textgraph/core/canonical_doc.py +131 -0
  12. textgraph/core/canonical_json.py +38 -0
  13. textgraph/core/config.py +120 -0
  14. textgraph/core/content_address.py +52 -0
  15. textgraph/core/incremental.py +122 -0
  16. textgraph/core/layout.py +109 -0
  17. textgraph/core/offsets.py +154 -0
  18. textgraph/doctor.py +201 -0
  19. textgraph/got/__init__.py +15 -0
  20. textgraph/got/reason.py +386 -0
  21. textgraph/got/thought.py +123 -0
  22. textgraph/gql/__init__.py +14 -0
  23. textgraph/gql/ast.py +96 -0
  24. textgraph/gql/engine.py +399 -0
  25. textgraph/gql/errors.py +16 -0
  26. textgraph/gql/parser.py +345 -0
  27. textgraph/gql/tokenizer.py +123 -0
  28. textgraph/integrations/__init__.py +22 -0
  29. textgraph/integrations/adapters.py +120 -0
  30. textgraph/l0_ingest/__init__.py +10 -0
  31. textgraph/l0_ingest/base.py +180 -0
  32. textgraph/l0_ingest/dispatch.py +38 -0
  33. textgraph/l0_ingest/logs.py +61 -0
  34. textgraph/l0_ingest/markdown.py +109 -0
  35. textgraph/l0_ingest/plaintext.py +48 -0
  36. textgraph/l0_ingest/richdocs.py +231 -0
  37. textgraph/l0_ingest/structured.py +98 -0
  38. textgraph/l0_ingest/transcript.py +52 -0
  39. textgraph/l1_structure/__init__.py +11 -0
  40. textgraph/l1_structure/decisions.py +149 -0
  41. textgraph/l1_structure/emit.py +81 -0
  42. textgraph/l1_structure/structure.py +276 -0
  43. textgraph/l2_linguistic/__init__.py +12 -0
  44. textgraph/l2_linguistic/negation.py +31 -0
  45. textgraph/l2_linguistic/sentences.py +65 -0
  46. textgraph/l3_encoder_ie/__init__.py +32 -0
  47. textgraph/l3_encoder_ie/canonicalize.py +100 -0
  48. textgraph/l3_encoder_ie/emit_ie.py +80 -0
  49. textgraph/l3_encoder_ie/extract.py +339 -0
  50. textgraph/l3_encoder_ie/gliner_backend.py +109 -0
  51. textgraph/l3_encoder_ie/model.py +72 -0
  52. textgraph/l3_encoder_ie/rules.py +181 -0
  53. textgraph/l4_llm_optional/__init__.py +12 -0
  54. textgraph/l4_llm_optional/cache.py +41 -0
  55. textgraph/l4_llm_optional/client.py +108 -0
  56. textgraph/l4_llm_optional/extract.py +113 -0
  57. textgraph/l4_llm_optional/synthesize.py +120 -0
  58. textgraph/l5_entity_resolution/__init__.py +25 -0
  59. textgraph/l5_entity_resolution/audit.py +38 -0
  60. textgraph/l5_entity_resolution/blocking.py +43 -0
  61. textgraph/l5_entity_resolution/clustering.py +52 -0
  62. textgraph/l5_entity_resolution/emit_er.py +47 -0
  63. textgraph/l5_entity_resolution/metrics.py +63 -0
  64. textgraph/l5_entity_resolution/model.py +53 -0
  65. textgraph/l5_entity_resolution/resolve.py +102 -0
  66. textgraph/l5_entity_resolution/scoring.py +57 -0
  67. textgraph/l5_entity_resolution/similarity.py +74 -0
  68. textgraph/l5_entity_resolution/splink_backend.py +33 -0
  69. textgraph/l6_graph_model/__init__.py +11 -0
  70. textgraph/l6_graph_model/claims.py +164 -0
  71. textgraph/l6_graph_model/conflicts.py +339 -0
  72. textgraph/l6_graph_model/temporal.py +99 -0
  73. textgraph/l7_analytics/__init__.py +10 -0
  74. textgraph/l7_analytics/algorithms.py +157 -0
  75. textgraph/l7_analytics/analyze.py +169 -0
  76. textgraph/l7_analytics/communities.py +194 -0
  77. textgraph/l7_analytics/enrich.py +80 -0
  78. textgraph/l7_analytics/layout.py +152 -0
  79. textgraph/l8_retrieval/__init__.py +11 -0
  80. textgraph/l8_retrieval/bm25.py +70 -0
  81. textgraph/l8_retrieval/dense.py +212 -0
  82. textgraph/l8_retrieval/emit_chunks.py +143 -0
  83. textgraph/l8_retrieval/engine.py +1138 -0
  84. textgraph/l8_retrieval/grounding.py +49 -0
  85. textgraph/l8_retrieval/model.py +446 -0
  86. textgraph/l8_retrieval/narrate.py +63 -0
  87. textgraph/l8_retrieval/rerank.py +72 -0
  88. textgraph/l8_retrieval/routing.py +145 -0
  89. textgraph/l8_retrieval/vision/__init__.py +20 -0
  90. textgraph/l8_retrieval/vision/embed.py +80 -0
  91. textgraph/l8_retrieval/vision/maxsim.py +45 -0
  92. textgraph/l8_retrieval/vision/retriever.py +59 -0
  93. textgraph/l9_artifacts/__init__.py +9 -0
  94. textgraph/l9_artifacts/analytics_lite.py +50 -0
  95. textgraph/l9_artifacts/artifacts.py +217 -0
  96. textgraph/l9_artifacts/graph_html.py +95 -0
  97. textgraph/l9_artifacts/graph_json.py +92 -0
  98. textgraph/l9_artifacts/prov.py +115 -0
  99. textgraph/l9_artifacts/report.py +249 -0
  100. textgraph/mcp/__init__.py +9 -0
  101. textgraph/mcp/server.py +99 -0
  102. textgraph/mcp/tools.py +132 -0
  103. textgraph/pipeline.py +465 -0
  104. textgraph/security/__init__.py +32 -0
  105. textgraph/security/abac.py +84 -0
  106. textgraph/security/context.py +42 -0
  107. textgraph/security/policy.py +119 -0
  108. textgraph/security/rebac.py +107 -0
  109. textgraph/store/__init__.py +10 -0
  110. textgraph/store/base.py +90 -0
  111. textgraph/store/duckdb_store.py +175 -0
  112. textgraph/store/memory.py +40 -0
  113. textgraph/watch.py +80 -0
  114. textgraph_kg-3.2.0.dist-info/METADATA +362 -0
  115. textgraph_kg-3.2.0.dist-info/RECORD +117 -0
  116. textgraph_kg-3.2.0.dist-info/WHEEL +4 -0
  117. textgraph_kg-3.2.0.dist-info/entry_points.txt +2 -0
textgraph/cli.py ADDED
@@ -0,0 +1,923 @@
1
+ """TextGraph command-line entry point.
2
+
3
+ Build:
4
+ * ``textgraph version`` — print the version.
5
+ * ``textgraph build <path> [-o DIR]`` — run the full pipeline and write the
6
+ textgraph-out/ artifacts. ``--json-only PATH`` writes just byte-stable graph.json.
7
+ * ``textgraph er audit <path>`` — review proposed SAME_AS merges.
8
+
9
+ Query (all eight L8 tools, over the same ``QueryEngine`` the MCP server uses):
10
+ * ``query`` (hybrid search), ``path`` (max-likelihood), ``explain`` (why),
11
+ ``neighbors``, ``timeline``, ``contradictions``, ``conflicts``, ``communities``, ``stats``.
12
+ * ``gql`` — a standard GQL (ISO-GQL/Cypher subset) query over the property graph.
13
+ * ``vision`` — late-interaction MaxSim page retrieval (ColPali behind ``[vision]``).
14
+ * ``secure`` — security-aware search under a ReBAC/ABAC policy (enterprise FGAC).
15
+ * ``reason`` — Graph-of-Thoughts reasoning: a KG-grounded, complexity-gated chain.
16
+ * ``console`` — serve the interactive web viewer; ``watch`` — incremental rebuilds.
17
+ * ``doctor`` — read-only environment health check (extras + on-machine determinism).
18
+ * ``export`` — export an interoperable view (PROV-O JSON-LD decision-provenance trail).
19
+ * ``trace-decision`` / ``find-decisions`` — walk a decision's causal chain; search decisions.
20
+
21
+ The human CLI and the MCP tool surface are built off the same underlying result
22
+ objects, formatted two ways — never two drifting code paths (§6.4).
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ from textgraph import __version__
32
+ from textgraph.l5_entity_resolution import build_records, render_audit, run_er
33
+ from textgraph.l8_retrieval import QueryEngine
34
+ from textgraph.l9_artifacts import write_artifacts
35
+ from textgraph.pipeline import build, build_graph_bytes
36
+
37
+
38
+ def _cmd_version(_: argparse.Namespace) -> int:
39
+ print(__version__)
40
+ return 0
41
+
42
+
43
+ def _engine(path: Path) -> QueryEngine:
44
+ # A .duckdb path is a persisted graph — load it straight from disk (no rebuild).
45
+ if path.is_file() and path.suffix == ".duckdb":
46
+ from textgraph.store.duckdb_store import load_graph
47
+
48
+ nodes, edges = load_graph(path)
49
+ return QueryEngine(nodes, edges)
50
+ result = build(path)
51
+ return QueryEngine(result.nodes, result.edges)
52
+
53
+
54
+ def _fmt_citation(cit: dict[str, object]) -> str:
55
+ return f"[{cit['doc_id']}:{cit['start']}-{cit['end']}]"
56
+
57
+
58
+ def _dense_engine(root: Path, args: argparse.Namespace) -> QueryEngine:
59
+ """Build a QueryEngine, wiring a dense embedder when ``--embed`` is given."""
60
+ backend = getattr(args, "embed", "") or ""
61
+ if not backend:
62
+ return _engine(root)
63
+ import tempfile
64
+
65
+ from textgraph.core.config import Config
66
+ from textgraph.l8_retrieval.dense import resolve_text_embedder
67
+
68
+ config = Config(
69
+ embed_backend=backend,
70
+ embed_model=args.embed_model or Config().embed_model,
71
+ embed_base_url=args.embed_url or Config().embed_base_url,
72
+ )
73
+ cache = Path(tempfile.gettempdir()) / "textgraph-embed-cache"
74
+ embedder = resolve_text_embedder(config, cache_dir=cache)
75
+ if root.is_file() and root.suffix == ".duckdb":
76
+ from textgraph.store.duckdb_store import load_graph
77
+
78
+ nodes, edges = load_graph(root)
79
+ else:
80
+ result = build(root)
81
+ nodes, edges = result.nodes, result.edges
82
+ return QueryEngine(nodes, edges, text_embedder=embedder)
83
+
84
+
85
+ def _cmd_query(args: argparse.Namespace) -> int:
86
+ root = Path(args.path)
87
+ if not root.exists():
88
+ print(f"error: path does not exist: {root}", file=sys.stderr)
89
+ return 2
90
+ res = _dense_engine(root, args).search(args.query, k=args.k).to_dict()
91
+ print(f"search: {res['query']} (routing: {res['routing']})")
92
+ for i, hit in enumerate(res["hits"], 1):
93
+ cites = " ".join(_fmt_citation(c) for c in hit["citations"])
94
+ print(f" {i}. [{hit['kind']}] {hit['name']} (score {hit['score']})")
95
+ if hit["snippet"]:
96
+ print(f" {hit['snippet'][:160]}")
97
+ if cites:
98
+ print(f" {cites}")
99
+ if res["truncated"]:
100
+ print(" ... (truncated to token budget)")
101
+ if getattr(args, "narrate", False):
102
+ from textgraph.core.config import Config
103
+ from textgraph.l4_llm_optional import resolve_client
104
+ from textgraph.l8_retrieval.model import Citation
105
+ from textgraph.l8_retrieval.narrate import narrate
106
+
107
+ client = resolve_client(Config())
108
+ if client is None:
109
+ print("\n[narrate] no LLM endpoint configured (set the LLM env vars).", file=sys.stderr)
110
+ return 0
111
+ passages = [
112
+ (h["snippet"], [Citation(**c) for c in h["citations"]])
113
+ for h in res["hits"]
114
+ if h.get("snippet")
115
+ ]
116
+ ans = narrate(client, args.query, passages)
117
+ if ans is not None:
118
+ print(f"\n[LLM answer -- GENERATED]\n{ans.text}")
119
+ return 0
120
+
121
+
122
+ def _cmd_path(args: argparse.Namespace) -> int:
123
+ root = Path(args.path)
124
+ if not root.exists():
125
+ print(f"error: path does not exist: {root}", file=sys.stderr)
126
+ return 2
127
+ res = _engine(root).path(args.source, args.target, k=args.k).to_dict()
128
+ if not res["paths"]:
129
+ print(f"no path found from {res['source']} to {res['target']}")
130
+ return 0
131
+ for i, p in enumerate(res["paths"], 1):
132
+ print(f"path {i} (likelihood {p['likelihood']}): " + " -> ".join(p["nodes"]))
133
+ for step in p["steps"]:
134
+ cites = " ".join(_fmt_citation(c) for c in step["citations"])
135
+ print(
136
+ f" {step['subject']} -{step['predicate']}-> {step['object']}"
137
+ f" [{step['tag']}] {cites}"
138
+ )
139
+ return 0
140
+
141
+
142
+ def _cmd_explain(args: argparse.Namespace) -> int:
143
+ root = Path(args.path)
144
+ if not root.exists():
145
+ print(f"error: path does not exist: {root}", file=sys.stderr)
146
+ return 2
147
+ res = _engine(root).why(args.node).to_dict()
148
+ print(f"why: {res['name']}")
149
+ for c in res["claims"]:
150
+ cites = " ".join(_fmt_citation(x) for x in c["citations"])
151
+ neg = " (negated)" if c["polarity"] == "neg" else ""
152
+ if c["t_valid"] and c.get("t_invalid"):
153
+ when = f" valid=[{c['t_valid']}, {c['t_invalid']}) SUPERSEDED"
154
+ elif c["t_valid"]:
155
+ when = f" valid=[{c['t_valid']}, now)"
156
+ else:
157
+ when = ""
158
+ print(
159
+ f" {c['subject']} -{c['predicate']}-> {c['object']}{neg}"
160
+ f" [{c['tag']} {c['confidence']}]{when} {cites}"
161
+ )
162
+ if res["rationale"]:
163
+ print("rationale:")
164
+ for r in res["rationale"]:
165
+ print(f" - {r}")
166
+ return 0
167
+
168
+
169
+ def _cmd_neighbors(args: argparse.Namespace) -> int:
170
+ root = Path(args.path)
171
+ if not root.exists():
172
+ print(f"error: path does not exist: {root}", file=sys.stderr)
173
+ return 2
174
+ res = _engine(root).neighbors(args.node, k=args.k).to_dict()
175
+ print(f"neighbors of {res['name']}:")
176
+ for n in res["neighbors"]:
177
+ arrow = "->" if n["direction"] == "out" else "<-"
178
+ cites = " ".join(_fmt_citation(c) for c in n["citations"])
179
+ print(
180
+ f" {arrow} {n['predicate']} {n['other_name']} [{n['tag']} {n['confidence']}] {cites}"
181
+ )
182
+ if res["truncated"]:
183
+ print(" ... (truncated to token budget)")
184
+ return 0
185
+
186
+
187
+ def _fmt_window(c: dict[str, object]) -> str:
188
+ if c["t_valid"] and c.get("t_invalid"):
189
+ return f" valid=[{c['t_valid']}, {c['t_invalid']}) SUPERSEDED"
190
+ if c["t_valid"]:
191
+ return f" valid=[{c['t_valid']}, now)"
192
+ return ""
193
+
194
+
195
+ def _cmd_timeline(args: argparse.Namespace) -> int:
196
+ root = Path(args.path)
197
+ if not root.exists():
198
+ print(f"error: path does not exist: {root}", file=sys.stderr)
199
+ return 2
200
+ res = _engine(root).timeline(args.node).to_dict()
201
+ print(f"timeline: {res['name']}")
202
+ for c in res["events"]:
203
+ neg = " (negated)" if c["polarity"] == "neg" else ""
204
+ cites = " ".join(_fmt_citation(x) for x in c["citations"])
205
+ print(f" {c['subject']} -{c['predicate']}-> {c['object']}{neg}{_fmt_window(c)} {cites}")
206
+ return 0
207
+
208
+
209
+ def _cmd_contradictions(args: argparse.Namespace) -> int:
210
+ root = Path(args.path)
211
+ if not root.exists():
212
+ print(f"error: path does not exist: {root}", file=sys.stderr)
213
+ return 2
214
+ res = _engine(root).contradictions().to_dict()
215
+ if not res["pairs"]:
216
+ print("no contradictions found")
217
+ return 0
218
+ print(f"contradictions: {len(res['pairs'])}")
219
+ for p in res["pairs"]:
220
+ a, b = p["claim_a"], p["claim_b"]
221
+ print(f" {a['subject']} -{a['predicate']}-> {a['object']}")
222
+ print(f" [{a['polarity']}]{_fmt_window(a)} vs [{b['polarity']}]{_fmt_window(b)}")
223
+ return 0
224
+
225
+
226
+ def _engine_with_resolution(root: Path, strategy: str, credibility_path: str | None) -> QueryEngine:
227
+ """Build a QueryEngine, optionally applying an opt-in conflict-resolution strategy."""
228
+ if not strategy:
229
+ return _engine(root)
230
+ if root.is_file() and root.suffix == ".duckdb":
231
+ from textgraph.l6_graph_model.conflicts import resolve_conflicts
232
+ from textgraph.store.duckdb_store import load_graph
233
+
234
+ nodes, edges = load_graph(root)
235
+ rn, re_ = resolve_conflicts(nodes, edges, strategy=strategy)
236
+ nmap = {n.node_id: n for n in nodes} | {n.node_id: n for n in rn}
237
+ emap = {e.edge_id: e for e in edges} | {e.edge_id: e for e in re_}
238
+ return QueryEngine(list(nmap.values()), list(emap.values()))
239
+ import json
240
+
241
+ from textgraph.core.config import Config
242
+
243
+ cred = json.loads(Path(credibility_path).read_text("utf-8")) if credibility_path else {}
244
+ cfg = Config(resolve_conflicts_strategy=strategy, source_credibility=cred)
245
+ result = build(root, config=cfg)
246
+ return QueryEngine(result.nodes, result.edges)
247
+
248
+
249
+ def _cmd_conflicts(args: argparse.Namespace) -> int:
250
+ root = Path(args.path)
251
+ if not root.exists():
252
+ print(f"error: path does not exist: {root}", file=sys.stderr)
253
+ return 2
254
+ res = _engine_with_resolution(root, args.resolve, args.credibility).conflicts().to_dict()
255
+ if not res["conflicts"]:
256
+ print("no conflicts found")
257
+ return 0
258
+ if args.resolve:
259
+ print(f"conflicts: {len(res['conflicts'])} (resolved by {args.resolve}; losers superseded)")
260
+ else:
261
+ print(f"conflicts: {len(res['conflicts'])} (single-truth; not resolved -- review each)")
262
+ for c in res["conflicts"]:
263
+ print(
264
+ f" [{c['severity']}] {c['subject']} -{c['predicate']}-> {{{', '.join(c['objects'])}}}"
265
+ )
266
+ if c["resolved"]:
267
+ print(f" => winner: {c['resolved_object']} (by {c['resolution_strategy']})")
268
+ elif c["resolution_note"]:
269
+ print(f" => {c['resolution_note']}")
270
+ for claim in c["claims"]:
271
+ cites = " ".join(_fmt_citation(x) for x in claim["citations"])
272
+ when = (
273
+ f" valid=[{claim['t_valid']}, {claim['t_invalid'] or 'now'})"
274
+ if claim["t_valid"]
275
+ else ""
276
+ )
277
+ print(f" {claim['subject']} -> {claim['object']}{when} {cites}")
278
+ return 0
279
+
280
+
281
+ def _cmd_trace_decision(args: argparse.Namespace) -> int:
282
+ root = Path(args.path)
283
+ if not root.exists():
284
+ print(f"error: path does not exist: {root}", file=sys.stderr)
285
+ return 2
286
+ res = _engine(root).trace_decision_chain(args.decision, max_hops=args.hops).to_dict()
287
+ if not res["found"]:
288
+ print(f"no decision matched: {args.decision}")
289
+ return 0
290
+ d = res["decision"]
291
+ dcites = " ".join(_fmt_citation(c) for c in d["citations"])
292
+ print(f"decision: {d['name']} [{d['category']}] {dcites}")
293
+
294
+ def _hop(h: dict[str, object]) -> str:
295
+ cites = " ".join(_fmt_citation(c) for c in h["citations"]) # type: ignore[union-attr]
296
+ return f" {h['from_name']} -{h['relation']}-> {h['to_name']} {cites}"
297
+
298
+ print(f"caused by / precedents ({len(res['ancestors'])}):")
299
+ for h in res["ancestors"]:
300
+ print(_hop(h))
301
+ print(f"led to / effects ({len(res['descendants'])}):")
302
+ for h in res["descendants"]:
303
+ print(_hop(h))
304
+ if res["truncated"]:
305
+ print(" ... (truncated to hop budget)")
306
+ return 0
307
+
308
+
309
+ def _cmd_find_decisions(args: argparse.Namespace) -> int:
310
+ root = Path(args.path)
311
+ if not root.exists():
312
+ print(f"error: path does not exist: {root}", file=sys.stderr)
313
+ return 2
314
+ res = _engine(root).find_similar_decisions(args.query, k=args.k).to_dict()
315
+ if not res["hits"]:
316
+ print("no decisions found")
317
+ return 0
318
+ print(f"decisions similar to: {res['query']}")
319
+ for i, h in enumerate(res["hits"], 1):
320
+ cites = " ".join(_fmt_citation(c) for c in h["citations"])
321
+ print(f" {i}. [{h['category']}] {h['name']} (score {h['score']})")
322
+ if cites:
323
+ print(f" {cites}")
324
+ return 0
325
+
326
+
327
+ def _cmd_communities(args: argparse.Namespace) -> int:
328
+ root = Path(args.path)
329
+ if not root.exists():
330
+ print(f"error: path does not exist: {root}", file=sys.stderr)
331
+ return 2
332
+ res = _engine(root).communities().to_dict()
333
+ print(f"communities: {len(res['communities'])}")
334
+ for c in res["communities"]:
335
+ print(f" #{c['community_id']} {c['label']} ({c['size']}): {', '.join(c['members'])}")
336
+ return 0
337
+
338
+
339
+ def _cmd_stats(args: argparse.Namespace) -> int:
340
+ root = Path(args.path)
341
+ if not root.exists():
342
+ print(f"error: path does not exist: {root}", file=sys.stderr)
343
+ return 2
344
+ res = _engine(root).stats().to_dict()
345
+ counts = res["counts"]
346
+ print("stats:")
347
+ for key in ("nodes", "edges", "entities", "chunks", "claims"):
348
+ print(f" {key}: {counts.get(key, 0)}")
349
+ print("top entities (by PageRank):")
350
+ for e in res["top_entities"]:
351
+ print(f" {e['name']} pr={e['pagerank']} [{e['community_label']}]")
352
+ return 0
353
+
354
+
355
+ def _cmd_watch(args: argparse.Namespace) -> int:
356
+ root = Path(args.path)
357
+ if not root.exists():
358
+ print(f"error: path does not exist: {root}", file=sys.stderr)
359
+ return 2
360
+ from textgraph.watch import watch
361
+
362
+ def _report(result: object) -> None:
363
+ r = result # BuildResult
364
+ print(
365
+ f"rebuilt: {len(r.nodes)} nodes, {len(r.edges)} edges " # type: ignore[attr-defined]
366
+ f"-> {args.output}"
367
+ )
368
+
369
+ print(f"watching {root} (every {args.interval}s; Ctrl-C to stop)...")
370
+ try:
371
+ watch(root, args.output, interval=args.interval, on_build=_report)
372
+ except KeyboardInterrupt:
373
+ print("\nstopped.")
374
+ return 0
375
+
376
+
377
+ def _cmd_vision(args: argparse.Namespace) -> int:
378
+ root = Path(args.path)
379
+ if not root.exists():
380
+ print(f"error: path does not exist: {root}", file=sys.stderr)
381
+ return 2
382
+ from textgraph.core.config import Config
383
+ from textgraph.l8_retrieval.vision import resolve_embedder
384
+
385
+ config = Config(vision_backend=args.backend)
386
+ embedder = resolve_embedder(config)
387
+ res = _engine(root).vision_search(args.query, k=args.k, embedder=embedder).to_dict()
388
+ print(f"vision search: {res['query']} (backend: {args.backend}, MaxSim late interaction)")
389
+ for i, hit in enumerate(res["hits"], 1):
390
+ cites = " ".join(_fmt_citation(c) for c in hit["citations"])
391
+ print(f" {i}. page {hit['name'][:60]} (score {hit['score']})")
392
+ if cites:
393
+ print(f" {cites}")
394
+ return 0
395
+
396
+
397
+ def _cmd_secure(args: argparse.Namespace) -> int:
398
+ root = Path(args.path)
399
+ if not root.exists():
400
+ print(f"error: path does not exist: {root}", file=sys.stderr)
401
+ return 2
402
+ policy_path = Path(args.policy)
403
+ if not policy_path.exists():
404
+ print(f"error: policy file does not exist: {policy_path}", file=sys.stderr)
405
+ return 2
406
+ import json
407
+
408
+ from textgraph.security import SecurityContext, policy_from_dict
409
+
410
+ policy = policy_from_dict(json.loads(policy_path.read_text(encoding="utf-8")))
411
+ if root.is_file() and root.suffix == ".duckdb":
412
+ from textgraph.store.duckdb_store import load_graph
413
+
414
+ nodes, edges = load_graph(root)
415
+ else:
416
+ result = build(root)
417
+ nodes, edges = result.nodes, result.edges
418
+ qe = QueryEngine(nodes, edges, policy=policy)
419
+ ctx = SecurityContext(
420
+ principal=args.principal,
421
+ groups=frozenset(args.group),
422
+ clearance=args.clearance,
423
+ ip=args.ip,
424
+ as_of=args.as_of,
425
+ )
426
+ res = qe.search(args.query, k=args.k, context=ctx).to_dict()
427
+ print(
428
+ f"secure search: {res['query']} "
429
+ f"(principal: {args.principal}, routing: {res['routing']}, backend: rebac)"
430
+ )
431
+ for i, hit in enumerate(res["hits"], 1):
432
+ cites = " ".join(_fmt_citation(c) for c in hit["citations"])
433
+ print(f" {i}. [{hit['kind']}] {hit['name']} (score {hit['score']})")
434
+ if hit["snippet"]:
435
+ print(f" {hit['snippet'][:160]}")
436
+ if cites:
437
+ print(f" {cites}")
438
+ if res["truncated"]:
439
+ print(" ... (truncated to token budget)")
440
+ return 0
441
+
442
+
443
+ def _cmd_reason(args: argparse.Namespace) -> int:
444
+ root = Path(args.path)
445
+ if not root.exists():
446
+ print(f"error: path does not exist: {root}", file=sys.stderr)
447
+ return 2
448
+ from textgraph.got import GraphOfThoughts
449
+
450
+ if root.is_file() and root.suffix == ".duckdb":
451
+ from textgraph.store.duckdb_store import load_graph
452
+
453
+ nodes, edges = load_graph(root)
454
+ else:
455
+ result = build(root)
456
+ nodes, edges = result.nodes, result.edges
457
+ res = GraphOfThoughts(nodes, edges).reason(args.query, mode=args.mode).to_dict()
458
+ print(
459
+ f"reason: {res['query']} (mode: {res['mode']}, complexity: {res['complexity']}, "
460
+ f"tool calls: {res['tool_calls']}, grounded: {res['grounded']})"
461
+ )
462
+ for v in res["graph"]["vertices"]:
463
+ print(f" [{v['role']}] {v['content']}")
464
+ cites = " ".join(_fmt_citation(c) for c in v["evidence"])
465
+ if cites:
466
+ print(f" {cites}")
467
+ print(f"answer: {res['answer']}")
468
+ return 0
469
+
470
+
471
+ def _cmd_gql(args: argparse.Namespace) -> int:
472
+ root = Path(args.path)
473
+ if not root.exists():
474
+ print(f"error: path does not exist: {root}", file=sys.stderr)
475
+ return 2
476
+ from textgraph.gql import GQLEngine, GQLError
477
+
478
+ if root.is_file() and root.suffix == ".duckdb":
479
+ from textgraph.store.duckdb_store import load_graph
480
+
481
+ nodes, edges = load_graph(root)
482
+ else:
483
+ result = build(root)
484
+ nodes, edges = result.nodes, result.edges
485
+ engine = GQLEngine(nodes, edges)
486
+ try:
487
+ res = engine.query(args.query)
488
+ except GQLError as exc:
489
+ print(f"gql error: {exc}", file=sys.stderr)
490
+ return 2
491
+
492
+ def cell(v: object) -> str:
493
+ if isinstance(v, list):
494
+ return " -> ".join(str(x) for x in v)
495
+ return "" if v is None else str(v)
496
+
497
+ print(" | ".join(res.columns))
498
+ print("-" * max(3, len(" | ".join(res.columns))))
499
+ for row in res.rows:
500
+ print(" | ".join(cell(v) for v in row))
501
+ print(f"({len(res.rows)} row{'s' if len(res.rows) != 1 else ''})")
502
+ return 0
503
+
504
+
505
+ def _cmd_console(args: argparse.Namespace) -> int:
506
+ root = Path(args.path)
507
+ if not root.exists():
508
+ print(f"error: path does not exist: {root}", file=sys.stderr)
509
+ return 2
510
+ from textgraph.console import build_engine, serve
511
+
512
+ print(f"building graph from {root} ...")
513
+ engine = build_engine(root)
514
+ serve(
515
+ engine,
516
+ host=args.host,
517
+ port=args.port,
518
+ source=root,
519
+ allow_ingest=args.allow_ingest and root.is_dir(),
520
+ token=args.token or None,
521
+ )
522
+ return 0
523
+
524
+
525
+ def _cmd_export(args: argparse.Namespace) -> int:
526
+ root = Path(args.path)
527
+ if not root.exists():
528
+ print(f"error: path does not exist: {root}", file=sys.stderr)
529
+ return 2
530
+ if root.is_file() and root.suffix == ".duckdb":
531
+ from textgraph.store.duckdb_store import load_graph
532
+
533
+ nodes, edges = load_graph(root)
534
+ else:
535
+ result = build(root)
536
+ nodes, edges = result.nodes, result.edges
537
+
538
+ if args.format == "prov-o":
539
+ from textgraph.l9_artifacts.prov import export_prov_bytes
540
+
541
+ body = export_prov_bytes(nodes, edges)
542
+ else: # pragma: no cover - argparse choices guard this
543
+ print(f"error: unknown format: {args.format}", file=sys.stderr)
544
+ return 2
545
+
546
+ if args.output:
547
+ out = Path(args.output)
548
+ out.parent.mkdir(parents=True, exist_ok=True)
549
+ out.write_bytes(body)
550
+ print(f"wrote {out} ({len(body)} bytes)")
551
+ else:
552
+ sys.stdout.write(body.decode("utf-8"))
553
+ return 0
554
+
555
+
556
+ def _cmd_doctor(args: argparse.Namespace) -> int:
557
+ import json
558
+
559
+ from textgraph.doctor import FAIL, format_text, run_checks
560
+
561
+ names = [args.check] if args.check else None
562
+ try:
563
+ checks = run_checks(names)
564
+ except KeyError as exc:
565
+ from textgraph.doctor import check_names
566
+
567
+ print(f"error: unknown check {exc}; valid: {', '.join(check_names())}", file=sys.stderr)
568
+ return 2
569
+ if args.json:
570
+ print(json.dumps([c.to_dict() for c in checks], ensure_ascii=False))
571
+ else:
572
+ print(format_text(checks))
573
+ return 1 if any(c.status == FAIL for c in checks) else 0
574
+
575
+
576
+ def _cmd_er_audit(args: argparse.Namespace) -> int:
577
+ root = Path(args.path)
578
+ if not root.exists():
579
+ print(f"error: path does not exist: {root}", file=sys.stderr)
580
+ return 2
581
+ result = build(root)
582
+ records = build_records(result.nodes, result.edges)
583
+ er = run_er(records)
584
+ report = render_audit(er, records)
585
+ if args.output:
586
+ Path(args.output).write_text(report, encoding="utf-8")
587
+ print(f"wrote {args.output}")
588
+ else:
589
+ print(report)
590
+ return 0
591
+
592
+
593
+ def _cmd_build(args: argparse.Namespace) -> int:
594
+ root = Path(args.path)
595
+ if not root.exists():
596
+ print(f"error: path does not exist: {root}", file=sys.stderr)
597
+ return 2
598
+
599
+ import json
600
+
601
+ from textgraph.core.config import Config
602
+
603
+ cred = json.loads(Path(args.credibility).read_text("utf-8")) if args.credibility else {}
604
+ config = Config(
605
+ llm_enabled=bool(args.llm) or bool(args.llm_extract),
606
+ llm_extract=bool(args.llm_extract),
607
+ resolve_conflicts_strategy=args.resolve_conflicts or "",
608
+ source_credibility=cred,
609
+ )
610
+
611
+ if args.json_only:
612
+ data = build_graph_bytes(root, config=config)
613
+ out = Path(args.json_only)
614
+ out.parent.mkdir(parents=True, exist_ok=True)
615
+ out.write_bytes(data)
616
+ print(f"wrote {out} ({len(data)} bytes)")
617
+ return 0
618
+
619
+ result = build(root, config=config)
620
+ paths = write_artifacts(
621
+ args.output,
622
+ config_hash=result.config_hash,
623
+ results=result.results,
624
+ nodes=result.nodes,
625
+ edges=result.edges,
626
+ timings_ms=result.timings_ms,
627
+ ie_stats=result.ie_stats,
628
+ er_stats=result.er_stats,
629
+ graph_stats=result.graph_stats,
630
+ llm_enabled=result.config.llm_enabled,
631
+ )
632
+ ie = result.ie_stats
633
+ er = result.er_stats
634
+ gs = result.graph_stats
635
+ print(
636
+ f"built graph: {len(result.results)} docs, {len(result.nodes)} nodes, "
637
+ f"{len(result.edges)} edges "
638
+ f"({ie.get('entities', 0)} entities, {ie.get('relations', 0)} relations, "
639
+ f"{er.get('canonical_entities', 0)} canonical merges, "
640
+ f"{gs.get('claims', 0)} claims, {gs.get('communities', 0)} communities, "
641
+ f"{gs.get('chunks', 0)} chunks)"
642
+ )
643
+ print(f" {paths.graph_json}")
644
+ print(f" {paths.report}")
645
+ print(f" {paths.graph_html}")
646
+ if args.store:
647
+ from textgraph.store.duckdb_store import persist
648
+
649
+ store_path = persist(args.store, result.nodes, result.edges)
650
+ print(f" {store_path} (persisted; query it directly without a rebuild)")
651
+ for warning in result.skipped:
652
+ print(f" skipped {warning}", file=sys.stderr)
653
+ return 0
654
+
655
+
656
+ def build_parser() -> argparse.ArgumentParser:
657
+ parser = argparse.ArgumentParser(prog="textgraph", description=__doc__)
658
+ parser.add_argument("--version", action="version", version=__version__)
659
+ sub = parser.add_subparsers(dest="command", required=True)
660
+
661
+ p_version = sub.add_parser("version", help="print the TextGraph version")
662
+ p_version.set_defaults(func=_cmd_version)
663
+
664
+ p_export = sub.add_parser(
665
+ "export", help="export the graph in an interoperable format (PROV-O decision trail)"
666
+ )
667
+ p_export.add_argument("path", help="corpus path or .duckdb snapshot")
668
+ p_export.add_argument(
669
+ "--format",
670
+ default="prov-o",
671
+ choices=["prov-o"],
672
+ help="export format (default: prov-o, a W3C PROV-O JSON-LD decision provenance trail)",
673
+ )
674
+ p_export.add_argument("-o", "--output", help="write to this file instead of stdout")
675
+ p_export.set_defaults(func=_cmd_export)
676
+
677
+ p_doctor = sub.add_parser(
678
+ "doctor", help="read-only environment health check (Python, extras, determinism)"
679
+ )
680
+ p_doctor.add_argument(
681
+ "--json", action="store_true", help="machine-readable output for CI preflight gates"
682
+ )
683
+ p_doctor.add_argument(
684
+ "--check", metavar="NAME", help="run only one named check (see docs for the list)"
685
+ )
686
+ p_doctor.set_defaults(func=_cmd_doctor)
687
+
688
+ p_build = sub.add_parser("build", help="build a knowledge graph from a corpus path")
689
+ p_build.add_argument("path", help="file or directory to ingest")
690
+ p_build.add_argument(
691
+ "-o",
692
+ "--output",
693
+ default="textgraph-out",
694
+ help="artifact directory (default: textgraph-out)",
695
+ )
696
+ p_build.add_argument(
697
+ "--json-only", metavar="PATH", help="write only graph.json to PATH and exit"
698
+ )
699
+ p_build.add_argument(
700
+ "--store",
701
+ metavar="PATH.duckdb",
702
+ help="also persist the graph to a DuckDB file (requires the [graph] extra)",
703
+ )
704
+ p_build.add_argument(
705
+ "--llm",
706
+ action="store_true",
707
+ help="run the opt-in L4 LLM pass (GENERATED community summaries); reads "
708
+ "API_KEY/MODEL_BASE_URL/MODEL_NAME from the environment",
709
+ )
710
+ p_build.add_argument(
711
+ "--llm-extract",
712
+ dest="llm_extract",
713
+ action="store_true",
714
+ help="opt-in: run the LLM over chunks to add GENERATED-tagged relations the "
715
+ "deterministic extractors missed (reads LLM env vars; bounded by budget)",
716
+ )
717
+ p_build.add_argument(
718
+ "--resolve-conflicts",
719
+ dest="resolve_conflicts",
720
+ default="",
721
+ choices=["", "most_recent", "voting", "credibility_weighted"],
722
+ help="opt-in: resolve single-truth conflicts into the graph (losers superseded, "
723
+ "never deleted). Default: detection only.",
724
+ )
725
+ p_build.add_argument(
726
+ "--credibility",
727
+ metavar="PATH.json",
728
+ help="JSON map source_name -> credibility, for --resolve-conflicts credibility_weighted",
729
+ )
730
+ p_build.set_defaults(func=_cmd_build)
731
+
732
+ p_er = sub.add_parser("er", help="entity-resolution utilities")
733
+ er_sub = p_er.add_subparsers(dest="er_command", required=True)
734
+ p_audit = er_sub.add_parser("audit", help="audit proposed SAME_AS merges for review")
735
+ p_audit.add_argument("path", help="corpus path to resolve")
736
+ p_audit.add_argument("-o", "--output", help="write the audit markdown to this path")
737
+ p_audit.set_defaults(func=_cmd_er_audit)
738
+
739
+ p_query = sub.add_parser("query", help="hybrid search over a corpus (BM25 + graph PPR)")
740
+ p_query.add_argument("path", help="corpus path to build and query")
741
+ p_query.add_argument("query", help="natural-language query")
742
+ p_query.add_argument("-k", type=int, default=5, help="number of hits (default 5)")
743
+ p_query.add_argument(
744
+ "--embed",
745
+ default="",
746
+ choices=["", "openai", "st", "hash"],
747
+ help="add dense semantic retrieval: openai (OpenAI-compatible /embeddings, e.g. local "
748
+ "Ollama nomic-embed-text), st (sentence-transformers [embed] extra), hash (test). "
749
+ "Default: off (BM25 + graph only).",
750
+ )
751
+ p_query.add_argument(
752
+ "--embed-model", default="", help="embedding model (default: nomic-embed-text)"
753
+ )
754
+ p_query.add_argument("--embed-url", default="", help="OpenAI-compatible embeddings base URL")
755
+ p_query.add_argument(
756
+ "--narrate",
757
+ action="store_true",
758
+ help="compose a grounded, cited LLM answer from the retrieved evidence (GENERATED; "
759
+ "reads LLM env vars)",
760
+ )
761
+ p_query.set_defaults(func=_cmd_query)
762
+
763
+ p_path = sub.add_parser("path", help="maximum-likelihood path(s) between two entities")
764
+ p_path.add_argument("path", help="corpus path to build")
765
+ p_path.add_argument("source", help="source entity (id or name)")
766
+ p_path.add_argument("target", help="target entity (id or name)")
767
+ p_path.add_argument("-k", type=int, default=1, help="number of paths (default 1)")
768
+ p_path.set_defaults(func=_cmd_path)
769
+
770
+ p_explain = sub.add_parser("explain", help="cited claims explaining an entity")
771
+ p_explain.add_argument("path", help="corpus path to build")
772
+ p_explain.add_argument("node", help="entity to explain (id or name)")
773
+ p_explain.set_defaults(func=_cmd_explain)
774
+
775
+ p_neigh = sub.add_parser("neighbors", help="1-hop typed neighbors of an entity")
776
+ p_neigh.add_argument("path", help="corpus path to build")
777
+ p_neigh.add_argument("node", help="entity (id or name)")
778
+ p_neigh.add_argument("-k", type=int, default=20, help="max neighbors (default 20)")
779
+ p_neigh.set_defaults(func=_cmd_neighbors)
780
+
781
+ p_timeline = sub.add_parser("timeline", help="claims about an entity ordered by validity")
782
+ p_timeline.add_argument("path", help="corpus path to build")
783
+ p_timeline.add_argument("node", help="entity (id or name)")
784
+ p_timeline.set_defaults(func=_cmd_timeline)
785
+
786
+ p_contra = sub.add_parser("contradictions", help="opposite-polarity claim pairs, cited")
787
+ p_contra.add_argument("path", help="corpus path to build")
788
+ p_contra.set_defaults(func=_cmd_contradictions)
789
+
790
+ p_comm = sub.add_parser("communities", help="detected communities with auto-labels")
791
+ p_comm.add_argument("path", help="corpus path to build")
792
+ p_comm.set_defaults(func=_cmd_communities)
793
+
794
+ p_conf = sub.add_parser(
795
+ "conflicts", help="single-truth conflicts (same subject/predicate, different objects)"
796
+ )
797
+ p_conf.add_argument("path", help="corpus path to build")
798
+ p_conf.add_argument(
799
+ "--resolve",
800
+ default="",
801
+ choices=["", "most_recent", "voting", "credibility_weighted"],
802
+ help="opt-in resolution strategy (default: none -- just surface each conflict)",
803
+ )
804
+ p_conf.add_argument(
805
+ "--credibility",
806
+ metavar="PATH.json",
807
+ help="JSON map of source_name -> credibility for --resolve credibility_weighted",
808
+ )
809
+ p_conf.set_defaults(func=_cmd_conflicts)
810
+
811
+ p_trace = sub.add_parser(
812
+ "trace-decision", help="trace a decision's causal lineage (ancestors + effects)"
813
+ )
814
+ p_trace.add_argument("path", help="corpus path or .duckdb snapshot")
815
+ p_trace.add_argument("decision", help="decision id or a phrase from its statement")
816
+ p_trace.add_argument("--hops", type=int, default=6, help="max causal hops each way (default 6)")
817
+ p_trace.set_defaults(func=_cmd_trace_decision)
818
+
819
+ p_findd = sub.add_parser(
820
+ "find-decisions", help="find decisions whose statement is most relevant to a query"
821
+ )
822
+ p_findd.add_argument("path", help="corpus path or .duckdb snapshot")
823
+ p_findd.add_argument("query", help="natural-language query")
824
+ p_findd.add_argument("-k", type=int, default=5, help="number of decisions (default 5)")
825
+ p_findd.set_defaults(func=_cmd_find_decisions)
826
+
827
+ p_stats = sub.add_parser("stats", help="graph counts and most central entities")
828
+ p_stats.add_argument("path", help="corpus path to build")
829
+ p_stats.set_defaults(func=_cmd_stats)
830
+
831
+ p_watch = sub.add_parser("watch", help="rebuild artifacts incrementally on corpus change")
832
+ p_watch.add_argument("path", help="corpus directory to watch")
833
+ p_watch.add_argument("-o", "--output", default="textgraph-out", help="artifact directory")
834
+ p_watch.add_argument("--interval", type=float, default=2.0, help="poll interval seconds")
835
+ p_watch.set_defaults(func=_cmd_watch)
836
+
837
+ p_vision = sub.add_parser(
838
+ "vision", help="late-interaction page retrieval (MaxSim); ColPali behind [vision]"
839
+ )
840
+ p_vision.add_argument("path", help="corpus path or .duckdb snapshot")
841
+ p_vision.add_argument("query", help="natural-language query")
842
+ p_vision.add_argument("-k", type=int, default=5, help="number of pages (default 5)")
843
+ p_vision.add_argument(
844
+ "--backend",
845
+ default="hash",
846
+ choices=["hash", "colpali"],
847
+ help="embedder: hash (deterministic default) or colpali ([vision] extra)",
848
+ )
849
+ p_vision.set_defaults(func=_cmd_vision)
850
+
851
+ p_reason = sub.add_parser(
852
+ "reason", help="Graph-of-Thoughts reasoning: a KG-grounded, complexity-gated chain"
853
+ )
854
+ p_reason.add_argument("path", help="corpus path or .duckdb snapshot")
855
+ p_reason.add_argument("query", help="natural-language question")
856
+ p_reason.add_argument(
857
+ "--mode",
858
+ default="adaptive",
859
+ choices=["adaptive", "static"],
860
+ help="adaptive (complexity-gated, cheaper) or static (full topology baseline)",
861
+ )
862
+ p_reason.set_defaults(func=_cmd_reason)
863
+
864
+ p_gql = sub.add_parser("gql", help="run a GQL (ISO-GQL/Cypher subset) query over the graph")
865
+ p_gql.add_argument("path", help="corpus path or .duckdb snapshot")
866
+ p_gql.add_argument(
867
+ "query", help='GQL query, e.g. "MATCH (a)-[:CONTROLS]->(b) RETURN a.name, b.name"'
868
+ )
869
+ p_gql.set_defaults(func=_cmd_gql)
870
+
871
+ p_secure = sub.add_parser(
872
+ "secure", help="security-aware search under a policy + principal (enterprise FGAC)"
873
+ )
874
+ p_secure.add_argument("path", help="corpus path or .duckdb snapshot")
875
+ p_secure.add_argument("query", help="natural-language query")
876
+ p_secure.add_argument("--policy", required=True, help="path to a JSON policy file")
877
+ p_secure.add_argument("--principal", required=True, help="requesting user id (e.g. alice)")
878
+ p_secure.add_argument(
879
+ "--group", action="append", default=[], help="a group the principal belongs to (repeatable)"
880
+ )
881
+ p_secure.add_argument("--clearance", type=int, default=0, help="ABAC clearance level")
882
+ p_secure.add_argument("--ip", default="", help="ABAC request origin IP")
883
+ p_secure.add_argument(
884
+ "--as-of", dest="as_of", default=None, help="ABAC ISO date (temporal window)"
885
+ )
886
+ p_secure.add_argument("-k", type=int, default=5, help="number of hits (default 5)")
887
+ p_secure.set_defaults(func=_cmd_secure)
888
+
889
+ p_console = sub.add_parser("console", help="serve the local web console over the graph")
890
+ p_console.add_argument("path", help="corpus path or .duckdb snapshot")
891
+ p_console.add_argument("--host", default="127.0.0.1", help="bind host (default 127.0.0.1)")
892
+ p_console.add_argument("--port", type=int, default=8765, help="bind port (default 8765)")
893
+ p_console.add_argument(
894
+ "--allow-ingest",
895
+ action="store_true",
896
+ help="enable file-attach in the Ask chat (writes uploads into the corpus dir)",
897
+ )
898
+ p_console.add_argument(
899
+ "--token",
900
+ default="",
901
+ help="require this bearer token on /api/* (recommended before --host 0.0.0.0)",
902
+ )
903
+ p_console.set_defaults(func=_cmd_console)
904
+
905
+ return parser
906
+
907
+
908
+ def main(argv: list[str] | None = None) -> int:
909
+ from textgraph.l0_ingest.base import UnsupportedFormat
910
+
911
+ parser = build_parser()
912
+ args = parser.parse_args(argv)
913
+ try:
914
+ result: int = args.func(args)
915
+ except UnsupportedFormat as exc:
916
+ # e.g. a .duckdb path or --store without the [graph] extra installed.
917
+ print(f"error: {exc}", file=sys.stderr)
918
+ return 2
919
+ return result
920
+
921
+
922
+ if __name__ == "__main__":
923
+ raise SystemExit(main())