Add Claude relay seams and entry points

Dependencies (exact pins): claude-agent-sdk 0.2.183, rtdb-relay 0.1.1,
httpx 0.28.1, hypothesis 6.170.15 (dev). The pylint hook env gets the
same pins.

Entry points, each reachable only through one module attribute:
_claude_connect.connect_sealed (RTDB + e2e unlock), _claude_sdk.run_model
(the model call), _claude_sync.pull_peers / publish (narrow pull, full
tick). SDK and rtdb_relay are imported only by these modules, never by the
gate or CLI at load time.

Test isolation, all fail closed: connect_sealed and run_model are replaced
by a function that raises; pull/publish return None; the sandbox dir and
kuhy's real Claude login path point into tmp_path; _test_guard also
protects ~/.config/diet_guard_claude and ~/.cache/diet_guard. Each of the
six redirects was removed once and its canary went red (fail closed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
This commit is contained in:
Krzysztof Rudnicki 2026-11-17 21:02:35 +01:00
parent a3d089fee3
commit 3d8d358abd
14 changed files with 595 additions and 6 deletions

View File

@ -29,7 +29,7 @@ repos:
args: [--pytest-test-first]
# Shared fakes and fixtures, not test modules. Split out of conftest.py
# and test_sync.py only because those files passed the 250-line cap.
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects)\.py$
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects|claude_redirects|claude_fakes)\.py$
- id: check-ast
- id: mixed-line-ending
args: [--fix=lf]
@ -114,7 +114,7 @@ repos:
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.14.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays
- rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.1.1#subdirectory=rtdb_relay
- claude-agent-sdk==0.2.183
- httpx==0.28.1

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none'
version: 1.0.165+1
version: 1.0.166+1
environment:
sdk: ^3.12.2

View File

@ -0,0 +1,102 @@
"""Connecting the relay worker to RTDB, signed in and unlocked.
The database URL and API key come from crdt-sync's shared
``~/.config/crdt-sync/firebase.json``; the signed-in session is the worker's
own app, ``~/.config/diet_guard_claude/firebase_auth.json`` (seeded once with
crdt-sync's ``seed_session --app diet_guard_claude``). Never the gate's
``diet_guard`` session file: two processes refreshing one token file corrupt
it. Never ``firebase_client_for``: without a session it falls back to the
dead shared password and fails with a misleading error.
:func:`connect_sealed` is the worker's only network entry point besides the
event stream it returns; ``conftest`` blocks it.
"""
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Final
from crdt_sync import (
ConfigError,
E2eLockedError,
FirebaseAuthError,
FirebaseConfig,
FirebaseTokenProvider,
credential_store_for,
)
from rtdb_relay.rtdb import Rtdb, RtdbError
from rtdb_relay.seal import Sealer
from rtdb_relay.unlock import unlock
from diet_guard import _sync_e2e
from diet_guard._claude_layout import E2E_LAYOUT, LAYOUT, ROOT
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
APP: Final = "diet_guard_claude"
class RelaySetupError(RuntimeError):
"""The relay cannot start: no config, no session, or the key is locked."""
def token_source(provider: FirebaseTokenProvider) -> Callable[[], Awaitable[str]]:
"""An async id-token getter (the provider is sync and refreshes itself)."""
async def token() -> str:
try:
return await asyncio.to_thread(provider.id_token)
except FirebaseAuthError as err:
msg = f"firebase auth failed: {err}"
raise RtdbError(msg) from None
return token
def connect() -> Rtdb:
"""An unsealed RTDB client rooted at the relay, signed in as the worker."""
try:
config = FirebaseConfig.load()
except ConfigError as err:
msg = f"no crdt-sync firebase config: {err}"
raise RelaySetupError(msg) from err
provider = FirebaseTokenProvider(config.api_key, credential_store_for(APP))
if not provider.has_session():
msg = (
f"no signed-in session in ~/.config/{APP}/firebase_auth.json; seed it "
f"with crdt-sync: python3 -m tool.seed_session ... --app {APP}"
)
raise RelaySetupError(msg)
return Rtdb(config.database_url, token_source(provider), root=ROOT)
def passphrase() -> str:
"""The shared crdt-sync passphrase of this PC, or "" (locked)."""
try:
return _sync_e2e.PASSWORD_FILE.read_text(encoding="utf-8").strip()
except OSError:
return ""
async def connect_sealed() -> Rtdb:
"""The test seam: the worker connects only through this name."""
return await unlock_sealed(connect())
async def unlock_sealed(rtdb: Rtdb) -> Rtdb:
"""Unlock ``rtdb``: everything it writes is sealed from now on.
Raises:
RelaySetupError: The e2e key is locked or unreachable. Nothing may be
read or written (fail closed).
"""
try:
key = await unlock(rtdb, passphrase(), E2E_LAYOUT, _sync_e2e.ARGON2_PARAMS)
except (E2eLockedError, RtdbError) as err:
await rtdb.aclose()
msg = f"e2e locked or unreachable ({err})"
raise RelaySetupError(msg) from err
rtdb.sealer = Sealer(key.cipher(), LAYOUT)
return rtdb

