@gate-forge/pack-sqlalchemy 0.1.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 (33) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +353 -0
  3. package/dist/adapter-schema.d.ts +84 -0
  4. package/dist/adapter-schema.d.ts.map +1 -0
  5. package/dist/adapter-schema.js +67 -0
  6. package/dist/adapter-schema.js.map +1 -0
  7. package/dist/detector.d.ts +116 -0
  8. package/dist/detector.d.ts.map +1 -0
  9. package/dist/detector.js +265 -0
  10. package/dist/detector.js.map +1 -0
  11. package/dist/index.d.ts +8 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +31 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/planes.d.ts +177 -0
  16. package/dist/planes.d.ts.map +1 -0
  17. package/dist/planes.js +280 -0
  18. package/dist/planes.js.map +1 -0
  19. package/dist/version.d.ts +12 -0
  20. package/dist/version.d.ts.map +1 -0
  21. package/dist/version.js +12 -0
  22. package/dist/version.js.map +1 -0
  23. package/examples/example.accounts.adapter.mjs +97 -0
  24. package/package.json +45 -0
  25. package/python/gateforge_sqlalchemy_detector/__init__.py +68 -0
  26. package/python/gateforge_sqlalchemy_detector/__main__.py +50 -0
  27. package/python/gateforge_sqlalchemy_detector/__pycache__/__init__.cpython-312.pyc +0 -0
  28. package/python/gateforge_sqlalchemy_detector/__pycache__/__init__.cpython-314.pyc +0 -0
  29. package/python/gateforge_sqlalchemy_detector/__pycache__/__main__.cpython-312.pyc +0 -0
  30. package/python/gateforge_sqlalchemy_detector/__pycache__/__main__.cpython-314.pyc +0 -0
  31. package/python/gateforge_sqlalchemy_detector/__pycache__/scan.cpython-312.pyc +0 -0
  32. package/python/gateforge_sqlalchemy_detector/__pycache__/scan.cpython-314.pyc +0 -0
  33. package/python/gateforge_sqlalchemy_detector/scan.py +1446 -0
