@gate-forge/pack-sqlalchemy 0.7.1 → 0.8.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.
package/README.md CHANGED
@@ -22,9 +22,11 @@ with `ast.parse` and reports:
22
22
  | Source construct | Emitted as |
23
23
  | --- | --- |
24
24
  | Declarative class with literal `__tablename__` (legacy `declarative_base()` and 2.0 `DeclarativeBase` styles) | `sqlalchemy.table` resource + class symbol |
25
+ | SQLModel class (`class X(SQLModel, table=True)` or a shared `SQLModel` base) with no `__tablename__` | `sqlalchemy.table` resource named by SQLModel's own rule (the lowercased class name, provenance `sqlmodel-class-name`) + class symbol |
26
+ | SQLModel class WITHOUT `table=True` (a plain class, or `table=False`) | nothing — it is not a table |
25
27
  | Direct `Table("name", ...)` call | `sqlalchemy.table` resource (provenance `table-call-first-arg`) |
26
28
  | Abstract base (`__abstract__ = True`) or `DeclarativeBase` subclass with no table facts | class symbol only (`abstract: true` / base); never a business resource |
27
- | Class whose tablename is a decorated function, f-string, call, name ref, or SQLModel `table=True` | class symbol with `tablenameUnresolved: true` + typed `unresolved` entry |
29
+ | Class whose tablename is a decorated function, f-string, call, name ref, or `table=True` on a non-SQLModel base | class symbol with `tablenameUnresolved: true` + typed `unresolved` entry |
28
30
  | Class with bases but no literal tablename anywhere | class symbol + `no_tablename_source` unresolved entry (the graph resolves through its repo-wide symbol table when a base carries a literal — same-file AND cross-file) |
29
31
  | Plain classes (mixins, no bases, no table facts) | nothing |
30
32
  | Malformed Python file | `PARSE_ERROR` finding with a line number; the file contributes no resources (GF-19) |
@@ -33,7 +35,8 @@ with `ast.parse` and reports:
33
35
 
34
36
  - **Business table resource** — `kind: "sqlalchemy.table"`, identity in
35
37
  `attributes.resourceName`, plus `classQname`, `scope`, `tableName`,
36
- `tablenameProvenance` (`literal` | `table-call-first-arg`),
38
+ `tablenameProvenance` (`literal` | `table-call-first-arg` |
39
+ `sqlmodel-class-name`),
37
40
  `hasTableArgs`/`tableArgsSchema` (literal `schema` from
38
41
  `__table_args__`), `tableKeywordTrue`, `abstract`, `baseNames`.
39
42
  - **Class-symbol resource** — `kind: "gateforge.class"` with the graph's
@@ -43,9 +46,9 @@ with `ast.parse` and reports:
43
46
  - **Unresolved entries** — `{code, detail, location}` at the class
44
47
  statement; codes: `computed_tablename` (decorator count + return
45
48
  expression kind retained in full, GF-02), `table_name_derived_runtime`
46
- (`table=True`), `no_tablename_source`. The graph retires an entry it
47
- resolves and synthesizes `inherited_tablename_unresolved` when it
48
- cannot.
49
+ (`table=True` on a non-SQLModel base), `no_tablename_source`. The graph
50
+ retires an entry it resolves and synthesizes
51
+ `inherited_tablename_unresolved` when it cannot.
49
52
  - **Findings** — `DUPLICATE_TABLE_NAME` (GF-20, **base-qualified**:
50
53
  a same-name group is flagged unless every pair provably sits on a
51
54
  different declarative Base root — separate `MetaData` at runtime — so
@@ -246,6 +249,67 @@ instead of scanning with partial trust). Precedence: the programmatic
246
249
  explicit `planesConfig` option overrides the document; the default
247
250
  document path can be moved with `planesConfigPath`.
248
251
 
252
+ ## Per-tenant singletons
253
+
254
+ A table whose UNIQUE constraint — or whose UNIQUE **index** — includes the
255
+ tenant scope column admits at most ONE row per tenant. A `create` of such a
256
+ resource is therefore provable only on a brand-new tenant, while the
257
+ witness's adapter reads use one process-global login: the create reads as
258
+ "the fixed tenant already has that row". The pack reports that as an
259
+ ADDITIVE fact and never as a verdict:
260
+
261
+ - `attributes.uniqueConstraints` — every declared
262
+ `UniqueConstraint("a", "b")`, `Index("ix", "a", "b", unique=True)`, and
263
+ column-level `unique=True`, as `{name, kind, columns}` (`kind` is
264
+ `constraint` | `index` | `column`; `name` is `null` when unnamed). The
265
+ attribute is **absent** when the table declares no unique constraint, and
266
+ a computed column expression or a non-literal `unique` flag is never
267
+ guessed.
268
+ - `attributes.singletonPerTenant` — `{constraint, tenantColumn, columns}`,
269
+ minted only when BOTH facts are provable: the table's plane evidence is
270
+ `tenant` AND one declared unique constraint includes a recognized
271
+ tenant-scope column (`TENANT_SCOPE_COLUMNS`: `tenant_id`, `tenant`,
272
+ `tenantId`, `tenant_uuid`, `tenant_key`). The first qualifying constraint
273
+ in written order is the one reported; every one of them says the same.
274
+
275
+ Both are attributes, not signals: nothing blocks on them. The gate turns
276
+ the tag into one non-blocking `RESOURCE_SINGLETON_PER_TENANT` advisory per
277
+ resource that owes a `persistence:create`, naming the constraint, the
278
+ tenant column and how to prove it (create the tenant in the test, then
279
+ register that tenant's login with the witness for that session only — see
280
+ `packages/cli/guides/TEST-ENVIRONMENT.md`). A table on another plane, an
281
+ unreviewed table, or a unique constraint that excludes the tenant scope
282
+ column is left byte-identical to before.
283
+
284
+ ### Declaring the tenant scope columns
285
+
286
+ The default list above recognizes the usual spellings only. When the
287
+ scope column is named differently — the ledger table scoped by
288
+ `contractor_id`, unique `(contractor_id, ledger_id, kind)` — the owner
289
+ declares it in `.gateforge.yml`:
290
+
291
+ ```yaml
292
+ # .gateforge.yml
293
+ tenancy:
294
+ scopeColumns: [contractor_id]
295
+ ```
296
+
297
+ - The declaration **replaces** `TENANT_SCOPE_COLUMNS`; it never extends
298
+ it. With the block above, `contractor_id` is recognized and `tenant_id`
299
+ is not, so the recognized scope is exactly what the owner said.
300
+ - **Absent** (no file, no `tenancy` block, no `scopeColumns`) means the
301
+ default list, byte-identical to a pack without this channel.
302
+ - The block must be a nonempty list of column names; anything else fails
303
+ closed with `invalid config <path>: …` rather than quietly disabling
304
+ the tag. The pack validates its own block only — the CLI owns the rest
305
+ of the config document.
306
+ - The key lives in `.gateforge.yml`, so it is inside the trusted policy
307
+ digest: widening the recognized tenant scope is an owner-approved
308
+ policy-revision change, never an agent-editable toggle.
309
+ - Programmatically: `createSqlalchemyDetector({ tenancyScopeColumns: [...] })`
310
+ (or `{ configPath }`) overrides the document channel entirely.
311
+
312
+
249
313
  ## Plane and resource classification
250
314
 