View File

@ -0,0 +1,34 @@
"""Where the "send to Claude" relay lives in RTDB and what is sealed.
The contract is ``docs/DOCS-claude-relay.md``; ``tests/fixtures/
claude_relay_contract.json`` pins the same layout for the phone. The root is
chosen so its e2e header is the one diet_guard already uses
(``diet-guard-sync/e2e``): same passphrase, same salt, same key.
Imports ``rtdb_relay`` and ``crdt_sync``, so only the relay worker's own
modules import this one -- never the gate or the CLI at load time.
"""
from __future__ import annotations
from typing import Final
from crdt_sync import E2eLayout
from rtdb_relay.layout import Layout
#: The unencrypted-era prefix the e2e root and header are derived from.
OLD_PREFIX: Final = "diet-guard-sync/claude"
E2E_LAYOUT: Final = E2eLayout.of(OLD_PREFIX)
ROOT: Final = E2E_LAYOUT.prefix
#: The only request kind this relay serves.
KIND: Final = "meal"
LAYOUT: Final = Layout(
root=ROOT,
clear=("requests/*/claim",),
units={
"requests/*/req": frozenset({"created"}),
"requests/*/result": frozenset({"at"}),
},
)

View File

@ -0,0 +1,138 @@
"""The isolated Claude config dir the meal estimator runs in.
kuhy's own ``~/.claude`` stays outside: its hooks and rules make the model
answer with a grilling round instead of JSON, and its credentials file also
holds a refresh token and every MCP server's OAuth tokens. The sandbox holds
exactly two things: a copy of the Claude access token (no refresh token, so
the CLI inside never refreshes and never rotates kuhy's own login out) and the
``diet-food`` skill. Same approach as ``~/src/tutor/tutor/model_login.py``.
``CLAUDE_CONFIG_DIR`` is set only in the model call's own ``env`` (see
:mod:`diet_guard._claude_sdk`), never in this process: ``HOST_LOGIN_FILE``
must keep naming kuhy's real login.
"""
from __future__ import annotations
import json
import logging
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import time
from typing import TYPE_CHECKING, Final
if TYPE_CHECKING:
from collections.abc import Callable
_logger = logging.getLogger(__name__)
#: Scratch config dir (``CLAUDE_CONFIG_DIR``); cache, not the synced data dir.
SANDBOX_DIR: Path = Path.home() / ".cache" / "diet_guard" / "claude-sandbox"
#: kuhy's own CLI login: read to copy the access token, never written.
HOST_LOGIN_FILE: Path = Path.home() / ".claude" / ".credentials.json"
#: The skill shipped in the repo (an editable install runs the working tree).
SKILL_DIR: Final = Path(__file__).resolve().parent.parent / "skills" / "diet-food"
#: The CLI refreshes its token within 5 minutes of expiry.
REFRESH_MARGIN_MS: Final = 300_000
_REFRESH_TIMEOUT_S: Final = 40
_LOGIN_NAME: Final = ".credentials.json"
def skill_text() -> str:
"""The ``SKILL.md`` body without its front matter (the system prompt)."""
text = SKILL_DIR.joinpath("SKILL.md").read_text(encoding="utf-8")
if text.startswith("---\n"):
_, _, text = text[4:].partition("\n---\n")
return text.strip()
def host_cli() -> Path | None:
"""The ``claude`` binary kuhy's login is refreshed with, if any."""
found = shutil.which("claude")
return Path(found) if found else None
def copy_login() -> int | None:
"""Copy the host's access token into the sandbox; its expiry in ms.
Only ``claudeAiOauth`` minus ``refreshToken`` is written (0600, atomic).
No readable host login writes nothing and returns None.
"""
try:
raw = json.loads(HOST_LOGIN_FILE.read_text(encoding="utf-8"))
oauth = dict(raw["claudeAiOauth"])
except (OSError, ValueError, KeyError, TypeError) as err:
_logger.warning("no host Claude login to copy: %r", err)
return None
oauth.pop("refreshToken", None)
SANDBOX_DIR.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=SANDBOX_DIR, prefix=".credentials.")
with os.fdopen(fd, "w", encoding="utf-8") as out:
json.dump({"claudeAiOauth": oauth}, out)
Path(tmp).replace(SANDBOX_DIR / _LOGIN_NAME)
expires = oauth.get("expiresAt")
return int(expires) if isinstance(expires, (int, float)) else None
def refresh_host_login() -> None:
"""Let kuhy's own CLI refresh his login: one tiny call, nothing loaded."""
cli = host_cli()
if cli is None:
return
cmd = [
str(cli),
"-p",
"Reply with OK.",
"--tools=",
"--setting-sources=",
"--strict-mcp-config",
"--max-turns=1",
"--no-session-persistence",
]
env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"}
work = SANDBOX_DIR / "refresh"
work.mkdir(parents=True, exist_ok=True)
subprocess.run(
cmd,
cwd=work,
env=env,
check=True,
capture_output=True,
timeout=_REFRESH_TIMEOUT_S,
)
def install_skill() -> None:
"""Copy the ``diet-food`` skill into the sandbox's ``skills/`` dir."""
target = SANDBOX_DIR / "skills" / SKILL_DIR.name
target.mkdir(parents=True, exist_ok=True)
shutil.copyfile(SKILL_DIR / "SKILL.md", target / "SKILL.md")
def prepare(
now: Callable[[], float] = time.time,
refresh: Callable[[], None] = refresh_host_login,
) -> Path | None:
"""Make the sandbox ready; its path, or None when there is no login.
A login about to expire is refreshed on the host first. Never raises on a
refresh failure: the model call then reports the CLI's own error and the
request fails closed as ``estimate_failed``.
"""
expires = copy_login()
if expires is None:
return None
if expires - now() * 1000 <= REFRESH_MARGIN_MS:
try:
refresh()
except (OSError, subprocess.SubprocessError) as err:
_logger.warning("could not refresh the Claude login: %r", err)
else:
copy_login()
install_skill()
(SANDBOX_DIR / "work").mkdir(exist_ok=True)
return SANDBOX_DIR

