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
83 changes: 83 additions & 0 deletions packages/flow/import_direction_debt.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
{
"about": "Upward imports that exist today, checked by tests/test_import_direction.py. This list only shrinks: when a change removes an edge, delete its row. Never add one; move the shared code down a layer instead.",
"edges": [
"openadapt_flow.agent.attended -> openadapt_flow.console.attention",
"openadapt_flow.approval_mode.approver_roster -> openadapt_flow.jit.authority",
"openadapt_flow.approval_mode.approver_roster -> openadapt_flow.jit.lifecycle",
"openadapt_flow.approval_mode.demo_approver -> openadapt_flow.jit.authority",
"openadapt_flow.approval_mode.durable_carry -> openadapt_flow.runtime.durable.approval",
"openadapt_flow.approval_mode.durable_carry -> openadapt_flow.runtime.durable.checkpoint",
"openadapt_flow.approval_mode.durable_carry -> openadapt_flow.runtime.durable.program_checkpoint",
"openadapt_flow.approval_mode.gate -> openadapt_flow.runtime.effects.adapter",
"openadapt_flow.approval_mode.human_attestation -> openadapt_flow.jit.authority",
"openadapt_flow.approval_mode.item_approval -> openadapt_flow.jit.lifecycle",
"openadapt_flow.approval_mode.signed_policy -> openadapt_flow.jit.authority",
"openadapt_flow.approval_mode.switch -> openadapt_flow.jit.lifecycle",
"openadapt_flow.backends.linux_backend -> openadapt_flow.repair.element_identity",
"openadapt_flow.backends.macos_backend -> openadapt_flow.repair.element_identity",
"openadapt_flow.deployment -> openadapt_flow.backends.factory",
"openadapt_flow.deployment -> openadapt_flow.runtime",
"openadapt_flow.deployment -> openadapt_flow.runtime.actuators",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.adapter",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.auth",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.deferred_report",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.desktop_readback",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.desktop_readback_sessions",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.frame",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.fresh_session",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.onscreen",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.smart_auth",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.sql",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.surfaces",
"openadapt_flow.deployment -> openadapt_flow.runtime.effects.ui_readback",
"openadapt_flow.deployment -> openadapt_flow.runtime.grounder",
"openadapt_flow.deployment -> openadapt_flow.runtime.identity_looks",
"openadapt_flow.deployment -> openadapt_flow.runtime.known_ids",
"openadapt_flow.deployment -> openadapt_flow.runtime.local_grounder",
"openadapt_flow.deployment -> openadapt_flow.runtime.remote_vlm",
"openadapt_flow.deployment -> openadapt_flow.runtime.speed",
"openadapt_flow.form_tx.receipt -> openadapt_flow.form_tx.types",
"openadapt_flow.ir -> openadapt_flow.approval_mode.model",
"openadapt_flow.ir -> openadapt_flow.qualification",
"openadapt_flow.ir -> openadapt_flow.qualification_faults",
"openadapt_flow.ir -> openadapt_flow.sealed_set",
"openadapt_flow.jit.cli -> openadapt_flow.cli_hints",
"openadapt_flow.offline_seal -> openadapt_flow.cli_hints",
"openadapt_flow.policy -> openadapt_flow.runtime.effects",
"openadapt_flow.policy -> openadapt_flow.runtime.target_param",
"openadapt_flow.production_qualification -> openadapt_flow.jit.hosted_authority",
"openadapt_flow.qualification -> openadapt_flow.compiler.codegen",
"openadapt_flow.qualification -> openadapt_flow.runtime.identity_template",
"openadapt_flow.qualification -> openadapt_flow.runtime.resolver",
"openadapt_flow.qualification_identity_evidence -> openadapt_flow.runtime.identity",
"openadapt_flow.qualification_identity_evidence -> openadapt_flow.runtime.identity_template",
"openadapt_flow.qualification_oracle_gate -> openadapt_flow.runtime.effects._common",
"openadapt_flow.qualification_oracle_gate -> openadapt_flow.runtime.effects.onscreen",
"openadapt_flow.qualification_oracle_gate -> openadapt_flow.runtime.effects.rest",
"openadapt_flow.qualification_proposal -> openadapt_flow.compiler.induction",
"openadapt_flow.qualification_proposal -> openadapt_flow.compiler.qualification_pins",
"openadapt_flow.qualification_proposal -> openadapt_flow.compiler.qualification_proposer",
"openadapt_flow.receipt -> openadapt_flow.repair.standard_change",
"openadapt_flow.repair.cli -> openadapt_flow.cli_hints",
"openadapt_flow.run_gate -> openadapt_flow.runtime.target_param",
"openadapt_flow.runtime.admitted_composition -> openadapt_flow.compiler.compose_authoring",
"openadapt_flow.runtime.authorization -> openadapt_flow.runtime.actuators.web_form",
"openadapt_flow.runtime.composition -> openadapt_flow.compiler.compose_authoring",
"openadapt_flow.runtime.effects.effect -> openadapt_flow.runtime.authorization",
"openadapt_flow.runtime.effects.effect -> openadapt_flow.runtime.effects.readback_values",
"openadapt_flow.runtime.replayer -> openadapt_flow.jit.dispatch_authority",
"openadapt_flow.runtime.replayer -> openadapt_flow.jit.lifecycle",
"openadapt_flow.runtime.replayer -> openadapt_flow.qualify.environment",
"openadapt_flow.runtime.replayer -> openadapt_flow.repair.registration",
"openadapt_flow.runtime.replayer -> openadapt_flow.runner.dispatch_envelope",
"openadapt_flow.runtime.replayer -> openadapt_flow.runner.inputs",
"openadapt_flow.runtime.replayer -> openadapt_flow.runner.protocol",
"openadapt_flow.runtime.variant_router -> openadapt_flow.compiler.compose_authoring",
"openadapt_flow.tx.receipt -> openadapt_flow.tx.request_index",
"openadapt_flow.tx.receipt -> openadapt_flow.tx.types",
"openadapt_flow.verify_run -> openadapt_flow.qualify.campaign",
"openadapt_flow.verify_run -> openadapt_flow.qualify.config",
"openadapt_flow.verify_run -> openadapt_flow.qualify.result"
]
}
92 changes: 91 additions & 1 deletion packages/flow/import_layers.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,95 @@
"openadapt_flow.teach_authorization_fixture"
]
},
"exceptions": []
"exceptions": [],
"layers_about": "Dependency direction, checked by tests/test_import_direction.py. Layers are listed lowest first. A module in one layer may import its own layer or a lower one, never a higher one, at module level or inside a function. A pattern ending in * matches every module whose name starts with the rest; the longest matching pattern decides a module's layer. Modules that match no pattern are not checked yet. Known upward edges are listed in import_direction_debt.json, which only shrinks. import_time_budgets caps how many openadapt_flow modules importing a module loads; a change may lower a budget, never raise it. See openadapt-internal docs/design/monorepo-refactor-2026-11/PLAN.md, section 3.",
"layers": [
{
"name": "foundations",
"modules": [
"openadapt_flow.at_rest",
"openadapt_flow.check_level",
"openadapt_flow.crypto",
"openadapt_flow.ed25519ph",
"openadapt_flow.ir",
"openadapt_flow.private_file",
"openadapt_flow.runtime.effects.effect",
"openadapt_flow.verification"
]
},
{
"name": "policy and formats",
"modules": [
"openadapt_flow.approval_mode",
"openadapt_flow.bundle_sealing",
"openadapt_flow.cloud_seal",
"openadapt_flow.countersign",
"openadapt_flow.deployment",
"openadapt_flow.form_tx.receipt",
"openadapt_flow.key_rotation",
"openadapt_flow.offline_seal",
"openadapt_flow.policy",
"openadapt_flow.production_qualification",
"openadapt_flow.public_seal",
"openadapt_flow.qualification*",
"openadapt_flow.receipt",
"openadapt_flow.receipt_log",
"openadapt_flow.run_gate",
"openadapt_flow.runtime.authorization",
"openadapt_flow.seal_*",
"openadapt_flow.sealed_maintenance",
"openadapt_flow.sealed_set",
"openadapt_flow.tx.receipt",
"openadapt_flow.write_receipt"
]
},
{
"name": "runtime",
"modules": [
"openadapt_flow.backend",
"openadapt_flow.backends",
"openadapt_flow.runtime",
"openadapt_flow.verification",
"openadapt_flow.verifier",
"openadapt_flow.verify",
"openadapt_flow.verify_run"
]
},
{
"name": "products",
"modules": [
"openadapt_flow.agent",
"openadapt_flow.compiler",
"openadapt_flow.connector",
"openadapt_flow.fleet",
"openadapt_flow.form_tx",
"openadapt_flow.generate",
"openadapt_flow.jit",
"openadapt_flow.qualify",
"openadapt_flow.repair",
"openadapt_flow.runner",
"openadapt_flow.tx",
"openadapt_flow.wrap"
]
},
{
"name": "surfaces",
"modules": [
"openadapt_flow.__main__",
"openadapt_flow.cli_*",
"openadapt_flow.console",
"openadapt_flow.services"
]
}
],
"import_time_budgets": {
"openadapt_flow": 3,
"openadapt_flow.crypto": 4,
"openadapt_flow.ir": 44,
"openadapt_flow.offline_seal": 4,
"openadapt_flow.public_seal": 5,
"openadapt_flow.receipt": 45,
"openadapt_flow.verification": 5,
"openadapt_flow.write_receipt": 6
}
}
1 change: 1 addition & 0 deletions packages/flow/public-artifacts.json
Original file line number Diff line number Diff line change
Expand Up @@ -1376,6 +1376,7 @@
"examples/claude-code-demo/policy.yaml",
"examples/legacy_records/answers.demo.json",
"examples/legacy_records/answers.ledger.demo.json",
"import_direction_debt.json",
"import_layers.json",
"import_layers_debt.json",
"openadapt_flow/app_profiles/openemr.yaml",
Expand Down
192 changes: 192 additions & 0 deletions packages/flow/tests/test_import_direction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
"""Flow's layers import downward only, and low modules stay cheap to import.

``import_layers.json`` lists five layers, lowest first: foundations, policy
and formats, runtime, products, surfaces (openadapt-internal
``docs/design/monorepo-refactor-2026-11/PLAN.md``, section 3). A module may
import from its own layer or a lower one. An import of a higher layer, at
module level or inside a function, is an upward edge.

* Every upward edge that exists today is listed in
``import_direction_debt.json``. A new one fails. A listed edge that no
longer exists fails too, so the list only shrinks: delete its row.
* ``import_time_budgets`` caps how many ``openadapt_flow`` modules a fresh
interpreter has loaded after importing each listed module. Over budget
fails; under budget prints the new number so the change can lower it.

Modules that match no layer pattern are not checked yet; the plan assigns them
as code moves. ``tests/test_import_layers.py`` keeps its own, separate rule
that core code never reaches app, benchmark, UI or lab code.
"""

