diff --git a/CHANGELOG/v4.md b/CHANGELOG/v4.md index 3509a6654..524ebca07 100644 --- a/CHANGELOG/v4.md +++ b/CHANGELOG/v4.md @@ -41,6 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **LIMITATIONS claimed a residual exposure-as-evidence path that has not existed since #1162 ([#1267](https://github.com/robotrocketscience/aelfrice/issues/1267)).** The sharp-edges entry said retrieval "still enqueues each surfaced belief" and that `aelf sweep-feedback` "applies a small alpha bump (default +0.05)", citing [#1091](https://github.com/robotrocketscience/aelfrice/issues/1091) as having only *flagged* the sweep for audit-only treatment. All three were stale: the sweeper has written nothing since [#1162](https://github.com/robotrocketscience/aelfrice/issues/1162) (it classifies what it *would* have applied and returns `mutated=False`), and the enqueue inside `retrieve()` is gated on `AELFRICE_IMPLICIT_FEEDBACK_ENQUEUE`, default off. A reader auditing where their posteriors come from was pointed at a mutation path that no longer fires. New `benchmarks/posterior_channel_audit.py` drives all three `apply_feedback` routes against a fresh store and fails non-zero if any default moves, so the entry cannot go stale silently again. - **An explicit `token_budget=2400` was silently downgraded to 2000 when the entity index was off ([#1271](https://github.com/robotrocketscience/aelfrice/issues/1271)).** `retrieve_with_tiers` declared the budget as a `None` sentinel meaning "caller did not ask", resolved it to a concrete int, then reconstructed the intent downstream as `token_budget != DEFAULT_TOKEN_BUDGET` — a different predicate that agrees most of the time and is wrong for exactly the caller who passes the default on purpose. `2399` and `2401` were honoured; `2400` was not, so the behaviour was discontinuous at precisely the default. It invalidated a measurement on [#1269](https://github.com/robotrocketscience/aelfrice/issues/1269) before it was found, where a 16.7% budget cut on one arm was read as a lane-precedence effect. `resolve_token_budget_with_provenance` now returns `(budget, defaulted)` and `resolve_token_budget` delegates to it so the precedence cannot drift; env and TOML both count as expressing a preference, and the legacy path stays for callers who expressed none. `retrieve()` resolves the budget before delegating, so it passes the provenance down explicitly — without that thread every no-argument call would have been promoted from 2000 to 2400, breaking the v1.2 parity the branch exists for. - **The multi-hop benchmark's ablation was confounded by the same predicate ([#1271](https://github.com/robotrocketscience/aelfrice/issues/1271)).** `benchmark.run_multihop_benchmark` passes an explicit `DEFAULT_TOKEN_BUDGET` and varies `entity_index_enabled` per arm, so the control arm (`multihop_l1_only`, index off) hit the legacy branch and ran at **2000** while both treatment arms ran at **2400**. Every `l1_l25 - l1_only` delta the harness produced attributed that 16.7% budget gap to the L2.5 entity lane. Fixed by the same change - all three arms now run at one budget. No file in `benchmarks/results/` records the multihop arms, so nothing on disk needs restating, but multihop arm deltas must not be pooled across this change. diff --git a/benchmarks/posterior_channel_audit.py b/benchmarks/posterior_channel_audit.py new file mode 100644 index 000000000..01d2514a1 --- /dev/null +++ b/benchmarks/posterior_channel_audit.py @@ -0,0 +1,246 @@ +"""#1267 posterior-channel audit — which channels move a belief posterior, +in which direction, at default settings. + +#1267 states an asymmetry: *"The system has an automatic, evidence-driven +channel that moves posteriors up, and none that moves them down."* This +enumerates every `apply_feedback` route on the production path and drives +each one against a fresh in-memory store, so the claim is settled by +observed alpha/beta rather than by reading constants. + +The distinction that matters is **resolver default vs. call-site +behaviour**. #1267 quotes `HOOK_RETRIEVAL_VALENCE = 0.1` and the +`apply_feedback` call in `record_retrieval`, which are both real — but the +call passes `update_posterior=_exposure_updates_posterior()`, and that +resolver has defaulted to False since #1086. Quoting the constant without +the gate reads as an always-on channel. + +Three channels are checked: + + 1. **Hook retrieval exposure** (`hook_search.record_retrieval`, + `HOOK_RETRIEVAL_VALENCE = +0.1`). Fires on the hot path for every + belief in every pack. Gated by `AELFRICE_EXPOSURE_UPDATES_POSTERIOR`, + default off (#1086) — audit row written, posterior untouched. + + 2. **Sentiment-from-prose** (`sentiment_feedback.apply_sentiment_to_pending`, + wired into `UserPromptSubmit` at #606). Regex-matches the user's prose + and distributes the signal over the previous turn's pack. Emits + **negative** valence, so this is an automatic down-channel. Opt-in via + `[feedback] sentiment_from_prose`, default off. + + 3. **Deferred-feedback sweeper** (`deferred_feedback.sweep_deferred_feedback`). + Audit-only since #1162 — classifies what it *would* have applied and + writes nothing. Its enqueue side is also default off. + +No live store is read and no belief content is emitted: every belief here +is synthetic. Ambient `AELFRICE_*` variables are cleared at import so a +developer's own opt-ins cannot change the reported defaults. + +Run: `python benchmarks/posterior_channel_audit.py` +Exits non-zero if any channel's observed behaviour departs from the table +above, so this doubles as a regression guard on the defaults. +""" +from __future__ import annotations + +import os +import sys + +# Clear ambient opt-ins BEFORE importing aelfrice: several of these +# resolvers read the environment at import time or per call, and the +# whole point of this script is to report the *default* posture. +_CLEARED = sorted(k for k in os.environ if k.startswith("AELFRICE_")) +for _k in _CLEARED: + del os.environ[_k] + +from aelfrice.deferred_feedback import ( # noqa: E402 + is_enqueue_on_retrieve_enabled, + sweep_deferred_feedback, +) +from aelfrice.hook_search import ( # noqa: E402 + HOOK_RETRIEVAL_VALENCE, + record_retrieval, +) +from aelfrice.models import BELIEF_FACTUAL, LOCK_NONE, Belief # noqa: E402 +from aelfrice.sentiment_feedback import ( # noqa: E402 + BASE_VALENCE, + ESCALATED_NEGATIVE_VALENCE, + apply_sentiment_to_pending, + detect_sentiment, + is_enabled as sentiment_is_enabled, +) +from aelfrice.store import MemoryStore # noqa: E402 + +ENV_EXPOSURE = "AELFRICE_EXPOSURE_UPDATES_POSTERIOR" + + +def _belief(bid: str) -> Belief: + return Belief( + id=bid, + content=f"synthetic belief {bid}", + content_hash=f"h_{bid}", + alpha=1.0, + beta=1.0, + type=BELIEF_FACTUAL, + lock_level=LOCK_NONE, + locked_at=None, + created_at="2026-07-31T00:00:00Z", + last_retrieved_at=None, + ) + + +def _seed(bid: str) -> MemoryStore: + store = MemoryStore(":memory:") + store.insert_belief(_belief(bid)) + return store + + +def _ab(store: MemoryStore, bid: str) -> tuple[float, float]: + belief = store.get_belief(bid) + return (belief.alpha, belief.beta) + + +def channel_1_exposure() -> list[str]: + """Hook retrieval exposure. Default: audit row, no posterior move.""" + failures: list[str] = [] + print("=" * 72) + print(f"CHANNEL 1 — hook retrieval exposure (valence +{HOOK_RETRIEVAL_VALENCE})") + print("=" * 72) + + for env_value in (None, "1"): + os.environ.pop(ENV_EXPOSURE, None) + if env_value is not None: + os.environ[ENV_EXPOSURE] = env_value + store = _seed("b1") + before = _ab(store, "b1") + written = record_retrieval(store, [store.get_belief("b1")]) + after = _ab(store, "b1") + audit_rows = int(store.count_feedback_events("b1")) + store.close() + + label = "DEFAULT (unset)" if env_value is None else f"{ENV_EXPOSURE}=1" + moved = before != after + print(f" {label:38s} rows={written} audit={audit_rows} " + f"a/b {before} -> {after} moved={moved}") + + if env_value is None: + if moved: + failures.append("exposure moved the posterior at DEFAULT") + if audit_rows != 1: + failures.append("exposure wrote no audit row at DEFAULT") + elif after[0] != before[0] + HOOK_RETRIEVAL_VALENCE: + failures.append("exposure did not apply +valence when opted in") + + os.environ.pop(ENV_EXPOSURE, None) + print(" => automatic UP channel is OFF by default (#1086); " + "opting in restores it.") + return failures + + +def channel_2_sentiment() -> list[str]: + """Sentiment-from-prose. An automatic DOWN channel, opt-in.""" + failures: list[str] = [] + print() + print("=" * 72) + print("CHANNEL 2 — sentiment-from-prose (UserPromptSubmit, #193/#606)") + print("=" * 72) + + enabled = sentiment_is_enabled({}) + print(f" is_enabled(default config) = {enabled}") + if enabled: + failures.append("sentiment-from-prose is enabled by default") + + signal = detect_sentiment("no that's wrong") + if signal is None or signal.valence >= 0: + failures.append("no negative sentiment signal detected for a correction") + print(" detect_sentiment('no that's wrong') -> None") + return failures + print(f" detect_sentiment(\"no that's wrong\") -> " + f"({signal.sentiment}, {signal.valence})") + + store = _seed("b2") + before = _ab(store, "b2") + apply_sentiment_to_pending( + store=store, signal=signal, pending_belief_ids=["b2"], + ) + plain = _ab(store, "b2") + apply_sentiment_to_pending( + store=store, signal=signal, pending_belief_ids=["b2"], escalated=True, + ) + escalated = _ab(store, "b2") + store.close() + + print(f" negative signal a/b {before} -> {plain} " + f"moved_down={plain[1] > before[1]}") + print(f" escalated negative a/b {plain} -> {escalated}") + print(f" magnitude vs exposure: " + f"{BASE_VALENCE / HOOK_RETRIEVAL_VALENCE:.0f}x .. " + f"{ESCALATED_NEGATIVE_VALENCE / HOOK_RETRIEVAL_VALENCE:.0f}x") + + if plain[1] <= before[1]: + failures.append("negative sentiment did not move the posterior down") + if escalated[1] <= plain[1]: + failures.append("escalated negative did not exceed the base negative") + + print(" => an automatic DOWN channel EXISTS and is wired to the hot " + "path; it is opt-in, exactly as the UP channel is.") + return failures + + +def channel_3_sweeper() -> list[str]: + """Deferred-feedback sweeper. Audit-only since #1162.""" + failures: list[str] = [] + print() + print("=" * 72) + print("CHANNEL 3 — deferred-feedback sweeper (#191, audit-only since #1162)") + print("=" * 72) + + enqueue_on = is_enqueue_on_retrieve_enabled() + print(f" is_enqueue_on_retrieve_enabled(default) = {enqueue_on}") + if enqueue_on: + failures.append("retrieval enqueues exposures by default") + + store = _seed("b3") + before = _ab(store, "b3") + result = sweep_deferred_feedback(store) + after = _ab(store, "b3") + store.close() + + print(f" sweep mutated={result.mutated} " + f"alpha_withheld={result.alpha_withheld} " + f"would_apply={result.would_apply}") + print(f" a/b {before} -> {after} moved={before != after}") + + if result.mutated or before != after: + failures.append("the sweeper mutated a posterior") + + print(" => no residual exposure-as-evidence path: the sweep writes " + "nothing and the enqueue is off.") + return failures + + +def main() -> int: + if _CLEARED: + print(f"(cleared ambient: {', '.join(_CLEARED)})\n") + + failures: list[str] = [] + failures += channel_1_exposure() + failures += channel_2_sentiment() + failures += channel_3_sweeper() + + print() + print("=" * 72) + print("VERDICT") + print("=" * 72) + print(" At default settings NO automatic channel moves a belief") + print(" posterior in EITHER direction. Both automatic channels are") + print(" opt-in: exposure (up) and sentiment-from-prose (down).") + + if failures: + print() + for failure in failures: + print(f" FAIL: {failure}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/user/LIMITATIONS.md b/docs/user/LIMITATIONS.md index 054f5a62c..bd9d2ee65 100644 --- a/docs/user/LIMITATIONS.md +++ b/docs/user/LIMITATIONS.md @@ -37,7 +37,7 @@ The default retrieval mode (recall, not audit) is correctly served by latest-ser - **Locks are durable.** Fresh lock = `(α, β) = (9.0, 0.5)`. Passive feedback (`aelf feedback harmful`, sentiment-derived turn valence, retrieval exposure, valence propagation) does not move a lock — enforced in `apply_feedback` and in the deferred sweeper since [#1168](https://github.com/robotrocketscience/aelfrice/issues/1168); the event is still recorded in `feedback_history`, and the CLI tells you it was recorded but not applied. `aelf confirm` is the exception: it is an explicit affirmation, not passive feedback, and still moves a locked posterior. Before #1168 the floor lived only in the (dead) `decay()` path, so passive feedback did move locks — v3.2.0 [#814](https://github.com/robotrocketscience/aelfrice/issues/814) removed the v2.x `demotion_pressure` / auto-demote machinery (v3.1.0 as released still contained it, see #833). Change a lock with `aelf unlock` / `aelf delete`, or re-lock the corrected statement; `aelf demote ` drops it immediately. - **Contradiction detection is partial.** Contradiction **resolution** (`aelf resolve`, the tie-breaker that picks a winner given a `CONTRADICTS` edge) ships; contradiction **detection** (the post-insert semantic-divergence detector that creates those edges automatically) is deferred. Until detection lands, contradiction-flagging surfaces only on edges produced by the triple extractor's six explicit relation-family regexes. Plus the `/aelf:reason` `VERDICT=CONTRADICTORY` path emits structured impasses at query time — but only over persisted `CONTRADICTS` edges. The edge-free query-time surface is the opt-in `AELF_SHOW_CONFLICTS=1` slot-conflict flag on `aelf search` (#938, v3.5.0), which marks hits whose value-slots collide with a locked belief. -- **Natural-language sentiment is not captured automatically.** Saying "ok good" or "no that's wrong" in chat does **not** strengthen or weaken the beliefs the agent just used. Explicit `aelf feedback used|harmful` (CLI) or the equivalent MCP `aelf:feedback` call remains the high-confidence channel. Retrieval **exposure** is not a posterior signal by default: since #1086 (v4.0) surfacing a belief is audit-only (`AELFRICE_EXPOSURE_UPDATES_POSTERIOR`, default off), logged for the recurrence axis but leaving α/β untouched — a retrieval is exposure, not endorsement. The one residual exposure-as-evidence path is the v1.6 (#191) deferred-feedback sweeper: retrieval still enqueues each surfaced belief, and the *manual* `aelf sweep-feedback` pass applies a small alpha bump (default +0.05) after a grace window (default 30 minutes) unless an explicit signal arrived first (#1091 flagged this sweep for the same audit-only treatment). That is an exposure-based signal, not a sentiment-from-prose signal: the user's affect words are not parsed — unless you opt in to the sentiment-from-prose detector (`[feedback] sentiment_from_prose = true` in `.aelfrice.toml`, default off, #193/#606), which regex-matches short affect phrases and distributes the signal across the previous turn's retrieved beliefs. +- **Natural-language sentiment is not captured automatically.** Saying "ok good" or "no that's wrong" in chat does **not** strengthen or weaken the beliefs the agent just used. Explicit `aelf feedback used|harmful` (CLI) or the equivalent MCP `aelf:feedback` call remains the high-confidence channel. Retrieval **exposure** is not a posterior signal by default: since #1086 (v4.0) surfacing a belief is audit-only (`AELFRICE_EXPOSURE_UPDATES_POSTERIOR`, default off), logged for the recurrence axis but leaving α/β untouched — a retrieval is exposure, not endorsement. There is no longer a residual exposure-as-evidence path. The v1.6 ([#191](https://github.com/robotrocketscience/aelfrice/issues/191)) deferred-feedback sweeper used to apply a small alpha bump (default +0.05) after a grace window (default 30 minutes) unless an explicit signal arrived first, but `aelf sweep-feedback` has been **audit-only since [#1162](https://github.com/robotrocketscience/aelfrice/issues/1162)**: it classifies every pending row exactly as the mutating sweeper did and reports what it *would* have applied, writing no `alpha` move, no `feedback_history` row and no queue-status change. The enqueue side is default-off too (`AELFRICE_IMPLICIT_FEEDBACK_ENQUEUE`), so `retrieve()` does not bank rows unless you opt in. The user's affect words are not parsed either — unless you opt in to the sentiment-from-prose detector (`[feedback] sentiment_from_prose = true` in `.aelfrice.toml`, default off, #193/#606), which regex-matches short affect phrases and distributes the signal across the previous turn's retrieved beliefs. - **Confidence drops below 0.5 do not auto-flag.** A belief whose posterior drifts under the prior is not surfaced as a warning. No automatic state change is driven by negative evidence in v3.x — the v2.x demotion-pressure auto-demote was removed at [#814](https://github.com/robotrocketscience/aelfrice/issues/814). To find drifting beliefs, use `aelf speculative --json` (emits per-belief α/β for non-locked beliefs) or query the SQLite store directly (e.g. `SELECT id, alpha, beta FROM beliefs WHERE alpha / (alpha + beta) < 0.5`). - **The organic sink is a rerank modifier, not a posterior decay — it demotes, it does not delete.** #1086 established that with exposure now audit-only, the store lacked an automatic force that pushes low-value "coordination junk" (bare PR/issue numbers, version/branch chatter) *down*. The answer that shipped is the entity-persistence demotion lane (#1096, `[retrieval] use_entity_persist_demote`): a deterministic rank down-weight that sinks candidates grounding only to transient tokens below those grounding to durable entities (file paths, error codes, symbols). It is content-referential, not time-based — a temporal/cold-decay sink was measured empirically inert (the junk is *hot*, not stale). As of **v4.0 it is default-on and live on the production `retrieve()` path** (flipped once #1103 cleared the G2 gate; graduated onto the live hook path by the #1107 cutover). The residual limitation is that it **ranks, it does not delete** — junk still occupies store rows and can resurface when a query's other candidates are weak, and there is no automatic posterior decay or hard GC of stale content. To *find* junk for manual curation use `aelf introspect --only-noise`, and `aelf retire` to soft-delete it. - **Origin trust is a default-off tie-break only.** The origin-priority tie-break (#1089, `[retrieval] use_origin_tiebreak`, **default off**) lets a higher-trust origin win *ties* on relevance, but it is not a rerank term and never overrides relevance — an origin *rerank lane* was refuted on LoCoMo (#1013), where the real gap was BM25 recall, which reranking cannot fix.