Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 2 additions & 1 deletion .agents/rules/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ available, before the outer middleware pipeline is finalized),
then async `check_data_compatibility(db)` (read-only upgrade checks before
settings hydration; an `error` refuses boot outside development), then async
`on_startup` / `on_shutdown` (reverse order). Non-hook overrides: `locale_dirs()`,
`db_extensions()`, `template_dirs()`, `static_mounts()`, `spa_mounts()`.
`db_extensions()`, `template_dirs()`, `static_mounts()`, `spa_mounts()`,
`doctor_diagnostics(database_url)` (extra read-only `make doctor` findings).

By default, `register_routes` includes `<package>.web.endpoints.{api,views}.router`
when present; import failures inside existing endpoints still fail boot.
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ All notable changes to this project are documented in this file. The format is b

### Added

- `ModuleBase.doctor_diagnostics(database_url)`: an optional, read-only override through which a module adds findings to `make doctor` / `smpy doctor` (never run at boot). A hook that raises or returns something other than `Diagnostic` objects is reported as `SM036` (ERROR) without its exception text, and Doctor continues with the other modules. The `users` module uses it for `SM035` (WARNING): no `users.base_url`, `host.public_base_url` or `host.forwarded_host_allowlist`, so account emails have no origin (#1126).
- CLI: `smpy fix-imports` rewrites imports of the framework paths deprecated by the domain-area layout moves (`import`, `from … import`, `from pkg import moved_module`, attribute chains and dotted strings) to their new area paths; `--check` fails CI while old paths remain and `--diff` previews. The rename table is generated from the registered shims by `scripts/gen_import_renames.py` (#1148).
- CLI / Hosting: `smpy new` now scaffolds a `cli/` project CLI package (as a sibling uv workspace member wired to `simple_module_remote`) and includes `simple_module_api_tokens` by default (`--no-cli` to opt out, `--cli-name` to override the command name), adds `make cli-schema` / `make ci-cli-schema-fresh` targets and CI/release workflows, adds idempotent `smpy add cli` (never overwrites edited files and reports `api_tokens` setup steps when missing), and adds `smpy openapi export --app <module:factory>` to export the real host app offline without a database (#1181).
- Project CLI (`simple_module_remote`): curated command provider interface (`CuratedProvider`, `CuratedContext`, `CuratedError`, required-operation gating with `doctor` reporting for hidden providers, `Provider: <name>` help attribution, `raw` fallback preservation, and `[curated] providers = [...]` allowlisted `simple_module_remote.commands` entry points) plus first-party curated command groups for `users`, `settings` (including `is_secret`-aware `export`/`import` with `0600` output and mask refusal, plus cross-environment `diff`), and `tenants` (#1180).
Expand Down
10 changes: 10 additions & 0 deletions docs/framework/lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,16 @@ def register_resource_types(self, registry: ResourceTypeRegistry) -> None:
)
```

## `doctor_diagnostics(database_url)`

A synchronous, read-only override that `make doctor` (`smpy doctor`) calls once
per module after the framework checks. It returns a sequence of `Diagnostic`
findings and is empty by default; a boot never runs it. Use it for deployment
configuration a module depends on but cannot enforce at boot, such as the
`users` module's `SM035` warning when account emails have no link origin.
Read stored settings without writing, and return nothing when the database is
unreachable (Doctor reports connectivity separately).

## `check_data_compatibility(db)`

This async read-only hook returns a sequence of `DataCompatibilityIssue` frozen
Expand Down
3 changes: 2 additions & 1 deletion docs/framework/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ port after the closing bracket.

If there is no eligible request origin, including sends without a request,
the mailer skips delivery and logs an ERROR naming `host.public_base_url`.
Public reset and verification responses stay generic.
Public reset and verification responses stay generic. Doctor warns with
SM035 when both configured origins and the allowlist are empty.
An explicitly stored users origin, including the old localhost default, keeps
winning. Clear it to inherit the host.

Expand Down
9 changes: 5 additions & 4 deletions docs/reference/diagnostic-codes.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ The framework runs a set of static checks over installed modules at app boot. Th
| `SM032` | ERROR (fails boot in every environment) | A `ModuleBase.spa_mounts()` prefix overlaps a module's `route_prefix`/`view_prefix`/`admin_view_prefix`, a `static_mounts()` prefix, a framework path (`/api`, `/admin`, `/setup`, `/i18n`, `/health`, `/static`, `/modules`) or another SPA mount. The mount would shadow, or be shadowed by, that router. | Pick a prefix nothing else uses. See [Legacy SPA mounts](/framework/spa-mounts). |
| `SM033` | ERROR or WARNING | A module data compatibility check found a missing semantic upgrade (a WARNING when the database could not be checked; a SQLite file that does not exist yet is skipped). Token schema/legacy credentials are errors; unmoved mail system keys warn. Errors refuse boot outside development. Never-migrated first runs defer checks. | Follow the module's remediation. If it gives a `smpy migrations prepare` command, review the generated revision and apply `upgrade heads`. See [Upgrading a host](/guide/upgrading). |
| `SM034` | WARNING | A `subscribe_durable(...)` call in a module's package source has no `name=`. The default name is the handler's import path, so moving or renaming the handler strands its undelivered outbox rows (they retry as an unknown handler, then go `dead`). Found by AST scan; `tests/` is skipped. | Pass `name=` with a constant from `constants.py` whose value is the current default name. See [Durable delivery](/framework/events#durable-delivery). |
| `SM035` | WARNING (Doctor only) | `make doctor` finds that Users is active and `users.base_url`, `host.public_base_url` and `host.forwarded_host_allowlist` are empty. | Set a configured origin or configure the [account email request allowlist](/framework/settings#shared-host-policy). Sends without a request require a configured origin. |
| `SM036` | ERROR (Doctor only) | A module’s `doctor_diagnostics` hook failed. Doctor continues checking the other modules and exits with status 1. | Check the failing module’s diagnostic hook and deployment configuration. |

`SM022`/`SM023` are the two halves of the same invariant: a module's optional [`theme.css` is imported unlayered and `styles.css` into `layer(components)`](/module-authoring#styling), and CSS put in the wrong one silently does nothing (or silently wins everything).

Expand Down Expand Up @@ -71,7 +73,6 @@ Treat a clean dev boot as the "ready to ship" gate. If you want to run the diagn

If you think a rule deserves a code, open a design doc in `docs/plans/` first — existing codes are stable contracts (downstream tooling can grep for them). Use the next free number in the `SM0XX` range and:

1. Add the check to `simple_module_core.diagnostics`.
2. Wire it into `run_diagnostics()` (or the relevant `*Diagnostics.run()` method) so it runs at app boot.
3. Update this page with the row.
4. Add a test case under `framework/core/tests/`.
1. For a framework check that runs at boot, add it to `simple_module_core.diagnostics` and wire it into `run_diagnostics()` or the relevant `*Diagnostics.run()` method. Add a test under `framework/core/tests/`.
2. For a module-specific deployment check, implement `doctor_diagnostics(database_url)` on the module and add a test under the module's tests. See [Lifecycle hooks](/framework/lifecycle).
3. Update this page with the new code and when it runs.
40 changes: 29 additions & 11 deletions framework/core/simple_module_core/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,8 @@ def _database_url() -> str:
return absolutize_sqlite_url(url, anchor=find_env_file().parent)


def _database_dialect() -> str:
"""Dialect name of ``SM_DATABASE_URL`` (``.env`` merged by the i18n loader first).

Defaults to ``sqlite`` like ``Settings.database_url``. Reads the env var
directly for the same reason the i18n settings do: no hosting import.
"""
url = _database_url()
def _database_dialect(url: str) -> str:
"""Extract the dialect without importing the hosting settings."""
return url.split(":", 1)[0].split("+", 1)[0]


Expand Down Expand Up @@ -188,18 +183,41 @@ def main() -> int:

unknown_overrides, override_findings = unknown_overrides_for(modules, extra, supported, default)

database_url = _database_url()
diagnostics = run_diagnostics(
modules,
i18n_supported_locales=supported,
i18n_default_locale=default,
i18n_extra_sources=extra,
i18n_unknown_overrides=unknown_overrides,
database_dialect=_database_dialect(),
existing_index_names=sqlite_file_index_names(_database_url()),
database_dialect=_database_dialect(database_url),
existing_index_names=sqlite_file_index_names(database_url),
)
diagnostics.extend(override_findings)
diagnostics.extend(migration_diagnostics(modules, _database_url()))
diagnostics.extend(data_compatibility_diagnostics(modules, _database_url()))
diagnostics.extend(migration_diagnostics(modules, database_url))
diagnostics.extend(data_compatibility_diagnostics(modules, database_url))
for module in modules:
try:
findings = tuple(module.doctor_diagnostics(database_url))
if any(
not isinstance(finding, Diagnostic)
or not isinstance(finding.level, DiagnosticLevel)
or not isinstance(finding.code, str)
for finding in findings
):
raise TypeError("Invalid module doctor diagnostic")
diagnostics.extend(findings)
except Exception:
# Diagnostic hooks may touch credentials; do not print exception text.
diagnostics.append(
Diagnostic(
level=DiagnosticLevel.ERROR,
code="SM036",
module_name=module.meta.name,
message="The module's doctor_diagnostics hook failed.",
suggestion="Check the module's diagnostic hook and deployment configuration.",
)
)
# A missing dependency only warns at a dev boot, but production refuses
# to start with it (GH #501), so doctor reports it as what it will be.
for finding in diagnostics:
Expand Down
5 changes: 5 additions & 0 deletions framework/core/simple_module_core/modules/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from simple_module_core.access.permissions import PermissionRegistry
from simple_module_core.access.principals import PrincipalRegistry
from simple_module_core.access.resources import ResourceTypeRegistry
from simple_module_core.diagnostics import Diagnostic
from simple_module_core.eventing.events import EventBus
from simple_module_core.eventing.invalidation import InvalidationBus
from simple_module_core.web.audit_links import AuditLinkRegistry
Expand Down Expand Up @@ -266,6 +267,10 @@ def db_extensions(self) -> list[str]:

# ── Lifecycle ─────────────────────────────────────────────

def doctor_diagnostics(self, database_url: str) -> Sequence[Diagnostic]:
"""Optional read-only checks of deployment configuration for Doctor."""
return ()

async def check_data_compatibility(self, db: Any) -> Sequence[DataCompatibilityIssue]:
"""Read-only upgrade checks before settings hydration and module startup.

Expand Down
77 changes: 77 additions & 0 deletions framework/core/tests/diagnostics/test_module_doctor_hook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""ModuleBase.doctor_diagnostics: module findings reach Doctor; a broken hook is SM036."""

import pytest
from simple_module_core import ModuleBase, ModuleMeta
from simple_module_core import __main__ as doctor
from simple_module_core.diagnostics import Diagnostic, DiagnosticLevel

_SECRET = "postgresql://user:hunter2@db/app"


class _Reporting(ModuleBase):
meta = ModuleMeta(name="Reporting")

def __init__(self) -> None:
self.seen_urls: list[str] = []

def doctor_diagnostics(self, database_url):
self.seen_urls.append(database_url)
return [Diagnostic(DiagnosticLevel.WARNING, "SM999", "Example finding", self.meta.name)]


class _Broken(ModuleBase):
meta = ModuleMeta(name="Broken")
mode = "exception"

def doctor_diagnostics(self, database_url):
if self.mode == "not_a_diagnostic":
return [_SECRET]
if self.mode == "bad_level":
return [Diagnostic("warning", "SM999", "Bad level", self.meta.name)]
if self.mode == "bad_code":
return [Diagnostic(DiagnosticLevel.WARNING, [], "Bad code", self.meta.name)]
raise RuntimeError(_SECRET)


@pytest.fixture
def run_doctor(monkeypatch, tmp_path, capsys):
monkeypatch.setenv("SM_DATABASE_URL", f"sqlite+aiosqlite:///{tmp_path / 'absent.db'}")
monkeypatch.setattr(doctor, "parse_dotenv", dict)
monkeypatch.setattr(doctor, "run_diagnostics", lambda *args, **kwargs: [])

def run(*modules: ModuleBase) -> tuple[int, str]:
monkeypatch.setattr(doctor, "discover_modules", lambda strict: list(modules))
status = doctor.main()
return status, capsys.readouterr().err

return run


def test_default_hook_reports_nothing():
class Plain(ModuleBase):
meta = ModuleMeta(name="Plain")

assert tuple(Plain().doctor_diagnostics("sqlite:///x.db")) == ()


def test_module_findings_are_reported_with_the_resolved_database_url(run_doctor, tmp_path):
module = _Reporting()

_, output = run_doctor(module)

assert "SM999 [WARNING] Reporting" in output
assert module.seen_urls == [f"sqlite+aiosqlite:///{tmp_path / 'absent.db'}"]


@pytest.mark.parametrize("mode", ["exception", "not_a_diagnostic", "bad_level", "bad_code"])
def test_broken_hook_reports_sm036_and_doctor_continues(run_doctor, mode):
broken = _Broken()
broken.mode = mode
reporting = _Reporting()

status, output = run_doctor(broken, reporting)

assert status == 1
assert "SM036 [ERROR] Broken" in output
assert "SM999 [WARNING] Reporting" in output
assert "hunter2" not in output
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ def __init__(self, entries: Iterable[str]) -> None:
host, port = parsed
(self._suffixes if wildcard else self._exact).append((host, port))

def __bool__(self) -> bool:
return bool(self._exact or self._suffixes)

def allows(self, host: str, port: str | None) -> bool:
def port_ok(allowed: str | None) -> bool:
return allowed is None or allowed == port
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,21 @@
from simple_module_hosting.pipeline._forwarded_host import TRUSTED_PROXY_SCOPE_KEY, HostAllowlist
from simple_module_hosting.pipeline._insecure_transport import _is_loopback

__all__ = ["public_origin", "trusted_request_origin"]
__all__ = ["has_usable_host_allowlist", "public_origin", "trusted_request_origin"]


def public_origin(settings: HostSettings | None, override: str = "") -> str:
"""Explicit module origin → host origin → relative links (fresh installs)."""
return (override.strip() or (settings.public_base_url if settings else "")).rstrip("/")


def has_usable_host_allowlist(settings: HostSettings | None) -> bool:
"""Return True when ``forwarded_host_allowlist`` has at least one valid host pattern."""
if not settings or not settings.forwarded_host_allowlist:
return False
return bool(_allowlist(tuple(settings.forwarded_host_allowlist)))


@lru_cache(maxsize=16)
def _allowlist(entries: tuple[str, ...]) -> HostAllowlist:
return HostAllowlist(entries)
Expand Down
Loading
Loading