from __future__ import annotations

import ast
import json
import subprocess
import sys
from collections.abc import Iterator
from pathlib import Path

import pytest

FLOW = Path(__file__).resolve().parents[1]
CONTRACT = FLOW / "import_layers.json"
DEBT = FLOW / "import_direction_debt.json"
PACKAGE = "openadapt_flow"


def _contract() -> dict:
return json.loads(CONTRACT.read_text(encoding="utf-8"))


def module_names(root: Path, package: str = PACKAGE) -> dict[str, Path]:
names = {}
for path in (root / package).rglob("*.py"):
parts = path.relative_to(root).with_suffix("").parts
if parts[-1] == "__init__":
parts = parts[:-1]
names[".".join(parts)] = path
return names


def layer_of(module: str, layers: list[dict]) -> int | None:
"""Index of the layer whose longest pattern matches ``module``."""
best: tuple[int, int] | None = None
for index, layer in enumerate(layers):
for pattern in layer["modules"]:
if pattern.endswith("*"):
hit = module.startswith(pattern[:-1])
else:
hit = module == pattern or module.startswith(pattern + ".")
if hit and (best is None or len(pattern) > best[0]):
best = (len(pattern), index)
return None if best is None else best[1]


def _targets(tree: ast.AST) -> Iterator[str]:
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
yield alias.name
elif isinstance(node, ast.ImportFrom) and not node.level and node.module:
yield node.module
for alias in node.names:
yield f"{node.module}.{alias.name}"


