specfact-cli 0.55.4__py3-none-any.whl → 0.55.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
specfact_cli/__init__.py CHANGED
@@ -76,6 +76,6 @@ def _install_progressive_disclosure() -> None:
76
76
  # keeps missing-command and missing-parameter UX consistent outside the root CLI too.
77
77
  _install_progressive_disclosure()
78
78
 
79
- __version__ = "0.55.4"
79
+ __version__ = "0.55.5"
80
80
 
81
81
  __all__ = ["__version__"]
@@ -261,22 +261,13 @@ class OpenSpecParser:
261
261
  return sections
262
262
 
263
263
  def _flush_spec_section(
264
- self,
265
- section: str | None,
266
- current_text: list[str],
267
- current_items: list[str],
268
- overview: str,
269
- requirements: list[str],
270
- scenarios: list[str],
271
- ) -> tuple[str, list[str], list[str]]:
272
- """Commit accumulated content for the current spec section and return updated accumulators."""
264
+ self, sections: dict[str, Any], section: str | None, text: list[str], items: list[str]
265
+ ) -> None:
266
+ """Finish the current recognized spec section."""
273
267
  if section == "overview":
274
- overview = "\n".join(current_text).strip()
275
- elif section == "requirements":
276
- requirements = current_items
277
- elif section == "scenarios":
278
- scenarios = current_items
279
- return overview, requirements, scenarios
268
+ sections[section] = "\n".join(text).strip()
269
+ elif section in {"requirements", "scenarios"}:
270
+ sections[section] = items
280
271
 
281
272
  @beartype
282
273
  @require(lambda content: isinstance(content, str), "Content must be str")
@@ -291,39 +282,29 @@ class OpenSpecParser:
291
282
  Returns:
292
283
  Dictionary with "overview", "requirements" and "scenarios"
