@kernlang/review-python 3.4.6-canary.44.1.a85ee2e8 → 3.4.6-canary.46.1.19dcfc19

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 (44) hide show
  1. package/dist/mapper/extractors/dependency.d.ts +3 -0
  2. package/dist/mapper/extractors/dependency.js +52 -0
  3. package/dist/mapper/extractors/effect.d.ts +3 -0
  4. package/dist/mapper/extractors/effect.js +74 -0
  5. package/dist/mapper/extractors/entrypoint.d.ts +3 -0
  6. package/dist/mapper/extractors/entrypoint.js +225 -0
  7. package/dist/mapper/extractors/error.d.ts +5 -0
  8. package/dist/mapper/extractors/error.js +129 -0
  9. package/dist/mapper/extractors/fastapi-pagination.d.ts +5 -0
  10. package/dist/mapper/extractors/fastapi-pagination.js +119 -0
  11. package/dist/mapper/extractors/fastapi-status.d.ts +6 -0
  12. package/dist/mapper/extractors/fastapi-status.js +115 -0
  13. package/dist/mapper/extractors/guard.d.ts +3 -0
  14. package/dist/mapper/extractors/guard.js +115 -0
  15. package/dist/mapper/extractors/pydantic.d.ts +13 -0
  16. package/dist/mapper/extractors/pydantic.js +61 -0
  17. package/dist/mapper/extractors/state-mutation.d.ts +3 -0
  18. package/dist/mapper/extractors/state-mutation.js +63 -0
  19. package/dist/mapper/helpers/ast.d.ts +9 -0
  20. package/dist/mapper/helpers/ast.js +62 -0
  21. package/dist/mapper/helpers/types.d.ts +7 -0
  22. package/dist/mapper/helpers/types.js +168 -0
  23. package/dist/mapper/index.d.ts +8 -0
  24. package/dist/mapper/index.js +42 -0
  25. package/dist/mapper/signatures.d.ts +17 -0
  26. package/dist/mapper/signatures.js +87 -0
  27. package/dist/mapper.d.ts +1 -8
  28. package/dist/mapper.js +1 -1286
  29. package/package.json +3 -3
  30. package/src/mapper/extractors/dependency.ts +60 -0
  31. package/src/mapper/extractors/effect.ts +84 -0
  32. package/src/mapper/extractors/entrypoint.ts +272 -0
  33. package/src/mapper/extractors/error.ts +152 -0
  34. package/src/mapper/extractors/fastapi-pagination.ts +117 -0
  35. package/src/mapper/extractors/fastapi-status.ts +119 -0
  36. package/src/mapper/extractors/guard.ts +114 -0
  37. package/src/mapper/extractors/pydantic.ts +74 -0
  38. package/src/mapper/extractors/state-mutation.ts +72 -0
  39. package/src/mapper/helpers/ast.ts +72 -0
  40. package/src/mapper/helpers/types.ts +164 -0
  41. package/src/mapper/index.ts +50 -0
  42. package/src/mapper/signatures.ts +94 -0
  43. package/src/mapper.ts +1 -1388
  44. package/tsconfig.tsbuildinfo +1 -1