def upward_edges(root: Path, layers: list[dict]) -> set[str]:
"""``importer -> imported`` for every import of a higher layer."""
modules = module_names(root)

def resolve(name: str) -> str | None:
while name not in modules:
if "." not in name:
return None
name = name.rsplit(".", 1)[0]
return name

edges = set()
for module, path in modules.items():
low = layer_of(module, layers)
if low is None:
continue
tree = ast.parse(path.read_text(encoding="utf-8"))
for target in _targets(tree):
imported = resolve(target)
if imported is None or imported == module:
continue
high = layer_of(imported, layers)
if high is not None and high > low:
edges.add(f"{module} -> {imported}")
return edges


def import_time_count(module: str) -> int:
"""How many openadapt_flow modules a fresh interpreter loads for ``module``."""
code = (
"import importlib, sys\n"
f"importlib.import_module({module!r})\n"
f"print(sum(1 for k in sys.modules if k == {PACKAGE!r} "
f"or k.startswith({PACKAGE + '.'!r})))\n"
)
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True,
check=True,
cwd=FLOW,
)
return int(result.stdout.strip().splitlines()[-1])


def test_no_new_upward_import() -> None:
contract = _contract()
debt = set(json.loads(DEBT.read_text(encoding="utf-8"))["edges"])
current = upward_edges(FLOW, contract["layers"])
new = sorted(current - debt)
assert new == [], (
f"imports from a lower layer into a higher one: {new}. Move the shared "
"code down a layer instead of importing up."
)
gone = sorted(debt - current)
assert gone == [], (
f"these listed upward edges no longer exist; delete them from "
f"{DEBT.name}: {gone}"
)


