Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
5b90b4a
test: specify Flask route and app metadata
ffroliva Nov 21, 2026
23ae479
feat: add defensive Flask app introspector
ffroliva Nov 21, 2026
444bba7
test: cover Flask app loading and autodetection
ffroliva Nov 21, 2026
e490692
test: enforce Flask adapter import boundary
ffroliva Nov 21, 2026
34d5a6d
test: cover malformed Flask app reporting
ffroliva Nov 21, 2026
f96bf04
feat: enforce Flask adapter import boundary
ffroliva Nov 21, 2026
922b1c6
docs: record Flask route model limits
ffroliva Nov 21, 2026
29272cb
feat: select Flask introspector in pytest plugin
ffroliva Nov 21, 2026
5b04a58
Merge remote-tracking branch 'origin/test/0.8.0-f2' into feat/0.8.0-f1
ffroliva Nov 21, 2026
732eeca
Merge remote-tracking branch 'origin/release/0.8.0' into feat/0.8.0-f1
ffroliva Nov 21, 2026
3c9c212
test: cover static Flask introspection
ffroliva Nov 21, 2026
5953d24
fix: read Flask metadata without host code
ffroliva Nov 21, 2026
43141a6
test: cover unreadable Flask route maps
ffroliva Nov 21, 2026
43318fe
test: cover callable Flask views
ffroliva Nov 21, 2026
85946d9
fix: keep callable Flask views in route model
ffroliva Nov 21, 2026
f8a0128
fix: derive callable view names from their class
ffroliva Nov 21, 2026
bc9de64
fix: report unreadable Flask maps as unknown
ffroliva Nov 21, 2026
0138887
fix: reject Flask descriptors during introspection
ffroliva Nov 21, 2026
dda1d1f
Merge remote-tracking branch 'origin/release/0.8.0' into feat/0.8.0-f1
ffroliva Nov 21, 2026
0bf1688
refactor: drop a redundant group from the Flask parameter pattern
ffroliva Nov 21, 2026
d7d0f2a
Merge remote-tracking branch 'origin/release/0.8.0' into feat/0.8.0-f1
ffroliva Nov 21, 2026
f15d470
test: exercise Flask rule descriptors with Werkzeug Map
ffroliva Nov 21, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ src/sharpit/settings.py SharpitSettings, load_settings (SHARPIT_* env + k
src/sharpit/engine/ framework-free core: activation, guard, masking, panels, collectors, paging
src/sharpit/engine/sqla/ the SQLAlchemy gatekeeper: listeners, events, orm, inspect, readonly (sharpit's own reads)
src/sharpit/fastapi/ the FastAPI/Starlette adapter: routes, introspection, dev-server signals
src/sharpit/flask/ the Flask adapter: route introspection over the public URL map
src/sharpit/pytest_plugin/ the pytest adapter: optional plugin entry point and test-session hooks
src/sharpit/cli/ the command-line client adapter: talks to a running app over HTTP; standard library only
src/sharpit/ui/static/ the built UI (committed; CI checks it matches ui/ when ui/ exists)
Expand Down Expand Up @@ -107,7 +108,8 @@ these on every run (a planted violation proves each rule still bites); a failing
to loosen. Change a rule only in that test and here, in the same PR, with the reason in the PR body.

1. **Framework-free engine.** `engine/` never imports `fastapi` or `starlette` (a `TYPE_CHECKING` block is allowed).
2. **Dependencies point inward.** `engine/` never imports `sharpit.fastapi`, `sharpit.pytest_plugin` or `sharpit.ui`,
2. **Dependencies point inward.** `engine/` never imports `sharpit.fastapi`, `sharpit.flask`, `sharpit.pytest_plugin`
or `sharpit.ui`,
not even for a type. No module under `src/sharpit/` outside `sharpit/cli/` imports `sharpit.cli`; modules under
`sharpit/cli/` import only the standard-library modules named in `CLI_STDLIB` in
`tests/engine/test_import_boundary.py`, `sharpit.cli`, and `__version__` from `sharpit`, not even for a type. When
Expand All @@ -117,8 +119,9 @@ to loosen. Change a rule only in that test and here, in the same PR, with the re
3. **One module per collector.** A collector under `engine/collectors/` never imports another. Shared code moves to
the engine (`context`, `paging`, `spi`, `singleflight`, ...). Inside `engine/collectors/insights/` the rule holds per
kind: a module under `kinds/` never imports another kind; shared code goes in the insights package.
4. **Gatekeepers.** One named file (or package) per optional or network library: SQLAlchemy only in the
`engine/sqla/` package, `sqlite3` only in `engine/sources/sqlite.py`, `pydantic_settings` and `dotenv` only in
4. **Gatekeepers.** One named file (or package) per optional or network library: Flask only in `sharpit/flask/`,
SQLAlchemy only in the `engine/sqla/` package, `sqlite3` only in `engine/sources/sqlite.py`, `pydantic_settings`
and `dotenv` only in
`engine/collectors/config/settings_source.py`, OpenTelemetry only in `engine/otel.py`, `prometheus_client` only in
`engine/collectors/metrics/prometheus.py`, `urllib.request` only in `engine/collectors/vulns/osv.py`,
`engine/collectors/vulns/epss.py`, `engine/collectors/github/client.py` and `sharpit/cli/client.py`;
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
| [reference/BOOTUI-CONTRACT-MVP.md](reference/BOOTUI-CONTRACT-MVP.md) | The BootUI HTTP contract the MVP must match: DTOs, error strings, activation reasons |
| [reference/BOOTUI-2.5.0-DELTA.md](reference/BOOTUI-2.5.0-DELTA.md) | Static fixture changes from BootUI 2.4.0 to 2.5.0 |
| [reference/BOOTUI-PYTHON-MAPPING.md](reference/BOOTUI-PYTHON-MAPPING.md) | How BootUI's Spring concepts map to Python/FastAPI |
| [reference/FLASK-ROUTE-MODEL.md](reference/FLASK-ROUTE-MODEL.md) | Flask route introspection scope and route facts unavailable in `RouteInfo` |
| [superpowers/specs/2026-10-30-sharpit-mvp-design.md](superpowers/specs/2026-10-30-sharpit-mvp-design.md) | MVP design spec; §14 deviation log, §15 coordinator's calls for the owner |
| [superpowers/specs/council/](superpowers/specs/council/) | Spec reviews by Claude, Codex and Gemini, and the round-1 synthesis |
| [superpowers/plans/2026-10-30-sharpit-mvp.md](superpowers/plans/2026-10-30-sharpit-mvp.md) | MVP implementation plan: Global Constraints, Review Focus, tasks |
Expand Down
19 changes: 19 additions & 0 deletions docs/reference/FLASK-ROUTE-MODEL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Flask route introspection

sharpit's pytest adapter can inspect Flask routes from Flask 2.3.3 onward. Flask stays in the `test` extra; it is not a
runtime dependency. Route discovery uses registered `url_map` rules and does not execute view functions. Blueprint
rules appear as Flask registers them, including static routes and distinct registrations of the same view.

Werkzeug paths such as `/items/<int:item_id>` appear as `/items/{item_id}`. The adapter reports effective rule methods,
including automatically added `HEAD` and `OPTIONS`, and preserves the rule's slash spelling.

The route model has no fields for `strict_slashes`, subdomain or host constraints, converter semantics, blueprint
provenance, declared-versus-automatic methods, response metadata, or produced and consumed media types. These facts are
not inferred; host is `null`, and unavailable response and media metadata are `null`. An unreadable URL map is
distinct from a confirmed empty map: route inspection returns `None` when the map cannot be read, and an explicitly
selected app is reported as `UNKNOWN`. Unreadable rule fields are skipped without evaluating descriptors. Callable
views are represented by their class identity and are never called.

Flask route introspection does not mount the sharpit console in Flask applications.

BootUI 2.5.0 has no Flask route model, so these framework-specific behaviors have no BootUI parity counterpart.
1 change: 1 addition & 0 deletions docs/reference/matrix-updates/0.8.0-f1.tsv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
adapter:flask-route-metadata adapted BootUI 2.5.0 has no Flask route model; Flask route metadata is read statically, unreadable maps report UNKNOWN, and callable views are identified by class without invocation; docs/reference/FLASK-ROUTE-MODEL.md
31 changes: 31 additions & 0 deletions docs/superpowers/plans/2026-11-21-0.8.0-f1-flask-route-model.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Flask route model

The F1 adapter exposes Flask route metadata to sharpit's pytest advisor. Flask remains a test-only dependency, with
2.3.3 as the supported floor and Flask 3.x as the current test target. The adapter reads the public `url_map` and
registered rules; it does not call views or inspect blueprint internals.

## Mapping

| Flask source | sharpit representation |
|---|---|
| `app.import_name` | `AppInfo.title` |
| Flask distribution metadata | `AppInfo.framework_version`; `docs_url=None` |
| Each `app.url_map.iter_rules()` rule | One `RouteInfo`, in registration order |
| `Rule.methods` | Sorted effective methods, including Werkzeug-added `HEAD` and `OPTIONS` |
| `Rule.rule` | Path with `<name>` and `<converter:name>` rendered as `{name}`; slash spelling is preserved |
| Registered view callable | `module:qualname` handler identity, read without calling it |
| `Rule.endpoint` | Route name |
| No dependency-provider graph | `providers() == []` |

`RouteInfo` cannot carry `strict_slashes`, subdomain or host constraints, converter validation semantics, blueprint
provenance, explicit-versus-automatic methods, response metadata, or media types. The adapter preserves the written
path, reports `host=None`, and reports unavailable response and media metadata as `None`. It does not infer semantic
equivalence between routes with different slash or host behavior.

An unreadable URL map is distinct from a confirmed empty map: route inspection returns `None` when the map cannot be
read, and an explicitly selected app is reported as `UNKNOWN`. Unreadable rule fields are skipped without evaluating
descriptors. Flask discovery checks already-loaded `sys.modules` entries; it does not import Flask. The Flask adapter
is loaded only after a Flask app is selected.

BootUI 2.5.0 has no Flask route model. Flask-specific route metadata and safe static reads have no BootUI parity
counterpart or shared contract key.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ settings = ["pydantic-settings>=2.4"]
test = [
"fastapi>=0.115",
"pydantic-settings>=2.4",
"flask>=3.0",
"flask>=2.3.3",
"flask-sqlalchemy>=3.1", # the Flask gate tests (F2); tests only
"uvicorn>=0.30",
"httpx>=0.27",
Expand Down
5 changes: 5 additions & 0 deletions src/sharpit/flask/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Flask framework adapter."""

from sharpit.flask.introspector import FlaskIntrospector

__all__ = ["FlaskIntrospector"]
103 changes: 103 additions & 0 deletions src/sharpit/flask/introspector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"""Read Flask route metadata without calling application code."""

from __future__ import annotations

import inspect
import re
from collections.abc import Iterable
from importlib.metadata import PackageNotFoundError, version
from types import FunctionType
from typing import cast

from werkzeug.routing import Map

from flask import Flask
from sharpit.engine.spi import AppInfo, ProviderInfo, RouteInfo

_PARAMETER = re.compile(r"<(?:[^<>:]+:)?([^<>:]+)>")
_MISSING = object()


def _attribute(value: object, name: str) -> object | None:
result = inspect.getattr_static(value, name, _MISSING)
result_type = cast(type[object], type(result))
if result is _MISSING or inspect.getattr_static(result_type, "__get__", _MISSING) is not _MISSING:
return None
return result


def _app_values(app: object) -> dict[str, object]:
if not issubclass(type(app), Flask):
return {}
try:
values = object.__getattribute__(app, "__dict__")
except Exception: # noqa: BLE001 - a slotted or unusual Flask subclass has no readable instance data
return {}
return cast(dict[str, object], values) if isinstance(values, dict) else {}


def _handler_name(value: object) -> str | None:
if not callable(value):
return None
if type(value) is FunctionType:
module = object.__getattribute__(value, "__module__")
qualname = object.__getattribute__(value, "__qualname__")
return f"{module}:{qualname}" if isinstance(module, str) and isinstance(qualname, str) else None
target = type(value)
module = type.__getattribute__(target, "__module__")
qualname = type.__getattribute__(target, "__qualname__")
if isinstance(module, str) and isinstance(qualname, str):
return f"{module}:{qualname}"
return None


class FlaskIntrospector:
def __init__(self, app: object) -> None:
self.app = app

def app_info(self) -> AppInfo:
values = _app_values(self.app)
title = values.get("import_name")
try:
flask_version = version("flask")
except PackageNotFoundError:
flask_version = None
return AppInfo(title if isinstance(title, str) else None, "Flask", flask_version, None)

def routes(self) -> list[RouteInfo] | None:
values = _app_values(self.app)
url_map = values.get("url_map")
raw_view_functions = values.get("view_functions")
if type(url_map) is not Map or type(raw_view_functions) is not dict:
return None
view_functions = cast(dict[str, object], raw_view_functions)
try:
rules = Map.iter_rules(url_map)
result: list[RouteInfo] = []
for rule in rules:
path = _attribute(rule, "rule")
endpoint = _attribute(rule, "endpoint")
methods = _attribute(rule, "methods")
handler = _handler_name(view_functions.get(endpoint)) if isinstance(endpoint, str) else None
if not isinstance(path, str) or handler is None:
continue
method_values = (
cast(Iterable[object], methods) if isinstance(methods, (set, frozenset, list, tuple)) else ()
)
result.append(
RouteInfo(
tuple(sorted(method for method in method_values if isinstance(method, str))),
_PARAMETER.sub(r"{\1}", path),
handler,
None,
None,
None,
endpoint if isinstance(endpoint, str) else None,
)
)
return result
except Exception:
return None

def providers(self) -> list[ProviderInfo]:
return []
63 changes: 56 additions & 7 deletions src/sharpit/pytest_plugin/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import importlib
import inspect
import os
import sys
import sysconfig
Expand All @@ -17,7 +18,7 @@
from sharpit.engine.advisors.registry import ADVISORS
from sharpit.engine.advisors.rules import Severity
from sharpit.engine.collectors.restapi.rules import application_routes
from sharpit.engine.spi import ApiModel
from sharpit.engine.spi import ApiModel, ApiRouteInfo
from sharpit.engine.testsession.outcome import AUTODETECT, NO_APPLICATION
from sharpit.fastapi.introspector import FastApiIntrospector

Expand All @@ -43,6 +44,7 @@


_HINT = "pass --sharpit-app module:attr"
_MISSING = object()
_NOT_FOUND = (
"no application found among the modules the tests imported "
"(conftest, test modules and installed packages are not searched)"
Expand Down Expand Up @@ -109,8 +111,13 @@ def _mounted(app: object, mounts: frozenset[type]) -> list[int]:


def autodetect_apps(test_files: Sequence[str] = TEST_FILES) -> tuple[tuple[str, object], ...]:
"""FastAPI/Starlette instances in loaded project-module globals; imports nothing, runs no module hook."""
apps = _classes("starlette.applications", "Starlette") | _classes("fastapi.applications", "FastAPI")
"""Flask/FastAPI/Starlette instances in loaded project-module globals; imports nothing, runs no module hook."""
apps = (
_classes("starlette.applications", "Starlette")
| _classes("fastapi.applications", "FastAPI")
| _classes("flask.app", "Flask")
| _classes("flask.sansio.app", "Flask")
)
if not apps:
return ()
paths = sysconfig.get_paths()
Expand Down Expand Up @@ -190,19 +197,49 @@ def load_app(spec: str) -> tuple[str, object]:
if not separator:
raise ValueError("--sharpit-app must be MOD:ATTR")
app = getattr(importlib.import_module(module_name), attr)
return spec, app() if callable(app) and not hasattr(app, "router") else app
has_router = inspect.getattr_static(app, "router", _MISSING) is not _MISSING
return spec, app() if callable(app) and not has_router and not _is_flask_app(app) else app


def model_of(app: object) -> ApiModel:
def _is_flask_app(app: object) -> bool:
return not (_classes("flask.app", "Flask") | _classes("flask.sansio.app", "Flask")).isdisjoint(type(app).__mro__)


def _app_model(app: object) -> ApiModel | None:
if _is_flask_app(app):
from sharpit.flask import FlaskIntrospector

routes = FlaskIntrospector(app).routes()
if routes is None:
return None
return ApiModel(tuple(ApiRouteInfo(route.methods, route.path, route.handler) for route in routes), (), ())
return FastApiIntrospector(app).api_model()


def model_of(app: object) -> ApiModel:
model = _app_model(app)
return model if model is not None else ApiModel((), (), ())


def _configured_models(
state: Any, load_app: Callable[[str], tuple[str, object]] | None
) -> list[tuple[str, ApiModel]] | None:
try:
name, app = (load_app or _load_app)(state.options.app)
return [(name, FastApiIntrospector(app).api_model())]
model = _app_model(app)
if model is None:
state.sink.facts.advisor_runs.append(
AdvisorRun(
"rest-api",
"UNKNOWN",
(),
{},
"application routes cannot be inspected (Flask URL map)",
name,
)
)
return None
return [(name, model)]
except Exception as exc: # noqa: BLE001
state.sink.facts.advisor_runs.append(
AdvisorRun(
Expand All @@ -225,7 +262,19 @@ def _discovered_models(state: Any) -> list[tuple[str, ApiModel]] | None:
if (run := no_app_run(state.autodetected, state.options.require_app)) is not None:
state.sink.facts.advisor_runs.append(run)
return None
model = FastApiIntrospector(chosen[1]).api_model()
model = _app_model(chosen[1])
if model is None:
state.sink.facts.advisor_runs.append(
AdvisorRun(
"rest-api",
"UNKNOWN",
(),
{},
"application routes cannot be inspected (Flask URL map)",
chosen[0],
)
)
return None
if not application_routes(model.routes):
state.sink.facts.advisor_runs.append(bare_app_run(chosen[0], state.options.require_app))
return None
Expand Down
Loading