132
diet_guard/_claude_sdk.py Normal file
View File

@ -0,0 +1,132 @@
"""The one place that talks to Claude: ``claude_agent_sdk`` in the sandbox.
Every other module reaches the model through :func:`run_model`, so a single
test seam (``conftest`` blocks it) keeps the suite off the network and off
kuhy's subscription. The SDK is imported inside the function: the gate and
the CLI import this package at load time, and system Python has no
``claude_agent_sdk`` until the install step ran (the 2026-06-19 outage
shape).
Isolation: ``CLAUDE_CONFIG_DIR`` points at the sandbox (token copy + skill),
``setting_sources`` is empty and there are no tools, MCP servers or hooks, so
nothing of kuhy's own configuration can steer the model.
"""
from __future__ import annotations
import asyncio
from importlib import import_module
from typing import TYPE_CHECKING, Any, Final
from diet_guard import _claude_sandbox
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from pathlib import Path
from claude_agent_sdk import ClaudeAgentOptions
MODEL: Final = "claude-sonnet-5-5"
_SDK: Final = "claude_agent_sdk" # imported lazily, see the module docstring
class ModelError(RuntimeError):
"""The model call failed or returned no structured answer."""
class ModelTimeoutError(ModelError):
"""The model call ran past its time budget."""
def _blocks(content: list[dict[str, Any]]) -> AsyncIterator[dict[str, Any]]:
"""One streamed user message carrying content blocks (how images go in)."""
async def stream() -> AsyncIterator[dict[str, Any]]:
message = {"role": "user", "content": content}
yield {"type": "user", "message": message, "parent_tool_use_id": None}
return stream()
def _options(
system_prompt: str, schema: dict[str, Any], config: Path
) -> ClaudeAgentOptions:
"""Isolated, tool-less options with the structured-output schema."""
work = config / "work"
return import_module(_SDK).ClaudeAgentOptions(
model=MODEL,
system_prompt=system_prompt,
tools=[],
allowed_tools=[],
setting_sources=[],
strict_mcp_config=True,
mcp_servers={},
cwd=work,
output_format={"type": "json_schema", "schema": schema},
effort="low",
env={
"CLAUDE_CONFIG_DIR": str(config),
"CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1",
"DISABLE_TELEMETRY": "1",
"DISABLE_AUTOUPDATER": "1",
},
extra_args={"disable-slash-commands": None, "no-session-persistence": None},
)
async def _ask(
system_prompt: str, content: list[dict[str, Any]], schema: dict[str, Any]
) -> dict[str, Any]:
config = await asyncio.to_thread(_claude_sandbox.prepare)
if config is None:
msg = "no Claude login to copy into the sandbox"
raise ModelError(msg)
options = _options(system_prompt, schema, config)
answer: object = None
sdk = import_module(_SDK)
async for message in sdk.query(prompt=_blocks(content), options=options):
if isinstance(message, sdk.ResultMessage):
if message.is_error:
detail = f"{message.subtype} {message.errors} {message.result}"
raise ModelError(detail)
answer = message.structured_output
if not isinstance(answer, dict):
msg = "model returned no structured object"
raise ModelError(msg)
return answer
async def run_model(
system_prompt: str,
content: list[dict[str, Any]],
schema: dict[str, Any],
*,
budget_s: float,
) -> dict[str, Any]:
"""The test seam: callers reach the model only through this name."""
return await bounded_ask(system_prompt, content, schema, budget_s=budget_s)
async def bounded_ask(
system_prompt: str,
content: list[dict[str, Any]],
schema: dict[str, Any],
*,
budget_s: float,
) -> dict[str, Any]:
"""Ask the model once; its structured answer (a JSON object).
Raises:
ModelTimeoutError: ``budget_s`` seconds passed.
ModelError: any other failure: login, CLI, API, or a missing answer.
"""
try:
async with asyncio.timeout(budget_s):
return await _ask(system_prompt, content, schema)
except TimeoutError as err:
msg = f"model call exceeded {budget_s:g} s"
raise ModelTimeoutError(msg) from err
except ModelError:
raise
except Exception as err: # SDK/CLI errors have no common base worth naming
raise ModelError(type(err).__name__) from err