251
315
  The detector emits normalized facts, plane evidence (from
@@ -35,6 +35,19 @@ export interface SqlalchemyDetectorOptions {
35
35
  * byte-identical to `NO_PLANE_MAPPING`; a malformed document throws.
36
36
  */
37
37
  planesConfigPath?: string;
38
+ /**
39
+ * Explicit owner-declared tenant scope columns. Overrides the
40
+ * `.gateforge.yml` `tenancy.scopeColumns` document entirely when given.
41
+ */
42
+ tenancyScopeColumns?: readonly string[];
43
+ /**
44
+ * Repo-relative path of the owner config (YAML) the tenant scope
45
+ * declaration is read from, resolved against the working directory at
46
+ * discover time (default `.gateforge.yml`). Absence is normal — the
47
+ * outcome is then byte-identical to the built-in
48
+ * {@link TENANT_SCOPE_COLUMNS}; a malformed document throws.
49
+ */
50
+ configPath?: string;
38
51
  /** Subprocess argv (default: `python3 -m gateforge_sqlalchemy_detector`). */
39
52
  command?: readonly string[];
40
53
  /** Subprocess environment (default: {@link pythonEnvironment}). */
@@ -64,11 +77,13 @@ type RawOutcome = DiscoveryOutcome;
64
77
  * Args:
65
78
  * outcome: The python discovery outcome.
66
79
  * plane: The plane rule to apply.
80
+ * scopeColumns: The tenant-scope column names to recognize (default:
81
+ * {@link TENANT_SCOPE_COLUMNS}).
67
82
  *
68
83
  * Returns:
69
84
  * RawOutcome: New outcome; tables the rule maps carry `plane`.
70
85
  */
71
- export declare function applyPlaneMapping(outcome: RawOutcome, plane: PlaneRule): RawOutcome;
86
+ export declare function applyPlaneMapping(outcome: RawOutcome, plane: PlaneRule, scopeColumns?: readonly string[]): RawOutcome;
72
87
  /** The code of the blocking declarative-plane conflict finding. */
73
88
  export declare const PLANE_RULE_CONTRADICTION = "PLANE_RULE_CONTRADICTION";
74
89
  /**
@@ -89,11 +104,13 @@ export declare const PLANE_RULE_CONTRADICTION = "PLANE_RULE_CONTRADICTION";
89
104
  * Args:
90
105
  * outcome: The python discovery outcome.
91
106
  * config: The validated declarative plane config.
107
+ * scopeColumns: The tenant-scope column names to recognize (default:
108
+ * {@link TENANT_SCOPE_COLUMNS}).
92
109
  *
93
110
  * Returns:
94
111
  * RawOutcome: New outcome with agreed planes and any conflict findings.
95
112
  */
96
- export declare function applyPlanesConfig(outcome: RawOutcome, config: PlanesConfig): RawOutcome;
113
+ export declare function applyPlanesConfig(outcome: RawOutcome, config: PlanesConfig, scopeColumns?: readonly string[]): RawOutcome;
97
114
  /**
98
115
  * Creates a discover-capable detector module. The default export of the
99
116
  * pack is `createSqlalchemyDetector()` — the CLI in-process contract.
@@ -1 +1 @@
1
- {"version":3,"file":"detector.d.ts","sourceRoot":"","sources":["../src/detector.ts"],"names":[],"mappings":"AAsBA,OAAO,EAEL,KAAK,gBAAgB,EAEtB,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAKL,KAAK,YAAY,EACjB,KAAK,SAAS,EAGf,MAAM,aAAa,CAAC;AAUrB,2EAA2E;AAC3E,eAAO,MAAM,eAAe,UAAqD,CAAC;AAElF;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,GAAE,SAAS,MAAM,EAAO,GAAG,MAAM,CAAC,UAAU,CAGlF;AAED,oDAAoD;AACpD,MAAM,WAAW,yBAAyB;IACxC;;;;OAIG;IACH,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB;;;;OAIG;IACH,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,6EAA6E;IAC7E,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,mEAAmE;IACnE,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,yDAAyD;IACzD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mEAAmE;IACnE,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,oEAAoE;AACpE,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CACN,KAAK,EAAE,SAAS,MAAM,EAAE,GACvB,OAAO,CAAC;QACT,SAAS,EAAE,OAAO,EAAE,CAAC;QACrB,UAAU,EAAE,OAAO,EAAE,CAAC;QACtB,QAAQ,EAAE,OAA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AAC,EAAE,MAAM,CAAC;IACpB,6EAA6E;IAC7E,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,mEAAmE;IACnE,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,yDAAyD;IACzD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mEAAmE;IACnE,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,oEAAoE;AACpE,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CACN,KAAK,EAAE,SAAS,MAAM,EAAE,GACvB,OAAO,CAAC;QACT,SAAS,EAAE,OAAO,EAAE,CAAC;QACrB,UAAU,EAAE,OAAO,EAAE,CAAC;QACtB,QAAQ,EAAE,OAAO,EAAE,CAAC;QACpB,qBAAqB,EAAE,OAAO,EAAE,CAAC;QACjC,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;KACzB,CAAC,CAAC;CACJ;AAED,wDAAwD;AACxD,KAAK,UAAU,GAAG,gBAAgB,CAAC;AA2DnC;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,UAAU,EACnB,KAAK,EAAE,SAAS,EAChB,YAAY,GAAE,SAAS,MAAM,EAAyB,GACrD,UAAU,CAWZ;AAmBD,mEAAmE;AACnE,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AA2CnE;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,UAAU,EACnB,MAAM,EAAE,YAAY,EACpB,YAAY,GAAE,SAAS,MAAM,EAAyB,GACrD,UAAU,CA0BZ;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,GAAE,yBAA8B,GAAG,kBAAkB,CAqDpG"}
package/dist/detector.js CHANGED
@@ -23,6 +23,8 @@ import { delimiter, resolve } from 'node:path';
23
23
  import { PluginSession, } from '@gate-forge/plugin-protocol';
24
24
  import { PACK_PLUGIN_ID, PACK_VERSION } from './version.js';
25
25
  import { NO_PLANE_MAPPING, PLANES_CONFIG_PATH, readPlanesConfigOrNull, resolvePlaneByRules, } from './planes.js';
26
+ import { applySingletonTags, TENANT_SCOPE_COLUMNS } from './singleton.js';
27
+ import { readTenancyScopeColumnsOrNull, CONFIG_PATH } from './tenancy.js';
26
28
  /** Absolute dir of this pack's `python/` tree (the detector package). */
27
29
  const PACK_PYTHON_DIR = fileURLToPath(new URL('../python', import.meta.url));
28
30
  /** Absolute dir of the sibling `@gate-forge/plugin-protocol` python client. */
@@ -42,7 +44,11 @@ export const DEFAULT_COMMAND = ['python3', '-m', 'gateforge_sqlalchemy_detector'
42
44
  */
43
45
  export function pythonEnvironment(extra = []) {
44
46
  const entries = [...extra, PACK_PYTHON_DIR, PROTOCOL_PYTHON_DIR];
45
- return { ...process.env, PYTHONPATH: entries.join(delimiter) };
47
+ return {
48
+ ...process.env,
49
+ PYTHONDONTWRITEBYTECODE: '1',
50
+ PYTHONPATH: entries.join(delimiter),
51
+ };
46
52
  }
47
53
  /** The table facts of one resource, or null when it is not a named table. */
48
54
  function tableFactsOf(resource) {
@@ -95,16 +101,34 @@ function mapTablePlanes(outcome, decide) {
95
101
  * Args:
96
102
  * outcome: The python discovery outcome.
97
103
  * plane: The plane rule to apply.
104
+ * scopeColumns: The tenant-scope column names to recognize (default:
105
+ * {@link TENANT_SCOPE_COLUMNS}).
98
106
  *
99
107
  * Returns:
100
108
  * RawOutcome: New outcome; tables the rule maps carry `plane`.
101
109
  */
102
- export function applyPlaneMapping(outcome, plane) {
103
- return mapTablePlanes(outcome, (facts) => plane({
110
+ export function applyPlaneMapping(outcome, plane, scopeColumns = TENANT_SCOPE_COLUMNS) {
111
+ return withSingletonTags(mapTablePlanes(outcome, (facts) => plane({
104
112
  tableName: facts.tableName,
105
113
  classQname: facts.classQname,
106
114
  provenance: facts.provenance,
107
- }));
115
+ })), scopeColumns);
116
+ }
117
+ /**
118
+ * Rewrites one plane-applied outcome into its per-tenant-singleton form.
119
+ * Every plane channel funnels through here, so the tag is minted exactly
120
+ * once per run and a table without both provable facts is untouched
121
+ * (byte-identical to the pre-tag output).
122
+ *
123
+ * Args:
124
+ * outcome: The outcome with planes already applied.
125
+ * scopeColumns: The tenant-scope column names to recognize.
126
+ *
127
+ * Returns:
128
+ * RawOutcome: The same outcome with `singletonPerTenant` added where earned.
129
+ */
130
+ function withSingletonTags(outcome, scopeColumns) {
131
+ return { ...outcome, resources: applySingletonTags(outcome.resources, scopeColumns) };
108
132
  }
109
133
  /** The code of the blocking declarative-plane conflict finding. */
110
134
  export const PLANE_RULE_CONTRADICTION = 'PLANE_RULE_CONTRADICTION';
@@ -165,11 +189,13 @@ function compareFindings(a, b) {
165
189
  * Args:
166
190
  * outcome: The python discovery outcome.
167
191
  * config: The validated declarative plane config.
192
+ * scopeColumns: The tenant-scope column names to recognize (default:
193
+ * {@link TENANT_SCOPE_COLUMNS}).
168
194
  *
169
195
  * Returns:
170
196
  * RawOutcome: New outcome with agreed planes and any conflict findings.
171
197
  */
172
- export function applyPlanesConfig(outcome, config) {
198
+ export function applyPlanesConfig(outcome, config, scopeColumns = TENANT_SCOPE_COLUMNS) {
173
199
  const contradictionFindings = [];
174
200
  const resources = outcome.resources.map((resource) => {
175
201
  const facts = tableFactsOf(resource);
@@ -188,13 +214,13 @@ export function applyPlanesConfig(outcome, config) {
188
214
  return { ...resource, attributes: { ...resource.attributes, plane: resolution.plane } };
189
215
  });
190
216
  contradictionFindings.sort(compareFindings);
191
- return {
217
+ return withSingletonTags({
192
218
  resources,
193
219
  unresolved: outcome.unresolved,
194
220
  findings: [...outcome.findings, ...contradictionFindings],
195
221
  classificationSignals: outcome.classificationSignals,
196
222
  ...(outcome.scannedPaths !== undefined ? { scannedPaths: outcome.scannedPaths } : {}),
197
- };
223
+ }, scopeColumns);
198
224
  }
199
225
  /**
200
226
  * Creates a discover-capable detector module. The default export of the
@@ -219,6 +245,12 @@ export function createSqlalchemyDetector(options = {}) {
219
245
  const env = options.env ?? pythonEnvironment();
220
246
  const pluginId = options.pluginId ?? PACK_PLUGIN_ID;
221
247
  const pluginVersion = options.pluginVersion ?? PACK_VERSION;
248
+ // The tenant scope channel, resolved once per discover: the explicit
249
+ // option, else the owner's `.gateforge.yml` declaration, else the
250
+ // pack's default list (absence → byte-identical).
251
+ const resolveScopeColumns = () => options.tenancyScopeColumns ??
252
+ readTenancyScopeColumnsOrNull(resolve(process.cwd(), options.configPath ?? CONFIG_PATH)) ??
253
+ TENANT_SCOPE_COLUMNS;
222
254
  return {
223
255
  async discover(paths) {
224
256
  if (paths.length === 0) {
@@ -242,15 +274,16 @@ export function createSqlalchemyDetector(options = {}) {
242
274
  classificationSignals: outcome.classificationSignals,
243
275
  ...(outcome.scannedPaths !== undefined ? { scannedPaths: outcome.scannedPaths } : {}),
244
276
  };
277
+ const scopeColumns = resolveScopeColumns();
245
278
  if (plane !== undefined) {
246
- return planeIsNoop(plane) ? withSignals : applyPlaneMapping(withSignals, plane);
279
+ return planeIsNoop(plane) ? withSignals : applyPlaneMapping(withSignals, plane, scopeColumns);
247
280
  }
248
281
  const config = options.planesConfig ??
249
282
  readPlanesConfigOrNull(resolve(process.cwd(), options.planesConfigPath ?? PLANES_CONFIG_PATH));
250
283
  if (config.rules.length === 0) {
251
284
  return withSignals; // no rules: byte-identical to NO_PLANE_MAPPING
252
285
  }
253
- return applyPlanesConfig(withSignals, config);
286
+ return applyPlanesConfig(withSignals, config, scopeColumns);
254
287
  }
255
288
  finally {
256
289
  await session.dispose();
@@ -1 +1 @@
1
- {"version":3,"file":"detector.js","sourceRoot":"","sources":["../src/detector.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EACL,aAAa,GAGd,MAAM,6BAA6B,CAAC;AACrC,OAA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9B,QAAQ,EAAE,OAAO,CAAC,QAAQ;oBAC1B,qBAAqB,EAAE,OAAO,CAAC,qBAAqB;oBACpD,GAAG,CAAC,OAAO,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBACtF,CAAC;gBACF,MAAM,YAAY,GAAG,mBAAmB,EAAE,CAAC;gBAC3C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;oBACxB,OAAO,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,iBAAiB,CAAC,WAAW,EAAE,KAAK,EAAE,YAAY,CAAC,CAAC;gBAChG,CAAC;gBACD,MAAM,MAAM,GACV,OAAO,CAAC,YAAY;oBACpB,sBAAsB,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,OAAO,CAAC,gBAAgB,IAAI,kBAAkB,CAAC,CAAC,CAAC;gBACjG,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;oBAC9B,OAAO,WAAW,CAAC,CAAC,+CAA+C;gBACrE,CAAC;gBACD,OAAO,iBAAiB,CAAC,WAAW,EAAE,MAAM,EAAE,YAAY,CAAC,CAAC;YAC9D,CAAC;oBAAS,CAAC;gBACT,MAAM,OAAO,CAAC,OAAO,EAAE,CAAC;YAC1B,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AAED,qDAAqD;AACrD,SAAS,WAAW,CAAC,KAAgB;IACnC,OAAO,KAAK,KAAK,gBAAgB,CAAC;AACpC,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export { PACK_PLUGIN_ID, PACK_VERSION } from './version.js';
2
2
  export { createSqlalchemyDetector, DEFAULT_COMMAND, pythonEnvironment, applyPlaneMapping, applyPlanesConfig, PLANE_RULE_CONTRADICTION, type SqlalchemyDetector, type SqlalchemyDetectorOptions, } from './detector.js';
3
3
  export { DEFAULT_PLANES_CONFIG, NO_PLANE_MAPPING, PLANES_CONFIG_PATH, byTableName, planeRuleMatches, readPlanesConfigOrNull, parsePlanesConfigText, resolvePlaneByRules, type PlaneConfigRule, type PlaneContext, type PlaneMatchInput, type PlaneResolution, type PlaneRule, type PlaneRuleHit, type PlanesConfig, type SqlalchemyPlane, } from './planes.js';
4
+ export { applySingletonTags, singletonTagFor, TENANT_SCOPE_COLUMNS, type SingletonPerTenantFact, } from './singleton.js';
5
+ export { readTenancyScopeColumnsOrNull, CONFIG_PATH as TENANCY_CONFIG_PATH, } from './tenancy.js';
4
6
  export { EntityAdapterSchema, validateEntityAdapter, type EntityAdapter, type EntityAdapterContext, type NormalizedEntity, type EntityAdapterValidation, } from './adapter-schema.js';
5
7
  /** The default CLI in-process plugin module: `{ discover(paths) }`. */
6
8
  declare const _default: import("./detector.js").SqlalchemyDetector;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EACL,wBAAwB,EACxB,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,wBAAwB,EACxB,KAAK,kBAAkB,EACvB,KAAK,yBAAyB,GAC/B,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,kBAAkB,EAClB,WAAW,EACX,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EACnB,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,eAAe,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,GAC7B,MAAM,qBAAqB,CAAC;AAC7B,uEAAuE;;AACvE,wBAA0C"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EACL,wBAAwB,EACxB,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,wBAAwB,EACxB,KAAK,kBAAkB,EACvB,KAAK,yBAAyB,GAC/B,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,kBAAkB,EAClB,WAAW,EACX,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EACnB,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,eAAe,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,oBAAoB,EACpB,KAAK,sBAAsB,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,6BAA6B,EAC7B,WAAW,IAAI,mBAAmB,GACnC,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,GAC7B,MAAM,qBAAqB,CAAC;AAC7B,uEAAuE;;AACvE,wBAA0C"}
package/dist/index.js CHANGED
@@ -25,6 +25,8 @@ import { createSqlalchemyDetector } from './detector.js';
25
25
  export { PACK_PLUGIN_ID, PACK_VERSION } from './version.js';
26
26
  export { createSqlalchemyDetector, DEFAULT_COMMAND, pythonEnvironment, applyPlaneMapping, applyPlanesConfig, PLANE_RULE_CONTRADICTION, } from './detector.js';
27
27
  export { DEFAULT_PLANES_CONFIG, NO_PLANE_MAPPING, PLANES_CONFIG_PATH, byTableName, planeRuleMatches, readPlanesConfigOrNull, parsePlanesConfigText, resolvePlaneByRules, } from './planes.js';
28
+ export { applySingletonTags, singletonTagFor, TENANT_SCOPE_COLUMNS, } from './singleton.js';
29
+ export { readTenancyScopeColumnsOrNull, CONFIG_PATH as TENANCY_CONFIG_PATH, } from './tenancy.js';
28
30
  export { EntityAdapterSchema, validateEntityAdapter, } from './adapter-schema.js';
29
31
  /** The default CLI in-process plugin module: `{ discover(paths) }`. */
30
32
  export default createSqlalchemyDetector();
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EACL,wBAAwB,EACxB,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,wBAAwB,GAGzB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,kBAAkB,EAClB,WAAW,EACX,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,GASpB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GAKtB,MAAM,qBAAqB,CAAC;AAC7B,uEAAuE;AACvE,eAAe,wBAAwB,EAAE,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EACL,wBAAwB,EACxB,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,wBAAwB,GAGzB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,kBAAkB,EAClB,WAAW,EACX,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,GASpB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,oBAAoB,GAErB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,6BAA6B,EAC7B,WAAW,IAAI,mBAAmB,GACnC,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GAKtB,MAAM,qBAAqB,CAAC;AAC7B,uEAAuE;AACvE,eAAe,wBAAwB,EAAE,CAAC"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Per-tenant singleton facts (plan 2026-09-25 Phase 4b item 3a).
3
+ *
4
+ * A table whose UNIQUE constraint — or whose UNIQUE INDEX — includes the
5
+ * tenant scope column admits at most ONE row per tenant. A create of such
6
+ * a resource is therefore provable only on a brand-new tenant, while the
7
+ * witness's adapter reads use one process-global login: the create reads
8
+ * as "the fixed tenant already has that row". This module mints the
9
+ * additive `singletonPerTenant` attribute that lets the gate TELL the
10
+ * owner; it never decides a verdict, never blocks, and never guesses.
11
+ * The rule is deliberately narrow and stated in full: BOTH facts must be
12
+ * provable statically — the table must carry plane evidence of `tenant`
13
+ * (the reviewed decision, resolved by the plane channel) AND one of its
14
+ * declared `uniqueConstraints` must include a tenant-scope column. A
15
+ * table on another plane, an unreviewed table, or a unique constraint
16
+ * that excludes the tenant scope column is left untouched, so the
17
+ * output stays byte-identical wherever the tag is not earned.
18
+ *
19
+ * WHICH columns carry the tenant scope is the owner's call: the default
20
+ * is {@link TENANT_SCOPE_COLUMNS}, and an application whose scope column
21
+ * is spelled differently (`contractor_id`, ...) passes its own list, read
22
+ * from `.gateforge.yml` (`tenancy.scopeColumns`, see `tenancy.ts`). The
23
+ * passed list REPLACES the default — it never extends it.
24
+ */
25
+ /** Column names that RESEMBLE the tenant scope of a tenant-plane table. */
26
+ export declare const TENANT_SCOPE_COLUMNS: readonly string[];
27
+ /** The additive tag one per-tenant-singleton table carries. */
28
+ export interface SingletonPerTenantFact {
29
+ /** Declared constraint/index name, or null when it is unnamed. */
30
+ constraint: string | null;
31
+ /** The recognized tenant-scope column inside {@link columns}. */
32
+ tenantColumn: string;
33
+ /** Every column of the unique constraint/index, written order. */
34
+ columns: readonly string[];
35
+ }
36
+ /** The discovered-resource attribute bag the tag is computed from. */
37
+ type Attributes = Readonly<Record<string, unknown>>;
38
+ /**
39
+ * The unique constraint that makes this table a singleton per tenant,
40
+ * or null when no declared constraint includes the tenant scope column.
41
+ *
42
+ * Args:
43
+ * attributes: One `sqlalchemy.table` resource's attributes.
44
+ *
45
+ * Returns:
46
+ * SingletonPerTenantFact | null: the deciding constraint's fact, or null.
47
+ */
48
+ export declare function singletonTagFor(attributes: Attributes, scopeColumns?: readonly string[]): SingletonPerTenantFact | null;
49
+ /** The discovered-resource shape the tag pass rewrites. */
50
+ interface DiscoverableResource {
51
+ readonly kind: string;
52
+ readonly attributes: Attributes;
53
+ }
54
+ /**
55
+ * Adds `singletonPerTenant` to every table that earns it and changes
56
+ * nothing else. Pure over its inputs — deterministic.
57
+ *
58
+ * Args:
59
+ * resources: The discovery outcome's resource list.
60
+ * scopeColumns: The tenant-scope column names to recognize (default:
61
+ * {@link TENANT_SCOPE_COLUMNS}; an owner-declared list REPLACES it).
62
+ *
63
+ * Returns:
64
+ * DiscoverableResource[]: the same resources, tagged where provable.
65
+ */
66
+ export declare function applySingletonTags<T extends DiscoverableResource>(resources: readonly T[], scopeColumns?: readonly string[]): T[];
67
+ export {};
68
+ //# sourceMappingURL=singleton.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"singleton.d.ts","sourceRoot":"","sources":["../src/singleton.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,2EAA2E;AAC3E,eAAO,MAAM,oBAAoB,EAAE,SAAS,MAAM,EAMhD,CAAC;AAEH,+DAA+D;AAC/D,MAAM,WAAW,sBAAsB;IACrC,kEAAkE;IAClE,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,iEAAiE;IACjE,YAAY,EAAE,MAAM,CAAC;IACrB,kEAAkE;IAClE,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5B;AASD,sEAAsE;AACtE,KAAK,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAuBpD;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC7B,UAAU,EAAE,UAAU,EACtB,YAAY,GAAE,SAAS,MAAM,EAAyB,GACrD,sBAAsB,GAAG,IAAI,CAoB/B;AAED,2DAA2D;AAC3D,UAAU,oBAAoB;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;CACjC;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,oBAAoB,EAC/D,SAAS,EAAE,SAAS,CAAC,EAAE,EACvB,YAAY,GAAE,SAAS,MAAM,EAAyB,GACrD,CAAC,EAAE,CAOL"}
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Per-tenant singleton facts (plan 2026-09-25 Phase 4b item 3a).
3
+ *
4
+ * A table whose UNIQUE constraint — or whose UNIQUE INDEX — includes the
5
+ * tenant scope column admits at most ONE row per tenant. A create of such
6
+ * a resource is therefore provable only on a brand-new tenant, while the
7
+ * witness's adapter reads use one process-global login: the create reads
8
+ * as "the fixed tenant already has that row". This module mints the
9
+ * additive `singletonPerTenant` attribute that lets the gate TELL the
10
+ * owner; it never decides a verdict, never blocks, and never guesses.
11
+ * The rule is deliberately narrow and stated in full: BOTH facts must be
12
+ * provable statically — the table must carry plane evidence of `tenant`
13
+ * (the reviewed decision, resolved by the plane channel) AND one of its
14
+ * declared `uniqueConstraints` must include a tenant-scope column. A
15
+ * table on another plane, an unreviewed table, or a unique constraint
16
+ * that excludes the tenant scope column is left untouched, so the
17
+ * output stays byte-identical wherever the tag is not earned.
18
+ *
19
+ * WHICH columns carry the tenant scope is the owner's call: the default
20
+ * is {@link TENANT_SCOPE_COLUMNS}, and an application whose scope column
21
+ * is spelled differently (`contractor_id`, ...) passes its own list, read
22
+ * from `.gateforge.yml` (`tenancy.scopeColumns`, see `tenancy.ts`). The
23
+ * passed list REPLACES the default — it never extends it.
24
+ */
25
+ /** Column names that RESEMBLE the tenant scope of a tenant-plane table. */
26
+ export const TENANT_SCOPE_COLUMNS = Object.freeze([
27
+ 'tenant_id',
28
+ 'tenant',
29
+ 'tenantId',
30
+ 'tenant_uuid',
31
+ 'tenant_key',
32
+ ]);
33
+ /**
34
+ * Reads one `uniqueConstraints` entry, or null when the attribute is
35
+ * absent or malformed (never a partial guess).
36
+ */
37
+ function uniqueConstraintOf(value) {
38
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
39
+ return null;
40
+ const entry = value;
41
+ if (typeof entry.kind !== 'string' || entry.kind.length === 0)
42
+ return null;
43
+ if (!Array.isArray(entry.columns) || entry.columns.length === 0)
44
+ return null;
45
+ const columns = [];
46
+ for (const column of entry.columns) {
47
+ if (typeof column !== 'string' || column.length === 0)
48
+ return null;
49
+ columns.push(column);
50
+ }
51
+ return {
52
+ name: typeof entry.name === 'string' && entry.name.length > 0 ? entry.name : null,
53
+ kind: entry.kind,
54
+ columns,
55
+ };
56
+ }
57
+ /**
58
+ * The unique constraint that makes this table a singleton per tenant,
59
+ * or null when no declared constraint includes the tenant scope column.
60
+ *
61
+ * Args:
62
+ * attributes: One `sqlalchemy.table` resource's attributes.
63
+ *
64
+ * Returns:
65
+ * SingletonPerTenantFact | null: the deciding constraint's fact, or null.
66
+ */
67
+ export function singletonTagFor(attributes, scopeColumns = TENANT_SCOPE_COLUMNS) {
68
+ // Plane evidence first: an unreviewed table is never a tenant table.
69
+ if (attributes['plane'] !== 'tenant')
70
+ return null;
71
+ const declared = attributes['uniqueConstraints'];
72
+ if (!Array.isArray(declared))
73
+ return null;
74
+ for (const raw of declared) {
75
+ const constraint = uniqueConstraintOf(raw);
76
+ if (constraint === null)
77
+ continue;
78
+ // Written order decides which constraint is reported when several
79
+ // qualify — deterministic, and every one of them still says the same.
80
+ for (const column of constraint.columns) {
81
+ if (!scopeColumns.includes(column))
82
+ continue;
83
+ return {
84
+ constraint: constraint.name,
85
+ tenantColumn: column,
86
+ columns: [...constraint.columns],
87
+ };
88
+ }
89
+ }
90
+ return null;
91
+ }
92
+ /**
93
+ * Adds `singletonPerTenant` to every table that earns it and changes
94
+ * nothing else. Pure over its inputs — deterministic.
95
+ *
96
+ * Args:
97
+ * resources: The discovery outcome's resource list.
98
+ * scopeColumns: The tenant-scope column names to recognize (default:
99
+ * {@link TENANT_SCOPE_COLUMNS}; an owner-declared list REPLACES it).
100
+ *
101
+ * Returns:
102
+ * DiscoverableResource[]: the same resources, tagged where provable.
103
+ */
104
+ export function applySingletonTags(resources, scopeColumns = TENANT_SCOPE_COLUMNS) {
105
+ return resources.map((resource) => {
106
+ if (resource.kind !== 'sqlalchemy.table')
107
+ return resource;
108
+ const fact = singletonTagFor(resource.attributes, scopeColumns);
109
+ if (fact === null)
110
+ return resource;
111
+ return { ...resource, attributes: { ...resource.attributes, singletonPerTenant: fact } };
112
+ });
113
+ }
114
+ //# sourceMappingURL=singleton.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"singleton.js","sourceRoot":"","sources":["../src/singleton.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,2EAA2E;AAC3E,MAAM,CAAC,MAAM,oBAAoB,GAAsB,MAAM,CAAC,MAAM,CAAC;IACnE,WAAW;IACX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reads the owner-declared tenant scope columns out of a config file.
5
+ *
6
+ * Args:
7
+ * path: Absolute or cwd-relative config path; null disables the
8
+ * channel entirely (today's behavior, byte-identical).
9
+ *
10
+ * Returns:
11
+ * readonly string[] | null: the declared columns, or null when the
12
+ * file is absent/unreadable or declares no tenancy scope.
13
+ *
14
+ * Raises:
15
+ * Error: for unparsable YAML or a malformed `tenancy` block.
16
+ */
17
+ export declare function readTenancyScopeColumnsOrNull(path: string | null): readonly string[] | null;
18
+ //# sourceMappingURL=tenancy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tenancy.d.ts","sourceRoot":"","sources":["../src/tenancy.ts"],"names":[],"mappings":"AA+BA,iEAAiE;AACjE,eAAO,MAAM,WAAW,mBAAmB,CAAC;AAE5C;;;;;;;;;;;;;GAaG;AACH,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,MAAM,EAAE,GAAG,IAAI,CA2C3F"}
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The owner-declared tenant scope channel (plan 2026-09-25 Phase 4b
3
+ * item 3a).
4
+ *
5
+ * The per-tenant-singleton tag needs to know which column carries the
6
+ * tenant scope. The pack ships a FIXED default list of the usual
7
+ * spellings (`tenant_id`, `tenant`, ...), but scope columns differ per
8
+ * application — the incident's ledger table is scoped by
9
+ * `contractor_id`. The owner therefore declares them in `.gateforge.yml`:
10
+ *
11
+ * ```yaml
12
+ * tenancy:
13
+ * scopeColumns: [contractor_id]
14
+ * ```
15
+ *
16
+ * The declaration REPLACES the default list (never extends it), so the
17
+ * recognized scope is exactly what the owner said and nothing else. A
18
+ * missing file, a missing key, and a config that says nothing about
19
+ * tenancy all read as `null` — absence, byte-identical to today. A
20
+ * present but MALFORMED `tenancy` block throws (fail closed, a typo must
21
+ * not silently disable the tag).
22
+ *
23
+ * SCOPE: this reader validates the `tenancy` block only. The pack is a
24
+ * detector, not the config authority — the CLI loads `.gateforge.yml`
25
+ * fail-closed before any pack runs, and a detector must keep working
26
+ * (byte-identically) in a repository whose config carries an unrelated
27
+ * problem it has no opinion about.
28
+ */
29
+ import { readFileSync } from 'node:fs';
30
+ import { parse as parseYaml } from 'yaml';
31
+ /** Repo-relative path of the owner config this channel reads. */
32
+ export const CONFIG_PATH = '.gateforge.yml';
33
+ /**
34
+ * Reads the owner-declared tenant scope columns out of a config file.
35
+ *
36
+ * Args:
37
+ * path: Absolute or cwd-relative config path; null disables the
38
+ * channel entirely (today's behavior, byte-identical).
39
+ *
40
+ * Returns:
41
+ * readonly string[] | null: the declared columns, or null when the
42
+ * file is absent/unreadable or declares no tenancy scope.
43
+ *
44
+ * Raises:
45
+ * Error: for unparsable YAML or a malformed `tenancy` block.
46
+ */
47
+ export function readTenancyScopeColumnsOrNull(path) {
48
+ if (path === null)
49
+ return null;
50
+ let text;
51
+ try {
52
+ text = readFileSync(path, 'utf8');
53
+ }
54
+ catch {
55
+ return null; // absence is normal; malformed is not (below)
56
+ }
57
+ let document;
58
+ try {
59
+ document = parseYaml(text);
60
+ }
61
+ catch (cause) {
62
+ throw new Error(`invalid config ${path}: invalid YAML: ${cause.message.split('\n')[0] ?? 'parse error'}`);
63
+ }
64
+ if (document === null || document === undefined)
65
+ return null;
66
+ if (typeof document !== 'object' || Array.isArray(document)) {
67
+ throw new Error(`invalid config ${path}: expected a mapping at the document root`);
68
+ }
69
+ const tenancy = document['tenancy'];
70
+ if (tenancy === undefined)
71
+ return null;
72
+ if (typeof tenancy !== 'object' || tenancy === null || Array.isArray(tenancy)) {
73
+ throw new Error(`invalid config ${path}: 'tenancy' must be a mapping`);
74
+ }
75
+ const block = tenancy;
76
+ const unknownKeys = Object.keys(block).filter((key) => key !== 'scopeColumns');
77
+ if (unknownKeys.length > 0) {
78
+ throw new Error(`invalid config ${path}: unknown key(s) ${unknownKeys.sort().join(', ')} under 'tenancy'`);
79
+ }
80
+ const declared = block['scopeColumns'];
81
+ if (declared === undefined)
82
+ return null; // the block exists but says nothing
83
+ if (!Array.isArray(declared) || declared.length === 0) {
84
+ throw new Error(`invalid config ${path}: 'tenancy.scopeColumns' must be a nonempty list of column names`);
85
+ }
86
+ for (const column of declared) {
87
+ if (typeof column !== 'string' || column.length === 0) {
88
+ throw new Error(`invalid config ${path}: 'tenancy.scopeColumns' must be a nonempty list of column names`);
89
+ }
90
+ }
91
+ return Object.freeze([...declared]);
92
+ }
93
+ //# sourceMappingURL=tenancy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tenancy.js","sourceRoot":"","sources":["../src/tenancy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,MAAM,CAAC;AAE1C,iEAAiE;AACjE,MAAM,CAAC,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAE5C;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,6BAA6B,CAAC,IAAmB;IAC/D,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAC/B,IAAI,IAAY,CAAC;IACjB,IAAI,CAAC;QACH,IAAI,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACpC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC,CAAC,8CAA8C;IAC7D,CAAC;IACD,IAAI,QAAiB,CAAC;IACtB,IAAI,CAAC;QACH,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CACb,kBAAkB,IAAI,mBAAoB,KAAe,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,aAAa,EAAE,CACpG,CAAC;IACJ,CAAC;IACD,IAAI,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS;QAAE,OAA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AO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtD,MAAM,IAAI,KAAK,CAAC,kBAAkB,IAAI,kEAAkE,CAAC,CAAC;QAC5G,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,GAAI,QAAqB,CAAC,CAAC,CAAC;AACpD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gate-forge/pack-sqlalchemy",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "SQLAlchemy CRUD discovery pack: AST-only python detector (GPP/3), in-process TS discover entry, configurable plane mapping, entity-adapter schema.",
6
6
  "type": "module",
@@ -25,8 +25,8 @@
25
25
  "test": "vitest run"
26
26
  },
27
27
  "dependencies": {
28
- "@gate-forge/core": "^0.7.1",
29
- "@gate-forge/plugin-protocol": "^0.7.1",
28
+ "@gate-forge/core": "^0.8.0",
29
+ "@gate-forge/plugin-protocol": "^0.8.0",
30
30
  "yaml": "^2.8.1",
31
31
  "zod": "^4.1.5"
32
32
  },
@@ -31,8 +31,17 @@ Detector vocabulary (frozen with the pack):
31
31
  ``argparse``, ``dataclasses``, ``marshmallow``, ``fastapi`` — can
32
32
  never qualify. A non-candidate class is emitted NOWHERE: no symbol,
33
33
  no table, no unresolved entry.
34
+ - SQLModel tables: ``class X(SQLModel, table=True)`` (or a shared
35
+ ``SQLModel`` base, resolved through a cross-file SQLModel closure) is a
36
+ table whose name SQLModel derives at runtime by lowercasing the class
37
+ name. The AST can see that rule, so the name is a FACT
38
+ (``tablenameProvenance`` ``sqlmodel-class-name``), not a guess. A
39
+ ``Field(...)`` call counts as a column constructor only when the file
40
+ imports it from ``sqlmodel``; ``table=False`` (or a computed value) is
41
+ NOT a table, so a plain SQLModel class is invisible in every channel.
34
42
  - ``unresolved`` entries: typed reasons (``computed_tablename``,
35
- ``table_name_derived_runtime``, ``no_tablename_source``) located at
43
+ ``table_name_derived_runtime`` — a ``table=True`` on a NON-SQLModel
44
+ base, whose name the AST cannot see, ``no_tablename_source``) located at
36
45
  the class statement; the graph retires them when it resolves the name
37
46
  and synthesizes ``inherited_tablename_unresolved`` when it cannot
38
47
  (GF-21: computed identity is typed, never absent).
@@ -43,7 +52,8 @@ Detector vocabulary (frozen with the pack):
43
52
  ``__gateforge_delete_semantics__``, ``__gateforge_archive_state__``,
44
53
  ``__gateforge_read_only__``; never an exposure claim (a table
45
54
  declaration proves nothing about external reachability).
46
- - additional table attributes: ``primaryKeyColumns``,
55
+ - additional table attributes: ``columnNames`` (every literal column,
56
+ written order), ``primaryKeyColumns``,
47
57
  ``foreignKeyReferences`` (literal ``ForeignKey`` targets),
48
58
  ``softDeleteCandidateFields`` (bookkeeping-resembling column names —
49
59
  facts for reviewers, never semantics), ``readOnly``.
@@ -102,6 +102,21 @@ UPDATEABLE_FIELDS_ATTR = "__gateforge_updateable_fields__"
102
102
  # Column-call constructors carrying column facts.
103
103
  COLUMN_CALL_NAMES = ("Column", "mapped_column")
104
104
 
105
+ # SQLModel declares tables with the class keyword ``table=True`` on a
106
+ # class deriving from ``SQLModel`` — no declarative base, no
107
+ # ``__tablename__``. SQLModel derives the table name at runtime by
108
+ # lowercasing the class name, which the AST CAN see, so the name is a
109
+ # fact (``sqlmodel-class-name`` provenance), not a guess. The root is
110
+ # recognized by import provenance (``from sqlmodel import SQLModel``,
111
+ # including aliases) or the exact conventional name ``SQLModel``; a
112
+ # denylisted provenance (Pydantic's ``BaseModel`` family) never matches.
113
+ SQLMODEL_MODULES = ("sqlmodel",)
114
+ SQLMODEL_ROOT_NAME = "SQLModel"
115
+
116
+ # Tablename provenance label for a name SQLModel derives at runtime from
117
+ # the class name.
118
+ SQLMODEL_CLASS_NAME_PROVENANCE = "sqlmodel-class-name"
119
+
105
120
  # Import provenance that can NEVER make a base name a declarative root
106
121
  # (phase 2 denylist). The conventional-name rule ("Base") is a flat-file
107
122
  # heuristic: most projects do ``from app.db import Base`` (cross-file,
@@ -244,6 +259,28 @@ class ColumnFacts:
244
259
  self.foreign_keys: dict[str, str] = {}
245
260
  #: Sorted column names resembling soft-delete bookkeeping.
246
261
  self.soft_delete_candidates: list[str] = []
262
+ #: Every literal column name, in written order (deduplicated).
263
+ self.column_names: list[str] = []
264
+ #: Declared UNIQUE constraints/indexes in written order, as
265
+ #: ``{"name": str | None, "kind": "constraint"|"index"|"column",
266
+ #: "columns": [...]}``. Literal evidence only — a computed column
267
+ #: expression is never guessed.
268
+ self.unique_constraints: list[dict] = []
269
+
270
+ def add_unique(self, name: str | None, kind: str, columns: list[str]) -> None:
271
+ """Records one declared UNIQUE constraint/index, deduplicated.
272
+
273
+ Args:
274
+ name: The declared constraint/index name, or None when unnamed.
275
+ kind: ``constraint`` (UniqueConstraint), ``index`` (a unique
276
+ Index), or ``column`` (a column declared ``unique=True``).
277
+ columns: The unique columns, written order.
278
+ """
279
+ if not columns:
280
+ return
281
+ fact = {"name": name, "kind": kind, "columns": list(columns)}
282
+ if fact not in self.unique_constraints:
283
+ self.unique_constraints.append(fact)
247
284
 
248
285
  @property
249
286
  def has_pk_evidence(self) -> bool:
@@ -270,8 +307,16 @@ def _literal_kwarg_true(call: ast.Call, name: str) -> bool | None:
270
307
  return None
271
308
 
272
309
 
310
+
311
+
273
312
  def _column_call_name(call: ast.expr) -> str | None:
274
- """Simple name of a call, when it is a column constructor."""
313
+ """Simple name of a call, when it is a plain column constructor.
314
+
315
+ The unqualified SQLAlchemy constructors only. SQLModel's ``Field`` is
316
+ recognized per class in `ClassRecord._column_call_name`, which can see
317
+ the import provenance; it never appears in ``__table_args__`` or in a
318
+ ``Table(...)`` argument list.
319
+ """
275
320
  name = call_name(call.func) if isinstance(call, ast.Call) else None
276
321
  return name if name in COLUMN_CALL_NAMES else None
277
322
 
@@ -292,7 +337,13 @@ def _column_name(call: ast.Call, target: str | None) -> str | None:
292
337
 
293
338
 
294
339
  def _foreign_key_reference(call: ast.Call) -> str | None:
295
- """Finds a literal ``ForeignKey("<table>.<column>")`` argument."""
340
+ """Finds a literal foreign-key target, by ``ForeignKey("t.c")`` or by string.
341
+
342
+ SQLModel spells the target as a literal string instead of a call:
343
+ ``hero_id: int | None = Field(foreign_key="hero.id")``. A declarative
344
+ ``Column`` never takes that keyword, so reading it changes nothing for
345
+ the existing styles.
346
+ """
296
347
  for arg in call.args:
297
348
  if (
298
349
  isinstance(arg, ast.Call)
@@ -311,6 +362,13 @@ def _foreign_key_reference(call: ast.Call) -> str | None:
311
362
  and isinstance(kw.value.args[0].value, str)
312
363
  ):
313
364
  return kw.value.args[0].value
365
+ for kw in call.keywords:
366
+ if (
367
+ kw.arg == "foreign_key"
368
+ and isinstance(kw.value, ast.Constant)
369
+ and isinstance(kw.value.value, str)
370
+ ):
371
+ return kw.value.value
314
372
  return None
315
373
 
316
374
 
@@ -336,6 +394,10 @@ def _record_column(facts: ColumnFacts, call: ast.Call, target: str | None) -> No
336
394
  facts.foreign_keys[column_name] = reference
337
395
  if column_name in SOFT_DELETE_CANDIDATE_FIELDS:
338
396
  facts.soft_delete_candidates.append(column_name)
397
+ if column_name not in facts.column_names:
398
+ facts.column_names.append(column_name)
399
+ if _literal_kwarg_true(call, "unique") is True:
400
+ facts.add_unique(None, "column", [column_name])
339
401
 
340
402
 
341
403
  def _facts_from_column_calls(calls: list[tuple[ast.Call, str | None]]) -> ColumnFacts:
@@ -368,13 +430,75 @@ def _pk_constraint_columns(node: ast.expr) -> list[str] | None:
368
430
  return None
369
431
 
370
432
 
433
+ def _literal_string_args(args: list[ast.expr]) -> list[str] | None:
434
+ """Every argument as a non-empty literal string, or None."""
435
+ if not args or not all(
436
+ isinstance(a, ast.Constant) and isinstance(a.value, str) and a.value for a in args
437
+ ):
438
+ return None
439
+ return [a.value for a in args if isinstance(a, ast.Constant)]
440
+
441
+
442
+ def _unique_constraint(node: ast.expr) -> dict | None:
443
+ """One declared UNIQUE constraint or UNIQUE index of a table.
444
+
445
+ ``UniqueConstraint("a", "b")`` (name via the ``name=`` keyword) and
446
+ ``Index("ix", "a", "b", unique=True)`` (name = the first argument)
447
+ say the same thing about uniqueness. Literal columns only: a computed
448
+ expression or a non-literal ``unique`` flag yields None (the hole is
449
+ never filled with a guess).
450
+
451
+ Args:
452
+ node: An ``__table_args__`` tuple element.
453
+
454
+ Returns:
455
+ dict | None: ``{"name", "kind", "columns"}``, or None.
456
+ """
457
+ if not isinstance(node, ast.Call):
458
+ return None
459
+ called = call_name(node.func)
460
+ if called == "UniqueConstraint":
461
+ columns = _literal_string_args(node.args)
462
+ if columns is None:
463
+ return None
464
+ name = _literal_string_keyword(node, "name")
465
+ return {"name": name, "kind": "constraint", "columns": columns}
466
+ if called == "Index" and _literal_kwarg_true(node, "unique") is True:
467
+ columns = _literal_string_args(node.args)
468
+ if columns is None:
469
+ return None
470
+ # An Index's first argument is its name, not a column.
471
+ name = node.args[0].value
472
+ return {"name": name, "kind": "index", "columns": columns[1:]}
473
+ return None
474
+
475
+
476
+ def _literal_string_keyword(call: ast.Call, name: str) -> str | None:
477
+ """A literal string keyword value, or None (absent or computed)."""
478
+ for kw in call.keywords:
479
+ if kw.arg == name and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
480
+ return kw.value.value
481
+ return None
482
+
483
+
371
484
  class ClassRecord:
372
485
  """AST facts about one class definition, at any lexical scope."""
373
486
 
374
- def __init__(self, qname: str, node: ast.ClassDef, scope: str):
487
+ def __init__(
488
+ self,
489
+ qname: str,
490
+ node: ast.ClassDef,
491
+ scope: str,
492
+ imports: "dict[str, ImportRef] | None" = None,
493
+ ):
375
494
  self.qname = qname
376
495
  self.node = node
377
496
  self.scope = scope # "" at module level, enclosing dotted scope otherwise
497
+ # Import bindings of the OWNING file (complete before any class is
498
+ # recorded): the only provenance evidence for a SQLModel ``Field``
499
+ # column, whose spelling alone proves nothing (dataclasses and
500
+ # SQLAlchemy itself export one).
501
+ self.imports: dict[str, ImportRef] = imports if imports is not None else {}
378
502
  self.bases: list[str] = [b for b in (base_name(b) for b in node.bases) if b is not None]
379
503
  self.keywords = {kw.arg: kw.value for kw in node.keywords if kw.arg}
380
504
  self.tablename_literal: str | None = None
@@ -404,7 +528,11 @@ class ClassRecord:
404
528
  )
405
529
  names = [t.id for t in targets if isinstance(t, ast.Name)]
406
530
  value = stmt.value
407
- if value is not None and isinstance(value, ast.Call) and _column_call_name(value) is not None:
531
+ if (
532
+ value is not None
533
+ and isinstance(value, ast.Call)
534
+ and self._column_call_name(value) is not None
535
+ ):
408
536
  for name in names:
409
537
  column_calls.append((value, name))
410
538
  if TABULAR_ATTR in names and self.tablename_expr is None:
@@ -453,6 +581,64 @@ class ClassRecord:
453
581
  if constraint is not None:
454
582
  self.column_facts.primary_key_columns = constraint
455
583
  self.column_facts.has_pk_constraint = True
584
+ unique = _unique_constraint(element)
585
+ if unique is not None:
586
+ self.column_facts.add_unique(unique["name"], unique["kind"], unique["columns"])
587
+
588
+ def _column_call_name(self, call: ast.expr) -> str | None:
589
+ """Whether a call is a column constructor, honoring SQLModel Field().
590
+
591
+ ``Column``/``mapped_column`` are unqualified column constructors.
592
+ ``Field`` is not: ``dataclasses`` and SQLAlchemy export one too, so
593
+ it counts only when this file imports it from ``sqlmodel`` (the
594
+ SQLModel table style). Facts attach only to emitted tables, so the
595
+ gate never sees a column from a non-model class.
596
+
597
+ Args:
598
+ call: The candidate call expression.
599
+
600
+ Returns:
601
+ str | None: The simple constructor name, or None.
602
+ """
603
+ if not isinstance(call, ast.Call):
604
+ return None
605
+ name = call_name(call.func)
606
+ if name is None:
607
+ return None
608
+ if name in COLUMN_CALL_NAMES:
609
+ return name
610
+ if name == "Field":
611
+ ref = self.imports.get(name)
612
+ provenance = ref.module.split(".")[0] if ref is not None else None
613
+ return name if provenance in SQLMODEL_MODULES else None
614
+ return None
615
+
616
+ @property
617
+ def table_keyword_true(self) -> bool:
618
+ """Whether the class keyword ``table=True`` is literally present.
619
+
620
+ Only the literal True marks a SQLModel table; ``table=False`` (and
621
+ a computed value) marks a class that is NOT one, and guessing True
622
+ there would invent tables.
623
+ """
624
+ value = self.keywords.get("table")
625
+ return isinstance(value, ast.Constant) and value.value is True
626
+
627
+ def is_sqlmodel_table(self, idx: "FileIndex", sqlmodel_names: frozenset[str]) -> bool:
628
+ """Whether this class is a SQLModel table (``table=True`` on a SQLModel base).
629
+
630
+ Args:
631
+ idx: The owning file index (import provenance).
632
+ sqlmodel_names: Simple names of classes derived from SQLModel
633
+ across ALL scanned files (the SQLModel closure `scan`
634
+ computes before emission, e.g. a shared ``UserBase``).
635
+
636
+ Returns:
637
+ bool: True only for ``class X(<SQLModel base>, table=True)``.
638
+ """
639
+ if not self.table_keyword_true:
640
+ return False
641
+ return any(idx.base_is_sqlmodel(base, sqlmodel_names) for base in self.bases)
456
642
 
457
643
  # -- Classification ----------------------------------------------------
458
644
 
@@ -492,7 +678,7 @@ class ClassRecord:
492
678
  self.tablename_literal is not None
493
679
  or self.tablename_expr is not None
494
680
  or self.tablename_func is not None
495
- or "table" in self.keywords
681
+ or self.table_keyword_true
496
682
  )
497
683
  if has_facts:
498
684
  return True
@@ -523,16 +709,18 @@ def _literal_record(node: ast.expr) -> dict[str, str | int | float | bool] | Non
523
709
 
524
710
 
525
711
  def _string_sequence_literal(node: ast.expr) -> list[str] | None:
526
- """Reads a list/tuple literal of distinct non-empty string literals.
712
+ """Reads list/tuple literals of distinct non-empty strings.
713
+
714
+ Empty list/tuple literals are valid.
527
715
 
528
716
  Args:
529
717
  node: The AST expression (e.g. the value of
530
718
  ``__gateforge_updateable_fields__``).
531
719
 
532
720
  Returns:
533
- list[str] | None: the strings in written order, or None when the
534
- node is not a list/tuple of string literals (the classifier
535
- then simply sees no attribute — never a guessed one).
721
+ list[str] | None: string values in written order, including an
722
+ empty list for an empty literal, or None when the node is not
723
+ a list/tuple of string literals.
536
724
  """
537
725
  if not isinstance(node, (ast.List, ast.Tuple)):
538
726
  return None
@@ -541,7 +729,7 @@ def _string_sequence_literal(node: ast.expr) -> list[str] | None:
541
729
  if not (isinstance(elt, ast.Constant) and isinstance(elt.value, str) and elt.value):
542
730
  return None
543
731
  values.append(elt.value)
544
- return values or None
732
+ return values
545
733
 
546
734
 
547
735
  def _table_args_elements(node: ast.expr | None) -> list[ast.expr]:
@@ -763,6 +951,32 @@ class FileIndex:
763
951
  return True
764
952
  return name in model_names
765
953
 
954
+ def base_is_sqlmodel(self, name: str, sqlmodel_names: frozenset[str]) -> bool:
955
+ """Whether one base simple name makes its class a SQLModel class.
956
+
957
+ The same fail-closed shape as `base_is_declarative`: a denylisted
958
+ provenance or a locally defined namesake vetoes the SQLModel
959
+ reading; otherwise the name is a SQLModel root when it is imported
960
+ from ``sqlmodel`` (alias-aware — ``from sqlmodel import SQLModel as
961
+ Model``), is the exact conventional name ``SQLModel``, or belongs
962
+ to the cross-file SQLModel closure.
963
+
964
+ Args:
965
+ name: The base's simple name.
966
+ sqlmodel_names: Simple names of SQLModel-derived classes so far.
967
+
968
+ Returns:
969
+ bool: True only when the base derives from ``SQLModel``.
970
+ """
971
+ if self._import_denied(name) or name in self.locally_denied_base_names:
972
+ return False
973
+ ref = self.imports.get(name)
974
+ if ref is not None and ref.name == SQLMODEL_ROOT_NAME:
975
+ return ref.module.split(".")[0] in SQLMODEL_MODULES
976
+ if name == SQLMODEL_ROOT_NAME:
977
+ return True
978
+ return name in sqlmodel_names
979
+
766
980
  @staticmethod
767
981
  def _literal_name_arg(call: ast.Call) -> bool:
768
982
  return bool(call.args) and isinstance(call.args[0], ast.Constant) and isinstance(
@@ -776,7 +990,9 @@ class FileIndex:
776
990
  visit(child, stack + [child.name])
777
991
  elif isinstance(child, ast.ClassDef):
778
992
  qname = ".".join(stack + [child.name])
779
- self.classes.append(ClassRecord(qname, child, ".".join(stack)))
993
+ self.classes.append(
994
+ ClassRecord(qname, child, ".".join(stack), self.imports)
995
+ )
780
996
  visit(child, stack + [child.name])
781
997
  else:
782
998
  visit(child, stack)
@@ -817,7 +1033,9 @@ def loc(relpath: str, node: ast.AST) -> dict:
817
1033
  return {"file": relpath, "line": node.lineno, "col": node.col_offset}
818
1034
 
819
1035
 
820
- def _symbol_resource(relpath: str, rec: ClassRecord, name_unresolved: bool) -> dict:
1036
+ def _symbol_resource(
1037
+ relpath: str, rec: ClassRecord, name_unresolved: bool, table_name: str | None = None
1038
+ ) -> dict:
821
1039
  """The graph class-symbol resource for one declarative class.
822
1040
 
823
1041
  Args:
@@ -826,6 +1044,8 @@ def _symbol_resource(relpath: str, rec: ClassRecord, name_unresolved: bool) -> d
826
1044
  name_unresolved: Detector assertion that this class's tablename is
827
1045
  unresolved (true for table candidates the detector cannot name;
828
1046
  false for pure bases and literal-named classes).
1047
+ table_name: The resolved table name when the detector has one
1048
+ (a declared literal, or the name SQLModel derives at runtime).
829
1049
 
830
1050
  Returns:
831
1051
  dict: A ``gateforge.class`` resource consumed by the symbol table.
@@ -838,8 +1058,10 @@ def _symbol_resource(relpath: str, rec: ClassRecord, name_unresolved: bool) -> d
838
1058
  }
839
1059
  if rec.bases:
840
1060
  attrs["baseNames"] = list(rec.bases)
841
- if rec.tablename_literal is not None:
842
- attrs["tableName"] = rec.tablename_literal
1061
+ if table_name is None:
1062
+ table_name = rec.tablename_literal
1063
+ if table_name is not None:
1064
+ attrs["tableName"] = table_name
843
1065
  return {
844
1066
  "schemaVersion": 1,
845
1067
  "id": f"sqlalchemy.class:{relpath}:{rec.qname}",
@@ -851,17 +1073,24 @@ def _symbol_resource(relpath: str, rec: ClassRecord, name_unresolved: bool) -> d
851
1073
  }
852
1074
 
853
1075
 
854
- def _table_resource(relpath: str, rec: ClassRecord, provenance: str) -> dict:
855
- """The business table resource for a class with a literal tablename.
1076
+ def _table_resource(
1077
+ relpath: str, rec: ClassRecord, provenance: str, table_name: str | None = None
1078
+ ) -> dict:
1079
+ """The business table resource for a class with a resolved tablename.
856
1080
 
857
1081
  Args:
858
1082
  relpath: Repo-root-relative source path.
859
1083
  rec: The class record.
860
- provenance: Tablename provenance label (always ``literal`` here).
1084
+ provenance: Tablename provenance label: ``literal`` for a declared
1085
+ ``__tablename__``, ``sqlmodel-class-name`` for the name
1086
+ SQLModel derives from the class name.
1087
+ table_name: The resolved name (defaults to the declared literal).
861
1088
 
862
1089
  Returns:
863
1090
  dict: A ``sqlalchemy.table`` resource.
864
1091
  """
1092
+ if table_name is None:
1093
+ table_name = rec.tablename_literal
865
1094
  return {
866
1095
  "schemaVersion": 1,
867
1096
  "id": f"sqlalchemy.table:{relpath}:{rec.qname}",
@@ -870,14 +1099,14 @@ def _table_resource(relpath: str, rec: ClassRecord, provenance: str) -> dict:
870
1099
  "location": loc(relpath, rec.node),
871
1100
  "detectorVersion": VERSION,
872
1101
  "attributes": {
873
- "resourceName": rec.tablename_literal,
1102
+ "resourceName": table_name,
874
1103
  "classQname": rec.qname,
875
1104
  "scope": rec.scope or "module",
876
- "tableName": rec.tablename_literal,
1105
+ "tableName": table_name,
877
1106
  "tablenameProvenance": provenance,
878
1107
  "hasTableArgs": rec.has_table_args,
879
1108
  "tableArgsSchema": rec.table_args_schema,
880
- "tableKeywordTrue": "table" in rec.keywords,
1109
+ "tableKeywordTrue": rec.table_keyword_true,
881
1110
  "abstract": False,
882
1111
  "baseNames": list(rec.bases),
883
1112
  **_attribute_facts(rec.column_facts, rec),
@@ -1048,11 +1277,14 @@ def _attribute_facts(facts: ColumnFacts, rec: ClassRecord | None) -> dict:
1048
1277
  rec: The class record (None for Table() calls).
1049
1278
 
1050
1279
  Returns:
1051
- dict: Attribute entries (only when non-empty): ordered
1280
+ dict: Attribute entries (only when non-empty): `columnNames`
1281
+ (every literal column, written order), ordered
1052
1282
  `primaryKeyColumns`, `foreignKeyReferences` (sorted by
1053
1283
  column), `softDeleteCandidateFields`, and `readOnly`.
1054
1284
  """
1055
1285
  entries: dict = {}
1286
+ if facts.column_names:
1287
+ entries["columnNames"] = list(facts.column_names)
1056
1288
  if facts.has_pk_evidence:
1057
1289
  entries["primaryKeyColumns"] = list(facts.primary_key_columns)
1058
1290
  if facts.foreign_keys:
@@ -1062,9 +1294,14 @@ def _attribute_facts(facts: ColumnFacts, rec: ClassRecord | None) -> dict:
1062
1294
  ]
1063
1295
  if facts.soft_delete_candidates:
1064
1296
  entries["softDeleteCandidateFields"] = sorted(set(facts.soft_delete_candidates))
1297
+ if facts.unique_constraints:
1298
+ entries["uniqueConstraints"] = [
1299
+ {"name": u["name"], "kind": u["kind"], "columns": list(u["columns"])}
1300
+ for u in facts.unique_constraints
1301
+ ]
1065
1302
  if rec is not None and rec.read_only:
1066
1303
  entries["readOnly"] = True
1067
- if rec is not None and rec.updateable_fields_literal:
1304
+ if rec is not None and rec.updateable_fields_literal is not None:
1068
1305
  entries["updateableFields"] = list(rec.updateable_fields_literal)
1069
1306
  return entries
1070
1307
 
@@ -1605,26 +1842,68 @@ def scan(paths: list[str], root: Path | None = None) -> dict:
1605
1842
  model_names.add(simple)
1606
1843
  changed = True
1607
1844
 
1845
+ # Pass 0b: the SQLModel closure, to a fixpoint over ALL scanned
1846
+ # files. A class deriving from ``SQLModel`` (or from another
1847
+ # SQLModel-derived class in any file) enters it; the same
1848
+ # fail-closed provenance rules apply, so a Pydantic namesake never
1849
+ # does. Needed for the split-base style the FastAPI template ships:
1850
+ # ``class UserBase(SQLModel)`` + ``class User(UserBase, table=True)``.
1851
+ sqlmodel_names: set[str] = set()
1852
+ changed = True
1853
+ while changed:
1854
+ changed = False
1855
+ for idx in indexes.values():
1856
+ for rec in idx.classes:
1857
+ simple = rec.qname.rsplit(".", 1)[-1]
1858
+ if simple in sqlmodel_names:
1859
+ continue
1860
+ if any(idx.base_is_sqlmodel(base, sqlmodel_names) for base in rec.bases):
1861
+ sqlmodel_names.add(simple)
1862
+ changed = True
1863
+
1864
+ sqlmodel_closure = frozenset(sqlmodel_names)
1865
+
1608
1866
  # Pass 1: class symbols + business tables + typed unresolved + signals.
1609
1867
  for relpath in sorted(indexes):
1610
1868
  idx = indexes[relpath]
1611
1869
  for rec in idx.classes:
1612
- if rec.is_table_candidate(idx, model_names) or rec.is_pure_base(idx):
1613
- last_segment_unresolved = (
1614
- rec.tablename_literal is None and not rec.is_pure_base(idx)
1870
+ candidate = rec.is_table_candidate(idx, model_names)
1871
+ # SQLModel derives an undeclared table name at runtime by
1872
+ # lowercasing the class name — a name the AST can see, so it
1873
+ # is a fact, not a guess (any OTHER declared name source —
1874
+ # a literal, an expression, a method — stays unresolved).
1875
+ derived_name = (
1876
+ rec.qname.rsplit(".", 1)[-1].lower()
1877
+ if rec.is_sqlmodel_table(idx, sqlmodel_closure)
1878
+ and rec.tablename_literal is None
1879
+ and rec.tablename_expr is None
1880
+ and rec.tablename_func is None
1881
+ else None
1882
+ )
1883
+ table_name = rec.tablename_literal or derived_name
1884
+ if candidate or rec.is_pure_base(idx):
1885
+ resources.append(
1886
+ _symbol_resource(
1887
+ relpath,
1888
+ rec,
1889
+ table_name is None and not rec.is_pure_base(idx),
1890
+ table_name,
1891
+ )
1615
1892
  )
1616
- resources.append(_symbol_resource(relpath, rec, last_segment_unresolved))
1617
1893
  if rec.is_pure_base(idx):
1618
1894
  continue # bases never materialize; the symbol table owns them
1619
- if rec.tablename_literal is not None:
1620
- resources.append(_table_resource(relpath, rec, "literal"))
1621
- table_name = rec.tablename_literal
1895
+ if table_name is not None:
1896
+ provenance = (
1897
+ "literal" if rec.tablename_literal is not None
1898
+ else SQLMODEL_CLASS_NAME_PROVENANCE
1899
+ )
1900
+ resources.append(_table_resource(relpath, rec, provenance, table_name))
1622
1901
  identity = _identity_signal(rec, relpath, table_name, rec.node)
1623
1902
  if identity is not None:
1624
1903
  signals.append(identity)
1625
1904
  signals.extend(_declaration_signals(rec, relpath, table_name))
1626
1905
  unresolved.extend(_signal_unresolved_entries(rec, relpath, identity is not None))
1627
- elif rec.is_table_candidate(idx, model_names):
1906
+ elif candidate:
1628
1907
  unresolved.append(_unresolved_entry(relpath, rec))
1629
1908
 
1630
1909
  # Pass 2: direct Table("name", ...) declarations.