293
284
  """
294
- overview: str = ""
295
- requirements: list[str] = []
296
- scenarios: list[str] = []
297
-
285
+ sections: dict[str, Any] = {"overview": "", "requirements": [], "scenarios": []}
298
286
  current_section: str | None = None
299
287
  current_items: list[str] = []
300
288
  current_text: list[str] = []
301
-
302
289
  for line in content.splitlines():
303
290
  if line.startswith("##"):
304
- overview, requirements, scenarios = self._flush_spec_section(
305
- current_section, current_text, current_items, overview, requirements, scenarios
306
- )
291
+ self._flush_spec_section(sections, current_section, current_text, current_items)
307
292
  current_section = line.lstrip("#").strip().lower()
308
293
  current_items = []
309
294
  current_text = []
310
- elif line.strip().startswith("-") or line.strip().startswith("*"):
311
- item = line.strip().lstrip("-*").strip()
312
- if item:
313
- current_items.append(item)
314
- elif current_section:
315
- if current_section == "overview" or (current_section in ("requirements", "scenarios") and line.strip()):
316
- current_text.append(line)
317
-
318
- overview, requirements, scenarios = self._flush_spec_section(
319
- current_section, current_text, current_items, overview, requirements, scenarios
320
- )
321
-
322
- return {
323
- "overview": overview,
324
- "requirements": requirements,
325
- "scenarios": scenarios,
326
- }
295
+ continue
296
+ stripped = line.strip()
297
+ bullet = stripped.startswith(("-", "*"))
298
+ item = stripped.lstrip("-*").strip() if bullet else ""
299
+ if item:
300
+ current_items.append(item)
301
+ if not bullet and (
302
+ current_section == "overview" or (current_section in {"requirements", "scenarios"} and stripped)
303
+ ):
304
+ current_text.append(line)
305
+
306
+ self._flush_spec_section(sections, current_section, current_text, current_items)
307
+ return sections
327
308
 
328
309
  @beartype
329
310
  @require(lambda content: isinstance(content, str), "Content must be str")
@@ -346,30 +327,20 @@ class OpenSpecParser:
346
327
  "impact": "",
347
328
  }
348
329
 
349
- current_section: str | None = None
330
+ current_section = ""
350
331
  current_content: list[str] = []
351
-
352
332
  for line in content.splitlines():
353
- # Check for section headers
354
333
  if line.startswith("##"):
355
- # Save previous section
356
- if current_section:
357
- section_key = self._normalize_section_name(current_section)
358
- if section_key and section_key in sections:
359
- sections[section_key] = "\n".join(current_content).strip()
360
- # Start new section
361
- current_section = line.lstrip("#").strip()
334
+ if current_section in sections:
335
+ sections[current_section] = "\n".join(current_content).strip()
336
+ current_section = self._normalize_section_name(line.lstrip("#").strip())
362
337
  current_content = []
363
- else:
364
- if current_section:
365
- current_content.append(line)
366
-
367
- # Save last section
368
- if current_section:
369
- section_key = self._normalize_section_name(current_section)
370
- if section_key and section_key in sections:
371
- sections[section_key] = "\n".join(current_content).strip()
338
+ continue
339
+ if current_section:
340
+ current_content.append(line)
372
341
 
342
+ if current_section in sections:
343
+ sections[current_section] = "\n".join(current_content).strip()
373
344
  return sections
374
345
 
375
346
  @beartype
@@ -392,21 +363,19 @@ class OpenSpecParser:
392
363
  current_section: str | None = None
393
364
 
394
365
  for line in content.splitlines():
366
+ if current_section == "content":
367
+ delta_content.append(line)
368
+ continue
395
369
  if line.startswith("##"):
396
- if current_section == "content":
397
- delta_content.append(line)
398
- continue
399
370
  current_section = line.lstrip("#").strip().lower()
400
371
  continue
401
- if not current_section:
402
- continue
403
372
  stripped = line.strip()
404
- if current_section == "type" and stripped:
373
+ if not stripped:
374
+ continue
375
+ if current_section == "type":
405
376
  change_type = stripped.upper()
406
- elif current_section in ("feature id", "feature_id") and stripped:
377
+ elif current_section in {"feature id", "feature_id"}:
407
378
  feature_id = stripped
408
- elif current_section == "content":
409
- delta_content.append(line)
410
379
 
411
380
  return {
412
381
  "type": change_type,
@@ -0,0 +1,440 @@
1
+ """Analyze async Python source without importing or editing the target project."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import ast
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import sys
11
+ import tokenize
12
+ from collections.abc import Iterator, Sequence
13
+ from dataclasses import asdict, dataclass
14
+ from itertools import pairwise
15
+ from pathlib import Path
16
+
17
+
18
+ RULES = {
19
+ "asyncio-create-task-not-awaited": ("error", "Keep a reference to the scheduled task or await it."),
20
+ "blocking-sleep-in-async": ("error", "Replace the blocking wait with an awaited async equivalent."),
21
+ "missing-await-on-coroutine": ("error", "Await this coroutine or pass it to a task scheduler."),
22
+ "bare-except-in-async": ("warning", "Use specific exception types and handle the exception."),
23
+ "missing-timeout-on-wait": ("warning", "Set an explicit timeout on this asyncio wait."),
24
+ "blocking-file-io-in-async": ("warning", "Move blocking file I/O to a worker or use an async file API."),
25
+ "asyncio-gather-without-error-handling": ("warning", "Handle gather failures explicitly."),
26
+ "event-loop-in-async-context": ("error", "Await the coroutine directly in the running event loop."),
27
+ "missing-async-context-manager": ("info", "Consider binding the async context manager value."),
28
+ "sync-lock-in-async": ("error", "Use an async synchronization primitive."),
29
+ "sequential-await-could-be-parallel": ("info", "Only parallelize these awaits when operations are independent."),
30
+ "missing-cancellation-handling": ("info", "Review whether this coroutine needs cancellation cleanup."),
31
+ "task-result-not-checked": ("warning", "Await this task or inspect its result or exception."),
32
+ }
33
+ LEGACY_PACK_SHA256 = "a73e31b8fc7bfc200403037e8aad73c9cf2cadc89ddc662d97b7b1b2bd7fe64f"
34
+ PROJECT_EXCLUDES = frozenset({".git", ".hg", ".svn", ".venv", ".tox", ".nox", "__pycache__", "node_modules"})
35
+
36
+
37
+ @dataclass(frozen=True, order=True, slots=True)
38
+ class AsyncFinding:
39
+ """Stable diagnostic for a Python source location."""
40
+
41
+ file: str
42
+ line: int
43
+ column: int
44
+ rule_id: str
45
+ severity: str
46
+ message: str
47
+
48
+
49
+ def qualified_name(node: ast.AST, aliases: dict[str, str]) -> str:
50
+ """Resolve a syntactically qualified name through known imports."""
51
+ if isinstance(node, ast.Name):
52
+ return aliases.get(node.id, node.id)
53
+ if isinstance(node, ast.Attribute):
54
+ return f"{qualified_name(node.value, aliases)}.{node.attr}"
55
+ return ""
56
+
57
+
58
+ def import_aliases(nodes: Sequence[ast.AST]) -> dict[str, str]:
59
+ """Map aliases to imported Python names without loading modules."""
60
+ aliases: dict[str, str] = {}
61
+ for node in nodes:
62
+ if isinstance(node, ast.Import):
63
+ aliases.update({name.asname: name.name for name in node.names if name.asname})
64
+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
65
+ aliases.update({name.asname or name.name: f"{node.module}.{name.name}" for name in node.names})
66
+ return aliases
67
+
68
+
69
+ def _scoped_nodes(node: ast.AST) -> Iterator[ast.AST]:
70
+ def descend(parent: ast.AST) -> Iterator[ast.AST]:
71
+ for child in ast.iter_child_nodes(parent):
72
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
73
+ continue
74
+ yield child
75
+ yield from descend(child)
76
+
77
+ return descend(node)
78
+
79
+
80
+ def _is_true(node: ast.AST) -> bool:
81
+ return isinstance(node, ast.Constant) and node.value is True
82
+
83
+
84
+ def _has_explicit_timeout(call: ast.Call) -> bool:
85
+ timeout = call.args[1] if len(call.args) > 1 else None
86
+ timeout = next((keyword.value for keyword in call.keywords if keyword.arg == "timeout"), timeout)
87
+ return timeout is not None and not (isinstance(timeout, ast.Constant) and timeout.value is None)
88
+
89
+
90
+ def _runs_in_handler_scope(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> bool:
91
+ while (parent := parents.get(node)) is not None:
92
+ if isinstance(parent, (ast.Try, ast.TryStar)) and parent.handlers and node in parent.body:
93
+ return True
94
+ node = parent
95
+ return False
96
+
97
+
98
+ CALL_RULES = {
99
+ "time.sleep": "blocking-sleep-in-async",
100
+ "time.wait": "blocking-sleep-in-async",
101
+ "open": "blocking-file-io-in-async",
102
+ "builtins.open": "blocking-file-io-in-async",
103
+ "io.open": "blocking-file-io-in-async",
104
+ "asyncio.run": "event-loop-in-async-context",
105
+ "threading.Lock": "sync-lock-in-async",
106
+ "threading.RLock": "sync-lock-in-async",
107
+ "threading.Semaphore": "sync-lock-in-async",
108
+ }
109
+
110
+
111
+ def _nested_event_loop(call: ast.Call, aliases: dict[str, str]) -> bool:
112
+ target = call.func
113
+ return (
114
+ isinstance(target, ast.Attribute)
115
+ and target.attr == "run_until_complete"
116
+ and isinstance(target.value, ast.Call)
117
+ and qualified_name(target.value.func, aliases) == "asyncio.get_event_loop"
118
+ )
119
+
120
+
121
+ def _unprotected_gather(call: ast.Call, parents: dict[ast.AST, ast.AST]) -> bool:
122
+ accepts_exceptions = any(
123
+ keyword.arg == "return_exceptions" and _is_true(keyword.value) for keyword in call.keywords
124
+ )
125
+ return not accepts_exceptions and not _runs_in_handler_scope(call, parents)
126
+
127
+
128
+ def _awaited_call_rules(call: ast.Call, name: str, parents: dict[ast.AST, ast.AST]) -> Iterator[str]:
129
+ if name in {"asyncio.wait", "asyncio.wait_for"} and not _has_explicit_timeout(call):
130
+ yield "missing-timeout-on-wait"
131
+ if name == "asyncio.gather" and _unprotected_gather(call, parents):
132
+ yield "asyncio-gather-without-error-handling"
133
+
134
+
135
+ def _async_call_rules(
136
+ call: ast.Call,
137
+ parents: dict[ast.AST, ast.AST],
138
+ aliases: dict[str, str],
139
+ coroutines: set[str],
140
+ ) -> Iterator[str]:
141
+ name = qualified_name(call.func, aliases)
142
+ if rule := CALL_RULES.get(name):
143
+ yield rule
144
+ parent = parents.get(call)
145
+ if isinstance(parent, ast.Expr):
146
+ if name == "asyncio.create_task":
147
+ yield "asyncio-create-task-not-awaited"
148
+ if name in coroutines:
149
+ yield "missing-await-on-coroutine"
150
+ elif isinstance(parent, ast.Await):
151
+ yield from _awaited_call_rules(call, name, parents)
152
+ if _nested_event_loop(call, aliases):
153
+ yield "event-loop-in-async-context"
154
+
155
+
156
+ def _handler_names(node: ast.AST | None, aliases: dict[str, str]) -> set[str]:
157
+ if node is None:
158
+ return set()
159
+ children = node.elts if isinstance(node, ast.Tuple) else [node]
160
+ return {qualified_name(child, aliases) for child in children}
161
+
162
+
163
+ def _is_await_statement(statement: ast.AST) -> bool:
164
+ return isinstance(statement, ast.Expr) and isinstance(statement.value, ast.Await)
165
+
166
+
167
+ def _adjacent_awaits(node: ast.AST) -> Iterator[ast.stmt]:
168
+ for _, children in ast.iter_fields(node):
169
+ if not isinstance(children, list):
170
+ continue
171
+ statements = (item for item in children if isinstance(item, ast.stmt))
172
+ for first, second in pairwise(statements):
173
+ if _is_await_statement(first) and _is_await_statement(second):
174
+ yield first
175
+
176
+
177
+ def _task_names(node: ast.AST) -> list[str]:
178
+ if isinstance(node, ast.Assign):
179
+ return [target.id for target in node.targets if isinstance(target, ast.Name)]
180
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
181
+ return [node.target.id]
182
+ return []
183
+
184
+
185
+ def _task_result_references(node: ast.AST, aliases: dict[str, str]) -> Iterator[str]:
186
+ if isinstance(node, ast.Await) and isinstance(node.value, ast.Name):
187
+ yield node.value.id
188
+ if not isinstance(node, ast.Call):
189
+ return
190
+ if (
191
+ isinstance(node.func, ast.Attribute)
192
+ and node.func.attr in {"result", "exception"}
193
+ and isinstance(node.func.value, ast.Name)
194
+ ):
195
+ yield node.func.value.id
196
+ if qualified_name(node.func, aliases) in {"asyncio.wait_for", "asyncio.gather", "asyncio.shield"}:
197
+ yield from (arg.id for arg in node.args if isinstance(arg, ast.Name))
198
+
199
+
200
+ def _assigns_value(node: ast.AST) -> bool:
201
+ return isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value is not None
202
+
203
+
204
+ def _task_event_position(node: ast.AST) -> tuple[int, int]:
205
+ if isinstance(node, (ast.Assign, ast.AnnAssign)):
206
+ return (node.end_lineno or node.lineno, node.end_col_offset or node.col_offset)
207
+ if isinstance(node, (ast.Call, ast.Await)):
208
+ return (node.lineno, node.col_offset)
209
+ raise TypeError("Task events must be assignments, calls or awaits")
210
+
211
+
212
+ def _task_assignment(value: ast.AST | None, aliases: dict[str, str]) -> ast.Call | None:
213
+ if isinstance(value, ast.Call) and qualified_name(value.func, aliases) == "asyncio.create_task":
214
+ return value
215
+ return None
216
+
217
+
218
+ def _track_task_assignment(
219
+ node: ast.Assign | ast.AnnAssign, aliases: dict[str, str], active: dict[str, ast.Call]
220
+ ) -> ast.Call | None:
221
+ names = _task_names(node)
222
+ for name in names:
223
+ active.pop(name, None)
224
+ task = _task_assignment(node.value, aliases)
225
+ if names and task is not None:
226
+ active.update(dict.fromkeys(names, task))
227
+ return task
228
+ return None
229
+
230
+
231
+ def _unobserved_tasks(nodes: Sequence[ast.AST], aliases: dict[str, str]) -> Iterator[ast.Call]:
232
+ active: dict[str, ast.Call] = {}
233
+ assignments: list[ast.Call] = []
234
+ observed: set[ast.Call] = set()
235
+ events = (node for node in nodes if _assigns_value(node) or isinstance(node, (ast.Call, ast.Await)))
236
+ for node in sorted(events, key=_task_event_position):
237
+ if isinstance(node, (ast.Assign, ast.AnnAssign)):
238
+ if (task := _track_task_assignment(node, aliases, active)) is not None:
239
+ assignments.append(task)
240
+ else:
241
+ observed.update(active[name] for name in _task_result_references(node, aliases) if name in active)
242
+ yield from (call for call in assignments if call not in observed)
243
+
244
+
245
+ def _silent_handler(handler: ast.ExceptHandler, aliases: dict[str, str]) -> bool:
246
+ names = _handler_names(handler.type, aliases)
247
+ return handler.type is None or ("Exception" in names and all(isinstance(item, ast.Pass) for item in handler.body))
248
+
249
+
250
+ def _async_statement_rules(
251
+ node: ast.AST, aliases: dict[str, str]
252
+ ) -> Iterator[tuple[str, ast.stmt | ast.ExceptHandler]]:
253
+ if isinstance(node, ast.ExceptHandler) and _silent_handler(node, aliases):
254
+ yield "bare-except-in-async", node
255
+ if isinstance(node, ast.AsyncWith) and any(item.optional_vars is None for item in node.items):
256
+ yield "missing-async-context-manager", node
257
+ yield from (("sequential-await-could-be-parallel", item) for item in _adjacent_awaits(node))
258
+
259
+
260
+ def _has_cancellation_handler(nodes: Sequence[ast.AST], aliases: dict[str, str]) -> bool:
261
+ handlers = (node for node in nodes if isinstance(node, ast.ExceptHandler))
262
+ return any("asyncio.CancelledError" in _handler_names(node.type, aliases) for node in handlers)
263
+
264
+
265
+ def _scope_findings(
266
+ scope: ast.AsyncFunctionDef,
267
+ aliases: dict[str, str],
268
+ coroutines: set[str],
269
+ ) -> Iterator[tuple[str, ast.stmt | ast.expr | ast.ExceptHandler]]:
270
+ nodes: list[ast.AST] = [scope]
271
+ for statement in scope.body:
272
+ if not isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
273
+ nodes.extend((statement, *_scoped_nodes(statement)))
274
+ imports = {**aliases, **import_aliases(nodes)}
275
+ parents = {child: node for node in nodes for child in ast.iter_child_nodes(node)}
276
+ for node in nodes:
277
+ if isinstance(node, ast.Call):
278
+ yield from ((rule, node) for rule in _async_call_rules(node, parents, imports, coroutines))
279
+ yield from _async_statement_rules(node, imports)
280
+ yield from (("task-result-not-checked", call) for call in _unobserved_tasks(nodes, imports))
281
+ if not _has_cancellation_handler(nodes, imports):
282
+ yield "missing-cancellation-handling", scope
283
+
284
+
285
+ _LexicalScope = (
286
+ ast.Module
287
+ | ast.FunctionDef
288
+ | ast.AsyncFunctionDef
289
+ | ast.ClassDef
290
+ | ast.Lambda
291
+ | ast.ListComp
292
+ | ast.SetComp
293
+ | ast.DictComp
294
+ | ast.GeneratorExp
295
+ )
296
+
297
+
298
+ def _enclosing_scope(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> _LexicalScope | None:
299
+ while (parent := parents.get(node)) is not None:
300
+ if isinstance(parent, _LexicalScope):
301
+ return parent
302
+ node = parent
303
+ return None
304
+
305
+
306
+ def _scope_functions(tree: ast.Module, parents: dict[ast.AST, ast.AST]) -> dict[_LexicalScope, dict[str, bool]]:
307
+ definitions: dict[_LexicalScope, dict[str, bool]] = {}
308
+ bindings = (
309
+ node
310
+ for node in ast.walk(tree)
311
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
312
+ or (isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store))
313
+ )
314
+ for node in sorted(bindings, key=lambda item: (item.lineno, item.col_offset)):
315
+ owner = _enclosing_scope(node, parents)
316
+ if owner is not None:
317
+ name = node.id if isinstance(node, ast.Name) else node.name
318
+ definitions.setdefault(owner, {})[name] = isinstance(node, ast.AsyncFunctionDef)
319
+ return definitions
320
+
321
+
322
+ def _method_coroutines(
323
+ scope: ast.AsyncFunctionDef, owner: _LexicalScope | None, definitions: dict[_LexicalScope, dict[str, bool]]
324
+ ) -> set[str]:
325
+ arguments = scope.args.posonlyargs + scope.args.args
326
+ if not isinstance(owner, ast.ClassDef) or not arguments:
327
+ return set()
328
+ if any(qualified_name(node, {}).rsplit(".", 1)[-1] == "staticmethod" for node in scope.decorator_list):
329
+ return set()
330
+ receiver = arguments[0].arg
331
+ return {f"{receiver}.{name}" for name, is_async in definitions.get(owner, {}).items() if is_async}
332
+
333
+
334
+ def _visible_coroutines(
335
+ scope: ast.AsyncFunctionDef, parents: dict[ast.AST, ast.AST], definitions: dict[_LexicalScope, dict[str, bool]]
336
+ ) -> set[str]:
337
+ owner = _enclosing_scope(scope, parents)
338
+ visible = dict(definitions.get(scope, {}))
339
+ visible.update(
340
+ dict.fromkeys((arg.arg for arg in scope.args.posonlyargs + scope.args.args + scope.args.kwonlyargs), False)
341
+ )
342
+ result = _method_coroutines(scope, owner, definitions)
343
+ while owner is not None:
344
+ if not isinstance(owner, ast.ClassDef):
345
+ for name, is_async in definitions.get(owner, {}).items():
346
+ visible.setdefault(name, is_async)
347
+ owner = _enclosing_scope(owner, parents)
348
+ return result | {name for name, is_async in visible.items() if is_async}
349
+
350
+
351
+ def async_findings(tree: ast.Module, filename: str) -> list[AsyncFinding]:
352
+ """Check each async function and attribute findings to source positions."""
353
+ aliases = import_aliases(tree.body)
354
+ nodes = list(ast.walk(tree))
355
+ parents = {child: node for node in nodes for child in ast.iter_child_nodes(node)}
356
+ definitions = _scope_functions(tree, parents)
357
+ findings: set[AsyncFinding] = set()
358
+ for scope in (node for node in nodes if isinstance(node, ast.AsyncFunctionDef)):
359
+ coroutines = _visible_coroutines(scope, parents, definitions)
360
+ for rule, node in _scope_findings(scope, aliases, coroutines):
361
+ severity, message = RULES[rule]
362
+ findings.add(AsyncFinding(filename, node.lineno, node.col_offset + 1, rule, severity, message))
363
+ return sorted(findings)
364
+
365
+
366
+ def _source_paths(root: Path, paths: Sequence[str]) -> Iterator[Path]:
367
+ for argument in paths:
368
+ path = root / argument
369
+ if path.is_dir() and not path.is_symlink():
370
+ for directory, subdirectories, files in os.walk(path):
371
+ subdirectories[:] = sorted(name for name in subdirectories if name not in PROJECT_EXCLUDES)
372
+ yield from (Path(directory) / name for name in sorted(files) if name.endswith(".py"))
373
+ else:
374
+ yield path
375
+
376
+
377
+ def _scan(root: Path, paths: Sequence[str]) -> tuple[list[AsyncFinding], list[dict[str, str]], int]:
378
+ findings: list[AsyncFinding] = []
379
+ diagnostics: list[dict[str, str]] = []
380
+ scanned = 0
381
+ for path in sorted(set(_source_paths(root, paths))):
382
+ try:
383
+ relative = path.relative_to(root)
384
+ if not path.resolve().is_relative_to(root) or path.is_symlink() or path.suffix != ".py":
385
+ raise OSError("not an in-project Python source file")
386
+ with tokenize.open(path) as stream:
387
+ tree = ast.parse(stream.read(), filename=str(relative))
388
+ except (OSError, ValueError, SyntaxError, UnicodeError) as exc:
389
+ diagnostics.append({"file": os.path.relpath(path, root), "message": str(exc)})
390
+ else:
391
+ scanned += 1
392
+ findings.extend(async_findings(tree, str(relative)))
393
+ return findings, diagnostics, scanned
394
+
395
+
396
+ def _legacy_policy_diagnostic(root: Path, policy: Path) -> str | None:
397
+ try:
398
+ if not policy.resolve().is_relative_to(root):
399
+ raise OSError("async policy outside project")
400
+ digest = hashlib.sha256(policy.read_bytes()).hexdigest()
401
+ except OSError:
402
+ return "Could not read the legacy async policy."
403
+ if digest != LEGACY_PACK_SHA256:
404
+ return "Custom Semgrep async rules require migration. Run the built-in checks explicitly with 'hatch run scan'."
405
+ return None
406
+
407
+
408
+ def main() -> int:
409
+ """Run source-only async checks and emit a machine-readable result."""
410
+ parser = argparse.ArgumentParser(description=__doc__)
411
+ parser.add_argument("--root", type=Path, default=Path.cwd())
412
+ parser.add_argument("--legacy-config", type=Path)
413
+ parser.add_argument("--fix", action="store_true", help="Report migration guidance for retired source fixes")
414
+ parser.add_argument("paths", nargs="*", default=["."])
415
+ args = parser.parse_intermixed_args()
416
+ root = args.root.resolve()
417
+ findings, diagnostics, scanned = _scan(root, args.paths or ["."])
418
+ if args.legacy_config is not None:
419
+ message = _legacy_policy_diagnostic(root, root / args.legacy_config)
420
+ if message:
421
+ diagnostics.append({"file": str(args.legacy_config), "message": message})
422
+ if args.fix and any(finding.rule_id == "blocking-sleep-in-async" for finding in findings):
423
+ diagnostics.append({"file": "", "message": "Apply manual fixes using the reported async finding locations."})
424
+ json.dump(
425
+ {
426
+ "engine": "python-ast",
427
+ "rules_run": len(RULES),
428
+ "targets_scanned": scanned,
429
+ "total_findings": len(findings),
430
+ "findings": [asdict(finding) for finding in findings],
431
+ "diagnostics": diagnostics,
432
+ },
433
+ sys.stdout,
434
+ )
435
+ sys.stdout.write("\n")
436
+ return 2 if diagnostics else int(any(finding.severity == "error" for finding in findings))
437
+
438
+
439
+ if __name__ == "__main__":
440
+ raise SystemExit(main())