View File

@ -0,0 +1,28 @@
"""The relay worker's two sync touch points, behind one module seam.
* :func:`pull_peers` runs before a request is served, so the due slot is
computed from a log that already holds what the phone logged. It is the
narrow pull (``_sync_refresh.pull_peer_logs``, ~84 ms), not a full tick.
* :func:`publish` runs after the answer is written: a full tick (15 to 27 s)
that must never sit in front of the answer (``docs/DOCS-claude-relay.md``
section 5).
Both return ``None`` on success or a short reason, never raise on an outage
(fail closed: the worker leaves the request pending on a failed pull).
``conftest`` patches both names here, so a test that logs through the worker
cannot reach the real remote.
"""
from __future__ import annotations
from diet_guard import _sync_events, _sync_refresh
def pull_peers() -> str | None:
"""Pull every peer's log; None on success, else why not."""
return _sync_refresh.pull_peer_logs()
def publish() -> str | None:
"""Run a full sync tick after a write; None on success, else why not."""
return _sync_events.publish_after_log()

View File

@ -50,6 +50,10 @@ def _resolved(path: pathlib.Path) -> pathlib.Path:
_PROTECTED = (
_resolved(pathlib.Path.home() / ".local" / "share" / "diet_guard"),
_resolved(pathlib.Path.home() / ".config" / "diet_guard"),
# The relay worker's own Firebase session and the estimator's scratch
# Claude config dir (a copy of kuhy's login lives there).
_resolved(pathlib.Path.home() / ".config" / "diet_guard_claude"),
_resolved(pathlib.Path.home() / ".cache" / "diet_guard"),
)