def test_every_layer_pattern_names_a_module() -> None:
modules = module_names(FLOW)
layers = _contract()["layers"]
unused = [
pattern
for layer in layers
for pattern in layer["modules"]
if not any(layer_of(m, [{"modules": [pattern]}]) == 0 for m in modules)
]
assert unused == [], f"layer patterns that match no module: {unused}"


@pytest.mark.parametrize("module", sorted(_contract()["import_time_budgets"]))
def test_import_time_budget(module: str, capsys: pytest.CaptureFixture[str]) -> None:
budget = _contract()["import_time_budgets"][module]
count = import_time_count(module)
assert count <= budget, (
f"importing {module} loads {count} openadapt_flow modules, budget "
f"{budget}. Import the new dependency inside the function that needs it, "
"or move it lower; never raise the budget."
)
if count < budget:
with capsys.disabled():
print(f"\n{module}: {count} modules, budget {budget}; lower it to {count}")


def test_checker_finds_upward_and_ignores_downward(tmp_path: Path) -> None:
pkg = tmp_path / PACKAGE
(pkg / "low").mkdir(parents=True)
(pkg / "__init__.py").write_text("")
(pkg / "low" / "__init__.py").write_text("")
(pkg / "low" / "a.py").write_text(
"def f():\n from openadapt_flow.high import thing\n"
)
(pkg / "high.py").write_text("from openadapt_flow.low import a\nthing = 1\n")
(pkg / "other.py").write_text("import openadapt_flow.high\n")
layers = [
{"name": "low", "modules": ["openadapt_flow.low"]},
{"name": "high", "modules": ["openadapt_flow.high*"]},
]
assert upward_edges(tmp_path, layers) == {
"openadapt_flow.low.a -> openadapt_flow.high"
}


def test_longest_pattern_decides_the_layer() -> None:
layers = [
{"name": "low", "modules": ["openadapt_flow.runtime.authorization"]},
{"name": "mid", "modules": ["openadapt_flow.runtime"]},
{"name": "high", "modules": ["openadapt_flow.cli_*"]},
]
assert layer_of("openadapt_flow.runtime.authorization.x", layers) == 0
assert layer_of("openadapt_flow.runtime.replayer", layers) == 1
assert layer_of("openadapt_flow.cli_undo", layers) == 2
assert layer_of("openadapt_flow.runtimes", layers) is None