diff --git a/CHANGELOG/v3.md b/CHANGELOG/v3.md index bd55a8380..20f0f621c 100644 --- a/CHANGELOG/v3.md +++ b/CHANGELOG/v3.md @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Stop-hook cadence policy — P1 every-K-turns checkpoint** ([#749](https://github.com/robotrocketscience/aelfrice/issues/749)). The Stop hook now supports a periodic-checkpoint cadence that fires the rebuilder pass every K turn boundaries, independent of when the host harness chooses to PreCompact. Originating concern: post-[#746](https://github.com/robotrocketscience/aelfrice/issues/746) PreCompact-fire-rate data showed 6 fires across 2 sessions over 6 days at `trigger_mode='threshold'` — the maintainer's typical workload `/clear`s faster than the harness compacts, so the P0 PreCompact-only policy misses most state-recovery opportunities. The [#749](https://github.com/robotrocketscience/aelfrice/issues/749) body OR-clause was tripped by maintainer self-report and this PR ships the smallest of the body's pre-registered policies. New `src/aelfrice/cadence.py` module: `CadenceConfig` dataclass, `[cadence]` TOML section (`enabled` / `policy` / `k`), env > kwarg > TOML > default resolvers, and the pure `should_fire(fire_idx, config)` predicate (`fire_idx > 0 AND fire_idx % k == 0`, gated on `enabled AND policy == "p1_every_k_turns"`). The resolver shape leaves a slot between env and kwarg for a future [#480](https://github.com/robotrocketscience/aelfrice/issues/480) `meta:hook.cadence_k` meta-belief read without changing call sites. Stop-hook wiring: a new `_maybe_fire_cadence_checkpoint(payload, session_id, serr)` helper reads the current session's `next_fire_idx` from `session_ring.read_ring_state` (same monotonic counter UPS already maintains), checks `should_fire`, and on True calls `_rebuild_and_format` with `rebuild_log_enabled=True` — discarding the returned body since Stop has no `additionalContext` channel. The rebuild_log entry and touch-state refresh are the side effects that carry value. Stderr observability line: `aelfrice: cadence checkpoint fired @ fire_idx=N (policy=p1_every_k_turns, k=15)`. Restructured `stop()` so a session with zero lock-prompt candidates no longer early-returns before cadence gets a chance to run; the lock-prompt behaviour itself is unchanged (41 existing `test_hook_stop_lock_prompt` + `test_setup_stop_hook` tests pass). Default-OFF (`enabled = false` is the default; an unset `[cadence]` section is byte-identical to a pre-#749 Stop hook). K defaults to 15 per the [#749](https://github.com/robotrocketscience/aelfrice/issues/749) body's literature-typical starting point. Determinism contract ([#605](https://github.com/robotrocketscience/aelfrice/issues/605)): the firing predicate is a pure function of `(fire_idx, k)` — no wall-clock, no random sampling. A replay with the same UPS sequence and same config produces the same fire decisions. 30 unit tests in `tests/test_cadence.py` cover the predicate cross-product (enabled / policy / k including k=0 / k=1 / negative-k / fire_idx=0 cold-start guard / negative fire_idx), TOML parser fail-soft on missing-file / missing-section / malformed-TOML / wrong-typed-enabled / unknown-policy / non-positive-k / bool-as-k / parent-dir walk, and the env > kwarg > TOML > default resolver precedence including env-unparseable falls-through. 11 integration tests in `tests/test_hook_stop_cadence.py` against the actual `hook.stop()` entry point cover default-OFF, policy-off-with-enabled-true, the multiples-of-K firing pattern (15/30/45 fire; 1/14/16/29 skip), cold-start fire_idx=0 suppression, missing/session-mismatched ring sentinel, empty recent-turns slice, env-override beats TOML, the stderr observability line carries policy/k/fire_idx, the regression that zero-lock-candidate sessions still fire cadence, and the lock-prompt + cadence coexistence path. P2 (token-budget watermark) and P3 (turn-density-aware) per the [#749](https://github.com/robotrocketscience/aelfrice/issues/749) body remain unimplemented; the policy enum is forward-compatible so those land as new values without rewriting the resolver or predicate. + - **Session-scoped retrieval exclusion — `aelf scope-out` / `/aelf:scope-out`** ([#856](https://github.com/robotrocketscience/aelfrice/issues/856), defect 1 of [#855](https://github.com/robotrocketscience/aelfrice/issues/855)). The UserPromptSubmit memory hook now honors a per-session exclusion list, addressing the failure mode where an agent appears unable to follow direct instructions because the hook keeps re-injecting beliefs about a topic the user has explicitly asked it to drop. `aelf scope-out ` (slash form `/aelf:scope-out `) writes a case-insensitive literal substring to `/aelfrice/session_exclusions.json`, keyed by the active `session_id` read from the sibling `session_first_prompt.json`. The hook reads the list inside `_filter_session_exclusions(hits, session_id)` immediately after `_retrieve()` and drops every belief whose content contains a listed pattern, before telemetry / dedup / format run so downstream counts reflect what was actually injected. L0 (locked) beliefs surfaced by the per-turn retrieval are filtered too — when the user explicitly says "stop bringing this up," that overrides ground-truth re-injection for the rest of the session; the lock stays in the DB and the one-shot SessionStart sub-block (which dumps L0 on the very first prompt of a session) runs before the user can have typed scope-out, so it remains unfiltered by design. Auto-clear on new session: a mismatch between the stored and current `session_id` returns an empty pattern list, so a fresh session starts with no carried-over exclusions. Sibling CLI flags: `aelf scope-out --list` prints active patterns, `aelf scope-out --clear` empties the list (preserving session_id). Regex deliberately not supported — substring keeps the surface deterministic per the v3.0 PHILOSOPHY ratification ([#605](https://github.com/robotrocketscience/aelfrice/issues/605)). 31 unit tests in `tests/test_session_exclusions.py` cover the module API (load / save / add / clear / `is_excluded` / `read_current_session_id`) including auto-clear on session_id mismatch, dedup-with-order-preservation on save, malformed-JSON tolerance, and empty-pattern guards. Six new hook-integration tests in `tests/test_hook_user_prompt_submit.py` cover the per-turn filter for L0 + L1 beliefs, case-insensitivity, multi-pattern composition, the no-file no-op, and the session-id-mismatch no-op. New module `src/aelfrice/session_exclusions.py`, slash file `src/aelfrice/slash_commands/scope-out.md`, CLI subparser in `src/aelfrice/cli.py`, hook filter in `src/aelfrice/hook.py`. - **Project-context retrieval filter — within-repo scope tag** ([#858](https://github.com/robotrocketscience/aelfrice/issues/858), defect 3 of [#855](https://github.com/robotrocketscience/aelfrice/issues/855)). The UserPromptSubmit hook now drops retrieved beliefs whose stored `project_context` disagrees with the active in-process context resolved by `db_paths.active_project_context()`. Cross-repo isolation already exists via `db_path()`'s `--git-common-dir` routing (two repos → two DBs → no contamination); `project_context` catches the within-repo re-scope case (same DB, same repo, but the project's conceptual identity has shifted and old-scope beliefs should no longer surface). Schema: `beliefs.project_context TEXT NOT NULL DEFAULT ''` plus `idx_beliefs_project_context`. The empty-string default preserves pre-#858 semantics — legacy rows always pass the filter. Active context is read once per UserPromptSubmit from `$AELFRICE_PROJECT_CONTEXT`; unset or whitespace-only means "no filter" (full backward compat). Filter rule: empty active → no-op; `scope != 'project'` (federation `global` / `shared:*` or user-promoted `user`) bypasses; project-scope rows kept iff `project_context == '' OR project_context == active`. Distinct from `scope` ([#688](https://github.com/robotrocketscience/aelfrice/issues/688) federation visibility) — the two columns answer orthogonal questions and the read-only federation overlay ([#661](https://github.com/robotrocketscience/aelfrice/issues/661)) does not interact with `project_context`. Implemented as a post-`_retrieve()` filter in `hook.py` rather than a SQL WHERE clause pushed into `MemoryStore.search_beliefs`, keeping the L0/L2.5/L1/L3 retrieval-tier matrix trivial and including federation peer hits (`search_peer_beliefs`) under the same scope check. 25 new tests across `tests/test_project_context_field.py` (schema migration on fresh + legacy DB, column default `''`, insert/update round-trip, search round-trip), `tests/test_active_project_context.py` (env-var resolver, whitespace strip, public constant name), and `tests/test_hook_project_context_filter.py` (full filter matrix: legacy cross-context, matching/mismatching active context, user / global / `shared:*` bypass, whitespace-active no-op, order preservation, empty-input fast path). State-file fallback (`.aelfrice/context` at git-common-dir set by an `aelf context set ` CLI subcommand) deferred to a follow-up issue; env var alone is sufficient for interactive agent sessions and CI pipelines that set context at startup. Write-side stamping ships in the same PR but is opt-in: callers that want a belief tagged set `b.project_context` before `insert_belief` / `update_belief`; legacy writers fall through to the `''` default unchanged. diff --git a/src/aelfrice/cadence.py b/src/aelfrice/cadence.py new file mode 100644 index 000000000..3b546f7c2 --- /dev/null +++ b/src/aelfrice/cadence.py @@ -0,0 +1,349 @@ +"""Stop-hook cadence policy — periodic-checkpoint rebuild firing (#749). + +The host harness fires PreCompact when its own context-window +threshold is crossed. Empirical post-#746 data (6 fires across 2 +sessions over 6 days at trigger_mode='threshold') showed that +maintainer-typical workloads `/clear` faster than the harness compacts, +so PreCompact-only ("P0" in #749 body terminology) misses most of the +state-recovery opportunities. + +This module implements **P1 every-K-turns**: a deterministic, monotonic- +counter-keyed cadence policy that fires a rebuilder pass from the Stop +hook every K turn boundaries. The rebuilder's side effects (rebuild_log +entry, touch-state refresh) accumulate at the chosen cadence instead of +at whatever rate the harness chooses to compact. + +P1 ships **default-OFF** behind a `[cadence] enabled` opt-in flag, +mirroring the bench-gate / ship-or-defer pattern used by the #480 meta- +belief consumers (B-F) and the #769 type-aware-compression flag. The +campaign to evaluate P1 against P2/P3 (token-budget watermark / turn- +density-aware) is the #749 tracker's broader scope; this module ships +the P1 mechanism only. + +Determinism (#605): the firing predicate is a pure function of +``(fire_idx, k)`` — no wall-clock, no random sampling. A replay with +the same fire_idx sequence produces the same fire decisions. + +Discretion (`ab96e9d3501b1c14`): cadence reads no content from +``~/.claude/``; the rebuilder pass it triggers operates on the same +public surfaces PreCompact already drives. + +Resolver shape: ``resolve_*`` functions follow the env > kwarg > TOML > +default precedence used by every other ``.aelfrice.toml``-backed knob +in the project. Future #480 meta-belief integration (``meta:hook. +cadence_k``) slots in between env and kwarg without changing call +sites — see ``resolve_cadence_k`` for the placement. +""" +from __future__ import annotations + +import os +import sys +import tomllib +from dataclasses import dataclass +from pathlib import Path +from typing import IO, Any, Final + +CONFIG_FILENAME: Final[str] = ".aelfrice.toml" +CADENCE_SECTION: Final[str] = "cadence" + +ENABLED_KEY: Final[str] = "enabled" +POLICY_KEY: Final[str] = "policy" +K_KEY: Final[str] = "k" + +ENV_CADENCE_ENABLED: Final[str] = "AELFRICE_CADENCE_ENABLED" +ENV_CADENCE_POLICY: Final[str] = "AELFRICE_CADENCE_POLICY" +ENV_CADENCE_K: Final[str] = "AELFRICE_CADENCE_K" + +POLICY_OFF: Final[str] = "off" +POLICY_P1_EVERY_K_TURNS: Final[str] = "p1_every_k_turns" + +_VALID_POLICIES: Final[frozenset[str]] = frozenset({ + POLICY_OFF, + POLICY_P1_EVERY_K_TURNS, +}) + +DEFAULT_ENABLED: Final[bool] = False +DEFAULT_POLICY: Final[str] = POLICY_OFF +DEFAULT_K: Final[int] = 15 +"""K=15 turns is the body-suggested literature-typical starting point per +the #749 §"Pre-registered policies to evaluate" P1 entry. Operator +override via `[cadence] k` once empirical evidence narrows the band.""" + +_ENV_TRUTHY: Final[frozenset[str]] = frozenset({"1", "true", "yes", "on"}) +_ENV_FALSY: Final[frozenset[str]] = frozenset({"0", "false", "no", "off"}) + + +@dataclass(frozen=True) +class CadenceConfig: + """Resolved `[cadence]` section of `.aelfrice.toml`. + + Three fields. ``enabled`` gates the whole feature: when False, no + cadence fire ever happens regardless of policy/k. ``policy`` selects + the firing pattern; only ``p1_every_k_turns`` is implemented at + v3.x. ``k`` parameterises P1 (turns between fires). + + Defaults are off / off / 15. The K default ships even when enabled + and policy aren't set, so a half-configured TOML is well-defined. + """ + enabled: bool = DEFAULT_ENABLED + policy: str = DEFAULT_POLICY + k: int = DEFAULT_K + + +def _env_bool(name: str) -> bool | None: + """Parse env truthy/falsy; return None on unset / unparseable.""" + raw = os.environ.get(name) + if raw is None: + return None + norm = raw.strip().lower() + if not norm: + return None + if norm in _ENV_TRUTHY: + return True + if norm in _ENV_FALSY: + return False + return None + + +def _env_positive_int(name: str) -> int | None: + """Parse env positive-int; return None on unset / non-int / non-positive.""" + raw = os.environ.get(name) + if raw is None: + return None + norm = raw.strip() + if not norm: + return None + try: + val = int(norm) + except ValueError: + return None + if val <= 0: + return None + return val + + +def _env_policy() -> str | None: + """Parse env policy string; return None on unset / unknown policy.""" + raw = os.environ.get(ENV_CADENCE_POLICY) + if raw is None: + return None + norm = raw.strip().lower() + if norm in _VALID_POLICIES: + return norm + return None + + +def load_cadence_config(start: Path | None = None) -> CadenceConfig: + """Walk up from ``start`` looking for ``.aelfrice.toml``. + + Returns the resolved ``[cadence]`` section. Missing file / missing + section / malformed TOML / wrong-typed values all degrade to + defaults; never raises. Wrong-typed values trace to stderr, + matching the ``RebuilderConfig`` / ``UserPromptSubmitConfig`` + fail-soft contract. + """ + serr: IO[str] = sys.stderr + current = (start if start is not None else Path.cwd()).resolve() + seen: set[Path] = set() + while current not in seen: + seen.add(current) + candidate = current / CONFIG_FILENAME + if candidate.is_file(): + try: + raw = candidate.read_bytes() + except OSError as exc: + print( + f"aelfrice cadence: cannot read {candidate}: {exc}", + file=serr, + ) + return CadenceConfig() + try: + parsed: dict[str, Any] = tomllib.loads( + raw.decode("utf-8", errors="replace"), + ) + except tomllib.TOMLDecodeError as exc: + print( + f"aelfrice cadence: malformed TOML in {candidate}: {exc}", + file=serr, + ) + return CadenceConfig() + section_obj: Any = parsed.get(CADENCE_SECTION, {}) + if not isinstance(section_obj, dict): + return CadenceConfig() + section = section_obj + enabled = _read_bool(section, ENABLED_KEY, DEFAULT_ENABLED, candidate, serr) + policy = _read_policy(section, candidate, serr) + k = _read_k(section, candidate, serr) + return CadenceConfig(enabled=enabled, policy=policy, k=k) + if current.parent == current: + break + current = current.parent + return CadenceConfig() + + +def _read_bool( + section: dict[str, Any], + key: str, + default: bool, + candidate: Path, + serr: IO[str], +) -> bool: + if key not in section: + return default + value = section[key] + if isinstance(value, bool): + return value + print( + f"aelfrice cadence: ignoring [{CADENCE_SECTION}] {key} " + f"in {candidate} (expected bool)", + file=serr, + ) + return default + + +def _read_policy( + section: dict[str, Any], + candidate: Path, + serr: IO[str], +) -> str: + if POLICY_KEY not in section: + return DEFAULT_POLICY + value = section[POLICY_KEY] + if isinstance(value, str) and value in _VALID_POLICIES: + return value + print( + f"aelfrice cadence: ignoring [{CADENCE_SECTION}] {POLICY_KEY} " + f"in {candidate} (expected one of {sorted(_VALID_POLICIES)})", + file=serr, + ) + return DEFAULT_POLICY + + +def _read_k( + section: dict[str, Any], + candidate: Path, + serr: IO[str], +) -> int: + if K_KEY not in section: + return DEFAULT_K + value = section[K_KEY] + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + print( + f"aelfrice cadence: ignoring [{CADENCE_SECTION}] {K_KEY} " + f"in {candidate} (expected positive int)", + file=serr, + ) + return DEFAULT_K + return value + + +def resolve_cadence_enabled( + explicit: bool | None = None, + *, + start: Path | None = None, +) -> bool: + """Resolve the cadence enabled flag. + + Precedence (first decisive wins): + 1. ``AELFRICE_CADENCE_ENABLED`` env var. + 2. Explicit ``explicit`` kwarg from the caller. + 3. ``[cadence] enabled`` in ``.aelfrice.toml``. + 4. Default: ``False`` — ships default-OFF per #749 §"Why this is + parked" reasoning. Operator opts in once subjective experience + or empirical evidence (P0 fire-rate insufficient) justifies it. + + The env tier exists so an operator can flip cadence on for a + single shell without committing a TOML change. The kwarg tier is + for callers that want to inject behaviour in tests / replay. + """ + env = _env_bool(ENV_CADENCE_ENABLED) + if env is not None: + return env + if explicit is not None: + return explicit + return load_cadence_config(start).enabled + + +def resolve_cadence_policy( + explicit: str | None = None, + *, + start: Path | None = None, +) -> str: + """Resolve the cadence policy string. + + Precedence (first decisive wins): + 1. ``AELFRICE_CADENCE_POLICY`` env var. + 2. Explicit ``explicit`` kwarg from the caller. + 3. ``[cadence] policy`` in ``.aelfrice.toml``. + 4. Default: ``"off"`` — even with ``enabled=True``, an unset + policy means no fire ever happens. + + Currently recognised policies: ``off``, ``p1_every_k_turns``. + P2 (token-budget watermark) and P3 (turn-density-aware) per #749 + are unimplemented; the policy string is forward-compatible so + those land as new enum values without changing this resolver. + """ + env = _env_policy() + if env is not None: + return env + if explicit is not None and explicit in _VALID_POLICIES: + return explicit + return load_cadence_config(start).policy + + +def resolve_cadence_k( + explicit: int | None = None, + *, + start: Path | None = None, +) -> int: + """Resolve the cadence-K (turns between fires for P1). + + Precedence (first decisive wins): + 1. ``AELFRICE_CADENCE_K`` env var (positive int). + 2. Explicit ``explicit`` kwarg from the caller. + 3. ``[cadence] k`` in ``.aelfrice.toml``. + 4. Default: ``15`` — body-suggested literature-typical starting + point per #749 §"Pre-registered policies to evaluate". + + Future #480 meta-belief integration: a ``meta:hook.cadence_k`` + read can slot in between env and ``explicit`` — read the meta- + belief, decode via the log-linear bounded scheme already used by + #756, and pass the decoded value as the new tier-2 input. No + call-site changes required at integration time. + """ + env = _env_positive_int(ENV_CADENCE_K) + if env is not None: + return env + if explicit is not None and explicit > 0: + return explicit + return load_cadence_config(start).k + + +def should_fire(fire_idx: int, config: CadenceConfig) -> bool: + """Return True iff cadence should fire at this ``fire_idx``. + + Pure function of ``(fire_idx, config)``. Determinism (#605): a + replay with the same fire_idx sequence and same config produces + the same fire decisions. No wall-clock, no I/O. + + Conditions: + * ``config.enabled`` is True. + * ``config.policy`` is ``p1_every_k_turns``. + * ``config.k`` is positive. + * ``fire_idx`` is positive (the zeroth turn has no prior state + worth checkpointing — also avoids ``0 % k == 0`` firing at + session start, which would be a spurious cold-start fire). + * ``fire_idx % config.k == 0`` — i.e. ``fire_idx`` is a multiple + of ``k``. With k=15: fires at 15, 30, 45, ... + + Returns False on any condition unmet. Never raises. + """ + if not config.enabled: + return False + if config.policy != POLICY_P1_EVERY_K_TURNS: + return False + if config.k <= 0: + return False + if fire_idx <= 0: + return False + return fire_idx % config.k == 0 diff --git a/src/aelfrice/hook.py b/src/aelfrice/hook.py index 581d9da27..f65720b6a 100644 --- a/src/aelfrice/hook.py +++ b/src/aelfrice/hook.py @@ -2552,22 +2552,33 @@ def stop( try: store = _open_store() except Exception: - return 0 + store = None + if store is not None: + try: + candidates = _collect_lock_candidates(store, session_id) + if candidates: + if _autolock_enabled(env): + _autolock_candidates(store, candidates, serr) + else: + block = _format_stop_prompt(candidates) + if block: + # stderr per the Stop-hook contract: any + # prompt-shaped output to the human reading + # the session must go to stderr, not stdout + # (Stop has no additionalContext channel). + serr.write(block) + finally: + store.close() + # Cadence checkpoint (#749 P1) runs independently of the lock- + # prompt path so an empty-candidates session still fires when + # the configured policy says it should. try: - candidates = _collect_lock_candidates(store, session_id) - if not candidates: - return 0 - if _autolock_enabled(env): - _autolock_candidates(store, candidates, serr) - return 0 - block = _format_stop_prompt(candidates) - if block: - # stderr per the Stop-hook contract: any prompt-shaped - # output to the human reading the session must go to stderr, - # not stdout (Stop has no additionalContext channel). - serr.write(block) - finally: - store.close() + _maybe_fire_cadence_checkpoint(payload, session_id, serr) + except Exception as exc: # pragma: no cover — defensive + print( + f"aelfrice: cadence checkpoint failed (non-fatal): {exc}", + file=serr, + ) except Exception as exc: # Last-resort fail-soft. Surface to stderr so the hook log shows # the trace; never bubble to the harness. @@ -2578,6 +2589,79 @@ def stop( return 0 +def _maybe_fire_cadence_checkpoint( + payload: dict[str, object], + session_id: str, + serr: IO[str], +) -> None: + """Fire a P1 every-K-turns cadence checkpoint when conditions hold. + + Reads ``[cadence]`` config from ``payload['cwd']``'s parent chain, + the current session's ``next_fire_idx`` from the session ring, + and ``[rebuilder]`` config for the checkpoint pass. When + :func:`cadence.should_fire` returns True, runs the same + :func:`_rebuild_and_format` path PreCompact uses and discards the + body — Stop has no ``additionalContext`` channel, so the value is + in the rebuild_log + touch-state side effects. + + Fail-soft: any error short-circuits to a stderr line; never raises. + Default-OFF: an unset ``[cadence] enabled`` flag means this function + returns before reading anything substantive. + """ + # Local imports keep the Stop hot path free of cadence overhead + # when the feature is unused (the module-level imports load only + # on first cadence-enabled session). + from aelfrice.cadence import ( # noqa: PLC0415 + CadenceConfig, + POLICY_P1_EVERY_K_TURNS, + resolve_cadence_enabled, + resolve_cadence_k, + resolve_cadence_policy, + should_fire, + ) + from aelfrice.session_ring import read_ring_state # noqa: PLC0415 + + cwd_obj = payload.get(_CWD_KEY) + cwd = ( + Path(cwd_obj) if isinstance(cwd_obj, str) and cwd_obj + else Path.cwd() + ) + if not resolve_cadence_enabled(start=cwd): + return + policy = resolve_cadence_policy(start=cwd) + if policy != POLICY_P1_EVERY_K_TURNS: + return + k = resolve_cadence_k(start=cwd) + cfg = CadenceConfig(enabled=True, policy=policy, k=k) + state = read_ring_state(session_id) + raw_idx: Any = state.get("next_fire_idx") if isinstance(state, dict) else None + if isinstance(raw_idx, bool) or not isinstance(raw_idx, int): + return + fire_idx = raw_idx + if not should_fire(fire_idx, cfg): + return + rebuilder_cfg = load_rebuilder_config(cwd) + recent = _read_recent_for_pre_compact(payload, rebuilder_cfg.turn_window_n) + if not recent: + return + p = db_path() + if str(p) != ":memory:" and not p.exists(): + return + _rebuild_and_format( + recent, + rebuilder_cfg.token_budget, + rebuild_log_enabled=rebuilder_cfg.rebuild_log_enabled, + floor_session=rebuilder_cfg.floor_session, + floor_l1=rebuilder_cfg.floor_l1, + query_strategy=rebuilder_cfg.query_strategy, + ) + print( + f"aelfrice: cadence checkpoint fired @ fire_idx={fire_idx} " + f"(policy={policy}, k={k})", + file=serr, + ) + + def main() -> int: """Entry point for `python -m aelfrice.hook`.""" return user_prompt_submit() diff --git a/tests/test_cadence.py b/tests/test_cadence.py new file mode 100644 index 000000000..c421eb93f --- /dev/null +++ b/tests/test_cadence.py @@ -0,0 +1,341 @@ +"""Unit tests for src/aelfrice/cadence.py (#749 P1 every-K-turns).""" +from __future__ import annotations + +import textwrap +from pathlib import Path + +import pytest + +from aelfrice import cadence + + +# --- should_fire predicate (pure function) -------------------------------- + + +def _on_cfg(k: int = 15) -> cadence.CadenceConfig: + return cadence.CadenceConfig( + enabled=True, + policy=cadence.POLICY_P1_EVERY_K_TURNS, + k=k, + ) + + +def test_should_fire_default_config_never_fires() -> None: + cfg = cadence.CadenceConfig() + assert cfg.enabled is False + for fire_idx in range(0, 50): + assert cadence.should_fire(fire_idx, cfg) is False + + +def test_should_fire_disabled_never_fires_regardless_of_policy_and_k() -> None: + cfg = cadence.CadenceConfig( + enabled=False, + policy=cadence.POLICY_P1_EVERY_K_TURNS, + k=1, + ) + for fire_idx in range(0, 50): + assert cadence.should_fire(fire_idx, cfg) is False + + +def test_should_fire_policy_off_never_fires_even_when_enabled() -> None: + cfg = cadence.CadenceConfig( + enabled=True, policy=cadence.POLICY_OFF, k=15, + ) + for fire_idx in range(0, 50): + assert cadence.should_fire(fire_idx, cfg) is False + + +def test_should_fire_p1_k15_fires_at_multiples_of_k() -> None: + cfg = _on_cfg(k=15) + expected = {15, 30, 45} + for fire_idx in range(1, 50): + assert cadence.should_fire(fire_idx, cfg) is (fire_idx in expected), ( + f"fire_idx={fire_idx} should be {fire_idx in expected}" + ) + + +def test_should_fire_zero_fire_idx_suppresses_spurious_cold_start() -> None: + # 0 % k == 0 is True numerically; the predicate must reject it so + # the very first Stop after session start does not fire cadence. + assert cadence.should_fire(0, _on_cfg(k=15)) is False + assert cadence.should_fire(0, _on_cfg(k=1)) is False + + +def test_should_fire_negative_fire_idx_never_fires() -> None: + for fire_idx in (-1, -10, -100): + assert cadence.should_fire(fire_idx, _on_cfg(k=15)) is False + + +def test_should_fire_k_zero_or_negative_never_fires() -> None: + cfg_zero = cadence.CadenceConfig( + enabled=True, policy=cadence.POLICY_P1_EVERY_K_TURNS, k=0, + ) + cfg_neg = cadence.CadenceConfig( + enabled=True, policy=cadence.POLICY_P1_EVERY_K_TURNS, k=-5, + ) + for fire_idx in range(0, 30): + assert cadence.should_fire(fire_idx, cfg_zero) is False + assert cadence.should_fire(fire_idx, cfg_neg) is False + + +def test_should_fire_k1_fires_every_turn() -> None: + cfg = _on_cfg(k=1) + for fire_idx in range(1, 20): + assert cadence.should_fire(fire_idx, cfg) is True + + +# --- load_cadence_config (TOML parser) ------------------------------------ + + +def _write_toml(dirpath: Path, body: str) -> None: + (dirpath / cadence.CONFIG_FILENAME).write_text(textwrap.dedent(body)) + + +def test_load_config_missing_file_returns_defaults(tmp_path: Path) -> None: + cfg = cadence.load_cadence_config(start=tmp_path) + assert cfg == cadence.CadenceConfig() + + +def test_load_config_missing_section_returns_defaults(tmp_path: Path) -> None: + _write_toml(tmp_path, """ + [retrieval] + posterior_weight = 0.5 + """) + cfg = cadence.load_cadence_config(start=tmp_path) + assert cfg == cadence.CadenceConfig() + + +def test_load_config_full_section(tmp_path: Path) -> None: + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p1_every_k_turns" + k = 20 + """) + cfg = cadence.load_cadence_config(start=tmp_path) + assert cfg.enabled is True + assert cfg.policy == cadence.POLICY_P1_EVERY_K_TURNS + assert cfg.k == 20 + + +def test_load_config_partial_section_uses_defaults_for_missing_fields( + tmp_path: Path, +) -> None: + _write_toml(tmp_path, """ + [cadence] + enabled = true + """) + cfg = cadence.load_cadence_config(start=tmp_path) + assert cfg.enabled is True + assert cfg.policy == cadence.DEFAULT_POLICY # not flipped by enabled + assert cfg.k == cadence.DEFAULT_K + + +def test_load_config_malformed_toml_returns_defaults( + tmp_path: Path, capsys: pytest.CaptureFixture[str], +) -> None: + (tmp_path / cadence.CONFIG_FILENAME).write_text("[[cadence broken") + cfg = cadence.load_cadence_config(start=tmp_path) + assert cfg == cadence.CadenceConfig() + err = capsys.readouterr().err + assert "malformed TOML" in err + + +def test_load_config_wrong_typed_enabled_ignored( + tmp_path: Path, capsys: pytest.CaptureFixture[str], +) -> None: + _write_toml(tmp_path, """ + [cadence] + enabled = "yes" + k = 10 + """) + cfg = cadence.load_cadence_config(start=tmp_path) + # `enabled = "yes"` is wrong type (we require bool); falls back. + # k=10 still reads correctly. + assert cfg.enabled is False + assert cfg.k == 10 + err = capsys.readouterr().err + assert "expected bool" in err + + +def test_load_config_unknown_policy_ignored( + tmp_path: Path, capsys: pytest.CaptureFixture[str], +) -> None: + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p99_warp_drive" + """) + cfg = cadence.load_cadence_config(start=tmp_path) + assert cfg.policy == cadence.DEFAULT_POLICY + err = capsys.readouterr().err + assert "p99_warp_drive" not in err # the bad value isn't echoed + assert cadence.POLICY_P1_EVERY_K_TURNS in err # but valid options are + + +def test_load_config_non_positive_k_ignored( + tmp_path: Path, capsys: pytest.CaptureFixture[str], +) -> None: + _write_toml(tmp_path, """ + [cadence] + k = 0 + """) + cfg = cadence.load_cadence_config(start=tmp_path) + assert cfg.k == cadence.DEFAULT_K + err = capsys.readouterr().err + assert "expected positive int" in err + + +def test_load_config_k_as_bool_rejected( + tmp_path: Path, capsys: pytest.CaptureFixture[str], +) -> None: + # bool is a subclass of int in Python; we reject it explicitly to + # avoid `k = true` silently meaning k=1. + _write_toml(tmp_path, """ + [cadence] + k = true + """) + cfg = cadence.load_cadence_config(start=tmp_path) + assert cfg.k == cadence.DEFAULT_K + err = capsys.readouterr().err + assert "expected positive int" in err + + +def test_load_config_walks_up_parent_dirs(tmp_path: Path) -> None: + # Write TOML at tmp_path, start the walk from a nested child. + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p1_every_k_turns" + k = 7 + """) + child = tmp_path / "a" / "b" / "c" + child.mkdir(parents=True) + cfg = cadence.load_cadence_config(start=child) + assert cfg.enabled is True + assert cfg.k == 7 + + +# --- Resolvers (env > kwarg > TOML > default) ----------------------------- + + +def test_resolve_enabled_default_false( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(cadence.ENV_CADENCE_ENABLED, raising=False) + assert cadence.resolve_cadence_enabled(start=tmp_path) is False + + +def test_resolve_enabled_env_wins_over_toml( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + _write_toml(tmp_path, """ + [cadence] + enabled = true + """) + monkeypatch.setenv(cadence.ENV_CADENCE_ENABLED, "0") + # TOML says true, env says falsy → env wins. + assert cadence.resolve_cadence_enabled(start=tmp_path) is False + + +def test_resolve_enabled_kwarg_wins_over_toml( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + _write_toml(tmp_path, """ + [cadence] + enabled = true + """) + monkeypatch.delenv(cadence.ENV_CADENCE_ENABLED, raising=False) + # Explicit kwarg overrides TOML. + assert cadence.resolve_cadence_enabled(explicit=False, start=tmp_path) is False + + +def test_resolve_enabled_env_beats_kwarg( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv(cadence.ENV_CADENCE_ENABLED, "1") + # Env beats kwarg (operator override wins over caller-supplied value). + assert cadence.resolve_cadence_enabled(explicit=False, start=tmp_path) is True + + +def test_resolve_enabled_unparseable_env_falls_through( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv(cadence.ENV_CADENCE_ENABLED, "maybe") + _write_toml(tmp_path, """ + [cadence] + enabled = true + """) + # Unparseable env returns None from the env reader; TOML wins. + assert cadence.resolve_cadence_enabled(start=tmp_path) is True + + +def test_resolve_k_default_15( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(cadence.ENV_CADENCE_K, raising=False) + assert cadence.resolve_cadence_k(start=tmp_path) == cadence.DEFAULT_K + + +def test_resolve_k_env_wins( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv(cadence.ENV_CADENCE_K, "30") + _write_toml(tmp_path, """ + [cadence] + k = 5 + """) + assert cadence.resolve_cadence_k(start=tmp_path) == 30 + + +def test_resolve_k_env_non_int_falls_through( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv(cadence.ENV_CADENCE_K, "fifteen") + _write_toml(tmp_path, """ + [cadence] + k = 7 + """) + assert cadence.resolve_cadence_k(start=tmp_path) == 7 + + +def test_resolve_k_env_non_positive_falls_through( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv(cadence.ENV_CADENCE_K, "0") + _write_toml(tmp_path, """ + [cadence] + k = 7 + """) + assert cadence.resolve_cadence_k(start=tmp_path) == 7 + + +def test_resolve_policy_default_off( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(cadence.ENV_CADENCE_POLICY, raising=False) + assert cadence.resolve_cadence_policy(start=tmp_path) == cadence.POLICY_OFF + + +def test_resolve_policy_env_wins( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv( + cadence.ENV_CADENCE_POLICY, "p1_every_k_turns", + ) + assert cadence.resolve_cadence_policy(start=tmp_path) == ( + cadence.POLICY_P1_EVERY_K_TURNS + ) + + +def test_resolve_policy_env_unknown_falls_through( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv(cadence.ENV_CADENCE_POLICY, "warp") + _write_toml(tmp_path, """ + [cadence] + policy = "p1_every_k_turns" + """) + assert cadence.resolve_cadence_policy(start=tmp_path) == ( + cadence.POLICY_P1_EVERY_K_TURNS + ) diff --git a/tests/test_hook_stop_cadence.py b/tests/test_hook_stop_cadence.py new file mode 100644 index 000000000..575c986df --- /dev/null +++ b/tests/test_hook_stop_cadence.py @@ -0,0 +1,438 @@ +"""Integration tests for P1 every-K-turns cadence in the Stop hook (#749).""" +from __future__ import annotations + +import io +import json +import textwrap +from pathlib import Path + +import pytest + +from aelfrice import hook +from aelfrice.cadence import ( + CONFIG_FILENAME, + POLICY_OFF, + POLICY_P1_EVERY_K_TURNS, +) + + +# --- Fixtures ------------------------------------------------------------- + + +@pytest.fixture(autouse=True) +def _isolate_env(monkeypatch: pytest.MonkeyPatch) -> None: + # Ensure no inherited env tilts cadence on/off accidentally. + for var in ( + "AELFRICE_CADENCE_ENABLED", + "AELFRICE_CADENCE_POLICY", + "AELFRICE_CADENCE_K", + "AELF_AUTOLOCK_CORRECTIONS", + ): + monkeypatch.delenv(var, raising=False) + + +def _set_db(monkeypatch: pytest.MonkeyPatch, db: Path) -> None: + monkeypatch.setenv("AELFRICE_DB", str(db)) + + +def _seed_db(db: Path) -> None: + # Touch the DB so :func:`_open_store` succeeds (the file must exist + # for the Stop hook's existing lock-prompt path; cadence has its + # own `p.exists()` guard). + from aelfrice.store import MemoryStore + MemoryStore(str(db)).close() + + +def _write_toml(repo: Path, body: str) -> None: + (repo / CONFIG_FILENAME).write_text(textwrap.dedent(body)) + + +def _write_ring_state(state_dir: Path, session_id: str, next_fire_idx: int) -> None: + state_dir.mkdir(parents=True, exist_ok=True) + payload = { + "session_id": session_id, + "ring": [], + "ring_max": 200, + "next_fire_idx": next_fire_idx, + "evicted_total": 0, + } + (state_dir / "session_injected_ids.json").write_text(json.dumps(payload)) + + +def _stop_payload(session_id: str, cwd: Path) -> str: + return json.dumps({"session_id": session_id, "cwd": str(cwd)}) + + +def _stub_rebuild_and_format(monkeypatch: pytest.MonkeyPatch) -> list[dict]: + """Replace `_rebuild_and_format` with a recorder; return the call list.""" + calls: list[dict] = [] + + def _stub(recent, token_budget, **kwargs): # type: ignore[no-untyped-def] + calls.append({ + "n_recent": len(recent), + "token_budget": token_budget, + **kwargs, + }) + return "" + + monkeypatch.setattr(hook, "_rebuild_and_format", _stub) + return calls + + +def _stub_read_recent(monkeypatch: pytest.MonkeyPatch, n_turns: int = 1) -> None: + """Replace `_read_recent_for_pre_compact` to return a canned list. + + Cadence needs at least one recent turn to proceed past the + empty-transcript guard; tests should not depend on a real + transcript file. + """ + from aelfrice.context_rebuilder import RecentTurn + + canned = [ + RecentTurn(role="user", text=f"turn-{i}") + for i in range(n_turns) + ] + monkeypatch.setattr( + hook, "_read_recent_for_pre_compact", lambda _payload, _n: canned, + ) + + +# --- Tests ---------------------------------------------------------------- + + +def test_cadence_disabled_by_default( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """No [cadence] section + no env → cadence never fires.""" + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + _write_ring_state(db.parent, "sess-A", next_fire_idx=15) + calls = _stub_rebuild_and_format(monkeypatch) + + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + + assert rc == 0 + assert calls == [], "cadence should be inert when disabled" + assert "cadence checkpoint" not in serr.getvalue() + + +def test_cadence_enabled_policy_off_does_not_fire( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + _write_ring_state(db.parent, "sess-A", next_fire_idx=15) + _write_toml(tmp_path, """ + [cadence] + enabled = true + # policy defaults to "off" when unset, even with enabled=true + """) + calls = _stub_rebuild_and_format(monkeypatch) + + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + + assert rc == 0 + assert calls == [] + assert "cadence checkpoint" not in serr.getvalue() + + +def test_cadence_p1_fires_at_multiples_of_k( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p1_every_k_turns" + k = 15 + """) + _stub_read_recent(monkeypatch) + calls = _stub_rebuild_and_format(monkeypatch) + + for fire_idx, expected_fired in [ + (1, False), (14, False), (15, True), (16, False), + (29, False), (30, True), (45, True), + ]: + calls.clear() + _write_ring_state(db.parent, "sess-A", next_fire_idx=fire_idx) + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + assert rc == 0 + if expected_fired: + assert len(calls) == 1, f"fire_idx={fire_idx}: expected fire" + assert f"fire_idx={fire_idx}" in serr.getvalue() + assert "cadence checkpoint fired" in serr.getvalue() + else: + assert calls == [], f"fire_idx={fire_idx}: expected no fire" + assert "cadence checkpoint" not in serr.getvalue() + + +def test_cadence_fire_idx_zero_does_not_fire( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """Cold-start guard: fire_idx=0 must not trip cadence even though 0%k==0.""" + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p1_every_k_turns" + k = 15 + """) + _write_ring_state(db.parent, "sess-A", next_fire_idx=0) + _stub_read_recent(monkeypatch) + calls = _stub_rebuild_and_format(monkeypatch) + + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + + assert rc == 0 + assert calls == [] + assert "cadence checkpoint" not in serr.getvalue() + + +def test_cadence_missing_ring_state_skips_cadence( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """No ring sentinel → no fire_idx → cadence is a no-op.""" + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p1_every_k_turns" + k = 15 + """) + # NB: no _write_ring_state call. + calls = _stub_rebuild_and_format(monkeypatch) + + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + + assert rc == 0 + assert calls == [] + + +def test_cadence_session_mismatch_skips_cadence( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """Ring written under sess-B but Stop fires for sess-A → no cadence.""" + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p1_every_k_turns" + k = 15 + """) + _write_ring_state(db.parent, "sess-B", next_fire_idx=15) + calls = _stub_rebuild_and_format(monkeypatch) + + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + + assert rc == 0 + assert calls == [] + assert "cadence checkpoint" not in serr.getvalue() + + +def test_cadence_empty_recent_skips_fire( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """Cadence is gated on having a recent-turns slice; empty → no fire.""" + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p1_every_k_turns" + k = 15 + """) + _write_ring_state(db.parent, "sess-A", next_fire_idx=15) + # No _stub_read_recent — default returns [] when transcript is missing. + monkeypatch.setattr( + hook, "_read_recent_for_pre_compact", lambda _payload, _n: [], + ) + calls = _stub_rebuild_and_format(monkeypatch) + + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + + assert rc == 0 + assert calls == [] + + +def test_cadence_env_override_beats_toml( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """TOML says enabled=false; env flips it on. Cadence fires.""" + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + _write_toml(tmp_path, """ + [cadence] + enabled = false + policy = "p1_every_k_turns" + k = 15 + """) + monkeypatch.setenv("AELFRICE_CADENCE_ENABLED", "1") + _write_ring_state(db.parent, "sess-A", next_fire_idx=15) + _stub_read_recent(monkeypatch) + calls = _stub_rebuild_and_format(monkeypatch) + + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + + assert rc == 0 + assert len(calls) == 1 + assert "cadence checkpoint fired" in serr.getvalue() + + +def test_cadence_fires_even_with_no_lock_candidates( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """Regression: pre-#749 the Stop hook early-returned on empty + lock-candidate sets, which would have suppressed cadence too. The + restructured stop() must run cadence regardless.""" + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + # NB: zero beliefs in the store → zero lock candidates. + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p1_every_k_turns" + k = 15 + """) + _write_ring_state(db.parent, "sess-A", next_fire_idx=15) + _stub_read_recent(monkeypatch) + calls = _stub_rebuild_and_format(monkeypatch) + + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + + assert rc == 0 + assert len(calls) == 1, "cadence must fire when policy says so, even with no lock candidates" + + +def test_cadence_emits_policy_and_k_in_stderr_line( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """The stderr observability line includes policy + k for debugging.""" + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p1_every_k_turns" + k = 7 + """) + _write_ring_state(db.parent, "sess-A", next_fire_idx=14) + _stub_read_recent(monkeypatch) + _stub_rebuild_and_format(monkeypatch) + + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + + assert rc == 0 + out = serr.getvalue() + assert "policy=p1_every_k_turns" in out + assert "k=7" in out + assert "fire_idx=14" in out + + +def test_cadence_does_not_break_existing_lock_prompt( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """When both lock-prompt candidates exist AND cadence fires, + the stderr stream carries both outputs and rc is still 0.""" + from aelfrice.models import ( + BELIEF_CORRECTION, + LOCK_NONE, + Belief, + ) + from aelfrice.store import MemoryStore + + db = tmp_path / "memory.db" + _set_db(monkeypatch, db) + _seed_db(db) + # Insert one correction-class lock candidate. + s = MemoryStore(str(db)) + try: + s.insert_belief(Belief( + id="b1", + content="user asserted X about Y", + content_hash="h_b1", + alpha=1.0, beta=1.0, + type=BELIEF_CORRECTION, + lock_level=LOCK_NONE, + locked_at=None, + created_at="2026-01-01T00:00:00Z", + last_retrieved_at=None, + session_id="sess-A", + origin="user_stated", + )) + finally: + s.close() + _write_toml(tmp_path, """ + [cadence] + enabled = true + policy = "p1_every_k_turns" + k = 15 + """) + _write_ring_state(db.parent, "sess-A", next_fire_idx=15) + _stub_read_recent(monkeypatch) + calls = _stub_rebuild_and_format(monkeypatch) + + serr = io.StringIO() + rc = hook.stop( + stdin=io.StringIO(_stop_payload("sess-A", tmp_path)), + stderr=serr, + ) + + assert rc == 0 + out = serr.getvalue() + assert hook.STOP_PROMPT_OPEN_TAG in out # lock-prompt block emitted + assert "cadence checkpoint fired" in out # cadence emitted + assert len(calls) == 1