View File

@ -0,0 +1,54 @@
"""The redirects for the "send to Claude" relay and estimator.
Split out of ``_state_redirects.py`` for the 250-line cap. Two kinds, both
**fail closed**:
* the network and subscription entry points (RTDB connect, the model call)
are replaced by a function that *raises*, so a test that reaches one fails
loudly instead of talking to the live database or spending kuhy's Claude
quota; a test that needs one patches in its own fake;
* the sync touch points return ``None`` like the other call sites, and the
on-disk paths (sandbox dir, kuhy's real Claude login) point into ``tmp_path``.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import patch
if TYPE_CHECKING:
from collections.abc import Callable
from pathlib import Path
from unittest.mock import _patch
class RealIoBlockedError(AssertionError):
"""A test reached a real network or model entry point."""
def blocked(name: str) -> Callable[..., object]:
"""A replacement for ``name`` that raises when called."""
def refuse(*_args: object, **_kwargs: object) -> object:
msg = f"{name} reached from a test: patch your own fake in"
raise RealIoBlockedError(msg)
return refuse
def claude_redirects(tmp_path: Path) -> list[_patch[object]]:
"""Every patch that keeps the relay worker and estimator off live state."""
return [
patch(
"diet_guard._claude_connect.connect_sealed",
blocked("_claude_connect.connect_sealed"),
),
patch("diet_guard._claude_sdk.run_model", blocked("_claude_sdk.run_model")),
patch("diet_guard._claude_sync.pull_peers", return_value=None),
patch("diet_guard._claude_sync.publish", return_value=None),
patch("diet_guard._claude_sandbox.SANDBOX_DIR", tmp_path / "claude-sandbox"),
patch(
"diet_guard._claude_sandbox.HOST_LOGIN_FILE",
tmp_path / "host-claude-credentials.json",
),
]

View File

@ -14,6 +14,8 @@ from crdt_sync import Argon2Params
import freedays
import sickdays
from diet_guard.tests._claude_redirects import claude_redirects
if TYPE_CHECKING:
from pathlib import Path
from unittest.mock import _patch
@ -185,4 +187,6 @@ def state_redirects(tmp_path: Path) -> list[_patch[object]]:
"diet_guard._activity_sources.screen_locker_log_file",
return_value=None,
),
# The "send to Claude" relay worker and estimator: fail-closed seams.
*claude_redirects(tmp_path),
]

View File

@ -0,0 +1,49 @@
"""Canaries: the relay/estimator seams must fail closed, not open.
A redirect that names a moved or renamed target redirects nothing and the
suite stays green while it reaches the live database or kuhy's Claude quota
(``fail-open-test-seams``). Each test here is red the moment its patch is
missing from ``_claude_redirects.claude_redirects``: the entry point must
*raise* the blocker, the sync touch points must be mocks, and the on-disk
paths must live under ``tmp_path``.
"""
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING
from unittest.mock import Mock
import pytest
from diet_guard import _claude_connect, _claude_sandbox, _claude_sdk, _claude_sync
from diet_guard.tests._claude_redirects import RealIoBlockedError
if TYPE_CHECKING:
from pathlib import Path
def test_rtdb_connect_is_blocked() -> None:
"""The worker's RTDB connect raises instead of dialling Firebase."""
with pytest.raises(RealIoBlockedError):
asyncio.run(_claude_connect.connect_sealed())
def test_model_call_is_blocked() -> None:
"""The model call raises instead of spending kuhy's subscription."""
with pytest.raises(RealIoBlockedError):
asyncio.run(_claude_sdk.run_model("s", [], {}, budget_s=1))
@pytest.mark.parametrize("name", ["pull_peers", "publish"])
def test_sync_touch_points_are_patched(name: str) -> None:
"""Neither the narrow pull nor the full tick can reach the remote."""
touch = getattr(_claude_sync, name)
assert isinstance(touch, Mock)
assert touch() is None
def test_sandbox_and_host_login_are_under_tmp(tmp_path: Path) -> None:
"""The sandbox dir and kuhy's real login file never name the real home."""
assert _claude_sandbox.SANDBOX_DIR.is_relative_to(tmp_path)
assert _claude_sandbox.HOST_LOGIN_FILE.is_relative_to(tmp_path)