package/dist/mapper.js CHANGED
@@ -1,1286 +1 @@
1
- /**
2
- * Python Concept Mapper — tree-sitter based.
3
- *
4
- * Maps Python syntax → universal KERN concepts.
5
- * Phase 1: error_raise, error_handle, effect
6
- */
7
- import { conceptId, conceptSpan } from '@kernlang/core';
8
- import Parser from 'tree-sitter';
9
- import Python from 'tree-sitter-python';
10
- const EXTRACTOR_VERSION = '1.0.0';
11
- // ── Network call patterns ────────────────────────────────────────────────
12
- const NETWORK_MODULES = new Set(['requests', 'httpx', 'aiohttp', 'urllib']);
13
- const NETWORK_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'request', 'fetch']);
14
- const DB_MODULES = new Set(['psycopg2', 'asyncpg', 'pymongo', 'sqlalchemy', 'django']);
15
- const DB_METHODS = new Set([
16
- 'execute',
17
- 'executemany',
18
- 'fetchone',
19
- 'fetchall',
20
- 'fetchmany',
21
- 'query',
22
- 'find',
23
- 'find_one',
24
- 'insert_one',
25
- 'insert_many',
26
- 'update_one',
27
- 'delete_one',
28
- ]);
29
- const _FS_FUNCTIONS = new Set(['open', 'read', 'write', 'readlines', 'writelines']);
30
- const PY_API_ERROR_STATUS_CODES = new Set([401, 403, 404, 422, 500]);
31
- const PY_API_SUCCESS_STATUS_CODES = new Set([200, 201, 202, 204, 206]);
32
- // FastAPI's documented default success status is 200, regardless of HTTP method
33
- // (Codex plan-review #1, FastAPI docs:
34
- // https://fastapi.tiangolo.com/tutorial/response-status-code/). 201 for POST is
35
- // a per-route opt-in via `status_code=201`, not a method-derived default.
36
- const FASTAPI_DEFAULT_SUCCESS_STATUS = 200;
37
- // Pagination anchor families — mirror the TS classification in
38
- // `packages/review/src/concept-rules/cross-stack-utils.ts`. The size keys
39
- // (`limit`, `take`, `page_size`, `per_page`) are intentionally NOT anchors
40
- // — they're compatible with either offset or cursor pagination.
41
- const PY_PAGE_ANCHORS = new Set(['page', 'page_number', 'pageNumber']);
42
- const PY_OFFSET_ANCHORS = new Set(['offset', 'skip']);
43
- const PY_CURSOR_ANCHORS = new Set(['cursor', 'after', 'before', 'next', 'previous']);
44
- const PY_PAGINATION_RE = /\b(limit|offset|skip|cursor|page|page_size|per_page)\b|\.limit\s*\(/i;
45
- const PY_DB_COLLECTION_RE = /\.(find|all|fetchall|to_list|scalars)\s*\(|\bselect\s*\(/i;
46
- const PY_DB_WRITE_RE = /\.(insert_one|insert_many|update_one|update_many|delete_one|delete_many|add|create|save|commit)\s*\(/i;
47
- const PY_IDEMPOTENCY_RE = /\b(idempotency(?:[_-]?key)?|Idempotency-Key|transaction|unique|upsert|get_or_create|on_conflict)\b/i;
48
- const STDLIB_MODULES = new Set([
49
- 'os',
50
- 'sys',
51
- 'json',
52
- 're',
53
- 'math',
54
- 'datetime',
55
- 'time',
56
- 'logging',
57
- 'argparse',
58
- 'collections',
59
- 'itertools',
60
- 'functools',
61
- 'pathlib',
62
- 'shutil',
63
- 'subprocess',
64
- 'threading',
65
- 'multiprocessing',
66
- 'abc',
67
- 'typing',
68
- 'io',
69
- 'pickle',
70
- 'random',
71
- 'hashlib',
72
- 'hmac',
73
- 'base64',
74
- 'csv',
75
- 'sqlite3',
76
- 'zlib',
77
- 'gzip',
78
- 'tarfile',
79
- 'zipfile',
80
- 'enum',
81
- 'struct',
82
- 'tempfile',
83
- 'unittest',
84
- 'urllib',
85
- 'uuid',
86
- 'xml',
87
- ]);
88
- // ── Parser setup ─────────────────────────────────────────────────────────
89
- let parser = null;
90
- function getParser() {
91
- if (!parser) {
92
- parser = new Parser();
93
- parser.setLanguage(Python);
94
- }
95
- return parser;
96
- }
97
- // ── Main Extractor ───────────────────────────────────────────────────────
98
- export function extractPythonConcepts(source, filePath) {
99
- const tree = getParser().parse(source);
100
- const nodes = [];
101
- const edges = [];
102
- extractErrorRaise(tree.rootNode, source, filePath, nodes);
103
- extractErrorHandle(tree.rootNode, source, filePath, nodes);
104
- extractEffects(tree.rootNode, source, filePath, nodes);
105
- extractEntrypoints(tree.rootNode, source, filePath, nodes);
106
- extractGuards(tree.rootNode, source, filePath, nodes);
107
- extractStateMutation(tree.rootNode, source, filePath, nodes);
108
- extractDependencyEdges(tree.rootNode, source, filePath, edges);
109
- return {
110
- filePath,
111
- language: 'py',
112
- nodes,
113
- edges,
114
- extractorVersion: EXTRACTOR_VERSION,
115
- };
116
- }
117
- // ── error_raise ──────────────────────────────────────────────────────────
118
- function extractErrorRaise(root, source, filePath, nodes) {
119
- // raise statements
120
- walkNodes(root, 'raise_statement', (node) => {
121
- const errorType = extractRaiseType(node);
122
- nodes.push({
123
- id: conceptId(filePath, 'error_raise', node.startIndex),
124
- kind: 'error_raise',
125
- primarySpan: nodeSpan(filePath, node),
126
- evidence: nodeText(source, node, 100),
127
- confidence: 1.0,
128
- language: 'py',
129
- containerId: getContainerId(node, filePath),
130
- payload: {
131
- kind: 'error_raise',
132
- subtype: 'throw', // Python raise ≡ throw
133
- errorType,
134
- },
135
- });
136
- });
137
- }
138
- // ── error_handle ─────────────────────────────────────────────────────────
139
- function extractErrorHandle(root, source, filePath, nodes) {
140
- // except clauses
141
- walkNodes(root, 'except_clause', (node) => {
142
- const block = node.children.find((c) => c.type === 'block');
143
- const disposition = classifyPythonDisposition(block, source);
144
- const errorVar = extractExceptVar(node);
145
- nodes.push({
146
- id: conceptId(filePath, 'error_handle', node.startIndex),
147
- kind: 'error_handle',
148
- primarySpan: nodeSpan(filePath, node),
149
- evidence: nodeText(source, node, 150),
150
- confidence: disposition.confidence,
151
- language: 'py',
152
- containerId: getContainerId(node, filePath),
153
- payload: {
154
- kind: 'error_handle',
155
- disposition: disposition.type,
156
- errorVariable: errorVar,
157
- },
158
- });
159
- });
160
- }
161
- function classifyPythonDisposition(block, source) {
162
- if (!block)
163
- return { type: 'ignored', confidence: 1.0 };
164
- const children = block.namedChildren;
165
- // except: pass → ignored
166
- if (children.length === 1 && children[0].type === 'pass_statement') {
167
- return { type: 'ignored', confidence: 1.0 };
168
- }
169
- // except: ... (ellipsis) → ignored
170
- if (children.length === 1 && children[0].type === 'expression_statement') {
171
- const text = source.substring(children[0].startIndex, children[0].endIndex).trim();
172
- if (text === '...')
173
- return { type: 'ignored', confidence: 1.0 };
174
- }
175
- // Empty block
176
- if (children.length === 0) {
177
- return { type: 'ignored', confidence: 1.0 };
178
- }
179
- const bodyText = source.substring(block.startIndex, block.endIndex);
180
- // raise → rethrown or wrapped
181
- if (bodyText.includes('raise')) {
182
- // bare `raise` → rethrown
183
- if (/\braise\s*$|\braise\s*\n/m.test(bodyText)) {
184
- return { type: 'rethrown', confidence: 0.95 };
185
- }
186
- return { type: 'wrapped', confidence: 0.9 };
187
- }
188
- // return → returned
189
- if (bodyText.includes('return')) {
190
- return { type: 'returned', confidence: 0.85 };
191
- }
192
- // logging
193
- if (/\b(logging|logger|log|print)\b/.test(bodyText)) {
194
- if (children.length === 1)
195
- return { type: 'logged', confidence: 0.9 };
196
- return { type: 'logged', confidence: 0.7 };
197
- }
198
- return { type: 'wrapped', confidence: 0.5 };
199
- }
200
- // ── effect ───────────────────────────────────────────────────────────────
201
- function extractEffects(root, source, filePath, nodes) {
202
- walkNodes(root, 'call', (node) => {
203
- const funcNode = node.childForFieldName('function');
204
- if (!funcNode)
205
- return;
206
- const funcText = source.substring(funcNode.startIndex, funcNode.endIndex);
207
- // Network: requests.get(), httpx.post(), etc.
208
- if (funcNode.type === 'attribute') {
209
- const obj = funcNode.childForFieldName('object');
210
- const attr = funcNode.childForFieldName('attribute');
211
- if (obj && attr) {
212
- const objName = source.substring(obj.startIndex, obj.endIndex);
213
- const methodName = source.substring(attr.startIndex, attr.endIndex);
214
- if (NETWORK_MODULES.has(objName) && NETWORK_METHODS.has(methodName)) {
215
- nodes.push({
216
- id: conceptId(filePath, 'effect', node.startIndex),
217
- kind: 'effect',
218
- primarySpan: nodeSpan(filePath, node),
219
- evidence: nodeText(source, node, 120),
220
- confidence: 0.95,
221
- language: 'py',
222
- containerId: getContainerId(node, filePath),
223
- payload: { kind: 'effect', subtype: 'network', async: isInAsyncDef(node) },
224
- });
225
- return;
226
- }
227
- // DB: cursor.execute(), db.query(), etc.
228
- if (DB_METHODS.has(methodName) &&
229
- (DB_MODULES.has(objName) || /cursor|conn|db|session|collection/i.test(objName))) {
230
- nodes.push({
231
- id: conceptId(filePath, 'effect', node.startIndex),
232
- kind: 'effect',
233
- primarySpan: nodeSpan(filePath, node),
234
- evidence: nodeText(source, node, 120),
235
- confidence: 0.85,
236
- language: 'py',
237
- containerId: getContainerId(node, filePath),
238
- payload: { kind: 'effect', subtype: 'db', async: isInAsyncDef(node) },
239
- });
240
- return;
241
- }
242
- }
243
- }
244
- // FS: open()
245
- if (funcText === 'open') {
246
- nodes.push({
247
- id: conceptId(filePath, 'effect', node.startIndex),
248
- kind: 'effect',
249
- primarySpan: nodeSpan(filePath, node),
250
- evidence: nodeText(source, node, 120),
251
- confidence: 0.9,
252
- language: 'py',
253
- containerId: getContainerId(node, filePath),
254
- payload: { kind: 'effect', subtype: 'fs', async: false },
255
- });
256
- }
257
- // fetch() in async context (aiohttp pattern)
258
- if (funcText === 'fetch' || funcText === 'aiohttp.request') {
259
- nodes.push({
260
- id: conceptId(filePath, 'effect', node.startIndex),
261
- kind: 'effect',
262
- primarySpan: nodeSpan(filePath, node),
263
- evidence: nodeText(source, node, 120),
264
- confidence: 0.8,
265
- language: 'py',
266
- containerId: getContainerId(node, filePath),
267
- payload: { kind: 'effect', subtype: 'network', async: true },
268
- });
269
- }
270
- });
271
- }
272
- // ── entrypoint ──────────────────────────────────────────────────────────
273
- function extractEntrypoints(root, source, filePath, nodes) {
274
- const pydanticModels = collectPydanticModels(source);
275
- // FastAPI / Flask route decorators.
276
- //
277
- // The route *path* (e.g. `/current`) is what cross-stack rules need to
278
- // match against — not the Python function name. Prior to 2026-04-21 this
279
- // emitted the function name, which `collectRoutes` then silently dropped
280
- // (it filters on paths starting with `/`). The FastAPI router-prefix join
281
- // in `cross-stack-utils.collectRoutes` also needs `routerName` so it can
282
- // pair per-file routes with the `include_router(prefix=…)` call that
283
- // mounts them.
284
- walkNodes(root, 'decorated_definition', (node) => {
285
- const fnDef = node.children.find((c) => c.type === 'function_definition');
286
- if (!fnDef)
287
- return;
288
- for (const child of node.children) {
289
- if (child.type !== 'decorator')
290
- continue;
291
- const decText = source.substring(child.startIndex, child.endIndex);
292
- const routeMatch = decText.match(/@(\w+)\.(route|get|post|put|delete|patch)\s*\(/);
293
- if (!routeMatch)
294
- continue;
295
- const routerName = routeMatch[1];
296
- const method = routeMatch[2].toUpperCase();
297
- const pathMatch = decText.match(/['"]([^'"]+)['"]/);
298
- const routePath = pathMatch?.[1];
299
- // Only surface the decorator as a route when we could extract a URL
300
- // path literal. Mystery decorators with only kwargs (e.g. `@app.get`
301
- // stub) are noise — skip them instead of filling `name` with the
302
- // function name, which cross-stack routes treat as invalid.
303
- if (!routePath?.startsWith('/'))
304
- continue;
305
- const responseModel = extractResponseModel(decText);
306
- const routeContainerId = getSelfContainerId(fnDef, filePath);
307
- const routeAnalysis = analyzePythonRoute(fnDef, source, method, routePath, responseModel, pydanticModels, decText);
308
- nodes.push({
309
- id: conceptId(filePath, 'entrypoint', child.startIndex),
310
- kind: 'entrypoint',
311
- primarySpan: nodeSpan(filePath, child),
312
- evidence: nodeText(source, child, 100),
313
- confidence: 1.0,
314
- language: 'py',
315
- containerId: routeContainerId,
316
- payload: {
317
- kind: 'entrypoint',
318
- subtype: 'route',
319
- name: routePath,
320
- httpMethod: method === 'ROUTE' ? undefined : method,
321
- responseModel,
322
- isAsync: isAsyncFunction(fnDef),
323
- routerName,
324
- errorStatusCodes: routeAnalysis.errorStatusCodes,
325
- successStatusCodes: routeAnalysis.successStatusCodes,
326
- successStatusCodesResolved: routeAnalysis.successStatusCodesResolved,
327
- paginationStrategy: routeAnalysis.paginationStrategy,
328
- paginationStrategyResolved: routeAnalysis.paginationStrategyResolved,
329
- hasUnboundedCollectionQuery: routeAnalysis.hasUnboundedCollectionQuery,
330
- hasDbWrite: routeAnalysis.hasDbWrite,
331
- hasIdempotencyProtection: routeAnalysis.hasIdempotencyProtection,
332
- hasBodyValidation: routeAnalysis.hasBodyValidation,
333
- validatedBodyFields: routeAnalysis.validatedBodyFields,
334
- bodyValidationResolved: routeAnalysis.bodyValidationResolved,
335
- validatedBodyFieldTypes: routeAnalysis.validatedBodyFieldTypes,
336
- },
337
- });
338
- }
339
- });
340
- // FastAPI `app.include_router(<module>.<router>, prefix="/api/x")`.
341
- //
342
- // Emitted as a route-mount concept so `collectRoutes` can join it with
343
- // the per-file route nodes: a route declared on `router` in
344
- // `app/api/nutrition_goals.py` and mounted in `main.py` with
345
- // `app.include_router(nutrition_goals.router, prefix="/api/nutrition-goals")`
346
- // should resolve to the full URL `/api/nutrition-goals/<path>`.
347
- walkNodes(root, 'call', (node) => {
348
- const fn = node.childForFieldName('function');
349
- if (!fn)
350
- return;
351
- const fnText = source.substring(fn.startIndex, fn.endIndex);
352
- if (!/\.include_router$/.test(fnText))
353
- return;
354
- const argsNode = node.childForFieldName('arguments');
355
- if (!argsNode)
356
- return;
357
- const argsText = source.substring(argsNode.startIndex, argsNode.endIndex);
358
- // First positional arg is the router. Common shapes:
359
- // include_router(router) — local identifier
360
- // include_router(nutrition_goals.router) — imported-module attribute
361
- // include_router(auth_router) — aliased local identifier
362
- const posMatch = argsText.match(/^\(\s*([A-Za-z_][\w.]*)/);
363
- if (!posMatch)
364
- return;
365
- const routerRef = posMatch[1];
366
- const dot = routerRef.lastIndexOf('.');
367
- const sourceModule = dot === -1 ? undefined : routerRef.slice(0, dot);
368
- const routerName = dot === -1 ? routerRef : routerRef.slice(dot + 1);
369
- const prefixMatch = argsText.match(/prefix\s*=\s*['"]([^'"]*)['"]/);
370
- // Prefix defaults to '' when omitted — still valid (the route keeps its
371
- // declared path as-is), so emit the mount either way.
372
- const prefix = prefixMatch?.[1] ?? '';
373
- nodes.push({
374
- id: conceptId(filePath, 'entrypoint', node.startIndex),
375
- kind: 'entrypoint',
376
- primarySpan: nodeSpan(filePath, node),
377
- evidence: nodeText(source, node, 120),
378
- confidence: 0.95,
379
- language: 'py',
380
- payload: {
381
- kind: 'entrypoint',
382
- subtype: 'route-mount',
383
- name: prefix,
384
- routerName,
385
- sourceModule,
386
- },
387
- });
388
- });
389
- // `if __name__ == '__main__':`
390
- walkNodes(root, 'if_statement', (node) => {
391
- const condition = node.childForFieldName('condition');
392
- if (condition?.text.includes('__name__') && condition.text.includes('__main__')) {
393
- nodes.push({
394
- id: conceptId(filePath, 'entrypoint', node.startIndex),
395
- kind: 'entrypoint',
396
- primarySpan: nodeSpan(filePath, node),
397
- evidence: nodeText(source, node, 100),
398
- confidence: 1.0,
399
- language: 'py',
400
- payload: {
401
- kind: 'entrypoint',
402
- subtype: 'main',
403
- name: 'main',
404
- },
405
- });
406
- }
407
- });
408
- }
409
- // ── guard ───────────────────────────────────────────────────────────────
410
- function extractGuards(root, source, filePath, nodes) {
411
- // 1. Auth decorators (tree-sitter: decorated_definition → decorator + function_definition)
412
- walkNodes(root, 'decorated_definition', (node) => {
413
- for (const child of node.children) {
414
- if (child.type !== 'decorator')
415
- continue;
416
- const decText = source.substring(child.startIndex, child.endIndex);
417
- if (/@(login_required|requires_auth|permission_required|auth_required|authenticated)/.test(decText)) {
418
- nodes.push({
419
- id: conceptId(filePath, 'guard', child.startIndex),
420
- kind: 'guard',
421
- primarySpan: nodeSpan(filePath, child),
422
- evidence: nodeText(source, child, 100),
423
- confidence: 1.0,
424
- language: 'py',
425
- containerId: getContainerId(node, filePath),
426
- payload: {
427
- kind: 'guard',
428
- subtype: 'auth',
429
- name: decText.replace('@', '').split('(')[0].trim(),
430
- },
431
- });
432
- }
433
- }
434
- });
435
- // 2. Pydantic validation: BaseModel.model_validate()
436
- walkNodes(root, 'call', (node) => {
437
- const func = node.childForFieldName('function');
438
- if (func?.text.includes('model_validate')) {
439
- nodes.push({
440
- id: conceptId(filePath, 'guard', node.startIndex),
441
- kind: 'guard',
442
- primarySpan: nodeSpan(filePath, node),
443
- evidence: nodeText(source, node, 100),
444
- confidence: 0.9,
445
- language: 'py',
446
- containerId: getContainerId(node, filePath),
447
- payload: { kind: 'guard', subtype: 'validation', name: 'pydantic' },
448
- });
449
- }
450
- });
451
- // 3. FastAPI `Depends(...)` injection — route handler parameter with a
452
- // `Depends` default is the idiomatic FastAPI auth/validation guard.
453
- // Example:
454
- // @router.get("/me")
455
- // def me(user: User = Depends(get_current_user)):
456
- // Classified by the dependency function name:
457
- // - `get_current_user` / `current_user` / `require_auth` / `*_user` → 'auth'
458
- // - `verify_*` / `validate_*` → 'validation'
459
- // - `rate_limit_*` / `check_rate_limit` → 'rate-limit'
460
- // - everything else → 'policy'
461
- // Feeds the `auth-drift` cross-stack rule.
462
- walkNodes(root, 'default_parameter', (node) => {
463
- const val = node.childForFieldName('value');
464
- if (!val || val.type !== 'call')
465
- return;
466
- const func = val.childForFieldName('function');
467
- if (!func || func.text !== 'Depends')
468
- return;
469
- const args = val.childForFieldName('arguments');
470
- if (!args)
471
- return;
472
- const posArg = args.namedChildren.find((c) => c.type === 'identifier' || c.type === 'attribute');
473
- const depName = posArg ? posArg.text : 'Depends';
474
- const subtype = classifyDependency(depName);
475
- nodes.push({
476
- id: conceptId(filePath, 'guard', node.startIndex),
477
- kind: 'guard',
478
- primarySpan: nodeSpan(filePath, node),
479
- evidence: nodeText(source, node, 120),
480
- confidence: 0.85,
481
- language: 'py',
482
- containerId: getContainerId(node, filePath),
483
- payload: { kind: 'guard', subtype, name: depName },
484
- });
485
- });
486
- // 4. Early return/raise after auth check: if not request.user: raise/return
487
- walkNodes(root, 'if_statement', (node) => {
488
- const cond = node.childForFieldName('condition');
489
- if (cond && /\b(user|auth|request\.user)\b/.test(cond.text)) {
490
- const block = node.namedChildren.find((c) => c.type === 'block');
491
- if (block) {
492
- const firstStmt = block.namedChildren[0];
493
- if (firstStmt && (firstStmt.type === 'return_statement' || firstStmt.type === 'raise_statement')) {
494
- nodes.push({
495
- id: conceptId(filePath, 'guard', node.startIndex),
496
- kind: 'guard',
497
- primarySpan: nodeSpan(filePath, node),
498
- evidence: nodeText(source, node, 100),
499
- confidence: 0.8,
500
- language: 'py',
501
- containerId: getContainerId(node, filePath),
502
- payload: { kind: 'guard', subtype: 'auth' },
503
- });
504
- }
505
- }
506
- }
507
- });
508
- }
509
- function classifyDependency(depName) {
510
- // Strip module prefix (`auth.get_current_user` → `get_current_user`) so the
511
- // heuristic looks at the final identifier where intent usually lives.
512
- const tail = depName.split('.').pop() ?? depName;
513
- if (/^(get_current_user|current_user|require_auth|authenticated|is_authenticated)$/i.test(tail))
514
- return 'auth';
515
- if (/_user$|^user$|auth/i.test(tail))
516
- return 'auth';
517
- if (/^(verify_|validate_)/i.test(tail))
518
- return 'validation';
519
- if (/rate_?limit/i.test(tail))
520
- return 'rate-limit';
521
- return 'policy';
522
- }
523
- function analyzePythonRoute(fnDef, source, method, routePath, responseModel, pydanticModels, decText) {
524
- const text = source.substring(fnDef.startIndex, fnDef.endIndex);
525
- const validation = extractFastApiBodyValidation(fnDef, source, pydanticModels);
526
- const success = extractFastApiSuccessStatusCodes(decText, fnDef, source);
527
- const pagination = extractFastApiPaginationStrategy(fnDef, source);
528
- return {
529
- errorStatusCodes: extractPythonHttpExceptionStatusCodes(text),
530
- successStatusCodes: success.codes,
531
- successStatusCodesResolved: success.resolved,
532
- paginationStrategy: pagination.strategy,
533
- paginationStrategyResolved: pagination.resolved,
534
- hasUnboundedCollectionQuery: hasUnboundedPythonCollectionQuery(text, method, routePath, responseModel),
535
- hasDbWrite: PY_DB_WRITE_RE.test(text),
536
- hasIdempotencyProtection: PY_IDEMPOTENCY_RE.test(text),
537
- hasBodyValidation: validation.has,
538
- validatedBodyFields: validation.fields,
539
- bodyValidationResolved: validation.resolved,
540
- validatedBodyFieldTypes: validation.types,
541
- };
542
- }
543
- // ── FastAPI success status codes ─────────────────────────────────────────
544
- // Phase 2 of cross-stack `status-code-drift`. Populates the
545
- // `successStatusCodes` / `successStatusCodesResolved` payload fields so the
546
- // rule can flag clients checking a 2xx the FastAPI server doesn't emit.
547
- //
548
- // Sources of evidence (per buddy plan-review consensus):
549
- // 1. Decorator `status_code=N` (literal) or `status_code=status.HTTP_NNN_*`.
550
- // 2. Body-side `Response(status_code=N)` / `JSONResponse(...)` returns.
551
- // 3. Body-side `<param>.status_code = N` mutations (FastAPI's documented
552
- // pattern for routes that take a `Response` parameter).
553
- // 4. When the decorator omits status_code AND the body has no explicit
554
- // Response / mutation, default to 200 — FastAPI's documented default
555
- // regardless of HTTP method. Codex caught Gemini's POST→201 premise as
556
- // wrong (FastAPI docs:
557
- // https://fastapi.tiangolo.com/tutorial/response-status-code/).
558
- //
559
- // Marked unresolved when:
560
- // - Decorator status_code is set to a non-literal/non-status-constant
561
- // expression (variable, function call).
562
- // - Any `Response(status_code=...)` / `<x>.status_code = ...` RHS is dynamic.
563
- function extractFastApiSuccessStatusCodes(decText, fnDef, source) {
564
- let sawDynamic = false;
565
- // 1. Decorator `status_code=N` — applies ONLY to plain `return data` paths.
566
- // For routes whose return paths all use explicit Response/JSONResponse,
567
- // the decorator code is dead (Codex impl-review #1).
568
- const decStatusMatch = decText.match(/\bstatus_code\s*=\s*([^,)]+)/);
569
- let decoratorCode;
570
- if (decStatusMatch) {
571
- const code = parseFastApiStatusValue(decStatusMatch[1].trim());
572
- if (code === undefined)
573
- sawDynamic = true;
574
- else if (PY_API_SUCCESS_STATUS_CODES.has(code))
575
- decoratorCode = code;
576
- }
577
- const body = fnDef.childForFieldName('body') ?? fnDef.namedChildren.find((c) => c.type === 'block');
578
- const bodyText = body ? source.substring(body.startIndex, body.endIndex) : '';
579
- // 2. Response(status_code=N) / JSONResponse(...) etc. — applies only to
580
- // that specific return path. Multiple Response codes contribute a
581
- // multi-2xx route.
582
- const responseCodes = new Set();
583
- const responseRe = /\b(?:Response|JSONResponse|HTMLResponse|PlainTextResponse|RedirectResponse|StreamingResponse|FileResponse|ORJSONResponse|UJSONResponse)\s*\([^)]*?\bstatus_code\s*=\s*([^,)\n]+)/g;
584
- for (const match of bodyText.matchAll(responseRe)) {
585
- const code = parseFastApiStatusValue(match[1].trim());
586
- if (code === undefined)
587
- sawDynamic = true;
588
- else if (PY_API_SUCCESS_STATUS_CODES.has(code))
589
- responseCodes.add(code);
590
- }
591
- // 3. `<paramName>.status_code = N` — mutation on the injected Response
592
- // parameter. The parameter name varies (`response`, `resp`, `r`, `out`,
593
- // custom names — Codex impl-review #2). Match any identifier prefix
594
- // rather than a name whitelist; the API_SUCCESS_STATUS_CODES filter
595
- // keeps the noise tax low.
596
- const mutationCodes = new Set();
597
- // `=(?!=)` distinguishes assignment from `==` comparison so
598
- // `if response.status_code == 200:` doesn't masquerade as a dynamic
599
- // mutation (forge round, Claude engine).
600
- const mutateRe = /\b[A-Za-z_]\w*\.status_code\s*=(?!=)\s*([^\n;]+)/g;
601
- for (const match of bodyText.matchAll(mutateRe)) {
602
- const code = parseFastApiStatusValue(match[1].trim());
603
- if (code === undefined)
604
- sawDynamic = true;
605
- else if (PY_API_SUCCESS_STATUS_CODES.has(code))
606
- mutationCodes.add(code);
607
- }
608
- if (sawDynamic)
609
- return { codes: undefined, resolved: false };
610
- // Plain return paths inherit the route's "primary" success code, computed
611
- // as: mutation > decorator > FastAPI default 200. When a mutation is
612
- // present we treat it as the plain-return code (the conditional-mutation
613
- // case is a documented v1 false-negative — would require control-flow
614
- // analysis to disambiguate).
615
- const plainReturnRe = /\breturn\b(?!\s+(?:Response|JSONResponse|HTMLResponse|PlainTextResponse|RedirectResponse|StreamingResponse|FileResponse|ORJSONResponse|UJSONResponse)\s*\()/;
616
- const hasPlainReturn = plainReturnRe.test(bodyText);
617
- const final = new Set();
618
- if (hasPlainReturn) {
619
- if (mutationCodes.size > 0) {
620
- for (const c of mutationCodes)
621
- final.add(c);
622
- }
623
- else if (decoratorCode !== undefined) {
624
- final.add(decoratorCode);
625
- }
626
- else {
627
- final.add(FASTAPI_DEFAULT_SUCCESS_STATUS);
628
- }
629
- }
630
- else if (decoratorCode !== undefined && responseCodes.size === 0 && mutationCodes.size === 0) {
631
- // Handler with no plain return, no Response, no mutation — likely an
632
- // implicit-None-return stub or all-raise. Decorator is the only signal.
633
- final.add(decoratorCode);
634
- }
635
- // Response and mutation codes ALWAYS contribute (they're explicit choices
636
- // for their respective return paths).
637
- for (const c of responseCodes)
638
- final.add(c);
639
- for (const c of mutationCodes)
640
- final.add(c);
641
- return {
642
- codes: Array.from(final).sort((a, b) => a - b),
643
- resolved: true,
644
- };
645
- }
646
- function parseFastApiStatusValue(val) {
647
- const trimmed = val.trim();
648
- // Literal 3-digit int.
649
- const litMatch = trimmed.match(/^(\d{3})$/);
650
- if (litMatch)
651
- return Number(litMatch[1]);
652
- // status.HTTP_NNN_NAME / starlette.status.HTTP_NNN_NAME / fastapi.status.HTTP_NNN_NAME.
653
- const httpMatch = trimmed.match(/HTTP_(\d{3})_/);
654
- if (httpMatch)
655
- return Number(httpMatch[1]);
656
- return undefined;
657
- }
658
- // ── FastAPI pagination strategy ──────────────────────────────────────────
659
- // Iterates the route handler's parameters and classifies each by name (or
660
- // `Query(alias=...)` literal alias when present) against page/offset/cursor
661
- // anchor sets. Returns:
662
- // - `none` / resolved=true — handler reads no anchor params (and no opaque
663
- // paths to query data).
664
- // - `page` / `offset` / `cursor` / resolved=true — handler reads exactly
665
- // one family.
666
- // - `mixed` / resolved=true — handler reads multiple families.
667
- // - `undefined` / resolved=false — handler has a `Request` parameter,
668
- // `**kwargs`, or a `Query(alias=<dynamic>)` we can't statically resolve.
669
- function extractFastApiPaginationStrategy(fnDef, source) {
670
- const paramsNode = fnDef.childForFieldName('parameters');
671
- if (!paramsNode)
672
- return { strategy: 'none', resolved: true };
673
- const families = new Set();
674
- let sawOpaque = false;
675
- for (const child of paramsNode.namedChildren) {
676
- // **kwargs — handler may read any query key dynamically; opaque.
677
- if (child.type === 'dictionary_splat_pattern') {
678
- sawOpaque = true;
679
- continue;
680
- }
681
- // *args — positional spread, irrelevant for query keys but rare in
682
- // FastAPI handlers; keep silent.
683
- if (child.type === 'list_splat_pattern')
684
- continue;
685
- // Drop typing wrappers to find the param identifier.
686
- const paramName = extractParamName(child);
687
- if (!paramName)
688
- continue;
689
- // `request: Request` — handler may call `request.query_params.get(...)`
690
- // arbitrarily; mark opaque.
691
- const typeText = extractParamTypeText(child, source);
692
- if (typeText && /\bRequest\b/.test(typeText)) {
693
- sawOpaque = true;
694
- continue;
695
- }
696
- // Default-value AND type expression both can carry a `Query(alias="...")`
697
- // call. Modern FastAPI (≥0.95) puts the call inside the type annotation
698
- // via `Annotated[int, Query(alias="page")]` (Gemini/OpenCode impl-review).
699
- // Older / classic syntax puts it in the default: `Query(0, alias="page")`.
700
- // Check both — default-value form takes precedence when both are present.
701
- const defaultText = extractParamDefaultText(child, source);
702
- const aliasFromDefault = extractQueryAlias(defaultText);
703
- const aliasFromType = aliasFromDefault.alias === undefined ? extractQueryAlias(typeText) : aliasFromDefault;
704
- let key = paramName;
705
- if (aliasFromDefault.opaque || aliasFromType.opaque) {
706
- sawOpaque = true;
707
- continue;
708
- }
709
- if (aliasFromDefault.alias)
710
- key = aliasFromDefault.alias;
711
- else if (aliasFromType.alias)
712
- key = aliasFromType.alias;
713
- const family = classifyPyAnchor(key);
714
- if (family)
715
- families.add(family);
716
- }
717
- if (sawOpaque)
718
- return { strategy: undefined, resolved: false };
719
- if (families.size === 0)
720
- return { strategy: 'none', resolved: true };
721
- if (families.size === 1)
722
- return { strategy: [...families][0], resolved: true };
723
- return { strategy: 'mixed', resolved: true };
724
- }
725
- function extractParamName(node) {
726
- if (node.type === 'identifier')
727
- return node.text;
728
- if (node.type === 'typed_parameter' || node.type === 'typed_default_parameter' || node.type === 'default_parameter') {
729
- const nameChild = node.childForFieldName('name') ?? node.namedChildren.find((c) => c.type === 'identifier');
730
- if (nameChild)
731
- return nameChild.text;
732
- }
733
- return undefined;
734
- }
735
- function extractParamTypeText(node, source) {
736
- if (node.type !== 'typed_parameter' && node.type !== 'typed_default_parameter')
737
- return undefined;
738
- const typeChild = node.childForFieldName('type');
739
- if (typeChild)
740
- return source.substring(typeChild.startIndex, typeChild.endIndex);
741
- return undefined;
742
- }
743
- function extractParamDefaultText(node, source) {
744
- if (node.type !== 'default_parameter' && node.type !== 'typed_default_parameter')
745
- return undefined;
746
- const valueChild = node.childForFieldName('value');
747
- if (valueChild)
748
- return source.substring(valueChild.startIndex, valueChild.endIndex);
749
- return undefined;
750
- }
751
- function classifyPyAnchor(key) {
752
- if (PY_PAGE_ANCHORS.has(key))
753
- return 'page';
754
- if (PY_OFFSET_ANCHORS.has(key))
755
- return 'offset';
756
- if (PY_CURSOR_ANCHORS.has(key))
757
- return 'cursor';
758
- return undefined;
759
- }
760
- /** Extract a `Query(..., alias="...")` literal alias from a parameter's
761
- * default-value or type-annotation text. Used to support both classic
762
- * (`x = Query(0, alias="p")`) and modern (`x: Annotated[int, Query(alias="p")]`)
763
- * FastAPI patterns. Returns `{alias?, opaque}` where `opaque=true` indicates
764
- * a `Query(alias=<non-literal>)` we cannot statically resolve. */
765
- function extractQueryAlias(text) {
766
- if (!text)
767
- return { opaque: false };
768
- if (!/\bQuery\s*\(/.test(text))
769
- return { opaque: false };
770
- const aliasMatch = text.match(/\balias\s*=\s*['"]([^'"]+)['"]/);
771
- if (aliasMatch)
772
- return { alias: aliasMatch[1], opaque: false };
773
- if (/\balias\s*=/.test(text))
774
- return { opaque: true };
775
- return { opaque: false };
776
- }
777
- function extractPythonHttpExceptionStatusCodes(text) {
778
- const codes = new Set();
779
- const keywordRe = /HTTPException\s*\([^)]*status_code\s*=\s*(\d{3})/g;
780
- for (const match of text.matchAll(keywordRe)) {
781
- const code = Number(match[1]);
782
- if (PY_API_ERROR_STATUS_CODES.has(code))
783
- codes.add(code);
784
- }
785
- const positionalRe = /HTTPException\s*\(\s*(\d{3})/g;
786
- for (const match of text.matchAll(positionalRe)) {
787
- const code = Number(match[1]);
788
- if (PY_API_ERROR_STATUS_CODES.has(code))
789
- codes.add(code);
790
- }
791
- return codes.size > 0 ? Array.from(codes).sort((a, b) => a - b) : undefined;
792
- }
793
- function hasUnboundedPythonCollectionQuery(text, method, routePath, responseModel) {
794
- if (method !== 'GET')
795
- return false;
796
- if (/[{:]/.test(routePath))
797
- return false;
798
- if (PY_PAGINATION_RE.test(text))
799
- return false;
800
- const responseLooksList = responseModel ? /^(list|List|Sequence|Iterable)\s*\[/.test(responseModel) : false;
801
- return (PY_DB_COLLECTION_RE.test(text) &&
802
- (responseLooksList || /\breturn\b[\s\S]*(\.all\s*\(|\.find\s*\(|\.fetchall\s*\()/.test(text)));
803
- }
804
- function collectPydanticModels(source) {
805
- const models = new Map();
806
- const classRe = /^class\s+([A-Za-z_]\w*)\s*\([^)]*BaseModel[^)]*\)\s*:/gm;
807
- for (const match of source.matchAll(classRe)) {
808
- const name = match[1];
809
- const start = (match.index ?? 0) + match[0].length;
810
- const rest = source.slice(start);
811
- const nextTopLevel = rest.search(/\n\S/);
812
- const body = nextTopLevel === -1 ? rest : rest.slice(0, nextTopLevel);
813
- const fields = [];
814
- const types = {};
815
- // Capture annotations alongside names. The annotation runs until either
816
- // an `=` (default value) or end-of-line / inline comment. Multiline
817
- // annotations (`x: Annotated[\n str, Field(...)\n]`) are not handled —
818
- // false-negative on the type tag, never false-positive.
819
- const fieldRe = /^[ \t]+([A-Za-z_]\w*)[ \t]*:[ \t]*([^=#\n]+?)(?:[ \t]*=[^\n]*|[ \t]*#[^\n]*)?$/gm;
820
- for (const fieldMatch of body.matchAll(fieldRe)) {
821
- const field = fieldMatch[1];
822
- if (field === 'model_config' || field === 'Config')
823
- continue;
824
- fields.push(field);
825
- const annotation = fieldMatch[2].trim();
826
- types[field] = coarsenPythonTypeAnnotation(annotation);
827
- }
828
- if (fields.length > 0) {
829
- models.set(name, { fields: fields.sort(), types: Object.freeze({ ...types }) });
830
- }
831
- }
832
- return models;
833
- }
834
- // Split a type-annotation string at top-level commas / pipes — respecting
835
- // nested `[...]` brackets — so `Union[A, B[C, D]]` splits into `[A, B[C, D]]`
836
- // not `[A, B[C, D]]`.
837
- function splitTopLevelTypeArgs(s, delim) {
838
- const parts = [];
839
- let depth = 0;
840
- let cur = '';
841
- for (let i = 0; i < s.length; i++) {
842
- const c = s[i];
843
- if (c === '[' || c === '(')
844
- depth++;
845
- else if (c === ']' || c === ')')
846
- depth--;
847
- else if (c === delim && depth === 0) {
848
- parts.push(cur.trim());
849
- cur = '';
850
- continue;
851
- }
852
- cur += c;
853
- }
854
- if (cur.trim())
855
- parts.push(cur.trim());
856
- return parts;
857
- }
858
- // Coarsen a Pydantic field type annotation to the same FieldTypeTag union
859
- // the TS mapper uses, so cross-stack rules can compare client TS types
860
- // against server Pydantic types symmetrically. Handles the common shapes:
861
- //
862
- // str / int / float / bool / None / Decimal / UUID / EmailStr
863
- // Optional[T] / Annotated[T, ...] → coarsen T (drop wrapper)
864
- // Union[A, B] / `A | B` (PEP 604) → only stable if all agree
865
- // List[T] / list[T] / Sequence[T] / Tuple[...] → 'array'
866
- // Dict[K, V] / dict[K, V] / Mapping[K, V] → 'object'
867
- // Literal['admin'] / Literal[1] / Literal[True] → primitive of literal
868
- // <CapitalIdent> → 'object' (BaseModel sub)
869
- //
870
- // Anything we don't recognise → 'unknown'. Conservative on purpose:
871
- // /type rules skip 'unknown' tags.
872
- function coarsenPythonTypeAnnotation(ann) {
873
- const t = ann.trim();
874
- if (t === '')
875
- return 'unknown';
876
- // Optional[T] / typing.Optional[T] — strip and recurse.
877
- const optMatch = t.match(/^(?:typing\.)?Optional\[([\s\S]+)\]$/);
878
- if (optMatch)
879
- return coarsenPythonTypeAnnotation(optMatch[1]);
880
- // Annotated[T, ...] — first arg is the underlying type.
881
- const annoMatch = t.match(/^(?:typing\.)?Annotated\[([\s\S]+)\]$/);
882
- if (annoMatch) {
883
- const parts = splitTopLevelTypeArgs(annoMatch[1], ',');
884
- if (parts.length >= 1)
885
- return coarsenPythonTypeAnnotation(parts[0]);
886
- return 'unknown';
887
- }
888
- // Union[A, B, ...] — only stable if every non-null branch agrees.
889
- // ANY 'unknown' branch poisons the result.
890
- const unionMatch = t.match(/^(?:typing\.)?Union\[([\s\S]+)\]$/);
891
- if (unionMatch) {
892
- return coarsenUnionParts(splitTopLevelTypeArgs(unionMatch[1], ','));
893
- }
894
- // PEP 604 `int | None | str`. Only treat `|` as a union separator when
895
- // it appears OUTSIDE of any `[...]` — otherwise `Dict[str, int | None]`
896
- // would be split incorrectly.
897
- if (containsTopLevelChar(t, '|')) {
898
- return coarsenUnionParts(splitTopLevelTypeArgs(t, '|'));
899
- }
900
- // Container types — coarsen to wire shape.
901
- if (/^(?:typing\.)?(?:List|list|Sequence|Iterable|Tuple|tuple|Set|set|FrozenSet|frozenset)\[/.test(t))
902
- return 'array';
903
- if (/^(?:typing\.)?(?:Dict|dict|Mapping|MutableMapping)\[/.test(t))
904
- return 'object';
905
- // Literal[X, Y, ...] — coarsen every literal arg, return the shared tag
906
- // ONLY when all literals agree. Mixed-primitive literals like
907
- // `Literal['a', 1]` accept either string or number on the wire, so
908
- // tagging it 'string' (first-only) would FP-flag a number client.
909
- // OpenCode caught this in the v1 review.
910
- const litMatch = t.match(/^(?:typing\.)?Literal\[([\s\S]+)\]$/);
911
- if (litMatch) {
912
- const parts = splitTopLevelTypeArgs(litMatch[1], ',');
913
- if (parts.length === 0)
914
- return 'unknown';
915
- const tags = parts.map((p) => coarsenLiteralValue(p.trim()));
916
- if (tags.includes('unknown'))
917
- return 'unknown';
918
- const set = new Set(tags);
919
- return set.size === 1 ? [...set][0] : 'unknown';
920
- }
921
- // Plain primitives + common Pydantic-string newtypes. `bytes` intentionally
922
- // stays 'unknown' — it's binary on the wire and not a JSON primitive.
923
- switch (t) {
924
- case 'str':
925
- case 'EmailStr':
926
- case 'HttpUrl':
927
- case 'AnyUrl':
928
- case 'AnyHttpUrl':
929
- case 'UUID':
930
- case 'UUID1':
931
- case 'UUID3':
932
- case 'UUID4':
933
- case 'UUID5':
934
- case 'SecretStr':
935
- return 'string';
936
- case 'int':
937
- case 'float':
938
- case 'Decimal':
939
- case 'PositiveInt':
940
- case 'NegativeInt':
941
- case 'NonNegativeInt':
942
- case 'NonPositiveInt':
943
- case 'PositiveFloat':
944
- case 'NegativeFloat':
945
- return 'number';
946
- case 'bool':
947
- case 'StrictBool':
948
- return 'boolean';
949
- case 'None':
950
- case 'NoneType':
951
- return 'null';
952
- }
953
- // Capitalized bare identifier could be:
954
- // - A nested BaseModel ('object' on the wire)
955
- // - A `class Status(str, Enum)` ('string' on the wire)
956
- // - A `Status = Literal['a','b']` type alias ('string' on the wire)
957
- // - A custom newtype like StrictStr / IPvAnyAddress
958
- // We can't disambiguate without symbol resolution. Tagging 'object'
959
- // FP'd Enum/Literal aliases against string clients (Codex flag); tag
960
- // 'unknown' instead — the rule will skip and we trade FN for FP.
961
- if (/^[A-Z][\w]*$/.test(t))
962
- return 'unknown';
963
- return 'unknown';
964
- }
965
- // Coarsen a single literal-value source token (e.g. `'admin'`, `42`, `True`)
966
- // to its primitive tag. Anything we don't recognise as one of the four JSON
967
- // primitives → 'unknown'.
968
- function coarsenLiteralValue(v) {
969
- if (/^['"]/.test(v))
970
- return 'string';
971
- if (/^-?\d/.test(v))
972
- return 'number';
973
- if (v === 'True' || v === 'False')
974
- return 'boolean';
975
- if (v === 'None')
976
- return 'null';
977
- return 'unknown';
978
- }
979
- function coarsenUnionParts(parts) {
980
- const tags = parts.map(coarsenPythonTypeAnnotation);
981
- if (tags.includes('unknown'))
982
- return 'unknown';
983
- const noNull = tags.filter((tag) => tag !== 'null');
984
- if (noNull.length === 0)
985
- return 'null';
986
- const set = new Set(noNull);
987
- return set.size === 1 ? [...set][0] : 'unknown';
988
- }
989
- function containsTopLevelChar(s, ch) {
990
- let depth = 0;
991
- for (let i = 0; i < s.length; i++) {
992
- const c = s[i];
993
- if (c === '[' || c === '(')
994
- depth++;
995
- else if (c === ']' || c === ')')
996
- depth--;
997
- else if (c === ch && depth === 0)
998
- return true;
999
- }
1000
- return false;
1001
- }
1002
- function extractFastApiBodyValidation(fnDef, source, pydanticModels) {
1003
- const body = fnDef.childForFieldName('body') ?? fnDef.namedChildren.find((child) => child.type === 'block');
1004
- const headerEnd = body ? body.startIndex : fnDef.endIndex;
1005
- const header = source.substring(fnDef.startIndex, headerEnd);
1006
- const fields = new Set();
1007
- const types = {};
1008
- let has = false;
1009
- const annotationRe = /([A-Za-z_]\w*)\s*:\s*([A-Za-z_]\w*)/g;
1010
- for (const match of header.matchAll(annotationRe)) {
1011
- const model = pydanticModels.get(match[2]);
1012
- if (!model)
1013
- continue;
1014
- has = true;
1015
- for (const field of model.fields)
1016
- fields.add(field);
1017
- for (const [name, tag] of Object.entries(model.types)) {
1018
- // Only record concrete tags. 'unknown' for a key would shadow a
1019
- // concrete tag from another model parameter on the same handler
1020
- // (rare, but multi-arg handlers do exist), so skip them.
1021
- if (tag !== 'unknown')
1022
- types[name] = tag;
1023
- }
1024
- }
1025
- return {
1026
- has,
1027
- fields: fields.size > 0 ? Array.from(fields).sort() : undefined,
1028
- resolved: fields.size > 0,
1029
- types: Object.keys(types).length > 0 ? Object.freeze({ ...types }) : undefined,
1030
- };
1031
- }
1032
- // ── state_mutation ───────────────────────────────────────────────────────
1033
- function extractStateMutation(root, source, filePath, nodes) {
1034
- // Track global keyword usage
1035
- const globalVarsInFile = new Set();
1036
- walkNodes(root, 'global_statement', (node) => {
1037
- for (const child of node.namedChildren) {
1038
- if (child.type === 'identifier')
1039
- globalVarsInFile.add(child.text);
1040
- }
1041
- });
1042
- walkNodes(root, 'assignment', (node) => {
1043
- const left = node.childForFieldName('left');
1044
- if (!left)
1045
- return;
1046
- // self.x = ... → scope 'module' (as requested)
1047
- if (left.type === 'attribute') {
1048
- const obj = left.childForFieldName('object');
1049
- if (obj && obj.text === 'self') {
1050
- nodes.push({
1051
- id: conceptId(filePath, 'state_mutation', node.startIndex),
1052
- kind: 'state_mutation',
1053
- primarySpan: nodeSpan(filePath, node),
1054
- evidence: nodeText(source, node, 100),
1055
- confidence: 0.9,
1056
- language: 'py',
1057
- containerId: getContainerId(node, filePath),
1058
- payload: { kind: 'state_mutation', target: left.text, scope: 'module' },
1059
- });
1060
- return;
1061
- }
1062
- }
1063
- // Global or Module level assignment
1064
- if (left.type === 'identifier') {
1065
- const name = left.text;
1066
- const containerId = getContainerId(node, filePath);
1067
- if (globalVarsInFile.has(name)) {
1068
- nodes.push({
1069
- id: conceptId(filePath, 'state_mutation', node.startIndex),
1070
- kind: 'state_mutation',
1071
- primarySpan: nodeSpan(filePath, node),
1072
- evidence: nodeText(source, node, 100),
1073
- confidence: 1.0,
1074
- language: 'py',
1075
- containerId,
1076
- payload: { kind: 'state_mutation', target: name, scope: 'global' },
1077
- });
1078
- }
1079
- else if (!containerId) {
1080
- // Module level (top level)
1081
- nodes.push({
1082
- id: conceptId(filePath, 'state_mutation', node.startIndex),
1083
- kind: 'state_mutation',
1084
- primarySpan: nodeSpan(filePath, node),
1085
- evidence: nodeText(source, node, 100),
1086
- confidence: 0.8,
1087
- language: 'py',
1088
- payload: { kind: 'state_mutation', target: name, scope: 'module' },
1089
- });
1090
- }
1091
- }
1092
- });
1093
- }
1094
- // ── dependency ──────────────────────────────────────────────────────────
1095
- function extractDependencyEdges(root, source, filePath, edges) {
1096
- const addDependency = (node, specifier) => {
1097
- let subtype = 'external';
1098
- if (specifier.startsWith('.')) {
1099
- subtype = 'internal';
1100
- }
1101
- else {
1102
- const rootModule = specifier.split('.')[0];
1103
- if (STDLIB_MODULES.has(rootModule)) {
1104
- subtype = 'stdlib';
1105
- }
1106
- }
1107
- edges.push({
1108
- id: `${filePath}#dep@${node.startIndex}`,
1109
- kind: 'dependency',
1110
- sourceId: filePath,
1111
- targetId: specifier,
1112
- primarySpan: nodeSpan(filePath, node),
1113
- evidence: nodeText(source, node, 100),
1114
- confidence: 1.0,
1115
- language: 'py',
1116
- payload: { kind: 'dependency', subtype, specifier },
1117
- });
1118
- };
1119
- walkNodes(root, 'import_statement', (node) => {
1120
- // import x, y as z
1121
- for (const child of node.namedChildren) {
1122
- if (child.type === 'dotted_name') {
1123
- addDependency(node, child.text);
1124
- }
1125
- else if (child.type === 'aliased_import') {
1126
- const name = child.childForFieldName('name');
1127
- if (name)
1128
- addDependency(node, name.text);
1129
- }
1130
- }
1131
- });
1132
- walkNodes(root, 'import_from_statement', (node) => {
1133
- // from x import y
1134
- const moduleNode = node.childForFieldName('module_name');
1135
- const relativeMatch = node.text.match(/^from\s+(\.+)/);
1136
- let specifier = moduleNode ? moduleNode.text : '';
1137
- if (relativeMatch) {
1138
- specifier = relativeMatch[1] + specifier;
1139
- }
1140
- if (specifier) {
1141
- addDependency(node, specifier);
1142
- }
1143
- });
1144
- }
1145
- // ── Tree-sitter Helpers ──────────────────────────────────────────────────
1146
- function walkNodes(root, type, callback) {
1147
- const cursor = root.walk();
1148
- let reachedRoot = false;
1149
- while (true) {
1150
- if (cursor.nodeType === type) {
1151
- callback(cursor.currentNode);
1152
- }
1153
- if (cursor.gotoFirstChild())
1154
- continue;
1155
- if (cursor.gotoNextSibling())
1156
- continue;
1157
- while (true) {
1158
- if (!cursor.gotoParent()) {
1159
- reachedRoot = true;
1160
- break;
1161
- }
1162
- if (cursor.gotoNextSibling())
1163
- break;
1164
- }
1165
- if (reachedRoot)
1166
- break;
1167
- }
1168
- }
1169
- function nodeSpan(filePath, node) {
1170
- return conceptSpan(filePath, node.startPosition.row + 1, node.startPosition.column + 1, node.endPosition.row + 1, node.endPosition.column + 1);
1171
- }
1172
- function nodeText(source, node, maxLen) {
1173
- return source.substring(node.startIndex, Math.min(node.endIndex, node.startIndex + maxLen));
1174
- }
1175
- function getContainerId(node, filePath) {
1176
- let parent = node.parent;
1177
- while (parent) {
1178
- if (parent.type === 'function_definition' || parent.type === 'class_definition') {
1179
- const nameNode = parent.childForFieldName('name');
1180
- const name = nameNode ? nameNode.text : 'anonymous';
1181
- return `${filePath}#fn:${name}@${parent.startIndex}`;
1182
- }
1183
- parent = parent.parent;
1184
- }
1185
- return undefined;
1186
- }
1187
- function getSelfContainerId(node, filePath) {
1188
- if (node.type !== 'function_definition' && node.type !== 'class_definition')
1189
- return undefined;
1190
- const nameNode = node.childForFieldName('name');
1191
- const name = nameNode ? nameNode.text : 'anonymous';
1192
- return `${filePath}#fn:${name}@${node.startIndex}`;
1193
- }
1194
- function extractResponseModel(decoratorText) {
1195
- const match = decoratorText.match(/\bresponse_model\s*=/);
1196
- if (!match || match.index === undefined)
1197
- return undefined;
1198
- let index = match.index + match[0].length;
1199
- while (/\s/.test(decoratorText[index] ?? ''))
1200
- index++;
1201
- const start = index;
1202
- let squareDepth = 0;
1203
- let parenDepth = 0;
1204
- let braceDepth = 0;
1205
- let quote;
1206
- while (index < decoratorText.length) {
1207
- const char = decoratorText[index];
1208
- const prev = decoratorText[index - 1];
1209
- if (quote) {
1210
- if (char === quote && prev !== '\\')
1211
- quote = undefined;
1212
- index++;
1213
- continue;
1214
- }
1215
- if (char === '"' || char === "'") {
1216
- quote = char;
1217
- index++;
1218
- continue;
1219
- }
1220
- if (char === '[')
1221
- squareDepth++;
1222
- else if (char === ']')
1223
- squareDepth = Math.max(0, squareDepth - 1);
1224
- else if (char === '(')
1225
- parenDepth++;
1226
- else if (char === ')') {
1227
- if (squareDepth === 0 && parenDepth === 0 && braceDepth === 0)
1228
- break;
1229
- parenDepth = Math.max(0, parenDepth - 1);
1230
- }
1231
- else if (char === '{')
1232
- braceDepth++;
1233
- else if (char === '}')
1234
- braceDepth = Math.max(0, braceDepth - 1);
1235
- else if (char === ',' && squareDepth === 0 && parenDepth === 0 && braceDepth === 0) {
1236
- break;
1237
- }
1238
- index++;
1239
- }
1240
- const model = decoratorText.slice(start, index).trim();
1241
- if (!model || model === 'None')
1242
- return undefined;
1243
- return model;
1244
- }
1245
- function extractRaiseType(node) {
1246
- // raise ValueError("...") → "ValueError"
1247
- const callNode = node.namedChildren.find((c) => c.type === 'call');
1248
- if (callNode) {
1249
- const func = callNode.childForFieldName('function');
1250
- if (func)
1251
- return func.text;
1252
- }
1253
- // raise ValueError → just identifier
1254
- const ident = node.namedChildren.find((c) => c.type === 'identifier');
1255
- if (ident)
1256
- return ident.text;
1257
- return undefined;
1258
- }
1259
- function extractExceptVar(node) {
1260
- // except Exception as e → "e"
1261
- for (const child of node.children) {
1262
- if (child.type === 'as_pattern') {
1263
- const alias = child.childForFieldName('alias');
1264
- if (alias)
1265
- return alias.text;
1266
- }
1267
- // Also try direct identifier after 'as'
1268
- if (child.type === 'identifier' && child.previousSibling?.text === 'as') {
1269
- return child.text;
1270
- }
1271
- }
1272
- return undefined;
1273
- }
1274
- function isInAsyncDef(node) {
1275
- let parent = node.parent;
1276
- while (parent) {
1277
- if (parent.type === 'function_definition') {
1278
- return isAsyncFunction(parent);
1279
- }
1280
- parent = parent.parent;
1281
- }
1282
- return false;
1283
- }
1284
- function isAsyncFunction(node) {
1285
- return node.children.some((c) => c.type === 'async');
1286
- }
1
+ export { extractPythonConcepts } from './mapper/index.js';