Files
settled-reach/tooling/core/logging.py
T
jpmschweitzerandClaude Opus 5 49fa6ada95 feat(config): T-1249 — the contract is a decorator, and now a test
Every non-zero exit names the command that would fix it, and still exits
non-zero. Both halves matter; the second is the one that gets lost, because a
tool that explains itself beautifully and exits 0 looks MORE correct while
having silently disabled its own gate.

core/errors.py holds ReachError(message, fix=) and @handle_errors.
core/logging.py holds @logged, emitting through console rather than a second
sink — one output path, so there is nothing to drift. core/command.py composes
them, and the order is load-bearing: handle_errors wraps logged, so the logger
sees the original exception. Inverted, every failure would be recorded as
"SystemExit" and the log would say nothing about what went wrong while looking
like it worked.

core/ raises SystemExit, not typer.Exit. A service must be callable from a
test, another service, or a future second front end, and an exception type that
only makes sense inside a CLI leaks the transport into every layer.

The check router is retrofitted off its hand-rolled verdict-and-exit pattern —
exactly the boilerplate this removes — and test_check_parity.py passes
unchanged across the retrofit. That test predates the decorators and pins exit
codes against the old script, so it is independent evidence, not a test tuned
to match new behaviour.

Unknown domains and unknown verbs now enumerate what exists instead of only
saying no. That needed a shared group class, which collided with "no typer
outside main.py and router.py" — resolved by sharpening the invariant rather
than breaking it, since its purpose is that a SERVICE never knows it was called
from a CLI. Transport now lives in main.py, router.py and core/cli.py; never in
service.py, schemas.py or helpers.py. The upside is that cli.domain() carries
the settings that were previously per-router decisions, including the
load-bearing rich_markup_mode=None that one forgetful domain could have undone.

test_conformance.py makes five invariants executable, AST-based rather than
grep. Scoped to the package, not the 123 legacy scripts — and deliberately so:
as T-1250 moves each script into domains/, it lands inside the scope and the
rules start applying automatically, so the test's reach grows with the
migration.

Proven to fail before being trusted: removing @command and removing a fix= each
produced a failure naming the file, the line and the reason.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 15:03:34 +02:00

67 lines
2.3 KiB
Python

"""One structured record per invocation (D-263).
**This is not a logging subsystem.** It is a decorator and an event kind. The
record goes out through `core/console` like everything else, because D-263 names
console the single output path and two sinks would drift — in format, in
destination, in level handling — with the second always being the one nobody
remembers to configure.
Quiet by default. The record is a `debug` event, so the push hook's output looks
exactly as it does today and `--verbose` is what surfaces it. A gate that
suddenly printed a line per check would train people to stop reading gate
output, which is worse than having no record at all.
"""
from __future__ import annotations
import functools
import time
from collections.abc import Callable
from typing import Any, TypeVar
from tooling.core import console
F = TypeVar("F", bound=Callable[..., Any])
# Values that should never appear in a log line even at debug level. Repo
# tooling is not handling credentials today, but the cost of the guard is one
# frozenset and the cost of discovering it was needed is a leaked secret.
_REDACT = frozenset({"password", "token", "secret", "api_key", "apikey"})
def logged(func: F) -> F:
"""Emit command, arguments, duration and outcome for one invocation.
Records the outcome in a `finally`, so a command that raises is still
reported — with the exception type as its outcome rather than silence.
"""
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
started = time.monotonic()
outcome = "ok"
try:
return func(*args, **kwargs)
except BaseException as exc:
outcome = type(exc).__name__
raise
finally:
console.event(
f"{func.__name__} {outcome}",
level="debug",
command=func.__name__,
args=_safe(kwargs),
duration_ms=round((time.monotonic() - started) * 1000, 1),
outcome=outcome,
)
return wrapper # type: ignore[return-value]
def _safe(kwargs: dict[str, Any]) -> dict[str, Any]:
"""Argument values, with anything secret-shaped replaced."""
return {
key: ("***" if key.lower() in _REDACT else value)
for key, value in kwargs.items()
}