View File

@ -8,9 +8,12 @@ dependencies = [
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays",
"holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays",
"claude-agent-sdk==0.2.183",
"defusedxml==0.7.1",
"httpx==0.28.1",
"requests==2.34.2",
"rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.1.1#subdirectory=rtdb_relay",
]
# Optional extras. The `mcp` group is ONLY needed by the MCP server

View File

@ -1,6 +1,7 @@
# Diet Guard — runtime + development dependencies
# Runtime: tkinter/json/hmac/fcntl (stdlib) plus gatelock and requests below.
bandit==1.9.4
claude-agent-sdk==0.2.183
codespell==2.4.3
coverage==7.17.3
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
@ -8,6 +9,8 @@ defusedxml==0.7.1
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.14.0#subdirectory=gatelock
holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds
httpx==0.28.1
hypothesis==6.170.15
mcp==2.3.0
mypy==2.4.1
pre-commit==4.7.0
@ -20,5 +23,6 @@ pytest-sugar==1.1.1
pytest-xdist==3.8.0
pytest-xvfb==3.1.1
requests==2.34.2
rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.1.1#subdirectory=rtdb_relay
ruff==0.17.5
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays

View File

@ -59,6 +59,37 @@ def patch_targets(root: pathlib.Path) -> Iterator[tuple[pathlib.Path, int, str]]
yield path, node.lineno, first.value
def _third_party_missing(exc: ImportError) -> bool:
"""Whether ``exc`` is a missing dependency, not a missing diet_guard module."""
missing = getattr(exc, "name", None) or ""
return isinstance(exc, ModuleNotFoundError) and not missing.startswith(PACKAGE)
def defined_statically(parts: list[str], split: int) -> bool:
"""Whether ``parts[split]`` is a top-level name of module ``parts[:split]``.
Reads the source, never imports it. Only one attribute deep: anything
deeper cannot be proven statically, so it counts as unresolved.
"""
source = pathlib.Path(*parts[:split]).with_suffix(".py")
if len(parts) != split + 1 or not source.is_file():
return False
tree = ast.parse(source.read_text(encoding="utf-8"), str(source))
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
names = [node.name]
elif isinstance(node, (ast.Assign, ast.AnnAssign)):
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
names = [t.id for t in targets if isinstance(t, ast.Name)]
elif isinstance(node, (ast.Import, ast.ImportFrom)):
names = [(a.asname or a.name).split(".")[0] for a in node.names]
else:
continue
if parts[split] in names:
return True
return False
def resolves(dotted: str) -> bool:
"""Whether ``dotted`` names a real attribute reachable from a real module.
@ -69,7 +100,13 @@ def resolves(dotted: str) -> bool:
for split in range(len(parts), 0, -1):
try:
module = importlib.import_module(".".join(parts[:split]))
except ImportError:
except ImportError as exc:
# A module whose own *third-party* import is missing (the relay
# worker's `rtdb_relay`, absent from the system python this hook
# runs under) still has a source file: check the name statically
# rather than call a present target stale.
if _third_party_missing(exc) and defined_statically(parts, split):
return True
continue
obj: object = module
for attr in parts[split:]: