@capagents/forgeqe 2.10.4 → 3.0.0

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 (162) hide show
  1. package/HOW_TO_USE.md +119 -16
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/dist/docs-site/docs/architecture/index.html +1 -0
  5. package/dist/docs-site/docs/cost-architecture/index.html +1 -1
  6. package/dist/docs-site/docs/index.html +158 -19
  7. package/dist/docs-site/docs/mobile/index.html +38 -2
  8. package/dist/docs-site/docs/search.js +1 -1
  9. package/dist/forgeqe.js +2121 -1947
  10. package/dist/web/assets/Agent-DISh0THc.js +8 -0
  11. package/dist/web/assets/ApiTests-CK0HqEH4.js +10 -0
  12. package/dist/web/assets/Browse-WylAQZvD.js +2 -0
  13. package/dist/web/assets/Chat-B7IOg3I3.js +5 -0
  14. package/dist/web/assets/CommandPalette-CkreEJ8R.js +1 -0
  15. package/dist/web/assets/Compare-CgOfZofk.js +1 -0
  16. package/dist/web/assets/Cost-Dl5-viu4.js +1 -0
  17. package/dist/web/assets/Data-Bv2S5wkW.js +6 -0
  18. package/dist/web/assets/Desktop-CifPwy5u.js +1 -0
  19. package/dist/web/assets/DesktopReview-fpGdtU4r.js +1 -0
  20. package/dist/web/assets/Evidence-hOZDzfKt.js +1 -0
  21. package/dist/web/assets/Explore-c85VGE9Q.js +2 -0
  22. package/dist/web/assets/Features-DXL_vSjn.js +1 -0
  23. package/dist/web/assets/Flags-B7x2pDud.js +2 -0
  24. package/dist/web/assets/Flaky-BM3syqCt.js +1 -0
  25. package/dist/web/assets/Impact-BUCh8OAI.js +3 -0
  26. package/dist/web/assets/Jobs-B8sBDYRI.js +5 -0
  27. package/dist/web/assets/KindPage-yVmpQm7L.js +6 -0
  28. package/dist/web/assets/Migration-BOLN1duU.js +2 -0
  29. package/dist/web/assets/Product-C0FeEaJg.js +7 -0
  30. package/dist/web/assets/Production-BSMQyWKd.js +1 -0
  31. package/dist/web/assets/Quality-DsM9gWZb.js +1 -0
  32. package/dist/web/assets/Readiness-BhqkAJYN.js +1 -0
  33. package/dist/web/assets/Record-CPx-lK53.js +2 -0
  34. package/dist/web/assets/Regression-BXbX46nO.js +5 -0
  35. package/dist/web/assets/{RelationGraph-D_ZVeOBh.js → RelationGraph-eoGXXz5t.js} +1 -1
  36. package/dist/web/assets/Reports-36YQzVhA.js +2 -0
  37. package/dist/web/assets/Response-DplUOsue.js +4 -0
  38. package/dist/web/assets/RunDiff-D0fDhRmK.js +1 -0
  39. package/dist/web/assets/Runs-Bv1Ef8zq.js +2 -0
  40. package/dist/web/assets/Steps-Cm-atRtk.js +2 -0
  41. package/dist/web/assets/TestCases-B9x9W3zJ.js +1 -0
  42. package/dist/web/assets/TestData-DsJ6Z2YI.js +2 -0
  43. package/dist/web/assets/TestDebt-B_FUbMOb.js +1 -0
  44. package/dist/web/assets/Tosca-nxVCubA5.js +3 -0
  45. package/dist/web/assets/WhatsNew-CdnbMvrr.js +1 -0
  46. package/dist/web/assets/agentLink-BGKAF6xd.js +1 -0
  47. package/dist/web/assets/capture.worklet-C2TjBQ56.js +11 -0
  48. package/dist/web/assets/capture.worklet-UcNywATd.js +1 -0
  49. package/dist/web/assets/dataParts-Bn-tzbKg.js +3 -0
  50. package/dist/web/assets/{families-zlLgApNV.js → families-DPlFfKf2.js} +1 -1
  51. package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
  52. package/dist/web/assets/fold-BhRpA0sy.js +1 -0
  53. package/dist/web/assets/frame-D_TPoUTD.js +16 -0
  54. package/dist/web/assets/index-BRB-oAMd.js +67 -0
  55. package/dist/web/assets/index-CIw5WfL8.css +2 -0
  56. package/dist/web/assets/{line-icons-CQ-3V8ax.js → line-icons-DBwNPSmu.js} +1 -1
  57. package/dist/web/assets/{logos-DfCytw3-.js → logos-839CfoKx.js} +1 -1
  58. package/dist/web/assets/{markdown-nTIj9lyp.js → markdown-6z0km3hN.js} +7 -7
  59. package/dist/web/assets/paletteCommands-CZFdKGhh.js +1 -0
  60. package/dist/web/assets/parts-VPcxh6Jc.js +1 -0
  61. package/dist/web/assets/{productParts-DK3ULNpv.js → productParts-BjfWgMtq.js} +1 -1
  62. package/dist/web/assets/qualityParts-PGN65yfI.js +1 -0
  63. package/dist/web/assets/{recordTest-CqxnF953.js → recordTest-EkxSMWbe.js} +1 -1
  64. package/dist/web/assets/rows-uLoguIo5.js +1 -0
  65. package/dist/web/assets/segmented-DphDskQz.js +1 -0
  66. package/dist/web/assets/{usePageChat-Dl2aUtHP.js → usePageChat-DqEwGcyO.js} +1 -1
  67. package/dist/web/index.html +6 -6
  68. package/docs/ARCHITECTURE.md +1 -0
  69. package/docs/COST_ARCHITECTURE.md +1 -1
  70. package/docs/MOBILE.md +40 -0
  71. package/docs/user-guide.html +158 -19
  72. package/evals/prompts/brain/browser-narrow-with-filters.yaml +20 -0
  73. package/forgeqe.example.yaml +11 -1
  74. package/package.json +4 -1
  75. package/prompts/brain.md +4 -0
  76. package/prompts/browser-goal-verification.md +2 -0
  77. package/prompts/refine.md +2 -0
  78. package/prompts/requests-rule.md +1 -1
  79. package/prompts/talk-summary.md +43 -0
  80. package/prompts/talk.md +49 -0
  81. package/prompts/test-agent.md +1 -0
  82. package/prompts/test-reviewer.md +2 -1
  83. package/prompts/test-rules.md +3 -0
  84. package/py/forgeqe_data/__init__.py +1 -0
  85. package/py/forgeqe_data/__main__.py +12 -0
  86. package/py/forgeqe_data/connect.py +290 -0
  87. package/py/forgeqe_data/connstr.py +169 -0
  88. package/py/forgeqe_data/flows.py +603 -0
  89. package/py/forgeqe_data/guard.py +214 -0
  90. package/py/forgeqe_data/mongo.py +219 -0
  91. package/py/forgeqe_data/schema.py +431 -0
  92. package/py/forgeqe_data/service.py +651 -0
  93. package/py/forgeqe_data/streams.py +400 -0
  94. package/py/forgeqe_data/subset.py +299 -0
  95. package/py/forgeqe_data/testdata.py +861 -0
  96. package/py/forgeqe_data/vector.py +113 -0
  97. package/py/forgeqe_desktop/workflow.py +6 -4
  98. package/py/forgeqe_engine/capture.py +5 -4
  99. package/py/forgeqe_engine/diagnostics.py +2 -2
  100. package/py/forgeqe_engine/lenient_json.py +96 -0
  101. package/py/forgeqe_engine/llm.py +4 -0
  102. package/py/forgeqe_engine/network.py +93 -15
  103. package/py/forgeqe_engine/neutral_log.py +16 -1
  104. package/py/forgeqe_engine/recordsession.py +54 -1
  105. package/py/forgeqe_engine/service.py +22 -3
  106. package/py/forgeqe_mobile/appium_driver.py +9 -0
  107. package/py/forgeqe_mobile/apps.py +4 -0
  108. package/py/forgeqe_mobile/maestro.py +3 -0
  109. package/py/forgeqe_mobile/record.py +610 -0
  110. package/py/forgeqe_mobile/service.py +37 -7
  111. package/py/forgeqe_talk/__init__.py +1 -0
  112. package/py/forgeqe_talk/__main__.py +65 -0
  113. package/py/forgeqe_voice/worker.py +141 -0
  114. package/skills/dotnet-nunit-playwright/SKILL.md +1 -0
  115. package/skills/playwright-typescript/SKILL.md +1 -1
  116. package/dist/web/assets/Agent-DaA5WhAY.js +0 -8
  117. package/dist/web/assets/ApiTests-B7xsTGyo.js +0 -10
  118. package/dist/web/assets/Browse-ByYCyAwd.js +0 -2
  119. package/dist/web/assets/Chat-D1-cYNBr.js +0 -3
  120. package/dist/web/assets/CommandPalette-DbxKJJJB.js +0 -1
  121. package/dist/web/assets/Compare-CYLFEtJl.js +0 -1
  122. package/dist/web/assets/Cost-Csz0jMHo.js +0 -1
  123. package/dist/web/assets/Data-BWTme_Yw.js +0 -6
  124. package/dist/web/assets/Desktop-rZ0vB6Ie.js +0 -1
  125. package/dist/web/assets/DesktopReview-_Xha22_d.js +0 -1
  126. package/dist/web/assets/Evidence-DmUyZy9F.js +0 -1
  127. package/dist/web/assets/Explore-2wzgwz3J.js +0 -2
  128. package/dist/web/assets/Features-DazEWqYu.js +0 -1
  129. package/dist/web/assets/Flags-BTt0-pqd.js +0 -2
  130. package/dist/web/assets/Flaky-CjkQp73T.js +0 -1
  131. package/dist/web/assets/Impact-De87sv5J.js +0 -3
  132. package/dist/web/assets/Jobs-aiNGBVHL.js +0 -5
  133. package/dist/web/assets/KindPage-CrGoFeSa.js +0 -6
  134. package/dist/web/assets/Migration-BAhQ1DZO.js +0 -2
  135. package/dist/web/assets/Product-DpK-PIxV.js +0 -7
  136. package/dist/web/assets/Production-D6A89rZZ.js +0 -1
  137. package/dist/web/assets/Quality-Bc5wCsog.js +0 -1
  138. package/dist/web/assets/Readiness-CoVgZw2X.js +0 -1
  139. package/dist/web/assets/Record-DcgBatJJ.js +0 -2
  140. package/dist/web/assets/Regression-BJLYrqST.js +0 -5
  141. package/dist/web/assets/Reports-DYfyfEDy.js +0 -2
  142. package/dist/web/assets/Response-CNLi9Dqu.js +0 -4
  143. package/dist/web/assets/RunDiff-BMTdRhii.js +0 -1
  144. package/dist/web/assets/Runs-lb78rvPV.js +0 -2
  145. package/dist/web/assets/Steps-BDSeIznj.js +0 -2
  146. package/dist/web/assets/TestCases-CfUwd67O.js +0 -1
  147. package/dist/web/assets/TestData-DP7cvW48.js +0 -2
  148. package/dist/web/assets/TestDebt-CqARxL7k.js +0 -1
  149. package/dist/web/assets/Tosca-CLAz9tWT.js +0 -3
  150. package/dist/web/assets/WhatsNew-1lhTRE5Z.js +0 -1
  151. package/dist/web/assets/dataParts-DI_OJhy5.js +0 -3
  152. package/dist/web/assets/filters-CflRmNDz.js +0 -1
  153. package/dist/web/assets/fold-pOBiaSlF.js +0 -1
  154. package/dist/web/assets/frame-CYYiRu5P.js +0 -4
  155. package/dist/web/assets/index-CNDoTeRV.css +0 -2
  156. package/dist/web/assets/index-D4a0w3Vl.js +0 -67
  157. package/dist/web/assets/palette-Cj4CUs0K.js +0 -1
  158. package/dist/web/assets/parts-C53RxMcR.js +0 -1
  159. package/dist/web/assets/qualityParts-C9FItsTg.js +0 -1
  160. package/dist/web/assets/rows-D6rPRkHl.js +0 -1
  161. package/dist/web/assets/segmented-CAf_qz5Z.js +0 -1
  162. package/dist/web/assets/thread-DQdyL3Sv.js +0 -5
@@ -0,0 +1,431 @@
1
+ """
2
+ What a database holds, for ForgeQE's agent to write SQL against.
3
+
4
+ - **Catalog**: every table and view with its columns (type, nullable, key, comment), primary and foreign keys, read in
5
+ bulk with SQLAlchemy's inspector and kept in ``catalog.json`` so later questions need no round trip.
6
+ - **Linking**: the tables a question needs, from the words in it (table, column and comment names, singular or
7
+ plural) and the foreign keys around them, so a database of a thousand tables still fits in a prompt.
8
+ - **Rendering**: those tables through DB-GPT's connector (``RDBMSConnector.get_table_info``: CREATE TABLE, and sample
9
+ rows when the entry allows them), with column comments and the joins added.
10
+
11
+ Names, comments and sample values come from the database, which other people write: they are data for the model, and
12
+ the agent's prompt says so.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import math
18
+ import re
19
+ import time
20
+ import warnings
21
+ from pathlib import Path
22
+ from typing import Any, Dict, List, Optional, Set
23
+
24
+ MAX_TABLES = 10
25
+ # Bumped when the catalog gains fields; a cached catalog of another version is read again.
26
+ CATALOG_VERSION = 2
27
+ # Characters of CREATE TABLE text per answer; tables past it are listed by their columns only.
28
+ DETAIL_CHARS = 24_000
29
+ WORD = re.compile(r"[a-z0-9]+")
30
+
31
+
32
+ def _words(text: str) -> Set[str]:
33
+ out: Set[str] = set()
34
+ for w in WORD.findall(re.sub(r"([a-z])([A-Z])", r"\1 \2", text or "").lower()):
35
+ if len(w) < 2:
36
+ continue
37
+ out.add(w)
38
+ # orders/order, categories/category, statuses/status: match either form.
39
+ if w.endswith("ies") and len(w) > 4:
40
+ out.add(w[:-3] + "y")
41
+ elif w.endswith("es") and len(w) > 4:
42
+ out.add(w[:-2])
43
+ if w.endswith("s") and len(w) > 3:
44
+ out.add(w[:-1])
45
+ return out
46
+
47
+
48
+ def read_catalog(engine: Any, schema: Optional[str] = None) -> Dict[str, Any]:
49
+ from sqlalchemy import inspect
50
+
51
+ insp = inspect(engine)
52
+ schema = schema or None
53
+ tables: Dict[str, Dict[str, Any]] = {}
54
+ names = insp.get_table_names(schema=schema)
55
+ views = set(insp.get_view_names(schema=schema))
56
+ for name in [*names, *sorted(views)]:
57
+ tables[name] = {"kind": "view" if name in views else "table", "columns": [], "pk": [], "fks": [], "comment": ""}
58
+ if not tables:
59
+ return {"version": CATALOG_VERSION, "schema": schema, "tables": {}, "read_at": time.time()}
60
+
61
+ def bulk(method: str, **kw: Any) -> Dict[Any, Any]:
62
+ try:
63
+ return dict(getattr(insp, method)(schema=schema, **kw))
64
+ except NotImplementedError:
65
+ return {}
66
+
67
+ for (_, table), cols in bulk("get_multi_columns", kind=_kinds()).items():
68
+ if table in tables:
69
+ tables[table]["columns"] = [_column(c) for c in cols]
70
+ for (_, table), pk in bulk("get_multi_pk_constraint").items():
71
+ if table in tables and pk:
72
+ tables[table]["pk"] = list(pk.get("constrained_columns") or [])
73
+ for (_, table), fks in bulk("get_multi_foreign_keys").items():
74
+ if table in tables:
75
+ tables[table]["fks"] = [
76
+ {"columns": fk["constrained_columns"], "table": fk["referred_table"], "references": fk["referred_columns"]}
77
+ for fk in fks if fk.get("referred_table")
78
+ ]
79
+ for (_, table), comment in bulk("get_multi_table_comment", kind=_kinds()).items():
80
+ if table in tables and comment and comment.get("text"):
81
+ tables[table]["comment"] = comment["text"]
82
+ # What test data must respect: unique keys (constraints and unique indexes) and CHECK constraints.
83
+ for (_, table), uniques in bulk("get_multi_unique_constraints").items():
84
+ if table in tables:
85
+ tables[table].setdefault("unique", []).extend([list(u["column_names"]) for u in uniques if u.get("column_names")])
86
+ for (_, table), indexes in bulk("get_multi_indexes").items():
87
+ if table in tables:
88
+ for ix in indexes:
89
+ cols = [c for c in ix.get("column_names") or [] if c]
90
+ if ix.get("unique") and cols and cols not in tables[table].get("unique", []):
91
+ tables[table].setdefault("unique", []).append(cols)
92
+ for (_, table), checks in bulk("get_multi_check_constraints").items():
93
+ if table in tables and checks:
94
+ tables[table]["checks"] = [str(c.get("sqltext") or "") for c in checks if c.get("sqltext")]
95
+ for table, rows in _row_estimates(engine, schema).items():
96
+ if table in tables:
97
+ tables[table]["rows"] = rows
98
+ return {"version": CATALOG_VERSION, "schema": schema, "tables": tables, "read_at": time.time(), "fingerprint": fingerprint(engine, schema), "checked_at": time.time()}
99
+
100
+
101
+ def _column(c: Dict[str, Any]) -> Dict[str, Any]:
102
+ """A column as the catalog keeps it: name, type, nullable, and what test data needs (size, enum values, defaults)."""
103
+ t = c["type"]
104
+ out: Dict[str, Any] = {"name": c["name"], "type": str(t), "nullable": bool(c.get("nullable", True))}
105
+ if c.get("comment"):
106
+ out["comment"] = c["comment"]
107
+ for attr in ("length", "precision", "scale"):
108
+ value = getattr(t, attr, None)
109
+ if isinstance(value, int):
110
+ out[attr] = value
111
+ enums = getattr(t, "enums", None)
112
+ if enums:
113
+ out["enum"] = list(enums)
114
+ try:
115
+ out["python"] = t.python_type.__name__
116
+ except (NotImplementedError, AttributeError):
117
+ pass
118
+ if c.get("default") is not None:
119
+ out["default"] = str(c["default"])
120
+ if c.get("identity") or c.get("autoincrement") is True or "nextval(" in str(c.get("default") or ""):
121
+ out["generated"] = True
122
+ if c.get("computed"):
123
+ out["computed"] = True
124
+ return out
125
+
126
+
127
+ # A cheap fingerprint of the schema: how many tables and columns, and a checksum of their names and types where the
128
+ # database can make one in a query. A catalog whose fingerprint no longer matches is read again.
129
+ _FINGERPRINTS = {
130
+ "postgresql": "SELECT COUNT(DISTINCT table_name), COUNT(*), md5(string_agg(table_name || '.' || column_name || ':' || data_type, ',' ORDER BY table_name, ordinal_position)) "
131
+ "FROM information_schema.columns WHERE table_schema = COALESCE(:schema, current_schema())",
132
+ "mysql": "SELECT COUNT(DISTINCT table_name), COUNT(*), MD5(GROUP_CONCAT(CONCAT(table_name, '.', column_name, ':', data_type) ORDER BY table_name, ordinal_position SEPARATOR ',')) "
133
+ "FROM information_schema.columns WHERE table_schema = COALESCE(:schema, DATABASE())",
134
+ "mssql": "SELECT COUNT(DISTINCT TABLE_NAME), COUNT(*), CHECKSUM_AGG(CHECKSUM(TABLE_NAME, COLUMN_NAME, DATA_TYPE)) "
135
+ "FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = COALESCE(:schema, SCHEMA_NAME())",
136
+ "oracle": "SELECT COUNT(DISTINCT table_name), COUNT(*), SUM(ORA_HASH(table_name || '.' || column_name || ':' || data_type)) "
137
+ "FROM all_tab_columns WHERE owner = COALESCE(:schema, SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA'))",
138
+ "sqlite": "SELECT COUNT(DISTINCT m.name), COUNT(*), group_concat(m.name || '.' || p.name || ':' || p.type) FROM sqlite_master m JOIN pragma_table_info(m.name) p "
139
+ "WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite_%'",
140
+ "duckdb": "SELECT COUNT(DISTINCT table_name), COUNT(*), md5(string_agg(table_name || '.' || column_name || ':' || data_type, ',' ORDER BY table_name, ordinal_position)) "
141
+ "FROM information_schema.columns WHERE table_schema = COALESCE(:schema, current_schema())",
142
+ }
143
+
144
+
145
+ def fingerprint(engine: Any, schema: Optional[str]) -> Optional[str]:
146
+ """The schema's fingerprint, or None where the database has no cheap one (the catalog then ages out instead)."""
147
+ from sqlalchemy import text
148
+
149
+ sql = _FINGERPRINTS.get(engine.dialect.name)
150
+ if not sql:
151
+ return None
152
+ try:
153
+ with engine.connect() as conn:
154
+ row = conn.execute(text(sql), {} if engine.dialect.name == "sqlite" else {"schema": schema}).fetchone()
155
+ conn.rollback()
156
+ except Exception:
157
+ return None
158
+ if not row:
159
+ return None
160
+ tail = row[2] if row[2] is None or len(str(row[2])) <= 64 else __import__("hashlib").sha256(str(row[2]).encode()).hexdigest()
161
+ return f"{row[0]}:{row[1]}:{tail}"
162
+
163
+
164
+ # The database's own row estimates (statistics, no table scan); -1 or missing means not known.
165
+ _ROW_ESTIMATES = {
166
+ "postgresql": "SELECT c.relname, c.reltuples::bigint FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
167
+ "WHERE c.relkind IN ('r', 'p') AND n.nspname = COALESCE(:schema, current_schema())",
168
+ "mysql": "SELECT table_name, table_rows FROM information_schema.tables WHERE table_schema = COALESCE(:schema, DATABASE())",
169
+ "mssql": "SELECT t.name, SUM(p.rows) FROM sys.tables t JOIN sys.partitions p ON p.object_id = t.object_id AND p.index_id IN (0, 1) "
170
+ "WHERE SCHEMA_NAME(t.schema_id) = COALESCE(:schema, SCHEMA_NAME()) GROUP BY t.name",
171
+ "oracle": "SELECT table_name, num_rows FROM all_tables WHERE owner = COALESCE(:schema, SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA'))",
172
+ }
173
+
174
+
175
+ def _row_estimates(engine: Any, schema: Optional[str]) -> Dict[str, int]:
176
+ from sqlalchemy import text
177
+
178
+ sql = _ROW_ESTIMATES.get(engine.dialect.name)
179
+ if not sql:
180
+ return {}
181
+ try:
182
+ with engine.connect() as conn:
183
+ rows = conn.execute(text(sql), {"schema": schema}).fetchall()
184
+ conn.rollback()
185
+ except Exception:
186
+ return {}
187
+ out: Dict[str, int] = {}
188
+ for name, count in rows:
189
+ if count is not None and int(count) >= 0:
190
+ # Oracle keeps unquoted names in upper case; SQLAlchemy reports them in lower case.
191
+ out[name.lower() if engine.dialect.name == "oracle" and name.isupper() else name] = int(count)
192
+ return out
193
+
194
+
195
+ def _kinds() -> Any:
196
+ from sqlalchemy.engine.reflection import ObjectKind
197
+
198
+ return ObjectKind.TABLE | ObjectKind.VIEW
199
+
200
+
201
+ def save(catalog: Dict[str, Any], path: Path) -> None:
202
+ path.parent.mkdir(parents=True, exist_ok=True)
203
+ path.write_text(json.dumps(catalog, indent=1), encoding="utf-8")
204
+
205
+
206
+ def load(path: Path) -> Optional[Dict[str, Any]]:
207
+ try:
208
+ return json.loads(path.read_text(encoding="utf-8"))
209
+ except (OSError, ValueError):
210
+ return None
211
+
212
+
213
+ def _neighbours(tables: Dict[str, Any]) -> Dict[str, Set[str]]:
214
+ out: Dict[str, Set[str]] = {t: set() for t in tables}
215
+ for name, t in tables.items():
216
+ for fk in t["fks"]:
217
+ if fk["table"] in out:
218
+ out[name].add(fk["table"])
219
+ out[fk["table"]].add(name)
220
+ return out
221
+
222
+
223
+ def _tokens(name: str) -> List[str]:
224
+ return [w for w in WORD.findall(re.sub(r"([a-z])([A-Z])", r"\1 \2", name or "").lower()) if len(w) > 1]
225
+
226
+
227
+ def _hits(token: str, q: Set[str]) -> bool:
228
+ """A name's word matches the question's: the same word or its singular, or one is a stem of the other (quant, quantity)."""
229
+ if token in q or (token.endswith("s") and token[:-1] in q):
230
+ return True
231
+ return len(token) >= 4 and any(len(w) >= 4 and (w.startswith(token) or token.startswith(w)) for w in q)
232
+
233
+
234
+ def _is_junction(name: str, t: Dict[str, Any]) -> bool:
235
+ """A many-to-many link table: named *_rel, described as a relation, or nothing but foreign keys."""
236
+ if name.lower().endswith("_rel") or (t.get("comment") or "").upper().startswith("RELATION BETWEEN"):
237
+ return True
238
+ fk_cols = {c for fk in t.get("fks", []) for c in fk["columns"]}
239
+ cols = [c["name"] for c in t.get("columns", [])]
240
+ return 2 <= len(cols) <= 4 and len(fk_cols) >= 2 and all(c in fk_cols or c in t.get("pk", []) or c == "id" for c in cols)
241
+
242
+
243
+ def link(catalog: Dict[str, Any], question: str, *, limit: int = MAX_TABLES, named: Optional[List[str]] = None, hints: Optional[List[str]] = None) -> List[str]:
244
+ """
245
+ The tables a question most likely needs: those its words name, weighted by how rare each word is among the table
246
+ names (so a prefix every table shares counts for little); then the tables their foreign keys name in the question
247
+ (sale_order.partner_id for "partner"); then the tables that join them. Link tables and empty tables come last.
248
+ `hints`: tables another ranking found (DB-GPT's vector index), best first: they add to the words' scores, so they
249
+ can bring in a table the words missed but are judged by the same rules.
250
+ """
251
+ tables = catalog.get("tables") or {}
252
+ if not tables:
253
+ return []
254
+ lower = {n.lower(): n for n in tables}
255
+ picked = [lower[n.lower()] for n in (named or []) if n.lower() in lower]
256
+ if len(tables) <= limit and not named:
257
+ return list(tables)
258
+ q = _words(question)
259
+ n = len(tables)
260
+ df: Dict[str, int] = {}
261
+ for name in tables:
262
+ for tok in set(_tokens(name)):
263
+ df[tok] = df.get(tok, 0) + 1
264
+ idf = {tok: math.log((n + 1) / (c + 0.5)) for tok, c in df.items()}
265
+
266
+ scores: Dict[str, float] = {}
267
+ for name, t in tables.items():
268
+ toks = _tokens(name)
269
+ weight = sum(idf[tok] for tok in toks) or 1.0
270
+ matched = sum(idf[tok] for tok in toks if _hits(tok, q))
271
+ score = 6 * matched / weight if matched else 0.0
272
+ if name.lower() in (question or "").lower():
273
+ score += 4
274
+ comment = _words(t.get("comment", ""))
275
+ score += 0.75 * len(comment & q)
276
+ cols = set().union(*(set(_tokens(c["name"])) for c in t["columns"])) if t["columns"] else set()
277
+ score += 0.25 * min(4, sum(1 for w in q if w in cols))
278
+ if hints and name in hints:
279
+ score += 2.0 * (1 - hints.index(name) / max(1, len(hints)))
280
+ if score:
281
+ if _is_junction(name, t):
282
+ score *= 0.25
283
+ if t.get("rows") == 0:
284
+ score *= 0.5
285
+ scores[name] = score
286
+
287
+ ranked = sorted(scores, key=lambda x: -scores[x])
288
+ for name in ranked:
289
+ if len(picked) >= max(1, limit // 2):
290
+ break
291
+ if name not in picked:
292
+ picked.append(name)
293
+ # Foreign keys the question names: "partner names" on sale_order means res_partner through partner_id.
294
+ for name in list(picked):
295
+ for fk in tables[name].get("fks", []):
296
+ words = {w for c in fk["columns"] for w in _tokens(c) if w != "id"}
297
+ if fk["table"] in tables and fk["table"] not in picked and any(_hits(w, q) for w in words) and len(picked) < limit:
298
+ picked.append(fk["table"])
299
+ # Then what joins them, so the model sees the keys to join on: real tables before link tables.
300
+ near = _neighbours(tables)
301
+ for name in list(picked):
302
+ others = sorted(near.get(name, ()), key=lambda o: (_is_junction(o, tables[o]), -scores.get(o, 0)))
303
+ for other in others:
304
+ if len(picked) >= limit:
305
+ break
306
+ if other not in picked and not _is_junction(other, tables[other]):
307
+ picked.append(other)
308
+ return picked[:limit]
309
+
310
+
311
+ def search(catalog: Dict[str, Any], words: str, *, limit: int = 60) -> str:
312
+ """Tables whose name, comment or columns contain any of the words: for databases too large for the overview."""
313
+ tables = catalog.get("tables") or {}
314
+ wanted = [w for w in _words(words) if len(w) > 3]
315
+ out = []
316
+ for name, t in tables.items():
317
+ hay = " ".join([name, t.get("comment", ""), *(c["name"] for c in t["columns"])]).lower()
318
+ hits = sum(1 for w in wanted if w in hay)
319
+ if hits:
320
+ out.append((hits + (2 if any(w in name.lower() for w in wanted) else 0), name, t))
321
+ out.sort(key=lambda x: (-x[0], x[1]))
322
+ return "\n".join(_line(name, t) for _, name, t in out[:limit]) or "No table matches."
323
+
324
+
325
+ def _line(name: str, t: Dict[str, Any]) -> str:
326
+ rows = t.get("rows")
327
+ size = f", ~{rows} rows" if isinstance(rows, int) and rows >= 0 else ""
328
+ comment = f" -- {t['comment'][:80]}" if t.get("comment") else ""
329
+ return f"{name}{' (view)' if t['kind'] == 'view' else ''}: {len(t['columns'])} columns{size}{comment}"
330
+
331
+
332
+ def overview(catalog: Dict[str, Any], *, max_tables: int = 300) -> str:
333
+ """One line per table: the map the agent reads before asking for detail. Large databases list tables with rows first."""
334
+ tables = catalog.get("tables") or {}
335
+ names = list(tables)
336
+ if len(names) > max_tables:
337
+ names.sort(key=lambda n: (_is_junction(n, tables[n]), -(tables[n].get("rows") or 0)))
338
+ lines = [_line(name, tables[name]) for name in names[:max_tables]]
339
+ if len(tables) > max_tables:
340
+ lines.append(f"... and {len(tables) - max_tables} more tables: search them by word (search) or name them (tables)")
341
+ return "\n".join(lines)
342
+
343
+
344
+ def render(engine: Any, catalog: Dict[str, Any], names: List[str], *, sample_rows: int = 0, budget: int = DETAIL_CHARS) -> str:
345
+ """The chosen tables as DB-GPT renders them for text-to-SQL, with comments and joins from the catalog."""
346
+ tables = catalog.get("tables") or {}
347
+ # DB-GPT's CREATE TABLE text runs to about 90 characters a column with its keys and constraints: tables past the
348
+ # budget are listed with their columns only.
349
+ full: List[str] = []
350
+ used = 0
351
+ for name in names:
352
+ t = tables.get(name) or {}
353
+ cost = 150 + 90 * len(t.get("columns", [])) + 120 * len(t.get("fks", []))
354
+ if full and used + cost > budget:
355
+ break
356
+ full.append(name)
357
+ used += cost
358
+ brief = [n for n in names if n not in full]
359
+ with warnings.catch_warnings():
360
+ # Schemas with foreign keys in cycles (most ERPs) make SQLAlchemy warn that it cannot sort tables; order does not matter here.
361
+ warnings.simplefilter("ignore")
362
+ text = _render_full(engine, catalog, full, sample_rows)
363
+ if brief:
364
+ text += "\n\n-- More tables (ask for them by name for their full definition):\n" + "\n".join(
365
+ f"-- {n}({', '.join(c['name'] for c in tables[n]['columns'][:40])})" for n in brief if n in tables
366
+ )
367
+ notes: List[str] = []
368
+ for name in names:
369
+ t = tables.get(name) or {}
370
+ if t.get("comment"):
371
+ notes.append(f"-- {name}: {t['comment']}")
372
+ for c in t.get("columns", []) if name in full else []:
373
+ if c.get("comment"):
374
+ notes.append(f"-- {name}.{c['name']}: {c['comment']}")
375
+ for fk in t.get("fks", []):
376
+ if fk["table"] in names:
377
+ notes.append(f"-- join: {name}.({', '.join(fk['columns'])}) -> {fk['table']}.({', '.join(fk['references'])})")
378
+ return text + ("\n\n" + "\n".join(notes) if notes else "")
379
+
380
+
381
+ def _render_full(engine: Any, catalog: Dict[str, Any], names: List[str], sample_rows: int) -> str:
382
+ from dbgpt.datasource.rdbms.base import RDBMSConnector
383
+ from sqlalchemy import MetaData
384
+
385
+ if not names:
386
+ return ""
387
+ schema = catalog.get("schema") or None
388
+ metadata = MetaData(schema=schema)
389
+ metadata.reflect(bind=engine, only=names, views=True)
390
+
391
+ class _Reflected(MetaData):
392
+ # RDBMSConnector reflects the whole database when it starts; these tables are reflected already.
393
+ def reflect(self, *args: Any, **kwargs: Any) -> None:
394
+ return None
395
+
396
+ class _Connector(RDBMSConnector):
397
+ # RDBMSConnector (0.8.2) lists tables from a schema named after the database (empty on Postgres and SQL Server,
398
+ # a file path on SQLite) and drops include_tables; its tables are the ones chosen here.
399
+ def _sync_tables_from_db(self) -> Set[str]:
400
+ self._all_tables = set(names)
401
+ return self._all_tables
402
+
403
+ pre = _Reflected(schema=schema)
404
+ for table in metadata.sorted_tables:
405
+ table.to_metadata(pre)
406
+ connector = _Connector(engine, schema=schema, metadata=pre, sample_rows_in_table_info=max(0, sample_rows))
407
+ try:
408
+ return connector.get_table_info(names)
409
+ finally:
410
+ connector.close()
411
+
412
+
413
+ def as_map(catalog: Dict[str, Any], *, max_tables: int = 400, max_columns: int = 120) -> Dict[str, Any]:
414
+ """The catalog as the schema diagram draws it: each table's columns (name, type, nullable), key and foreign keys."""
415
+ tables = catalog.get("tables") or {}
416
+ names = sorted(tables)[:max_tables]
417
+ out = []
418
+ for name in names:
419
+ t = tables[name]
420
+ cols = t.get("columns") or []
421
+ out.append({
422
+ "name": name,
423
+ "kind": t.get("kind") or "table",
424
+ **({"rows": t["rows"]} if isinstance(t.get("rows"), int) else {}),
425
+ **({"comment": str(t["comment"])[:300]} if t.get("comment") else {}),
426
+ "pk": list(t.get("pk") or []),
427
+ "columns": [{"name": c["name"], "type": str(c.get("type") or "")[:60], "nullable": bool(c.get("nullable", True))} for c in cols[:max_columns]],
428
+ **({"more_columns": len(cols) - max_columns} if len(cols) > max_columns else {}),
429
+ "fks": [{"columns": list(fk.get("columns") or []), "table": fk.get("table"), "references": list(fk.get("references") or [])} for fk in (t.get("fks") or []) if fk.get("table")],
430
+ })
431
+ return {"tables": out, "total": len(tables)}