@@ -0,0 +1,1446 @@
1
+ """Gateforge SQLAlchemy discovery core (AST only, stdlib only).
2
+
3
+ Lineage: spikes/discovery/discover.py (Phase 0 spike) adapted to the
4
+ canonical detector vocabulary of the frozen resource graph:
5
+ - resources carry ``schemaVersion``/``id``/``kind``/``source``/
6
+ ``location``/``detectorVersion``/``attributes`` and use
7
+ ``attributes["resourceName"]`` as the graph identity attribute;
8
+ - TABLE-CANDIDATE classes are ALSO emitted as ``gateforge.class``
9
+ symbols so the graph's repo-wide symbol table can resolve inherited
10
+ tablenames across files (spike limitation 1 fixed by the graph);
11
+ - computed names (GF-21) are typed ``unresolved`` entries located at
12
+ the class statement -- never absent, never guessed (ADR 0001 D1);
13
+ - duplicate table names (GF-20) and repeated class names (GF-01) are
14
+ findings; malformed files (GF-19) are ``PARSE_ERROR`` findings.
15
+
16
+ Classification signals (plan phase 3, ADR 0003 D1): the detector emits
17
+ code-derived FACTS, never classifications and never exposure claims:
18
+
19
+ - ``identity`` signals carry the ORDERED primary-key columns (simple
20
+ and composite; declaration order preserved) derived from
21
+ ``Column(primary_key=True)``/``mapped_column(primary_key=True)`` or a
22
+ literal ``PrimaryKeyConstraint``. A table whose key is computed or
23
+ not visible in the class gets a typed ``PRIMARY_KEY_UNRESOLVED``
24
+ unresolved entry instead — the key is never defaulted to ``id``;
25
+ - ``delete-semantics``/``archive-state`` declaration signals are
26
+ emitted only from the machine-readable class declarations
27
+ ``__gateforge_delete_semantics__ = "hard"|"archive"`` and
28
+ ``__gateforge_archive_state__ = {<field>: <literal value>}``;
29
+ a non-literal archive declaration becomes ``ARCHIVE_STATE_UNRESOLVED``.
30
+ Column NAMES resembling soft-delete bookkeeping are reported as the
31
+ ``softDeleteCandidateFields`` attribute (a fact for reviewers), never
32
+ as semantics;
33
+ - ``__gateforge_read_only__ = True`` emits ``lifecycle.*`` declaration
34
+ signals asserting the operation unsupported (an assertion the core
35
+ classifier consumes conservatively — never a suppression on its own);
36
+ - ``foreignKeyReferences`` facts (column → ``<table>.<column>``) ride
37
+ the resource attributes for cross-artifact linkage.
38
+
39
+ No exposure signal is ever emitted from a table declaration alone
40
+ (plan phase 3 guard): exposure needs externally reachable evidence,
41
+ which only linkage detectors may provide.
42
+
43
+ Table-candidate recognition (phase 2, detector precision): a class is a
44
+ table candidate iff it carries explicit table facts (literal/computed
45
+ ``__tablename__`` or ``table=True``) OR one of its bases statically
46
+ resolves to a SQLAlchemy declarative base. "Resolves" is deliberately
47
+ CONSERVATIVE — a flat file scan cannot import anything, so a base name
48
+ is declarative only when it is the conventional name ``Base`` (exact;
49
+ ``BaseModel``/``BaseSettings``/``BaseException`` never match), the
50
+ literal ``DeclarativeBase``, a locally registered declarative alias
51
+ (``X = declarative_base()``, ``X = <alias>.declarative_base()``,
52
+ ``X = registry().generate_base()``, ``class X(DeclarativeBase)``), or
53
+ the simple name of an already-detected model class (inheritance closure
54
+ applied to a fixpoint, so multi-level chains resolve across files).
55
+ The closure is bounded by LOCAL DEFINITION EVIDENCE: when the same file
56
+ defines a class with that simple name whose own base is denylisted (a
57
+ Pydantic ``class WebhookEvent(BaseModel)`` shadowing a genuine
58
+ ``class WebhookEvent(Base)`` in a models module), the closure must not
59
+ claim it — or any local subclass beneath it.
60
+ Base names whose import provenance is a known NON-ORM module family
61
+ (``pydantic``, ``abc``, ``enum``, ``argparse``, ``dataclasses``,
62
+ ``marshmallow``, ``fastapi``) can never make a class a candidate — this
63
+ kills pathological aliasing like ``from pydantic import BaseModel as
64
+ Base``, which in a real dogfood produced ~1,100 false-positive blocking
65
+ entries from Pydantic schema directories alone. A class that is not a
66
+ candidate is emitted NOWHERE — no symbol, no table, no unresolved
67
+ entry: silence for non-models is the point of the predicate, while
68
+ genuine candidates keep every typed escape hatch (``__abstract__``,
69
+ computed names, pure bases).
70
+ """
71
+
72
+ from __future__ import annotations
73
+
74
+ import ast
75
+ import json
76
+ from dataclasses import dataclass
77
+ from pathlib import Path
78
+
79
+ from . import PLUGIN_ID, VERSION
80
+
81
+ TABULAR_ATTR = "__tablename__"
82
+ ABSTRACT_ATTR = "__abstract__"
83
+ TABLE_ARGS_ATTR = "__table_args__"
84
+
85
+ # Machine-readable source declarations this detector recognizes (plan
86
+ # phase 3). Declarations are assertions consumed by the core classifier —
87
+ # contradictory code signals still block (ADR 0003 D5).
88
+ DELETE_SEMANTICS_ATTR = "__gateforge_delete_semantics__"
89
+ ARCHIVE_STATE_ATTR = "__gateforge_archive_state__"
90
+ READ_ONLY_ATTR = "__gateforge_read_only__"
91
+ UPDATEABLE_FIELDS_ATTR = "__gateforge_updateable_fields__"
92
+
93
+ # Column-call constructors carrying column facts.
94
+ COLUMN_CALL_NAMES = ("Column", "mapped_column")
95
+
96
+ # Import provenance that can NEVER make a base name a declarative root
97
+ # (phase 2 denylist). The conventional-name rule ("Base") is a flat-file
98
+ # heuristic: most projects do ``from app.db import Base`` (cross-file,
99
+ # statically unresolvable here), but the SAME spelling is reachable
100
+ # through aliasing — ``from pydantic import BaseModel as Base`` — and a
101
+ # false positive is a BLOCKING finding in a closed-world gate. Root
102
+ # module matching (``pydantic`` covers ``pydantic.*``) is fail-closed in
103
+ # the anti-false-positive direction: an ORM base legitimately imported
104
+ # from one of these families does not exist in practice.
105
+ DENYLISTED_BASE_MODULES = (
106
+ "pydantic",
107
+ "abc",
108
+ "enum",
109
+ "argparse",
110
+ "dataclasses",
111
+ "marshmallow",
112
+ "fastapi",
113
+ )
114
+
115
+ # Column names that RESEMBLE soft-delete bookkeeping. Facts for
116
+ # reviewers (attribute only) — never delete semantics, which must be
117
+ # proven by a declaration or by the core classifier's lattice.
118
+ SOFT_DELETE_CANDIDATE_FIELDS = (
119
+ "archived",
120
+ "archived_at",
121
+ "deleted",
122
+ "deleted_at",
123
+ "is_deleted",
124
+ )
125
+
126
+
127
+ def expr_label(node: ast.expr) -> str:
128
+ """Classify a non-literal expression deterministically for UNRESOLVED reasons.
129
+
130
+ Args:
131
+ node: The AST expression to classify.
132
+
133
+ Returns:
134
+ str: A stable machine-readable label (never the unparsed source
135
+ of a nested decorator chain, which may be huge or truncated).
136
+ """
137
+ if isinstance(node, ast.Constant):
138
+ return f"constant:{type(node.value).__name__}"
139
+ if isinstance(node, ast.JoinedStr):
140
+ return "f-string"
141
+ if isinstance(node, ast.Name):
142
+ return f"name:{node.id}"
143
+ if isinstance(node, ast.Attribute):
144
+ return f"attribute:{ast.unparse(node)[:80]}"
145
+ if isinstance(node, ast.Call):
146
+ return f"call:{ast.unparse(node.func)[:80]}"
147
+ if isinstance(node, ast.BinOp):
148
+ return f"binop:{ast.unparse(node)[:80]}"
149
+ if isinstance(node, ast.IfExp):
150
+ return "conditional"
151
+ return f"expr:{type(node).__name__}"
152
+
153
+
154
+ def call_name(func: ast.expr) -> str | None:
155
+ """Simple name of a call's callable, for Name and Attribute forms.
156
+
157
+ Args:
158
+ func: The callable expression of a Call node.
159
+
160
+ Returns:
161
+ str | None: The simple (last-segment) name, or None.
162
+ """
163
+ if isinstance(func, ast.Name):
164
+ return func.id
165
+ if isinstance(func, ast.Attribute):
166
+ return func.attr
167
+ return None
168
+
169
+
170
+ def base_name(node: ast.expr) -> str | None:
171
+ """Derivable simple name of a base-class expression.
172
+
173
+ Args:
174
+ node: One base expression of a ClassDef.
175
+
176
+ Returns:
177
+ str | None: The simple name, or None when not derivable.
178
+ """
179
+ if isinstance(node, ast.Name):
180
+ return node.id
181
+ if isinstance(node, ast.Attribute):
182
+ return node.attr
183
+ return None
184
+
185
+
186
+ @dataclass
187
+ class ImportRef:
188
+ """One import binding usable for base-name provenance (phase 2).
189
+
190
+ Attributes:
191
+ module: The dotted source module (absolute portion; ``""`` for a
192
+ bare relative ``from . import x``). ``None``-free on purpose:
193
+ provenance decisions must see "no module" as an empty string.
194
+ name: The imported top-level name (``None`` when the binding is a
195
+ module alias from a plain ``import a.b``).
196
+ level: Relative-import depth (0: absolute).
197
+ """
198
+
199
+ module: str
200
+ name: str | None
201
+ level: int
202
+
203
+
204
+ def module_denied(module: str | None) -> bool:
205
+ """Whether an import source module is on the base-provenance denylist.
206
+
207
+ Args:
208
+ module: The dotted module of the import (``None``/``""`` = not
209
+ knowable, e.g. a relative import — never denied).
210
+
211
+ Returns:
212
+ bool: True when the module's ROOT is a known non-ORM family, so a
213
+ base bound from it can never make its class a table candidate.
214
+ """
215
+ if not module:
216
+ return False
217
+ return module.split(".")[0] in DENYLISTED_BASE_MODULES
218
+
219
+
220
+ class ColumnFacts:
221
+ """Column-level facts extracted from one model's AST, in written order.
222
+
223
+ Attributes of a table the detector can SEE statically. Anything not
224
+ provable here is reported unresolved (never defaulted, never guessed).
225
+ """
226
+
227
+ def __init__(self) -> None:
228
+ #: Ordered literal primary-key column names (simple + composite).
229
+ self.primary_key_columns: list[str] = []
230
+ #: True when a primary_key argument exists but is not the literal True.
231
+ self.has_computed_pk_arg: bool = False
232
+ #: True when PrimaryKeyConstraint literal columns were found.
233
+ self.has_pk_constraint: bool = False
234
+ #: {column: "<table>.<column>"} literal ForeignKey references.
235
+ self.foreign_keys: dict[str, str] = {}
236
+ #: Sorted column names resembling soft-delete bookkeeping.
237
+ self.soft_delete_candidates: list[str] = []
238
+
239
+ @property
240
+ def has_pk_evidence(self) -> bool:
241
+ """Whether any literal primary-key evidence was found."""
242
+ return bool(self.primary_key_columns)
243
+
244
+
245
+ def _literal_kwarg_true(call: ast.Call, name: str) -> bool | None:
246
+ """Reads a keyword flag of a call as True/False/None (non-literal).
247
+
248
+ Args:
249
+ call: The call node.
250
+ name: Keyword name.
251
+
252
+ Returns:
253
+ bool | None: The literal truth value, or None when absent or
254
+ non-literal (the caller must treat None as unproven).
255
+ """
256
+ for kw in call.keywords:
257
+ if kw.arg == name:
258
+ if isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, bool):
259
+ return kw.value.value
260
+ return None
261
+ return None
262
+
263
+
264
+ def _column_call_name(call: ast.expr) -> str | None:
265
+ """Simple name of a call, when it is a column constructor."""
266
+ name = call_name(call.func) if isinstance(call, ast.Call) else None
267
+ return name if name in COLUMN_CALL_NAMES else None
268
+
269
+
270
+ def _column_name(call: ast.Call, target: str | None) -> str | None:
271
+ """Derives a column's name: literal first arg wins, else the target.
272
+
273
+ Args:
274
+ call: The column constructor call.
275
+ target: Assignment target name (or None).
276
+
277
+ Returns:
278
+ str | None: The column name, or None when neither source is literal.
279
+ """
280
+ if call.args and isinstance(call.args[0], ast.Constant) and isinstance(call.args[0].value, str):
281
+ return call.args[0].value
282
+ return target
283
+
284
+
285
+ def _foreign_key_reference(call: ast.Call) -> str | None:
286
+ """Finds a literal ``ForeignKey("<table>.<column>")`` argument."""
287
+ for arg in call.args:
288
+ if (
289
+ isinstance(arg, ast.Call)
290
+ and call_name(arg.func) == "ForeignKey"
291
+ and arg.args
292
+ and isinstance(arg.args[0], ast.Constant)
293
+ and isinstance(arg.args[0].value, str)
294
+ ):
295
+ return arg.args[0].value
296
+ for kw in call.keywords:
297
+ if (
298
+ isinstance(kw.value, ast.Call)
299
+ and call_name(kw.value.func) == "ForeignKey"
300
+ and kw.value.args
301
+ and isinstance(kw.value.args[0], ast.Constant)
302
+ and isinstance(kw.value.args[0].value, str)
303
+ ):
304
+ return kw.value.args[0].value
305
+ return None
306
+
307
+
308
+ def _record_column(facts: ColumnFacts, call: ast.Call, target: str | None) -> None:
309
+ """Records one column-constructor call's facts into `facts`.
310
+
311
+ Args:
312
+ facts: Accumulating facts.
313
+ call: The column constructor call.
314
+ target: Assignment target name (or None for positional columns).
315
+ """
316
+ column_name = _column_name(call, target)
317
+ primary_key = _literal_kwarg_true(call, "primary_key")
318
+ if primary_key is None and any(kw.arg == "primary_key" for kw in call.keywords):
319
+ # A primary_key argument exists but is computed (GF-21 mechanic
320
+ # for keys): remember the hole — never guess the key.
321
+ facts.has_computed_pk_arg = True
322
+ if primary_key is True and column_name is not None:
323
+ facts.primary_key_columns.append(column_name)
324
+ if column_name is not None:
325
+ reference = _foreign_key_reference(call)
326
+ if reference is not None:
327
+ facts.foreign_keys[column_name] = reference
328
+ if column_name in SOFT_DELETE_CANDIDATE_FIELDS:
329
+ facts.soft_delete_candidates.append(column_name)
330
+
331
+
332
+ def _facts_from_column_calls(calls: list[tuple[ast.Call, str | None]]) -> ColumnFacts:
333
+ """Builds ColumnFacts from (call, target) pairs in written order."""
334
+ facts = ColumnFacts()
335
+ for call, target in calls:
336
+ _record_column(facts, call, target)
337
+ return facts
338
+
339
+
340
+ def _pk_constraint_columns(node: ast.expr) -> list[str] | None:
341
+ """Literal ordered columns of a ``PrimaryKeyConstraint("a", "b")``.
342
+
343
+ Args:
344
+ node: An ``__table_args__`` tuple element.
345
+
346
+ Returns:
347
+ list[str] | None: The ordered literal columns, or None when the
348
+ node is not a PrimaryKeyConstraint with literal args.
349
+ """
350
+ if (
351
+ isinstance(node, ast.Call)
352
+ and call_name(node.func) == "PrimaryKeyConstraint"
353
+ and node.args
354
+ and all(
355
+ isinstance(a, ast.Constant) and isinstance(a.value, str) for a in node.args
356
+ )
357
+ ):
358
+ return [a.value for a in node.args if isinstance(a.value, str)]
359
+ return None
360
+
361
+
362
+ class ClassRecord:
363
+ """AST facts about one class definition, at any lexical scope."""
364
+
365
+ def __init__(self, qname: str, node: ast.ClassDef, scope: str):
366
+ self.qname = qname
367
+ self.node = node
368
+ self.scope = scope # "" at module level, enclosing dotted scope otherwise
369
+ self.bases: list[str] = [b for b in (base_name(b) for b in node.bases) if b is not None]
370
+ self.keywords = {kw.arg: kw.value for kw in node.keywords if kw.arg}
371
+ self.tablename_literal: str | None = None
372
+ self.tablename_expr: ast.expr | None = None
373
+ self.tablename_func: ast.FunctionDef | ast.AsyncFunctionDef | None = None
374
+ self.abstract: bool = False
375
+ self.has_table_args: bool = False
376
+ self.table_args_schema: str | None = None
377
+ # Machine-readable source declarations (phase 3), None when absent.
378
+ self.delete_semantics_literal: str | None = None
379
+ self.delete_semantics_expr: ast.expr | None = None
380
+ self.archive_state_literal: dict[str, str | int | float | bool] | None = None
381
+ self.archive_state_expr: ast.expr | None = None
382
+ self.read_only: bool = False
383
+ self.updateable_fields_literal: list[str] | None = None
384
+ # Column-level facts, in written order (body first, then table args).
385
+ self.column_facts: ColumnFacts = ColumnFacts()
386
+ self._scan_body()
387
+
388
+ def _scan_body(self) -> None:
389
+ column_calls: list[tuple[ast.Call, str | None]] = []
390
+ table_args_node: ast.expr | None = None
391
+ for stmt in self.node.body:
392
+ if isinstance(stmt, (ast.Assign, ast.AnnAssign)):
393
+ targets = (
394
+ stmt.targets if isinstance(stmt, ast.Assign) else [stmt.target]
395
+ )
396
+ names = [t.id for t in targets if isinstance(t, ast.Name)]
397
+ value = stmt.value
398
+ if value is not None and isinstance(value, ast.Call) and _column_call_name(value) is not None:
399
+ for name in names:
400
+ column_calls.append((value, name))
401
+ if TABULAR_ATTR in names and self.tablename_expr is None:
402
+ if isinstance(value, ast.Constant) and isinstance(value.value, str):
403
+ self.tablename_literal = value.value
404
+ elif value is not None:
405
+ self.tablename_expr = value
406
+ if ABSTRACT_ATTR in names and isinstance(value, ast.Constant) and value.value is True:
407
+ self.abstract = True
408
+ if TABLE_ARGS_ATTR in names:
409
+ self.has_table_args = True
410
+ if isinstance(value, ast.Dict):
411
+ for k, v in zip(value.keys, value.values):
412
+ if (
413
+ isinstance(k, ast.Constant)
414
+ and k.value == "schema"
415
+ and isinstance(v, ast.Constant)
416
+ and isinstance(v.value, str)
417
+ ):
418
+ self.table_args_schema = v.value
419
+ elif value is not None:
420
+ table_args_node = value
421
+ if DELETE_SEMANTICS_ATTR in names and value is not None:
422
+ if isinstance(value, ast.Constant) and value.value in ("hard", "archive"):
423
+ self.delete_semantics_literal = value.value
424
+ else:
425
+ self.delete_semantics_expr = value
426
+ if ARCHIVE_STATE_ATTR in names and value is not None:
427
+ self.archive_state_literal = _literal_record(value)
428
+ if self.archive_state_literal is None:
429
+ self.archive_state_expr = value
430
+ if READ_ONLY_ATTR in names and isinstance(value, ast.Constant) and value.value is True:
431
+ self.read_only = True
432
+ if UPDATEABLE_FIELDS_ATTR in names and value is not None:
433
+ self.updateable_fields_literal = _string_sequence_literal(value)
434
+ elif isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)) and stmt.name == TABULAR_ATTR:
435
+ self.tablename_func = stmt
436
+ # Table-args columns/constraints after body columns, written order.
437
+ if table_args_node is not None:
438
+ column_calls.extend(_table_args_column_calls(table_args_node))
439
+ self.column_facts = _facts_from_column_calls(column_calls)
440
+ # Explicit constraint columns are the authoritative ordered key.
441
+ if table_args_node is not None:
442
+ for element in _table_args_elements(table_args_node):
443
+ constraint = _pk_constraint_columns(element)
444
+ if constraint is not None:
445
+ self.column_facts.primary_key_columns = constraint
446
+ self.column_facts.has_pk_constraint = True
447
+
448
+ # -- Classification ----------------------------------------------------
449
+
450
+ def is_pure_base(self, idx: "FileIndex") -> bool:
451
+ """Abstract bases, and DeclarativeBase subclasses that declare no table facts."""
452
+ if self.abstract:
453
+ return True
454
+ no_table_facts = (
455
+ self.tablename_literal is None
456
+ and self.tablename_expr is None
457
+ and self.tablename_func is None
458
+ )
459
+ return no_table_facts and any(b == "DeclarativeBase" for b in self.bases)
460
+
461
+ def is_table_candidate(self, idx: "FileIndex", model_names: frozenset[str] = frozenset()) -> bool:
462
+ """Whether this class claims a SQL table under the phase-2 predicate.
463
+
464
+ A class is a candidate iff it has explicit table facts OR one of
465
+ its bases statically resolves to a declarative base (see the
466
+ module docstring for the full conservative-resolution contract).
467
+ The old predicate — ``has_facts or bool(self.bases)`` — made every
468
+ based class (Pydantic models, Enums, ABCs, Exceptions, plain
469
+ project bases) a table candidate and emitted ~1,100 false-positive
470
+ blocking entries in a real dogfood; a base list alone is evidence
471
+ of NOTHING.
472
+
473
+ Args:
474
+ idx: The owning file index (import map + declarative aliases).
475
+ model_names: Simple names of already-detected model classes
476
+ across ALL scanned files (inheritance closure, computed to
477
+ a fixpoint by `scan` before emission).
478
+
479
+ Returns:
480
+ bool: True only for genuine SQLAlchemy table candidates.
481
+ """
482
+ has_facts = (
483
+ self.tablename_literal is not None
484
+ or self.tablename_expr is not None
485
+ or self.tablename_func is not None
486
+ or "table" in self.keywords
487
+ )
488
+ if has_facts:
489
+ return True
490
+ return any(idx.base_is_declarative(base, model_names) for base in self.bases)
491
+
492
+
493
+ def _literal_record(node: ast.expr) -> dict[str, str | int | float | bool] | None:
494
+ """Reads a dict literal of string keys and scalar values, else None.
495
+
496
+ Args:
497
+ node: The AST expression (e.g. the value of ``__gateforge_archive_state__``).
498
+
499
+ Returns:
500
+ dict | None: {field: literal scalar} preserving written order, or
501
+ None when any key/value is non-literal (the caller reports it
502
+ unresolved — the archived state is never guessed).
503
+ """
504
+ if not isinstance(node, ast.Dict):
505
+ return None
506
+ record: dict[str, str | int | float | bool] = {}
507
+ for k, v in zip(node.keys, node.values):
508
+ if not (isinstance(k, ast.Constant) and isinstance(k.value, str)):
509
+ return None
510
+ if not (isinstance(v, ast.Constant) and isinstance(v.value, (str, int, float, bool))):
511
+ return None
512
+ record[k.value] = v.value
513
+ return record
514
+
515
+
516
+ def _string_sequence_literal(node: ast.expr) -> list[str] | None:
517
+ """Reads a list/tuple literal of distinct non-empty string literals.
518
+
519
+ Args:
520
+ node: The AST expression (e.g. the value of
521
+ ``__gateforge_updateable_fields__``).
522
+
523
+ Returns:
524
+ list[str] | None: the strings in written order, or None when the
525
+ node is not a list/tuple of string literals (the classifier
526
+ then simply sees no attribute — never a guessed one).
527
+ """
528
+ if not isinstance(node, (ast.List, ast.Tuple)):
529
+ return None
530
+ values: list[str] = []
531
+ for elt in node.elts:
532
+ if not (isinstance(elt, ast.Constant) and isinstance(elt.value, str) and elt.value):
533
+ return None
534
+ values.append(elt.value)
535
+ return values or None
536
+
537
+
538
+ def _table_args_elements(node: ast.expr | None) -> list[ast.expr]:
539
+ """The elements of a tuple ``__table_args__`` (or the node itself)."""
540
+ if isinstance(node, ast.Tuple):
541
+ return list(node.elts)
542
+ if node is not None:
543
+ return [node]
544
+ return []
545
+
546
+
547
+ def _table_args_column_calls(node: ast.expr | None) -> list[tuple[ast.Call, str | None]]:
548
+ """Column-constructor calls inside ``__table_args__``, written order."""
549
+ calls: list[tuple[ast.Call, str | None]] = []
550
+ for element in _table_args_elements(node):
551
+ if isinstance(element, ast.Call) and _column_call_name(element) is not None:
552
+ calls.append((element, None))
553
+ return calls
554
+
555
+
556
+ class FileIndex:
557
+ """One parsed file plus every detector fact gathered from it."""
558
+
559
+ def __init__(self, relpath: str, tree: ast.Module):
560
+ self.relpath = relpath
561
+ self.classes: list[ClassRecord] = []
562
+ self.table_calls: list[dict] = [] # {table_name, target, node}
563
+ # Module-level bindings of the form ``X = declarative_base()`` /
564
+ # ``X = <alias>.declarative_base()`` / ``X =
565
+ # registry().generate_base()``, plus ``class X(DeclarativeBase)``
566
+ # style declarations: names that act as declarative bases IN THIS
567
+ # FILE (phase 2 resolution rule 2a).
568
+ self.declarative_base_aliases: set[str] = set()
569
+ # Names assigned from a ``registry()`` call; their
570
+ # ``.generate_base()`` results register declarative aliases.
571
+ self.registry_aliases: set[str] = set()
572
+ # Local-name -> ImportRef map for base-name provenance (phase 2
573
+ # denylist and import-alias resolution of declarative calls).
574
+ self.imports: dict[str, ImportRef] = {}
575
+ # Simple names defined in THIS file with a denylisted base (set
576
+ # properly at the end of `_collect`; empty until then).
577
+ self.locally_denied_base_names: set[str] = set()
578
+ self._collect(tree)
579
+
580
+ def _collect(self, tree: ast.Module) -> None:
581
+ assigned_call_nodes: set[int] = set()
582
+ for node in ast.walk(tree):
583
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
584
+ self._record_import(node)
585
+ if isinstance(node, ast.Assign):
586
+ target = (
587
+ node.targets[0].id
588
+ if len(node.targets) == 1 and isinstance(node.targets[0], ast.Name)
589
+ else None
590
+ )
591
+ if isinstance(node.value, ast.Call):
592
+ fname = call_name(node.value.func)
593
+ if not self._call_provenance_denied(fname) and target:
594
+ # Import-alias aware: ``from sqlalchemy.orm import
595
+ # declarative_base as dbase`` makes ``dbase()``
596
+ # register too; a denylisted provenance (e.g.
597
+ # ``from pydantic import x as declarative_base``)
598
+ # registers NOTHING (fail closed vs false models).
599
+ effective = self._effective_call_name(fname)
600
+ if effective == "declarative_base":
601
+ self.declarative_base_aliases.add(target)
602
+ elif effective == "registry":
603
+ self.registry_aliases.add(target)
604
+ elif (
605
+ isinstance(node.value.func, ast.Attribute)
606
+ and node.value.func.attr == "generate_base"
607
+ and self._receiver_is_registry(node.value.func.value)
608
+ ):
609
+ self.declarative_base_aliases.add(target)
610
+ if fname == "Table" and self._literal_name_arg(node.value):
611
+ self.table_calls.append(
612
+ {
613
+ "table_name": node.value.args[0].value,
614
+ "target": target or f"__anonymous_table_at_line_{node.lineno}",
615
+ "node": node.value,
616
+ }
617
+ )
618
+ assigned_call_nodes.add(id(node.value))
619
+ elif isinstance(node, ast.Call) and id(node) not in assigned_call_nodes:
620
+ if call_name(node.func) == "Table" and self._literal_name_arg(node):
621
+ self.table_calls.append(
622
+ {
623
+ "table_name": node.args[0].value,
624
+ "target": f"__anonymous_table_at_line_{node.lineno}",
625
+ "node": node,
626
+ }
627
+ )
628
+ self._collect_classes(tree)
629
+ self._register_declarative_class_aliases()
630
+ self._register_locally_denied_base_names()
631
+
632
+ def _record_import(self, node: ast.Import | ast.ImportFrom) -> None:
633
+ """Records one import statement's bindings into the import map."""
634
+ if isinstance(node, ast.ImportFrom):
635
+ module = node.module or ""
636
+ for alias in node.names:
637
+ local = alias.asname or alias.name
638
+ self.imports[local] = ImportRef(module=module, name=alias.name, level=node.level)
639
+ else:
640
+ for alias in node.names:
641
+ local = alias.asname or alias.name.split(".")[0]
642
+ self.imports[local] = ImportRef(module=alias.name, name=None, level=0)
643
+
644
+ def _effective_call_name(self, fname: str | None) -> str | None:
645
+ """A call's simple name with import aliases resolved.
646
+
647
+ ``from sqlalchemy.orm import declarative_base as dbase`` binds
648
+ ``dbase`` to imported name ``declarative_base``, so a ``dbase()``
649
+ call is seen as the declarative factory it is.
650
+ """
651
+ if fname is None:
652
+ return None
653
+ ref = self.imports.get(fname)
654
+ if ref is not None and ref.name:
655
+ return ref.name
656
+ return fname
657
+
658
+ def _call_provenance_denied(self, fname: str | None) -> bool:
659
+ """Whether a call's simple name is imported from a denylisted module."""
660
+ if fname is None:
661
+ return False
662
+ ref = self.imports.get(fname)
663
+ return ref is not None and module_denied(ref.module)
664
+
665
+ def _receiver_is_registry(self, expr: ast.expr) -> bool:
666
+ """Whether ``expr`` (the receiver of ``.generate_base()``) is a registry."""
667
+ if isinstance(expr, ast.Call):
668
+ fname = call_name(expr.func)
669
+ return self._effective_call_name(fname) == "registry" and not self._call_provenance_denied(fname)
670
+ if isinstance(expr, ast.Name):
671
+ return expr.id in self.registry_aliases
672
+ return False
673
+
674
+ def _register_declarative_class_aliases(self) -> None:
675
+ """Registers ``class X(DeclarativeBase)``-style names as base aliases.
676
+
677
+ Applied iteratively to a fixpoint so an alias chain inside one
678
+ file (``class Base(DeclarativeBase)``, then ``class NewBase(Base)``
679
+ acting as a project-wide base) registers every member. Only the
680
+ per-FILE alias registry is extended here; cross-file chains are
681
+ the global model-name closure in `scan`.
682
+ """
683
+ changed = True
684
+ while changed:
685
+ changed = False
686
+ for rec in self.classes:
687
+ simple = rec.qname.rsplit(".", 1)[-1]
688
+ if simple in self.declarative_base_aliases:
689
+ continue
690
+ if any(
691
+ (b == "DeclarativeBase" and not self._import_denied(b))
692
+ or b in self.declarative_base_aliases
693
+ for b in rec.bases
694
+ ):
695
+ self.declarative_base_aliases.add(simple)
696
+ changed = True
697
+
698
+ def _register_locally_denied_base_names(self) -> None:
699
+ """Records simple names DEFINED IN THIS FILE with a denylisted base.
700
+
701
+ ``class WebhookEvent(BaseModel)`` (Pydantic schema file) sharing a
702
+ simple name with a genuine ``class WebhookEvent(Base)`` (models
703
+ file) is the motivating collision: the global model-name closure
704
+ matches by simple name only, so without this registry the local
705
+ non-model — and every local subclass of it — silently inherits
706
+ candidacy from the remote namesake. A denylisted base is positive
707
+ non-model evidence; the closure must never override it.
708
+ """
709
+ self.locally_denied_base_names: set[str] = set()
710
+ for rec in self.classes:
711
+ if any(self._import_denied(b) for b in rec.bases):
712
+ self.locally_denied_base_names.add(rec.qname.rsplit(".", 1)[-1])
713
+
714
+ def _import_denied(self, name: str) -> bool:
715
+ """Whether a base simple name is bound from a denylisted module."""
716
+ ref = self.imports.get(name)
717
+ return ref is not None and module_denied(ref.module)
718
+
719
+ def base_is_declarative(self, name: str, model_names: frozenset[str]) -> bool:
720
+ """Whether one base simple name makes its class a declarative model.
721
+
722
+ The phase-2 resolution rules, in order: a denylisted provenance
723
+ vetoes EVERYTHING (even the exact name ``Base`` — this kills
724
+ ``from pydantic import BaseModel as Base``); then the exact
725
+ conventional names (``Base``, ``DeclarativeBase`` — exact only,
726
+ so ``BaseModel``/``BaseSettings``/``BaseException`` never match),
727
+ a locally registered declarative alias, or membership in the
728
+ global model-name closure (inheritance across files).
729
+
730
+ Args:
731
+ name: The base's simple name.
732
+ model_names: Simple names of detected model classes so far.
733
+
734
+ Returns:
735
+ bool: True only when the base is a declarative root.
736
+ """
737
+ if self._import_denied(name):
738
+ return False
739
+ if name in self.locally_denied_base_names:
740
+ # A class with this simple name is DEFINED IN THIS FILE with a
741
+ # denylisted base (e.g. ``class WebhookEvent(BaseModel)`` next
742
+ # to a genuine ``class WebhookEvent(Base)`` in a models module).
743
+ # Local definition evidence beats the cross-file closure: the
744
+ # closure matches by simple name only, so without this veto the
745
+ # local non-model and every local subclass of it silently
746
+ # inherit candidacy from the remote namesake (a real dogfood
747
+ # produced exactly this collision).
748
+ return False
749
+ if name == "Base":
750
+ return True
751
+ if name == "DeclarativeBase":
752
+ return True
753
+ if name in self.declarative_base_aliases:
754
+ return True
755
+ return name in model_names
756
+
757
+ @staticmethod
758
+ def _literal_name_arg(call: ast.Call) -> bool:
759
+ return bool(call.args) and isinstance(call.args[0], ast.Constant) and isinstance(
760
+ call.args[0].value, str
761
+ )
762
+
763
+ def _collect_classes(self, tree: ast.Module) -> None:
764
+ def visit(node: ast.AST, stack: list[str]) -> None:
765
+ for child in ast.iter_child_nodes(node):
766
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
767
+ visit(child, stack + [child.name])
768
+ elif isinstance(child, ast.ClassDef):
769
+ qname = ".".join(stack + [child.name])
770
+ self.classes.append(ClassRecord(qname, child, ".".join(stack)))
771
+ visit(child, stack + [child.name])
772
+ else:
773
+ visit(child, stack)
774
+
775
+ visit(tree, [])
776
+
777
+
778
+ def loc(relpath: str, node: ast.AST) -> dict:
779
+ """Build the canonical location triple for an AST node.
780
+
781
+ Args:
782
+ relpath: Repo-root-relative source path.
783
+ node: The AST node.
784
+
785
+ Returns:
786
+ dict: {"file", "line", "col"} with 1-based line and 0-based col.
787
+ """
788
+ return {"file": relpath, "line": node.lineno, "col": node.col_offset}
789
+
790
+
791
+ def _symbol_resource(relpath: str, rec: ClassRecord, name_unresolved: bool) -> dict:
792
+ """The graph class-symbol resource for one declarative class.
793
+
794
+ Args:
795
+ relpath: Repo-root-relative source path.
796
+ rec: The class record.
797
+ name_unresolved: Detector assertion that this class's tablename is
798
+ unresolved (true for table candidates the detector cannot name;
799
+ false for pure bases and literal-named classes).
800
+
801
+ Returns:
802
+ dict: A ``gateforge.class`` resource consumed by the symbol table.
803
+ """
804
+ attrs: dict = {
805
+ "qname": rec.qname,
806
+ "resourceKind": "sqlalchemy.table",
807
+ "abstract": rec.abstract,
808
+ "tablenameUnresolved": name_unresolved,
809
+ }
810
+ if rec.bases:
811
+ attrs["baseNames"] = list(rec.bases)
812
+ if rec.tablename_literal is not None:
813
+ attrs["tableName"] = rec.tablename_literal
814
+ return {
815
+ "schemaVersion": 1,
816
+ "id": f"sqlalchemy.class:{relpath}:{rec.qname}",
817
+ "kind": "gateforge.class",
818
+ "source": relpath,
819
+ "location": loc(relpath, rec.node),
820
+ "detectorVersion": VERSION,
821
+ "attributes": attrs,
822
+ }
823
+
824
+
825
+ def _table_resource(relpath: str, rec: ClassRecord, provenance: str) -> dict:
826
+ """The business table resource for a class with a literal tablename.
827
+
828
+ Args:
829
+ relpath: Repo-root-relative source path.
830
+ rec: The class record.
831
+ provenance: Tablename provenance label (always ``literal`` here).
832
+
833
+ Returns:
834
+ dict: A ``sqlalchemy.table`` resource.
835
+ """
836
+ return {
837
+ "schemaVersion": 1,
838
+ "id": f"sqlalchemy.table:{relpath}:{rec.qname}",
839
+ "kind": "sqlalchemy.table",
840
+ "source": relpath,
841
+ "location": loc(relpath, rec.node),
842
+ "detectorVersion": VERSION,
843
+ "attributes": {
844
+ "resourceName": rec.tablename_literal,
845
+ "classQname": rec.qname,
846
+ "scope": rec.scope or "module",
847
+ "tableName": rec.tablename_literal,
848
+ "tablenameProvenance": provenance,
849
+ "hasTableArgs": rec.has_table_args,
850
+ "tableArgsSchema": rec.table_args_schema,
851
+ "tableKeywordTrue": "table" in rec.keywords,
852
+ "abstract": False,
853
+ "baseNames": list(rec.bases),
854
+ **_attribute_facts(rec.column_facts, rec),
855
+ },
856
+ }
857
+
858
+
859
+ def _call_table_resource(relpath: str, call: dict) -> dict:
860
+ """The business table resource for a direct ``Table("name", ...)`` call.
861
+
862
+ Args:
863
+ relpath: Repo-root-relative source path.
864
+ call: The recorded Table-call facts.
865
+
866
+ Returns:
867
+ dict: A ``sqlalchemy.table`` resource.
868
+ """
869
+ return {
870
+ "schemaVersion": 1,
871
+ "id": f"sqlalchemy.table:{relpath}:{call['target']}",
872
+ "kind": "sqlalchemy.table",
873
+ "source": relpath,
874
+ "location": loc(relpath, call["node"]),
875
+ "detectorVersion": VERSION,
876
+ "attributes": {
877
+ "resourceName": call["table_name"],
878
+ "tableName": call["table_name"],
879
+ "tablenameProvenance": "table-call-first-arg",
880
+ "hasTableArgs": False,
881
+ "tableArgsSchema": None,
882
+ "tableKeywordTrue": False,
883
+ "abstract": False,
884
+ "baseNames": [],
885
+ },
886
+ }
887
+
888
+
889
+ # -- Classification signals (plan phase 3, ADR 0003 D1) --------------------
890
+
891
+ def _signal(
892
+ dimension: str,
893
+ assertion: "str | bool | list[str] | dict[str, str | int | float | bool]",
894
+ basis: str,
895
+ source: str,
896
+ location: dict,
897
+ target_name: str,
898
+ target_symbol: "str | None" = None,
899
+ ) -> dict:
900
+ """One canonical classification signal targeting a resource.
901
+
902
+ Args:
903
+ dimension: The classification dimension.
904
+ assertion: The dimension-typed assertion payload.
905
+ basis: The evidence basis (never a confidence score).
906
+ source: The issuing source (`PLUGIN_ID` or `gateforge.declaration:<key>`).
907
+ location: Where the evidence lives.
908
+ target_name: The bare resource name the signal speaks about.
909
+ target_symbol: The declaring class qname, when the evidence is
910
+ class-derived. Symbol-scoped targets bind ONLY to their own
911
+ class — a same-named table in another module/plane (the
912
+ two-Base consumer shape) must never inherit another tree's
913
+ declaration.
914
+
915
+ Returns:
916
+ dict: A @gate-forge/core `ClassificationSignal` document.
917
+ """
918
+ target: dict = {"resourceName": target_name}
919
+ if target_symbol is not None:
920
+ target["symbol"] = target_symbol
921
+ return {
922
+ "schemaVersion": 1,
923
+ "target": target,
924
+ "dimension": dimension,
925
+ "assertion": assertion,
926
+ "basis": basis,
927
+ "source": source,
928
+ "location": location,
929
+ "detector": {"id": PLUGIN_ID, "version": VERSION},
930
+ }
931
+
932
+
933
+ def _identity_signal(rec_or_facts: "ClassRecord | ColumnFacts", relpath: str, target_name: str, node: ast.AST) -> dict | None:
934
+ """The ordered primary-key signal for a table, or None when unprovable.
935
+
936
+ Args:
937
+ rec_or_facts: The class record (or bare column facts of a Table call).
938
+ relpath: Repo-root-relative source path.
939
+ target_name: The bare table name.
940
+ node: The declaration node the evidence lives at.
941
+
942
+ Returns:
943
+ dict | None: The `identity` signal with ordered columns (composite
944
+ order preserved), or None when no literal key was derivable.
945
+ """
946
+ facts = rec_or_facts.column_facts if isinstance(rec_or_facts, ClassRecord) else rec_or_facts
947
+ if not facts.has_pk_evidence:
948
+ return None
949
+ return _signal(
950
+ "identity",
951
+ list(facts.primary_key_columns),
952
+ "code-positive",
953
+ PLUGIN_ID,
954
+ loc(relpath, node),
955
+ target_name,
956
+ rec_or_facts.qname if isinstance(rec_or_facts, ClassRecord) else None,
957
+ )
958
+
959
+
960
+ def _declaration_signals(rec: ClassRecord, relpath: str, target_name: str) -> list[dict]:
961
+ """Declaration signals from machine-readable class declarations.
962
+
963
+ Args:
964
+ rec: The class record.
965
+ relpath: Repo-root-relative source path.
966
+ target_name: The bare table name.
967
+
968
+ Returns:
969
+ list[dict]: `delete-semantics`, `archive-state`, and read-only
970
+ `lifecycle.*` declaration signals. Declarations are ASSERTIONS
971
+ for the core classifier — never suppressions on their own.
972
+ """
973
+ signals: list[dict] = []
974
+ if rec.delete_semantics_literal is not None:
975
+ signals.append(
976
+ _signal(
977
+ "delete-semantics",
978
+ rec.delete_semantics_literal,
979
+ "declaration",
980
+ "gateforge.declaration:delete-semantics",
981
+ loc(relpath, rec.node),
982
+ target_name,
983
+ rec.qname,
984
+ )
985
+ )
986
+ if rec.archive_state_literal is not None:
987
+ signals.append(
988
+ _signal(
989
+ "archive-state",
990
+ rec.archive_state_literal,
991
+ "declaration",
992
+ "gateforge.declaration:archive-state",
993
+ loc(relpath, rec.node),
994
+ target_name,
995
+ rec.qname,
996
+ )
997
+ )
998
+ if rec.read_only:
999
+ for operation in ("create", "update", "delete"):
1000
+ signals.append(
1001
+ _signal(
1002
+ f"lifecycle.{operation}",
1003
+ False,
1004
+ "declaration",
1005
+ "gateforge.declaration:read-only",
1006
+ loc(relpath, rec.node),
1007
+ target_name,
1008
+ rec.qname,
1009
+ )
1010
+ )
1011
+ return signals
1012
+
1013
+
1014
+ def _attribute_facts(facts: ColumnFacts, rec: ClassRecord | None) -> dict:
1015
+ """Non-authoritative attribute facts for cross-artifact linkage.
1016
+
1017
+ Args:
1018
+ facts: The extracted column facts.
1019
+ rec: The class record (None for Table() calls).
1020
+
1021
+ Returns:
1022
+ dict: Attribute entries (only when non-empty): ordered
1023
+ `primaryKeyColumns`, `foreignKeyReferences` (sorted by
1024
+ column), `softDeleteCandidateFields`, and `readOnly`.
1025
+ """
1026
+ entries: dict = {}
1027
+ if facts.has_pk_evidence:
1028
+ entries["primaryKeyColumns"] = list(facts.primary_key_columns)
1029
+ if facts.foreign_keys:
1030
+ entries["foreignKeyReferences"] = [
1031
+ {"column": column, "references": facts.foreign_keys[column]}
1032
+ for column in sorted(facts.foreign_keys)
1033
+ ]
1034
+ if facts.soft_delete_candidates:
1035
+ entries["softDeleteCandidateFields"] = sorted(set(facts.soft_delete_candidates))
1036
+ if rec is not None and rec.read_only:
1037
+ entries["readOnly"] = True
1038
+ if rec is not None and rec.updateable_fields_literal:
1039
+ entries["updateableFields"] = list(rec.updateable_fields_literal)
1040
+ return entries
1041
+
1042
+
1043
+ def _signal_unresolved_entries(rec: ClassRecord, relpath: str, has_identity: bool) -> list[dict]:
1044
+ """Typed unresolved entries for unprovable identity/archive facts.
1045
+
1046
+ Args:
1047
+ rec: The class record.
1048
+ relpath: Repo-root-relative source path.
1049
+ has_identity: Whether an `identity` signal was emitted (skips the
1050
+ primary-key entry — the key is proven).
1051
+
1052
+ Returns:
1053
+ list[dict]: ``PRIMARY_KEY_UNRESOLVED`` when the table's key is
1054
+ computed or not visible in the class (inherited keys count as
1055
+ not visible), and ``ARCHIVE_STATE_UNRESOLVED`` when the
1056
+ archive declaration's value is non-literal. Never guesses.
1057
+ """
1058
+ entries: list[dict] = []
1059
+ facts = rec.column_facts
1060
+ if not has_identity and not facts.has_pk_evidence:
1061
+ if facts.has_computed_pk_arg:
1062
+ detail = (
1063
+ "primary_key_unresolved: a primary_key argument is computed "
1064
+ "(not the literal True); the ordered key is never guessed"
1065
+ )
1066
+ elif facts.has_pk_constraint:
1067
+ detail = (
1068
+ "primary_key_unresolved: PrimaryKeyConstraint columns are "
1069
+ "not all string literals; the ordered key is never guessed"
1070
+ )
1071
+ else:
1072
+ detail = (
1073
+ "primary_key_unresolved: no literal primary-key column is "
1074
+ "declared on this class (an inherited mixin/base key is not "
1075
+ "visible to the AST scan); the key is never defaulted to 'id'"
1076
+ )
1077
+ entries.append(
1078
+ {
1079
+ "code": "PRIMARY_KEY_UNRESOLVED",
1080
+ "detail": detail,
1081
+ "location": loc(relpath, rec.node),
1082
+ }
1083
+ )
1084
+ if rec.archive_state_expr is not None:
1085
+ entries.append(
1086
+ {
1087
+ "code": "ARCHIVE_STATE_UNRESOLVED",
1088
+ "detail": (
1089
+ "archive_state_unresolved: "
1090
+ f"{ARCHIVE_STATE_ATTR} is assigned from "
1091
+ f"{expr_label(rec.archive_state_expr)}; the owner-owned "
1092
+ "archived field values are never guessed"
1093
+ ),
1094
+ "location": loc(relpath, rec.node),
1095
+ }
1096
+ )
1097
+ return entries
1098
+
1099
+
1100
+ def _table_call_facts(call: dict) -> ColumnFacts:
1101
+ """Column facts of a direct ``Table(...)`` call (positional columns).
1102
+
1103
+ Args:
1104
+ call: The recorded Table-call facts.
1105
+
1106
+ Returns:
1107
+ ColumnFacts: Facts from the call's column arguments, written order.
1108
+ """
1109
+ node = call["node"]
1110
+ calls: list[tuple[ast.Call, str | None]] = []
1111
+ for arg in node.args[2:]:
1112
+ if isinstance(arg, ast.Call) and _column_call_name(arg) is not None:
1113
+ calls.append((arg, None))
1114
+ return _facts_from_column_calls(calls)
1115
+
1116
+
1117
+ def _computed_reason(rec: ClassRecord) -> str:
1118
+ """The single-cause reason for a class whose tablename is not literal.
1119
+
1120
+ Args:
1121
+ rec: The class record.
1122
+
1123
+ Returns:
1124
+ str: A machine-readable (code, reason) explanation, never truncated.
1125
+ """
1126
+ if rec.tablename_func is not None:
1127
+ fn = rec.tablename_func
1128
+ ret = fn.body[0].value if fn.body and isinstance(fn.body[0], ast.Return) else None
1129
+ return (
1130
+ f"computed_tablename: decorated function "
1131
+ f"({len(fn.decorator_list)} decorator(s)); "
1132
+ f"returns {expr_label(ret) if ret else 'unknown'}"
1133
+ )
1134
+ if rec.tablename_expr is not None:
1135
+ return f"computed_tablename: assigned from {expr_label(rec.tablename_expr)}"
1136
+ if "table" in rec.keywords:
1137
+ return (
1138
+ "table_name_derived_runtime: class keyword table=True marks a "
1139
+ "table but the name is derived by the framework from the class "
1140
+ "name at runtime, not visible in the AST"
1141
+ )
1142
+ return (
1143
+ "no_tablename_source: declarative-style class with bases "
1144
+ f"{rec.bases} but no __tablename__ in the class or any resolvable "
1145
+ "base chain"
1146
+ )
1147
+
1148
+
1149
+ def _unresolved_entry(relpath: str, rec: ClassRecord) -> dict:
1150
+ """A typed unresolved entry located at the class statement.
1151
+
1152
+ Args:
1153
+ relpath: Repo-root-relative source path.
1154
+ rec: The class record.
1155
+
1156
+ Returns:
1157
+ dict: The canonical unresolved-reason shape; the location points
1158
+ at the class so the graph can retire it when it resolves the
1159
+ name via the symbol table.
1160
+ """
1161
+ reason = _computed_reason(rec)
1162
+ code = reason.split(":", 1)[0]
1163
+ return {
1164
+ "code": code,
1165
+ "detail": reason,
1166
+ "location": loc(relpath, rec.node),
1167
+ }
1168
+
1169
+
1170
+ def _duplicate_findings(resources: list[dict]) -> list[dict]:
1171
+ """Duplicate table names (GF-20): same name in 2 files or twice in 1.
1172
+
1173
+ Args:
1174
+ resources: The business table resources of one discovery request.
1175
+
1176
+ Returns:
1177
+ list[dict]: One finding per duplicated table name, locations sorted.
1178
+ """
1179
+ by_table: dict[str, list[dict]] = {}
1180
+ for r in resources:
1181
+ if r["kind"] == "sqlalchemy.table" and r["attributes"].get("resourceName"):
1182
+ by_table.setdefault(r["attributes"]["resourceName"], []).append(r)
1183
+ findings: list[dict] = []
1184
+ for table_name in sorted(by_table):
1185
+ group = by_table[table_name]
1186
+ if len(group) < 2:
1187
+ continue
1188
+ sorted_group = sorted(
1189
+ group,
1190
+ key=lambda g: (g["location"]["file"], g["location"]["line"], g["location"]["col"], g["id"]),
1191
+ )
1192
+ locations = [
1193
+ {"file": g["location"]["file"], "line": g["location"]["line"], "col": g["location"]["col"]}
1194
+ for g in sorted_group
1195
+ ]
1196
+ files = sorted({l["file"] for l in locations})
1197
+ qnames = [g["attributes"].get("classQname") for g in sorted_group]
1198
+ qnames = [q for q in qnames if q is not None]
1199
+ detail = (
1200
+ f"table '{table_name}' declared {len(group)} times across "
1201
+ f"{len(files)} file(s)"
1202
+ )
1203
+ if qnames:
1204
+ detail += f" (declarations: {', '.join(qnames)})"
1205
+ findings.append(
1206
+ {
1207
+ "code": "DUPLICATE_TABLE_NAME",
1208
+ "detail": detail,
1209
+ "locations": locations,
1210
+ }
1211
+ )
1212
+ return findings
1213
+
1214
+
1215
+ def _class_name_findings(
1216
+ indexes: dict[str, FileIndex], model_names: frozenset[str] = frozenset()
1217
+ ) -> list[dict]:
1218
+ """Repeated class names in one file (GF-01): non-collapse proof.
1219
+
1220
+ Only classes that EMIT SOMETHING (table candidates, pure bases) take
1221
+ part: a repeated simple name can only create linkage ambiguity when
1222
+ the repeated class becomes a resource the classifier can address by
1223
+ name. Non-emitting classes (Pydantic's nested ``Config`` idiom, for
1224
+ example) have no resource identity to confuse, so repeating them is
1225
+ not a detector fact — flagging them blocked a real dogfood on noise.
1226
+
1227
+ Args:
1228
+ indexes: Parsed-file indexes of one discovery request.
1229
+ model_names: The pass-0 inheritance closure, so candidate-hood is
1230
+ judged under the SAME resolution the emission passes use.
1231
+
1232
+ Returns:
1233
+ list[dict]: One finding per repeated simple class name per file.
1234
+ """
1235
+ findings: list[dict] = []
1236
+ for relpath in sorted(indexes):
1237
+ by_simple: dict[str, list[ClassRecord]] = {}
1238
+ for rec in indexes[relpath].classes:
1239
+ if not (
1240
+ rec.is_table_candidate(indexes[relpath], model_names)
1241
+ or rec.is_pure_base(indexes[relpath])
1242
+ ):
1243
+ continue
1244
+ by_simple.setdefault(rec.qname.split(".")[-1], []).append(rec)
1245
+ for simple in sorted(by_simple):
1246
+ group = by_simple[simple]
1247
+ if len(group) < 2:
1248
+ continue
1249
+ qnames = sorted(rec.qname for rec in group)
1250
+ locations = [
1251
+ loc(relpath, rec.node) for rec in sorted(
1252
+ group, key=lambda r: (r.node.lineno, r.node.col_offset)
1253
+ )
1254
+ ]
1255
+ findings.append(
1256
+ {
1257
+ "code": "CLASS_NAME_REPEATED_IN_FILE",
1258
+ "detail": (
1259
+ f"class name '{simple}' occurs in {len(group)} distinct "
1260
+ f"scopes; kept as distinct resources: {qnames}"
1261
+ ),
1262
+ "locations": locations,
1263
+ }
1264
+ )
1265
+ return findings
1266
+
1267
+
1268
+ def _parse_error_finding(relpath: str, exc: BaseException) -> dict:
1269
+ """The GF-19 PARSE_ERROR finding for one malformed file.
1270
+
1271
+ Args:
1272
+ relpath: Repo-root-relative source path.
1273
+ exc: The SyntaxError/ValueError/UnicodeDecodeError raised.
1274
+
1275
+ Returns:
1276
+ dict: Canonical finding with a 1-based line and single-cause detail.
1277
+ """
1278
+ line = getattr(exc, "lineno", 0) or 0
1279
+ msg = exc.msg if isinstance(exc, SyntaxError) else str(exc)
1280
+ return {
1281
+ "code": "PARSE_ERROR",
1282
+ "detail": f"{type(exc).__name__}: {msg}",
1283
+ "locations": [{"file": relpath, "line": max(line, 1), "col": 0}],
1284
+ }
1285
+
1286
+
1287
+ def _scan_file(relpath: str, root: Path) -> tuple[FileIndex | None, dict | None]:
1288
+ """Parse one repo-relative file into its index, or a PARSE_ERROR finding.
1289
+
1290
+ Args:
1291
+ relpath: Repo-root-relative posix path (validated by caller).
1292
+ root: The scan root (process cwd by default).
1293
+
1294
+ Returns:
1295
+ tuple: (index or None, finding or None) — exactly one is set.
1296
+ """
1297
+ text = (root / relpath).read_text(encoding="utf-8")
1298
+ try:
1299
+ tree = ast.parse(text, filename=relpath)
1300
+ except (SyntaxError, ValueError, UnicodeDecodeError) as exc:
1301
+ return None, _parse_error_finding(relpath, exc)
1302
+ return FileIndex(relpath, tree), None
1303
+
1304
+
1305
+ def _normalize_path(rel: str) -> str:
1306
+ """Validate + normalize a repo-root-relative path.
1307
+
1308
+ Args:
1309
+ rel: A path from the discover request.
1310
+
1311
+ Returns:
1312
+ str: Posix repo-root-relative path (`./` stripped, backslashes → `/`).
1313
+
1314
+ Raises:
1315
+ ValueError: Non-relative paths (absolute, drive-qualified, `..`
1316
+ escaping, empty) are rejected fail-closed.
1317
+ """
1318
+ path = rel.replace("\\", "/")
1319
+ while path.startswith("./"):
1320
+ path = path[2:]
1321
+ if path == "":
1322
+ raise ValueError(f"target must be a repo-root-relative path, got {rel!r}")
1323
+ if path.startswith("/"):
1324
+ raise ValueError(f"target must be a repo-root-relative path, got {rel!r}")
1325
+ if ".." in path.split("/"):
1326
+ raise ValueError(f"target must be a repo-root-relative path, got {rel!r}")
1327
+ return path
1328
+
1329
+
1330
+ def scan(paths: list[str], root: Path | None = None) -> dict:
1331
+ """Collect the full deterministic discovery outcome for one request.
1332
+
1333
+ Args:
1334
+ paths: Repo-root-relative paths from the discover request.
1335
+ root: Scan root directory (defaults to the process cwd, which the
1336
+ CLI sets to the repo root).
1337
+
1338
+ Returns:
1339
+ dict: {"resources": [...], "unresolved": [...], "findings": [...],
1340
+ "classificationSignals": [...]} with every array
1341
+ deterministically sorted.
1342
+
1343
+ Raises:
1344
+ OSError: A scanned file is missing/unreadable — surfaced as a
1345
+ plugin error frame by the serve loop (fail closed).
1346
+ """
1347
+ base = root if root is not None else Path.cwd()
1348
+ relpaths = [_normalize_path(p) for p in paths]
1349
+
1350
+ indexes: dict[str, FileIndex] = {}
1351
+ findings: list[dict] = []
1352
+ scanned: list[str] = []
1353
+ for relpath in relpaths:
1354
+ if not relpath.endswith(".py"):
1355
+ continue
1356
+ index, finding = _scan_file(relpath, base)
1357
+ if finding is not None:
1358
+ findings.append(finding)
1359
+ continue
1360
+ scanned.append(relpath)
1361
+ indexes[relpath] = index
1362
+ resources: list[dict] = []
1363
+ unresolved: list[dict] = []
1364
+ signals: list[dict] = []
1365
+
1366
+ # Pass 0: the model-name inheritance closure (phase 2). Starting from
1367
+ # every class with table facts or a declarative root, a base whose
1368
+ # SIMPLE name equals a detected model's simple name makes its class a
1369
+ # model too — iterated to a fixpoint over ALL scanned files, because
1370
+ # a flat file scan sees ``class SalariedEmployee(Employee)`` and
1371
+ # ``class Employee(Base)`` in arbitrary order (or in different files)
1372
+ # and multi-level chains must still resolve. Only the closure is
1373
+ # global: a name enters it exclusively through the conservative
1374
+ # per-file predicate, never through bare base lists.
1375
+ model_names: set[str] = set()
1376
+ changed = True
1377
+ while changed:
1378
+ changed = False
1379
+ for idx in indexes.values():
1380
+ for rec in idx.classes:
1381
+ simple = rec.qname.rsplit(".", 1)[-1]
1382
+ if simple in model_names:
1383
+ continue
1384
+ if rec.is_table_candidate(idx, model_names):
1385
+ model_names.add(simple)
1386
+ changed = True
1387
+
1388
+ # Pass 1: class symbols + business tables + typed unresolved + signals.
1389
+ for relpath in sorted(indexes):
1390
+ idx = indexes[relpath]
1391
+ for rec in idx.classes:
1392
+ if rec.is_table_candidate(idx, model_names) or rec.is_pure_base(idx):
1393
+ last_segment_unresolved = (
1394
+ rec.tablename_literal is None and not rec.is_pure_base(idx)
1395
+ )
1396
+ resources.append(_symbol_resource(relpath, rec, last_segment_unresolved))
1397
+ if rec.is_pure_base(idx):
1398
+ continue # bases never materialize; the symbol table owns them
1399
+ if rec.tablename_literal is not None:
1400
+ resources.append(_table_resource(relpath, rec, "literal"))
1401
+ table_name = rec.tablename_literal
1402
+ identity = _identity_signal(rec, relpath, table_name, rec.node)
1403
+ if identity is not None:
1404
+ signals.append(identity)
1405
+ signals.extend(_declaration_signals(rec, relpath, table_name))
1406
+ unresolved.extend(_signal_unresolved_entries(rec, relpath, identity is not None))
1407
+ elif rec.is_table_candidate(idx, model_names):
1408
+ unresolved.append(_unresolved_entry(relpath, rec))
1409
+
1410
+ # Pass 2: direct Table("name", ...) declarations.
1411
+ for relpath in sorted(indexes):
1412
+ for call in indexes[relpath].table_calls:
1413
+ resources.append(_call_table_resource(relpath, call))
1414
+ facts = _table_call_facts(call)
1415
+ identity = _identity_signal(facts, relpath, call["table_name"], call["node"])
1416
+ if identity is not None:
1417
+ signals.append(identity)
1418
+
1419
+ resources.sort(key=lambda r: r["id"])
1420
+ unresolved.sort(
1421
+ key=lambda u: (
1422
+ u["location"]["file"], u["location"]["line"],
1423
+ u["location"]["col"], u["code"], u["detail"],
1424
+ )
1425
+ )
1426
+ findings.extend(_duplicate_findings(resources))
1427
+ findings.extend(_class_name_findings(indexes, frozenset(model_names)))
1428
+ findings.sort(
1429
+ key=lambda f: (
1430
+ f["code"], f["detail"],
1431
+ f["locations"][0]["file"] if f["locations"] else "",
1432
+ f["locations"][0]["line"] if f["locations"] else 0,
1433
+ )
1434
+ )
1435
+ # Canonical wire order: by GF-canonical-JSON text — deterministic and
1436
+ # identical to what the core classifier's signalId sorting expects.
1437
+ signals.sort(key=lambda s: json.dumps(s, sort_keys=True, separators=(",", ":"), ensure_ascii=False))
1438
+
1439
+ return {
1440
+ "resources": resources,
1441
+ "unresolved": unresolved,
1442
+ "findings": findings,
1443
+ "classificationSignals": signals,
1444
+ # Coverage evidence (ADR 0003 D4): files parsed successfully.
1445
+ "scannedPaths": sorted(scanned),
1446
+ }