Doenexecutor memory research
← ResearchResearch log

Every entry: the intent, the reasoning and numbers behind it, and its references. Newest first within each phase.

[Previous Phase] Shifting to Oversight (BD-12 to BD-105)

Minimizing the "Operator" tax and scaling human judgment.

A capability nobody used, and the number that was missing (BD-104)
- **Intent:** Memory verification had every piece it needed and had not happened. BD-35 removed the
  human gate from `mark_memory_verified`, `list_memory_for_audit` existed to drive a batch pass,
  and agents.md instructed the executor to run a Consistency Check after every memory hit.
  Measured on production 2026-09-30: **79 of 82** entries in active projects had never been
  verified once, the oldest 122 days old. A standing instruction had roughly four months and
  produced three verifications.

- **Research thinking:**

  _The gap was not authority or capability, it was that nothing carried the number._ This is worth
  separating from the usual shape of these findings. Nothing was gated, nothing was missing, and
  the instruction was correct and already written down. The reason it did not happen is that acting
  on it required an executor to remember a tool existed and choose to call it, at a moment when it
  was doing something else. So the fix is not a new capability — it is putting the count on a
  response the executor is already reading.

  _Which response, and why it matters._ The signal rides on `get_spec`, the call the operating loop
  mandates first. `get_context` was the alternative and was rejected: it is called repeatedly per
  query, so the same count would repeat as noise and get tuned out — which would reproduce the
  original failure in a louder form.

  _Two sub-counts, not one._ `never_verified` (76) and `beyond_window` (3) are different
  situations: nobody has ever checked the entry, versus someone did and it has gone stale.
  Collapsing them into "79 due" would hide that this is an adoption problem rather than a
  re-verification cadence problem, which is the only thing the number is useful for right now.

  _What was deliberately not automated._ Verification itself. Deciding whether a memory entry still
  matches the codebase requires reading the codebase, so no code path stamps `last_verified_at`
  without an executor having checked. A fabricated verification is strictly worse than an
  unverified entry: it removes the row from the queue permanently while leaving the drift
  undetected, and `last_verified_at` is the only thing that makes staleness queryable at all. The
  same asymmetry that governs BD-105's convert/retain floor governs this.

  _Baseline for the criterion, recorded here because there is no metric store._ The spec asked for
  the before/after to be "observable in the build-doen metric store" and "via the project
  dashboard". Neither exists; SQL plus this log is the channel every measured claim in this project
  has used (BD-89, BD-97, BD-101, BD-102). The spec also hardcoded a baseline of 76 measured
  2026-09-29, which had already moved by the time the work started — building to it would have
  recorded a false baseline. Resolved under dec_a7be2125236b.

      BEFORE (production, 2026-09-30, active projects only)
        due ................ 79
        never_verified ..... 76
        beyond_window ....... 3
        oldest_age_days .... 122
        total entries ...... 82

  The AFTER value is deliberately not recorded yet. It requires a real executor pass after this
  ships, and the open question is not whether the count is arithmetically right — a test proves
  that marking K entries moves it by exactly K — but whether its PLACEMENT causes an executor to
  act. Closing the criterion on the arithmetic would assume the thing worth measuring.

- **Key references:** `backend/app/services/conversation.py::spec_enrichment`,
  `backend/app/store/memory.py::count_memory_for_audit`, `docs/spec-contract.md`,
  decision `dec_a7be2125236b`.
Auto-approval is an authoring problem, and the guard on it was dead (BD-105)
- **Intent:** The stated goal was to have far more evidence confirmed by Jev and less by a human.
  The obvious lever is the confidence threshold. Measuring first showed that is the wrong lever
  and would have made things worse.

- **Research thinking:**

  _The rate is decided when a spec is authored, not when Jev votes._ Over all 712 confirmed
  criteria: 310 of 630 verified were auto-approved — 49% — but split by `verify.kind` the picture
  is stark. `test` 71%, `behavior` 22%, `metric` 20%, `human_judgment` **0%**. Not "low": zero,
  ever, because BD-61's gate forbids the reviewer from auto-approving that kind. 92 criteria — 13%
  of everything — were guaranteed human work the moment someone picked the kind.

  Checking BD-101 and BD-102's own submissions made the mechanism concrete: 6 of their 9
  non-approvals were predetermined before Jev saw any evidence. Two were `human_judgment`. Four
  specified a post-deploy observation inside a spec whose scope excluded deploying — those cannot
  be closed at all, so they do not merely need a human, they stall. Only 2-3 were genuine reviewer
  uncertainty, and one of those was a 51/49 coin-flip caused by a verify detail naming a test
  harness the build reasonably did not use.

  _The root cause was one line of rubric._ `prompts/classification-jev.txt` — the shaping
  self-review pass, the one place that could have caught a mis-kinded criterion — said: "An item
  with verify_kind == "human_judgment" is inherently verifiable — never mark it not_confident
  solely for that." True about verifiability, wrong about cost: it instructed the only available
  detector to stop looking at the largest source of permanent human work. Replaced with rules 2a
  (mis-kinded human_judgment) and 2b (verification the initiative's scope cannot deliver).

  _Two wrong turns while building the audit, both the same shape as the bug being fixed._ The
  first triage was keyword-based. It classified "The Advisor pushes back when it disagrees with a
  proposed approach" as CONVERT because the text contained "is present", and a VPC deployment
  walkthrough as CONVERT because it mentioned "endpoint". Keyword vocabulary tracks SUBJECT MATTER;
  the real question is the FORM of the verdict. Switched to a Jev call per criterion, which
  re-judged both as RETAIN at 99% and 75%.

  Then Jev itself returned CONVERT at 10% and 35% confidence on some rows — near-coin-flips
  recommending that human verification be _removed_. Its own rubric says "when you cannot tell, say
  RETAIN"; trusting a model to self-police a tie was the mistake. `CRITERIA_AUDIT_CONVERT_CONFIDENCE`
  (0.50) now enforces it numerically, and deliberately in one direction only: low confidence can
  hold a CONVERT back but never promote a RETAIN, because an unnecessary human check costs minutes
  while a wrongly converted criterion is machine-verified forever and its false approval is
  invisible. That moved 9 of 82 rows; final audit 32 CONVERT / 50 RETAIN.

  _The finding that matters most, and it was incidental._ Running the false-approval eval — the
  thing agents.md invariant 9 names as what governs the auto-approval judge — revealed it has been
  broken since **BD-95**. `_apply_assessments` became a 2-tuple when the 3-way verdict collapsed to
  binary; the eval still unpacked three values and raised `ValueError` before reaching a single
  assertion. Nothing surfaced it because evals are opt-in and outside default CI. So the one guard
  against false approvals was dead for the entire period Jev's remit was being widened — BD-90,
  BD-95, BD-97, BD-101 and BD-102 all shipped behind a safety check that could not run. Repaired
  under dec_f49b98283d41. The generalisable point is not the typo: **a guard that is opt-in is a
  guard you will discover is broken by accident, years later, while relying on it.**

  _What was deliberately NOT done._ `JEV_AUTO_APPROVE_CONFIDENCE` was not touched. The ask was more
  automation; the safe form of that is fewer criteria that are _structurally_ human, not a bolder
  judge. Those pull opposite ways on the one risk nothing reveals. And ~45 of the 82 audited
  criteria are genuinely subjective — UI quality, prose, "was this the right call" — and are
  correctly human forever.

- **Key references:** `backend/app/prompts/classification-jev.txt` (rules 2a/2b),
  `backend/app/prompts/shaping.txt`, `backend/app/audit_criteria_kinds.py`,
  `backend/tests/evals/test_jev_reviewer_eval.py`, decision `dec_f49b98283d41`.
Two correct decisions that composed into a dead pipeline (BD-102)
- **Intent:** BD-101 made a confirmed consolidation the only route into the citable tier, which
  moved the dream pass from housekeeping onto the critical path: consolidation became the sole
  supply of citable guidance. Measuring that supply is what produced this initiative. Across
  fifteen months of production `llm_cost_log`: `heuristic_admission` had 159 calls whose first and
  last were **the same day**, `heuristic_generalization` had **one**, and `merge_verdict` had
  **none at all**. Ten confirmed consolidations existed in total — one in June, nine in a single
  September burst — every one of them confirmed by hand.

- **Research thinking:**

  _Two bugs, and only one of them was the obvious one._ The scheduler was written
  `while True: sleep(interval); sweep()`. The next-run time therefore existed only as a pending
  `asyncio.sleep(86400)` inside one process, and every deploy discarded it and started a fresh
  24-hour wait. A service that restarts more often than daily never reaches the end of its first
  sleep. That explains why the pass had run on one day, and the fix is to persist dueness
  (`projects.last_swept_at`) and check it on startup rather than count down in memory.

  But fixing the scheduler would **not** have made `merge_verdict` fire, and that is the more
  interesting finding. Step 4 received only the proposals steps 2–3 had just created. Separately,
  the gardener refuses to re-propose a cluster that already has a pending proposal — which is
  correct on its own terms, since otherwise every pass would redraft the same merge. Compose the
  two and the verdict step becomes unreachable: a proposal that exists is never in `created`
  again, so a proposal that missed its verdict once could never receive one. The three
  `near_duplicate` proposals pending since 2026-09-14 were not held by the confidence threshold.
  Nothing had ever asked. The pass could have run hourly for a year and they would still be
  pending.

  Neither of those two behaviours is a mistake in isolation. That is the transferable lesson: the
  failure lived in the composition, and no test of either component would have found it. What
  found it was measuring the _output_ — a lifetime call count of zero for a step the docs
  described as running on every pass.

  _Why "no record" is the deeper defect._ Establishing any of this required grouping
  `llm_cost_log` by `purpose` — a cost-accounting table — because the pass returned counts, logged
  them, and persisted nothing. `dream_sweeps` now records every invocation, and the write ordering
  carries the contract: the row opens _before_ the work, so `finished_at IS NULL` means
  interrupted. A record written only on success cannot record a failure to succeed.

  _A bug this initiative introduced and caught._ The first draft of `sweep_project` had an except
  branch whose comment said it left the record open, and which then called `finish_dream_sweep` —
  stamping `finished_at` and advancing `last_swept_at`. A project whose pass _raised_ would have
  been marked swept and skipped for a full interval: a stall created by the code written to report
  stalls. Now split into `fail_dream_sweep`, which records the error and advances nothing. The
  test asserts the project stays due, which is the property that matters rather than the log line.

  _What stays human._ Retirement. Widening step 4 to all pending proposals means `retire` rows
  reach it, so the exclusion had to be re-verified as a code-level filter on `kind` rather than
  something the confidence threshold happens to catch — otherwise this initiative would have
  quietly automated the one direction BD-97 deliberately reserved for a person.

- **Key references:** `backend/app/services/dream_scheduler.py`,
  `backend/app/services/dream_phase.py` (step 4), `backend/migrations/0058_*.sql`,
  `docs/heuristic-flywheel.md` §7, decision `dec_b67c1ce5b2c6`.
The tier that wasn't: closing the standalone admission door (BD-101)
- **Intent:** BD-97 split the corpus into RAW and CONSOLIDATED so that retrieval could only
  answer from vetted material, then made membership the `admitted_at` column — stamped by Jev on
  any standalone rule it judged sound. A year later, measured against production rather than
  against the code, that door had passed essentially everything. Of `build-doen`'s 142 active
  rules, **137 were admitted singletons**; 4 were merged and 1 generalised. The gate had a 96%
  pass rate. BD-101 makes a confirmed consolidation the only route into the tier.

- **Research thinking:**

  _How a correct argument produced the wrong gate._ BD-97's reasoning was sound and is preserved
  in `docs/design-principles.md`: clusterability is not value. Only 70 of 153 embedded rules fell
  in any cluster at 0.55, and three of build-doen's four cited rules were singletons, including
  its most-cited at 13 citations. Gating on consolidation alone would make the corpus's best
  rules permanently uncitable. That argument was never refuted — it simply only ever weighed one
  side. Nobody measured what admitting singletons cost, because the cost is invisible: every
  flywheel metric stays healthy (37 citations in the last 30 days) while the _vetted_ property
  the entire two-tier design rests on quietly becomes false. A gate at 96% is indistinguishable
  from no gate except by looking at the pass rate, and nothing reported the pass rate —
  `/health/flywheel` carries `eligible_corpus_size` (active, embedded) but no admitted count.

  _The cost, quantified before the change rather than after._ Restricting citability to
  consolidation drops `build-doen` from 142 citable rules to **5**, and strands **42 of its 44
  citations** on rules retrieval can no longer return. Exactly one of the five survivors has ever
  been cited. This was measured first and accepted as the price, not discovered in production
  afterwards.

  _Why the recoverable error was preferred._ The two failures are not symmetric. Excluding a good
  singleton is visible and self-correcting — the rule gets consolidated later and comes back. A
  tier that admits everything is neither: it reports success while providing no selectivity, and
  the longer it runs the more the corpus's apparent health depends on a property that isn't true.
  Between a gate that is too tight and a gate that is not a gate, the first is the error you can
  see and undo.

  _What this makes load-bearing, and the honest trigger to revisit._ Consolidation throughput is
  now the sole supply of citable rules. The merge and generalisation steps move from housekeeping
  onto the critical path, and if the dream pass does not consolidate, retrieval starves rather
  than degrades. With 3 pending merge proposals and 1 generalisation ever created, that supply is
  currently thin — which is the thing to watch and the condition under which this decision
  deserves re-opening.

  _Implementation._ One function: `store/shared.py::consolidated_tier_predicate`, the helper BD-97
  deliberately created so the retrieval filter and the citation guard could not drift apart.
  Changing it changes both. `admitted_at` is not cleared — it still records Jev's standalone
  judgment and simply stops conferring citability — so the change is reversible by reverting the
  function, with no data migration in either direction. The recursive lineage walk BD-97 removed
  for its per-row cost is reinstated, because `replaces` chains mean a consolidated rule whose
  wording is later corrected must not be demoted out of the tier.

  _A process note worth more than the change._ The assessment that produced this was first run
  against a local Postgres that turned out to be a stale copy; the MCP server points at a Railway
  deployment. The local copy showed 1 citation in 30 days and a dead flywheel. Production showed
  37 and a working one. Three specs were drafted and archived on the strength of the wrong
  database. **Measure against the instance the MCP server is actually connected to** — check it
  before trusting any number.

- **Key references:** `docs/design-principles.md` ("Gating citability on consolidation alone"),
  `backend/app/store/shared.py`, `docs/heuristic-flywheel.md`.
Two-tier heuristic corpus: gate citability, then relax recall (BD-97)
- **Intent:** An assessment of the flywheel against the live corpus, rather than against the
  code, found the loop had stopped turning. The machinery was correct and the numbers were not:
  169 active heuristics with **159 never cited**; ten rules holding all 61 citations and two
  holding 29; **one** citation in the last thirty days; **zero** rules ever superseded despite
  seven supersession proposals sitting pending for 13 days; two merges in fifteen months; zero
  generalisation proposals ever created; 132 of 169 rules stuck at `quality_score` 0.667, i.e.
  one confirmed extraction and no usage evidence at all. Sixteen rules had sat NULL-embedded —
  invisible to retrieval, dedup and clustering — for 13 days.

- **Research thinking:**

  _Where precision was._ The corpus was large and unvetted, and retrieval answered that with a
  tight ranked cut: `limit` (8) slots shared by decisions, memory and heuristics. Precision by
  ranking, over material nothing had reviewed. Three defects compounded it, all found by reading
  the ranking code against real embeddings. Heuristics and the other corpora shared one candidate
  window, so a project with 138 heuristics and 11 decisions could return no decision at all. The
  final sort compared a heuristic's _normalised RRF score_ against a decision's _cosine
  similarity_; normalised RRF cannot drop below ~0.89 inside a k=60 window while real cosine
  similarities sit at 0.4–0.6, so every heuristic in the window outranked every decision by
  construction. And the "hybrid" BM25 pass only reranked dense candidates — `sparse_rank_map` was
  consulted for rows already returned and never added one — so it contributed exactly zero
  recall.

  _The inversion._ Ranking cannot vet; a person can. So gate citability on human consolidation
  and let retrieval over the survivors be generous. At ~20 rules a consolidated tier is ~1.6k
  tokens: the window can exceed the tier, which makes ordering across the tier stop mattering and
  retires all three ranking defects for the heuristic branch at once.

  _The finding that changed the design._ The obvious gate — "only generalised rules are citable"
  — is wrong, and only measurement showed it. At the 0.55 generalisation threshold only **70 of
  153** active embedded rules fell inside any cluster. Worse, the 54% excluded is uncorrelated
  with value: three of build-doen's four cited rules were singletons, including
  `heur_92207445814b` at 13 citations, the project's strongest. Similarity to other rules measures
  corpus redundancy, not worth. Hence two doors into the tier — generalised/merged, and promoted
  verbatim — and the invariant restated as _a human vetted this rule_, not _this rule was
  generalised_.

  _What the docs were hiding._ "Every corpus mutation is human-gated" was false and had been from
  the start: extraction auto-confirms `new` and `confirms:` proposals, 219 of the first 231. The
  gate sat on retirement, which had fired zero times. A corpus that only grows with a correction
  path nobody uses is precisely the mechanism behind 159-of-169. The fix is not to gate admission
  — raw rules are useful _as extraction input_ — but to say plainly what is gated, and to give the
  negative signal somewhere to go: a dismissal on a consolidated rule now raises a `retire`
  proposal at the same gate, and dismissal itself works while `building`, not only in `draft`.

  _Two corpora, one set of thresholds._ `freelance-pack` is now a second real corpus and it
  already disagrees with build-doen. build-doen's **maximum** pairwise similarity is **0.7627**,
  below the 0.78 merge threshold — the merge pass is structurally inert on the project it was
  tuned on. At 0.55, freelance-pack chains **21 of its 28** rules into one component, 75% of the
  corpus in a single partition call. Per-project calibration was left out of scope; the numbers
  are recorded in `docs/heuristic-flywheel.md` §10 for whoever takes it.

  _Why the dream pass could not heal itself._ Its only automatic trigger was a learn submission
  that produced new heuristics — the same event that creates rules. So the self-heal step could
  only ever repair rows created _before_ the most recent submission, and a row failing to embed
  during the last submission of a period stayed invisible indefinitely. That is the 16-rows-for-13-
  days figure exactly. Fixed with a plain asyncio sweep over every project
  (`DREAM_PHASE_INTERVAL_SECONDS`, daily), cheap because the pass skips clusters already at the
  gate before any model call.

  _And why none of it was measurable._ `gardener.py` passed `_purpose` but never `_pool`, and both
  providers only write a cost row when both are set — so every merge draft, generalisation draft
  and Jev pre-triage call was invisible in `llm_cost_log`. A 3-member merge draft demonstrably ran
  on 2026-09-14 and left no row. The learn-stage extraction calls passed none of the three. The
  subsystem the docs say to tune had no cost or invocation telemetry at all.

  _Ranking correctness, found by a failing test._ Pinning the cross-corpus fix broke
  `test_bd30_applied_on_top_of_rrf`, which claimed two rules had "equal RRF scores". They never
  had: `ts_rank` scored them 0.157 vs 0.099. The assertion had passed only because the arbitrary
  dense split among two identical embeddings happened to be exactly opposed to the sparse split
  and cancelled it. Both rank windows are now `RANK` rather than `ROW_NUMBER`, so tied scores
  share a rank and the `quality_score` tiebreak is reachable for the equally-relevant rules it
  exists to separate; the fixture was corrected to construct the tie it claims to test.

  _The reversal, inside the same initiative._ The first shape of the tier gate was two human
  doors: confirm each merge, and review the raw tier through a promote-as-is panel. It was
  measured-correct on coverage and wrong on cost, and the human said so as soon as he saw it —
  over half the corpus sits in the raw tier, so the panel asked one person to hold ~80 rules in
  context and re-read them as it grew. That is the same problem the two-tier split exists to
  solve, displaced by one step rather than solved. Both gates moved to Jev: a per-proposal
  consolidation verdict (`prompts/heuristic-merge-verdict-jev.txt`) and a per-rule admission
  judgment (`prompts/heuristic-admission-jev.txt`), each with a confidence threshold, each
  failing closed so a provider outage degrades to the old human-gated behaviour. Two asymmetries
  are deliberate: the consolidation verdict falls through to a human below threshold, so its
  failure mode is a queue; admission has nobody behind it, so both its error directions are
  silent and its threshold sits higher. Retirement stayed human-gated — leaving the corpus is the
  one direction worth a person's attention. Neither threshold is calibrated, which is the largest
  known gap this initiative leaves behind: every other Jev threshold in `config.py` cites a live
  sweep against a gold set, and these two have none.

  _The second cut, prompted by the human asking why any of it needed a proposal._ With the gates
  on Jev, `heuristic_merge_proposals` had four kinds and only two of them could ever be pending —
  `near_duplicate`/`generalization` when Jev was unsure, and `retire` always. `promotion` was a row
  created and instantly confirmed, or created and instantly dismissed. It existed only to keep
  membership derivable, a constraint carried forward from the human-gated design without being
  re-examined when the gate changed. Replaced with two timestamps (migration 0057), deleting ~130
  lines including a recursive CTE that ran per row on every retrieval and every citation. The rule
  worth keeping: derive a fact, store a decision. `origin` is a fact about merge history and stays
  derived; tier membership is a judgment made at a point in time and is a column.

  _Two bugs this cut surfaced, both from reuse patterns rather than logic._ `asyncpg`'s
  `Record.keys()` returns a **tuple_iterator**, not a view, so each `in` check consumes it — the
  pre-existing `_heuristic_from_row` only worked because its membership tests happened to run in
  column order, and adding one out of order silently returned False. And deleting the `promotion`
  branch by index-slicing removed `raise_retire_proposal` along with it; pyright missed it because
  a cross-mixin stub added minutes earlier in `store/base.py` declared the method it had just lost.
  A type stub that exists to satisfy a checker will also hide the thing it describes going missing.

  _Calibrating the admission gate, and three wrong diagnoses._ Enabling it required an eval the
  initiative had shipped without, and building that eval was most of the work. The first live run of
  the gate on the real corpus admitted **0 of 164 rules**, including the project's most-cited. Wrong
  diagnosis one: the threshold (0.75) is too high — plausible, and false, because the _choice_ was
  always `hold` (probabilities pinned at admit 0.38-0.44 for every rule) and no threshold rescues a
  choice. Wrong diagnosis two: the rubric leans toward holding — it did, and rebalancing helped, and
  it still was not the cause. The cause was **batching**: admission asked Jev 20 rules per call, and
  the same 7 rules scored p_admit 0.81-0.86 individually versus 0.54-0.68 batched with 29 others,
  with the negatives outscoring the positives when batched. Jev compares questions within a call, so
  a verdict was relative to its batch and therefore to `created_at` ordering. Unbatched: 0%
  false-admit, 86% admit-rate, flat from 0.20 to 0.70. Threshold set to 0.50, matching the other two
  Jev gates, so the plateau is margin rather than tuning.

  _And three wrong gold sets before a usable one._ The eval's negatives were first derived from a
  regex for a leading condition keyword; 37% of what it flagged carried a condition later in the
  sentence, so the first sweep measured the labels. Tightened to an anywhere-keyword test; it still
  labelled "Prefer native Postgres full-text search … for sparse retrieval on corpora up to ~200
  rows" a hold, and reported a 45% false-admit rate that inspection dissolved — every one of the 13
  admitted "negatives" was a good, specific, project-grounded rule whose condition was embedded
  rather than keyworded. Negatives are hand-written only now. Separately, the first version of the
  eval had only a false-admit bar, which a judge admitting nothing passes trivially — exactly the
  state it was in. A one-sided safety metric is not a gate.

  _A quiet cost of autonomy, found by the test suite._ Once the pass began writing proposals on
  its own, three existing tests failed and two teardowns broke — not because the pass was wrong,
  but because `heuristic_merge_proposals` rows are now produced by any test that completes an
  initiative, and several teardowns deleted heuristics before the proposals FK-referencing them.
  An autonomous writer changes the blast radius of every fixture that touches its table; the
  fixtures had been correct only because nothing wrote there unprompted.

- **Key references:** `docs/heuristic-flywheel.md` (§1 tiers, §4 retrieval, §5 guard and
  dismissal, §7 the two doors, §9 config, §10 the two-corpus disagreement);
  `docs/design-principles.md` ("The two-tier corpus", plus three rejected paths);
  `backend/app/store/shared.py::consolidated_tier_predicate`;
  `backend/app/store/retrieval.py::_merge_by_cosine`; `backend/app/services/dream_scheduler.py`;
  migrations `0055` (promotion) and `0056` (retire); `backend/app/services/admission.py`;
  `backend/tests/test_bd97.py`; decisions `dec_6589e8d8722d` and `dec_33fac817d15b`.
Tightening five decision gates: two more Jev swaps, three enum collapses (BD-95)
- **Intent:** A codebase audit of every human/agent decision point (prompted by a direct
  question: which gates could reasonably move to Jev, and which multi-option gates carry
  options that don't actually change downstream behavior) found five candidates: two plain
  StructuredLLM binary classifications structurally identical to gates already on Jev, and
  three enums (`AdvisorVerdict`, `DriftReportStatus`, importance-validation's verdict type)
  where an extra option collapsed to the same outcome as another one already on the books. The
  goal was fewer states to reason about and consistent use of Jev where the judgment is a
  genuine structural pass/fail — without reopening anything BD-89/BD-93 already rejected, and
  without ever letting an executor auto-approve its own evidence (invariant #8).
- **Research Thinking:** The two Jev migrations extend the BD-90–93 line, and the same
  calibration discipline applied to both — but one of them inverts the safety direction the
  other four Jev gates share, which is the finding worth keeping. `learn.py`'s
  `evaluate_learnings` (does a drafted retrospective learning restate a confirmed spec item) is
  structurally the discretion auditor's own shape reused: "none" plus one option per candidate
  item, keyed by the item's own id, so a hallucinated match is structurally impossible.
  Calibrated at 0.5 against 173 harvested historical auto-approvals (self-labeled from
  `learn_draft.auto_approved_learnings` — the richest gold set any Jev gate in this codebase has
  had) plus 8 hand-curated needs_review negatives: 0% false-auto-approve at every threshold
  swept, so the lowest (most automation) was kept, same as BD-90.

  `gardener.py`'s near_duplicate merge-proposal pre-triage is where the direction flips. Every
  other Jev gate in this codebase is safety-critical on its _negative_ class — a false "pass" or
  false "within discretion" lets something bad happen unreviewed. Here the costly mistake is the
  opposite: a confident "distinct" verdict on a cluster that genuinely IS a duplicate silently
  skips creating the proposal, which permanently denies the human the chance to ever merge it —
  there is no second look, because the proposal never existed. A wrong "duplicate" verdict, by
  contrast, costs nothing but a human's attention, since every proposal that _is_ created still
  goes through the normal human confirm/dismiss gate untouched (the gardener's "propose, don't
  dispose" invariant from BD-62/BD-89 holds exactly as before). So the eval's hard bar is a
  FALSE-SKIP rate on positives, not a false-approval rate on negatives — the scorecard and the
  threshold sweep both had to be built inverted from the BD-90–93 template to measure the
  property that actually matters here. Calibrated at 0.5 against only 2 harvested confirmed
  positives (this project has resolved just 2 near_duplicate proposals to date — thin, flagged
  in the config comment for revisit) plus 5 curated distinct-but-similar negatives: 0%
  false-skip at every threshold, with noise-reduction (the negatives correctly skipped) actually
  _highest_ at the lowest thresholds swept. `generalization`-kind clusters were kept off Jev
  entirely, for the same reason BD-93 kept shaping's flagged/uncertain split off it: partitioning
  a coarse cluster into rule sub-groups is a free-text semantic judgment, not a fixed-option
  choice.

  The three enum collapses surfaced one real behavioral conflict the spec's constraints hadn't
  anticipated: `DriftReportStatus` dropping `initiative_created` (folded into `dismissed`) would
  have silently changed what BD-51's `drifted_memory` loop signal counts, since that query
  treated the two statuses differently (dismissed = false alarm, excluded; initiative_created =
  confirmed real drift, included). Escalated rather than guessed at; the human's call was to
  accept the narrowing rather than add a column to preserve it, since the affected slice is only
  reports resolved by spinning off a fix initiative — by that point a human has already acted on
  the drift, so the loop signal's marginal value there was judged not worth the schema cost.
  `AdvisorVerdict`'s `borderline` and `DriftReportStatus`'s `initiative_created` both had legacy
  values already persisted (in `specs.doc` JSONB and the `drift_reports` table respectively) —
  handled as one-time migration data rewrites (migration 0054) rather than an ongoing
  read-time coercion shim, since the latter is exactly the kind of permanent backward-compat
  scaffolding this project's conventions steer away from once a clean cutover is possible.

- **Key References:** `backend/app/services/learn.py` (`evaluate_learnings`,
  `_build_learning_eval_question`), `backend/app/services/gardener.py`
  (`_should_skip_near_duplicate_cluster`), `backend/app/config.py`
  (`LEARNING_AUTO_APPROVE_CONFIDENCE`, `MERGE_PRETRIAGE_SKIP_CONFIDENCE`),
  `backend/tests/evals/test_learning_eval.py`, `backend/tests/evals/test_merge_pretriage_eval.py`,
  `backend/migrations/0054_bd95_collapse_decision_gates.sql`, `docs/design-principles.md` § Jev.
Jev: swapping four judgment calls onto a typed-choice provider
- **Intent:** Four services — review verdicts, heuristic dedup classification, discretion-auditor
  resolution, shaping confidence classification — each asked a free-text StructuredLLM call to
  also emit a confidence number alongside its answer. That is a weaker contract than it reads as:
  nothing structurally stops the model from stating high confidence in a wrong or malformed
  answer, and nothing stops a `discretion_item_id` from being hallucinated outright. The goal was
  a provider whose contract makes the failure mode structurally impossible, not just guarded
  against, for the judgments that are genuinely a choice among fixed options.
- **Research Thinking:** OpenRouter's `/api/alpha/decisions` endpoint exposes a real typed
  Choice-question contract with calibrated confidence — verified live that this is a distinct
  route from `/chat/completions` reshaped to look like one, not a wrapper over the same
  free-text call. `app/providers/jev.py` wraps it; each swap (BD-90 review, BD-91 dedup, BD-92
  discretion, BD-93 shaping) kept its call site's existing safety fallbacks unmodified and added
  a literal, tunable auto-approve/auto-resolve confidence threshold to `config.py` in place of a
  prompt-only "act confident" instruction, calibrated against a live eval for each: BD-90 at 0.5
  (0% false-approval across the full threshold sweep), BD-92 at 0.9 (5 harvested real
  agent-resolved decisions + 10 hand-curated negatives, 0% false-auto-resolve / 80%
  auto-resolve).

  BD-91 is the case worth remembering in six months: the first dedup rubric measured 12 points
  worse than the old StructuredLLM path (55.91% vs 67.74%) on the flywheel bench's controlled,
  cassette-replayed comparison, and was not shipped as a silent regression — it was escalated
  and the rubric revised to require an explicit guardrail-identity test (condition _and_
  prescription must both match, not just topic), which reached parity/improvement
  (67.74–68.82%), confirmed via live re-measurement and the bench's own `compare` run. A model
  swap regressing on a frozen metric is a signal to fix the rubric, not to revert the swap.

  BD-93 is the sharper finding: a v1 design gave Jev all three shaping categories (confident /
  flagged / uncertain) directly, on the reasoning that if Jev could do the binary split it could
  do the three-way one too. A live-eval investigation found its flagged-detection reliably weak
  — 2–7% agreement with the old classifier across three rubric iterations, including verified
  cases where a plain textual contradiction was present in context and Jev still missed it. The
  v1 design was never pushed; it was reverted in favour of narrowing Jev to the one binary split
  it is empirically reliable at (confident/not_confident, the one judgment that gates
  `batch_approve_confident`'s auto-approval) and routing the flagged-vs-uncertain sub-category —
  naming a _specific_ concern — to the existing free-text reason-generation call, which already
  does free-text reasoning. **The lesson: a typed-choice provider is reliable at choosing among
  fixed options, not at composing the free-text judgment of which concern to name — match the
  judgment type to the tool instead of assuming a provider that's good at one generalizes to the
  other.** The shipped design's own live eval (135-item harvested/replayed gold set) reads 47%
  primary binary agreement (69% gold-confident / 36% gold-not_confident) and 41% secondary
  sub-label agreement, both informational-only (no ground-truth labels exist to set a pass bar),
  with known confounds documented in the eval's docstring rather than hidden.

- **Key References:** `backend/app/providers/jev.py`, `backend/app/services/review.py`,
  `backend/app/services/learn.py` (`_classify_intent`), `backend/app/services/discretion_auditor.py`,
  `backend/app/services/shaping.py`, `backend/app/config.py`
  (`JEV_AUTO_APPROVE_CONFIDENCE`, `DISCRETION_AUDIT_AUTO_RESOLVE_CONFIDENCE`),
  `docs/design-principles.md` § Jev.
Offline flywheel bench: iterate against frozen ground data
- **Intent:** Make the heuristic flywheel tunable. Every change to a threshold, a prompt, or
  the scoring formula had been judged by running against the live corpus and reading the
  output, which is not a measurement: the corpus moves between runs, the model is
  non-deterministic, and the run mutates the very data being judged. The goal was a loop where
  a number that moves is the change.
- **Research Thinking:** Four seams had to be frozen for a run to be reproducible — the data,
  the model, the embedder, and the database. The data is a committed snapshot; the model and
  embedder are cassettes keyed by a hash of the exact prompt and input; the database is dropped
  and recreated per run. Keying cassettes on the prompt means **editing a prompt invalidates
  its recordings**, which is the correct behaviour and worth stating plainly: replaying an
  answer recorded from a different prompt would make the bench lie, so a miss is a hard error.

  The design decision that mattered most was _what not to measure here_. A metric belongs in
  the bench only if two runs of unchanged code produce the same number. Clustering (pgvector
  plus union-find), retrieval (RRF over frozen vectors) and corpus health (arithmetic over
  rows) all qualify. Whether an LLM-drafted general rule is any _good_ does not, and it stayed
  in `tests/evals/`. Splitting on determinism rather than on subject is what lets the bench run
  inside the normal suite in under three seconds with no API key, which in turn is what makes
  it get used.

  Ground truth came mostly from the database, extending the evals' "Doen self-labels" idea.
  Citations are the strongest signal: a citation records that a rule was _used_ while shaping
  an initiative, making (intent, rule) a labelled relevance pair. Confirmed `near_duplicate`
  merge proposals are a human saying "these are the same rule", so every within-cluster pair is
  a gold duplicate. Two subtleties surfaced while wiring that up. First, the duplicates are
  `merged_into` in the live corpus and therefore invisible to clustering, so the measurement has
  to restore merged rows and score the pass on the pre-consolidation corpus — without that,
  every consolidation metric read a vacuous zero. Second, restoring everything then puts each
  confirmed _generalisation_ back alongside the members it absorbed, which sit
  near-duplicate-close by construction; proposing to merge those echoes a decision rather than
  making a finding, so they are excluded from scoring while near-duplicate pairs are kept.
  Getting that distinction wrong in either direction silently produced a meaningless metric,
  which is a good argument for curated negatives as a tripwire.

  What could not be harvested had to be authored, and the reason is itself a finding: the
  negatives. Nothing in the database records "this rule was shown and did not apply" — the
  dismissal event that would say so has never once been written. So `scenarios/` carries
  hand-written pairs that must stay distinct and queries whose look-alike rules must not
  surface, each with a `why`. Recall alone would have been a trap: a threshold low enough to
  catch every duplicate also collapses rules that merely share vocabulary, and a bad merge is
  worse than a missed one because it destroys a distinction permanently.

  The bench immediately paid for itself twice. It showed the merge threshold is correctly
  calibrated — at 0.78 it rediscovers both confirmed duplicates with zero false merges, and at
  0.70 it buys no extra recall while collapsing two of five curated negatives — which is the
  first time that trade has been visible rather than argued. And `corpus.unconditioned_rate`
  reads **0.41**: four in ten active rules state a prescription with no leading condition, the
  same structural defect that produced the over-broad contract rule. That number now has a
  baseline and a direction.

- **Key References:** `backend/tests/bench/README.md`, `backend/tests/bench/bench.py`,
  `backend/tests/bench/scenarios/`, `backend/tests/bench/baselines/baseline.json`.
Cleanup pass: obsolete schema, dead code, consolidated-only heuristics
- **Intent:** After the BD-89 reset, audit what the codebase still carries that nothing uses —
  columns, code, UI, and documentation — and remove it. Not a spec; a maintenance pass with a
  measured basis for every removal.
- **Research Thinking:** The audit rule was "nothing reads it", checked against the live
  database rather than against intent. That split the candidates cleanly. Some columns were
  never populated at all (`initiatives.appetite`, `org_id`, `owner_id`: 0 of 150 rows — an
  auth seam sketched in spec 0001 and never built, plus a Shape Up estimation field that
  invariant 6 forbids outright). Others were written on every single write and read by
  nothing: `heuristics.confirmation_count`/`rejection_count` lost their only reader when
  BD-89 deleted Thompson sampling, `heuristic_merge_proposals.cluster_key` was a hash that
  idempotency never consulted, and `memory.useful_count`/`last_applied_at` carried 23 rows of
  real accumulated signal that no ranking, filter, or surface has ever read. The last one is
  the instructive case: dropping it also removed a Redis Set buffer, a store method, and three
  call sites — a whole mechanism whose only output was two columns nobody queried. Write-only
  state costs more than it looks like it does, because the machinery that feeds it hides
  behind the columns.

  Two findings came from following dead code outward rather than stopping at the symbol. The
  `GET /projects/{id}/specs/{ref}` endpoint resolved a short ref to a spec; its only client
  helper had no callers, and its only store method (`resolve_initiative`) had no other caller.
  Removing it then stranded `short_slug`, and stranded the web's `spec.short_id` — which the
  initiative page still rendered. That field had been silently `undefined` since the page
  switched to loading by canonical id: the breadcrumb had been falling back to the title and
  the header chip had never rendered. Since spec 0010 made `initiative_id` _be_ the
  human-readable id (`BD-89`), the fix was to delete the whole short-id concept and render the
  id. A dead endpoint had been hiding a dead feature behind it.

  **The most useful finding was that the corpus is giving bad advice.** The project's
  highest-scoring consolidated heuristic (`heur_975d43f802f1`, quality 0.86, a generalisation
  that absorbed three rules) reads: _"When extending an API or data contract with new fields,
  require all new fields to be optional and verify backward compatibility before shipping."_
  It generalised correctly from three initiatives that each had a real compatibility concern,
  but the generalisation dropped the condition that made them true. This project has one
  operator and deploys backend and frontend together, so there is no payload that can be old.
  The rule cost real work in this session: the new `origin` field was first written optional
  with a `?? "extracted"` fallback and a comment about older payloads, for payloads that
  cannot exist. The human's correction ("no backward compatibility, I am the only one running
  this") is a supersession candidate, not a new rule — the same insight with its scope
  restored: _when extending a contract that has a consumer you cannot deploy in the same
  change, require new fields to be optional; when backend and frontend ship together, make
  them required and update both._ Acting on the correction removed four more pieces of
  compat scaffolding found by grepping for the pattern: a `SubmitLearn.learnings` field kept
  "for tests that POST without learnings fields" (production schema bent to avoid touching two
  tests), its fallback in `submit_learn`, a `HeuristicConflict` re-export, and a dead
  `HeuristicCitationEntry` type labelled "kept for backward compatibility".

  A generalisation that is confirmed, highly scored, and _wrong for its own project_ is the
  sharpest argument yet that the human gate on supersession is the load-bearing part of the
  flywheel — and that quality score measures usage, not correctness.
  **Follow-up, same session: the rule was superseded and the defect was turned into a test.**
  `heur_975d43f802f1` is now retired, replaced by `heur_8c6491ce37b4`, which restores the
  condition its three sources all carried: _"When extending a data contract that has a consumer
  you cannot deploy in the same change, require new fields to be optional and verify the
  existing callers still pass. When the consumers ship together, make new fields required and
  update them in the same change."_ Doing that surfaced a gap in the origin derivation: it
  resolved only `survivor_id = h.id`, so a rule superseding a generalisation would have read as
  a raw extraction and dropped straight out of the consolidated list — hiding the correction in
  exactly the place a reader goes to see what the project believes. Origin now walks the
  `replaces` chain (depth-capped, since `replaces` is application-written and a cycle is
  reachable), and both cases are pinned in `test_cleanup_0053.py`.

  The test that matters is `tests/evals/test_generalization_eval.py`, and it is a
  **counterexample** eval rather than a similarity one. Similarity cannot see this defect: the
  bad rule is textually close to a good one and subsumes every member. So for each gold cluster
  it runs the real prompt, then asks a judge whether the drafted rule mandates its prescription
  in two scenarios — one where the shared condition holds, one where it explicitly does not.
  Firing on the second is the defect, and the gate is zero. Refusal to group is scored as safe
  (the prompt prefers it to a weak generalisation) with a guard against a vacuous green.

  The eval reproduced the defect on first run, which is the point. It also showed the failure
  was _intermittent_ — across runs the same cluster sometimes kept its condition and sometimes
  dropped it — so this was never a case of a prompt being simply wrong, which is why a human
  reading the output once would not have caught it. The fix was a "carry the condition" section
  in `heuristic-generalize.txt` with the real failure as a worked contrastive example and an
  explicit falsification step ("imagine a situation where the shared condition does not hold;
  if your rule still fires, put the condition back"). Five consecutive runs since: zero
  over-generalisations. One honest caveat, recorded in the eval itself — the contract-extension
  case is now a worked example inside the prompt, so it functions as a regression guard for a
  known defect rather than as independent evidence; the other two clusters carry that claim.

  A broader screen of all nine live consolidated rules through the same counterexample judge
  flagged eight as over-broad, but the screen is uncalibrated and over-flags badly (its
  counterexample for "When modifying behavior…" was fixing a typo in a comment, which is not
  modifying behaviour). Two look genuinely unconditioned on a careful reading —
  `heur_025f9f697dde` ("When modifying behavior, require an explicit regression or equivalence
  test") and `heur_20e65d1acdb0` ("When changing ranking or retrieval logic…"), the latter
  being a cluster the repaired prompt now declines to generalise at all. Worth noting that two
  of the flagged rules are `near_duplicate` survivors carrying their _original_ text verbatim,
  so unconditioned rules are not solely a generalisation artefact — extraction emits them too.
  Calibrating that screen before trusting it as a verdict is open work.

  One unrelated fix rode along because the pre-commit gate caught it:
  `test_bd43.py::test_latency_lower_than_correlated_subquery_baseline_at_1000_heuristics`
  asserted `mean_new < mean_old` on a microbenchmark whose two paths have since converged —
  the failing run measured 5.0023ms against 5.0010ms, a comparison decided by sub-microsecond
  noise. The claim BD-43 needs is that precomputing a score never costs _more_ than
  recomputing it, so the assertion now tolerates a tie within noise (max of either standard
  deviation, or 10%) and fails only on a real inversion. A benchmark assertion with no
  tolerance is a scheduled flake.

- **Decisions:** The project heuristics list now shows the **consolidated corpus only** (origin
  `generalized` or `merged`), filtered server-side. Raw extractions stay fully live at
  retrieval; they are working material, and listing 88 of them next to the 10 rules that
  subsume them buried the signal. `origin` and `absorbed_count` are derived by joining
  confirmed proposals — no column, no backfill. Documentation ownership was made explicit:
  `docs/data-model.md` had drifted to missing six tables entirely while three other files
  each carried a partial, disagreeing copy, so it is now the single canonical table reference
  and the others link to it. `agents.md` carries the ownership table; `/sync-docs` now treats
  a duplicated fact as drift even when both copies still agree.
- **Key References:** `backend/migrations/0053_drop_obsolete_columns.sql`,
  `backend/tests/test_cleanup_0053.py`, `docs/data-model.md`, `agents.md` ("Keeping these docs
  current"), `heur_975d43f802f1`.
BD-89: Heuristic Flywheel Reset — keep, improve, delete
- **Intent:** Return the heuristic flywheel to its stated purpose — every completed initiative
  leaves a few project-scoped, general, actionable rules that surface when the next spec is
  shaped, and the corpus gets sharper over time rather than larger — by deleting every
  mechanism that did not serve that loop and adding the one step that was missing:
  generalisation.
- **Research Thinking:** The trigger was a measurement, not a design argument. After BD-87
  shipped, a review queried the live corpus instead of reading the code: 118 active
  heuristics, 115 never cited; 17 citation events in total, 12 of them on one rule in the very
  spec (BD-69) that built the citation-fed score; 87 of 118 quality scores identical at 0.56;
  zero BD-78 shaping verdicts and zero BD-68 dismissals ever written; the BD-77 drafting path
  had produced zero citations across 22 drafts; three retrieval mechanisms (Thompson sampling,
  label boost, reranker) all flag-gated off "pending segmented data"; and 12,758 of 12,791
  impression-log rows written in three days by the BD-83 probe script, which meant the
  staleness signal built on that log measured "not in the probe's candidate set". The
  flywheel had more feedback machinery than feedback, and every threshold and weight had been
  tuned on one corpus that described Doen itself.

  Two findings shaped what replaced it. First, the dream phase (BD-83/84) classified and
  flagged but never generalised — the labeler's 0.55 clusters (two real themes of 18 and 19
  members) were computed and consumed by nothing, while the gardener's 0.78 clusters found
  roughly one pair in the whole corpus. The two clustering mechanisms sat at the wrong
  granularities for the goal; the fix is the gardener's shape (human-gated proposal, existing
  table, `merged_into` retirement with evidence concentration) at label granularity, with a
  prompt that asks for the one rule the members instantiate — or a refusal. BD-88, drafted in
  between, proposed a separate additive table keyed on label ids; it was revoked because
  label rows were rebuilt by delete-and-reinsert on every run (nothing durable could reference
  them), labels spanned projects while heuristics are project-scoped, and keeping members
  active under a new general rule grows the corpus that the step exists to shrink. Second, the
  human settled that heuristics are project-specific by design, which collapsed BD-88's
  proposed "transferable vs. project-local" LLM classification into a single branch in
  `get_context`: the thin-corpus fallback never returns heuristics.

  Three deletions were explicit human decisions rather than review findings, each recorded
  under "Deliberately rejected" in `docs/design-principles.md`: BD-87 check drafting (its own
  docs recorded two failed re-runs out of two; it read only Doen's tree; it made rules more
  codebase-specific, the opposite of generalisation), the BD-73 reranker (specificity 0.105 →
  a noisy 0.225–0.35 against a 0.40 gate), and the BD-40 second hop (always on, never
  measured, and its "or global" clause contradicted project scoping). The score was reduced
  to uniform-weight Laplace: with 17 events the five-weight theory of signal dominance had
  nothing to act on, and BD-80 had already made the score a tiebreaker only. One empirical correction landed during verification: asked for _one_ rule per coarse
  cluster, the model refused all three of the Build Doen corpus's largest 0.55 clusters (13,
  10 and 9 members) — correctly, because single-linkage at that threshold chains distinct
  topics into one blob. Asking it instead to partition a cluster into sub-groups of 3+ that
  share a rule produced eight generalisation proposals on the same corpus, all human-gated.
  The acceptance
  criteria enforce the reset mechanically — a grep-to-zero test over every deleted
  identifier, a net-negative line count, and the MCP surface down by exactly four tools — so
  the simplification cannot quietly erode.

- **Key References:**
  - `docs/heuristic-flywheel.md` — rewritten to describe only the surviving loop.
  - `docs/design-principles.md` — "The flywheel reset (BD-89)" and the new rejected-path
    entries.
  - `backend/migrations/0052_flywheel_reset.sql`, `backend/app/services/dream_phase.py`,
    `backend/app/services/gardener.py` (`run_generalizer`), `backend/tests/test_bd89.py`.
BD-87: Heuristic Check-Proposal Pathway + Gardener 2-Member Fix
- **Intent:** Close the gap between "a heuristic is classified enforceable/verifiable"
  (BD-83) and "a heuristic is actually mechanically checked" — nothing in the corpus turns a
  guardrail into a real, runnable test. Two prior POC sessions had shown an agentic LLM
  session, given only a heuristic's rule text plus ordinary codebase search/read tools,
  could locate the right code and draft a genuine, non-tautological pytest test on the
  first try. This spec built the pathway that captures that as a repeatable, human-gated
  system capability, plus an unrelated, smaller, already-proven fix to the merge gardener.
- **Research Thinking:** The interesting engineering problem wasn't the DB row (a
  `heuristic_check_proposals` table mirroring `heuristic_merge_proposals`' pending →
  confirmed/dismissed shape) — it was that the codebase's one existing LLM-provider pattern,
  `OpenAICompatibleLLM.complete_structured`, is a single forced-tool-call request and
  structurally cannot do the multi-step "search, read, search again, read again, then
  answer" traversal this task needs. Building a second, genuinely new provider primitive
  (`app/providers/agentic_drafter.py`) — a real OpenAI-compatible `tools` array with two
  read-only tools (`search_code` via bounded `grep`, `read_file` sandboxed inside `backend/`
  with path-traversal rejection) driven through an actual multi-turn loop — was therefore
  the load-bearing decision of the spec, not an implementation detail.

  Getting that loop to reliably land inside its own hard round budget (capped at 8
  round-trips per the human-confirmed spec; exceeding it is a clean failure, never a partial
  result) took two empirically-driven fixes, found only by running the real loop against
  the real repository rather than reasoning about it in the abstract:
  1. **Model choice was the first bottleneck.** `JUDGE_MODEL` (a small, cheap model already
     used for classification/dedup judging elsewhere in the corpus) ran out all 8 rounds on
     every real trial without ever settling — capable of using the tools, but not of
     recognizing when it had gathered enough to stop. Switching the drafter's default to
     `SHAPING_MODEL` (the same tier the codebase already trusts for structured spec
     drafting) fixed tool-use quality but not round discipline on its own: a written
     "be efficient, settle by turn 3-4" instruction in the system prompt was consistently
     ignored — the model has no way to introspect which turn it's actually on from the
     prompt text alone, so it kept behaving exactly as thoroughly as an unbounded research
     session would.
  2. **The fix was to make the budget concrete in the conversation itself, not just describe
     it.** The loop now injects an explicit `role: "user"` reminder once few rounds remain,
     escalating to an unmissable "this is your LAST investigation turn — your next message
     must contain no tool_calls" at the one-round-remaining mark. This is standard practice
     for agentic harnesses but wasn't yet a pattern this codebase had needed before (every
     other LLM call site is exactly one request). Even after that fix, a second, subtler
     defect surfaced on a live run: the system prompt described the final answer as returned
     "via the draft_check tool," and the model — having no way to see that `draft_check`
     genuinely isn't in the `tools` array during investigation, only during the dedicated
     final-extraction call — occasionally called it early anyway, which the loop then
     rejected as an "unknown tool," burning a round for nothing. Rewriting the prompt to
     describe the final answer passively ("you will then be asked, separately...") without
     naming a callable tool removed the temptation, and the loop was additionally hardened
     to treat an early well-formed attempt at that shape as a legitimate settle signal
     rather than an error — accepting a slightly-early correct answer is strictly better
     than failing a whole run over it. With both fixes in place the real end-to-end
     criterion (an unmocked run against a real, freshly-written guardrail in this same
     session's own gardener fix) passed reliably: the model found the exact `if len(members)
== 2` branch in `gardener.py`, discovered the test file this same spec had just added,
     and — rather than duplicate coverage — drafted a genuinely new edge case neither
     existing test covered (the quality-score tiebreaker), with a real positive control and
     a real negative/edge case, in valid Python, following the project's own test
     conventions unprompted.

  The gardener fix shipped in the same spec was unrelated in cause but small enough to
  bundle: a 2-member near-duplicate cluster has nothing for an LLM to genuinely "subsume" —
  the survivor's own rule already says everything the pair says — so the redraft LLM call is
  now skipped entirely for exactly-2-member clusters, reusing the survivor's own rule/tags
  verbatim; `_pick_survivor`'s tie-break logic and the 3+-member LLM-redraft path are both
  byte-for-byte unchanged, verified by an explicit regression test alongside the new
  2-member test.

  Throughout, the human-confirmed constraints did real work as a design forcing function:
  "never write to a git-tracked path" and "confirming only flips a DB column" meant the
  loop's two tools are both genuinely read-only (no `write_file`, no `bash`/`run_command`
  tool exists at all — not merely unused), so nothing about this pathway can accidentally
  mutate the codebase even if the model tried.

**Key References:**

- **BD-83** — Dream-Phase Corpus Health Pass (the `health_classification` field this
  spec's eligibility gate reads — only `enforceable`/`verifiable` heuristics qualify).
- **BD-62** — Merge Gardener (the `heuristic_merge_proposals` shape and pending →
  confirmed/dismissed lifecycle this spec's `heuristic_check_proposals` table mirrors; also
  the file carrying this spec's small unrelated 2-member fix).
- **BD-17 / BD-79** — Heuristic extraction in guardrail (condition + prescription) form —
  what makes a rule concrete enough for an agentic session to locate and test at all.
BD-84: Heuristic Subsystem Efficiency & Audit Pass
- **Intent:** Close out three confirmed performance defects in the heuristic subsystem, give
  the two BD-83 review signals (health classification, staleness) a combined high-priority
  view instead of leaving them uncorrelated, and produce a standing, honest audit of every
  flag-gated or always-on mechanism in the subsystem rather than let dormant machinery
  accumulate without anyone having tallied its cost in one place.
- **Research Thinking:** Triggered by a human-requested critical re-evaluation of the whole
  heuristic subsystem after BD-83 shipped — three parallel research passes (architecture
  inefficiency, dead-code/obsoletion, and RESEARCH_LOG/docs fidelity) turned up concrete,
  verified findings rather than vague impressions. `dream_phase.py` classified every
  heuristic with a sequential `await` per iteration (measured at 3–5 minutes for ~115
  heuristics in production); `gardener.py` issued one `get_heuristic` fetch per cluster
  member instead of a single batched call; `probe_heuristic_recall.py`'s reranker pass was
  fully serial and had already caused real transient timeouts. None of this was
  theoretical — all three were observed directly in the BD-83 session. Separately,
  `health_classification` (mechanically-checkable guardrail vs. irreducibly advisory) and
  `stale_flagged_at` (unused-for-45-days) were both shipped in BD-83 as independent BD-83
  output fields that never cross-referenced each other, even though a heuristic that is
  _both_ enforceable/verifiable _and_ stale — a checkable rule nobody has retrieved in over a
  month — is a materially stronger review signal than either alone.

  The fix was scoped narrowly and gated carefully: bounded concurrent dispatch
  (`asyncio.Semaphore(8)`, no existing concurrency-bound convention in the codebase to match)
  for the two sequential-await sites, and a single new batched `SpecStore.get_heuristics(ids)`
  method for the gardener's N+1 (labeler.py was investigated and found to have _no_ such
  defect — it already sourced heuristic data through one batched query, so nothing there
  needed changing). A new `critical_stale_candidates` field on `run_dream_phase`'s output
  computes the intersection of the same run's staleness and classification results —
  additive only, neither underlying signal's computation, storage, or meaning changes.

  The audit half was the more consequential design decision: rather than let the executor
  unilaterally decide what to remove, the spec required a written disposition
  (keep-as-is / change / recommend-removal-for-human-decision) for every flag-gated
  mechanism, with removal itself gated behind a human decision the executor cannot make on
  its own initiative. All four audited mechanisms (`HEURISTIC_RERANKER_ENABLED`,
  `HEURISTIC_THOMPSON_ENABLED`, `HEURISTIC_LABEL_BOOST_ENABLED`, and BD-40's always-on
  second-hop anchoring) landed on keep-as-is — each is either deliberately quarantined
  pending BD-82-style usage data (and already correctly documented as such) or, for the
  second hop, simply unmeasured rather than shown to be harmful. No mechanism was
  recommended for removal, so no human decision was actually needed this time — but the
  process existed and would have fired had the evidence gone the other way. The audit
  document itself was later merged into `docs/heuristic-flywheel.md` (§10.1) rather than
  kept as a separate file, on the reasoning that a flywheel document describing only how the
  system works, with a separate document describing where it doesn't, invites exactly the
  kind of silent drift RESEARCH_LOG.md itself was found to be vulnerable to in the BD-83
  follow-up session — one document, kept current together, beats two documents that can
  silently disagree.

**Key References:**

- **BD-83** — Dream-Phase Corpus Health Pass (introduced both `health_classification` and
  `stale_flagged_at`, the two signals BD-84 combines; also introduced the reranker default-
  flip attempt whose disposition BD-84's audit re-confirmed).
- **BD-62** — Merge Gardener (the per-cluster N+1 fixed here).
- **BD-80** — Deterministic Retrieval Baseline (the "prove it with segmented data before
  flipping a default" discipline BD-84's audit applied to all three flags it reviewed).
BD-83: Dream-Phase Corpus Health Pass
- **Intent:** Fixing the heuristic corpus's citation-skew problem (a few heuristics cited constantly, most never surfacing) at its root cause, and giving a human an on-demand way to run a corpus-health pass rather than waiting for it to happen implicitly at learn-time.
- **Research Thinking:** The initiative began as a proposal to build a new NLP pipeline — log ingestion from PRs/JIRA/ADRs, pattern clustering, an SLM trained on the heuristic corpus. A survey of the existing codebase found that pipeline already built (BD-17 through BD-79 already do condition→prescription extraction, dedup, merge-gardening, and quality scoring) and that Doen has none of the external data sources the proposal assumed — its only narrative material is its own specs, decisions, and Learn text. A read-only pilot script against the real production corpus (147 heuristics) then measured the actual bottleneck directly: paraphrases of a heuristic's own rule matched it in embedding space only 20% of the time (`text-embedding-3-small`, 1536-dim) — not because the rules were phrased too narrowly (an LLM "generalize the wording" pass barely moved the number, 0.20 → 0.235) but because of embedding-model granularity. Swapping to `text-embedding-3-large` (3072-dim) on the same sample raised recall to 0.76 but dropped specificity to 0.325 — a real recall/specificity trade, not a free win. This ruled out training a small LM on the corpus as an alternative fix: ~147 rows is far too small to fine-tune without reproducing the same overfitting the pilot had just measured (now relocated into weights instead of an embedding index), it would break the per-rule attribution (`heuristic_citations`, `quality_score`, supersession chain) the whole system is built around, and it would introduce training/versioning/eval infrastructure this project deliberately doesn't carry (the LLM/embedding layer is a thin pluggable provider, swappable by env, with zero owned-model infrastructure).

  The shipped fix has two coupled parts, gated independently rather than shipped as one unverified bundle: (1) the embedding upgrade itself — migration `0050_embedding_dim_3072.sql` resizes `decisions`/`memory`/`heuristics`/`heuristic_labels.centroid` and `app/backfill_embeddings.py` re-embeds every row; recall measured 1.0 against the real corpus post-migration, confirming the pilot's diagnosis; and (2) the BD-73 reranker, intended to recover the specificity the larger embedding space gives up, gated on `app/probe_heuristic_recall.py` measuring both recall ≥0.76 and specificity ≥0.40 together. That gate did its job: it caught a change that looked right in principle but measured wrong in practice — specificity came in at 0.105 on the real corpus, the reranker was promoting hard negatives rather than demoting them — so `HEURISTIC_RERANKER_ENABLED` stayed off by default rather than shipping on the strength of the embedding half's success alone.

  A follow-up investigation (same initiative, after human review) found a real defect behind that failure: the reranker's prompt (`heuristic-reranker.txt`) ended with "do not explain your reasoning," suppressing the exact judgment — distinguishing same-domain-different-triggering-condition candidates from genuine matches — a hard negative is built to test. The fix added a required per-candidate `reasoning`/`applies` field to the structured schema, a worked contrastive example, and a code-enforced rule that the final ordering cannot contradict the model's own `applies` verdict (an LLM can still misjudge a single candidate, but it can no longer produce an internally inconsistent list). Across five local probe runs specificity moved from 0.105 to a noisy 0.225–0.35 band — a real improvement in the right direction, but inside sample-to-sample variance large enough that further prompt-wording tweaks (a stronger worked example, an explicit "default to false when ambiguous" instruction) stopped showing a consistent trend, and a human call was made to stop chasing a noisy metric with more ad-hoc prompt edits rather than a properly-powered measurement. `HEURISTIC_RERANKER_ENABLED` remains off by default; re-enabling it needs a larger/fixed-sample rerun of the probe, or an investigation of whether the reranker's model choice (currently the shaping LLM singleton) is itself the ceiling — both recorded as explicit follow-up, not resolved here.

  A third, independent piece shipped cleanly: a staleness signal (`HEURISTIC_STALENESS_DAYS`, computed on-demand from the existing `heuristic_retrieval_events` impression log — no second event table) that surfaces heuristics with no retrieval impression inside the window as review candidates for the existing human-gated merge gardener, addressing the over-citation half of the original skew (staleness never auto-suppresses or archives — advisory only). All of it is exposed through one new on-demand MCP tool, `run_dream_phase`, which reuses the existing gardener and labeler machinery unchanged and adds an enforceable/verifiable/advisable classification pass per heuristic — a triage step so a heuristic whose guardrail is mechanically checkable (a schema/lockfile-shaped rule) can eventually be promoted out of advisory retrieval into an actual constraint or lint check, rather than sitting in the corpus as text forever.

  Also decided mid-initiative, by human call rather than executor discretion: pgvector's HNSW/IVFFLAT indexes cap out at 2000 dimensions for the plain `vector` type, so the 3072-dim migration would have left the four affected columns on an unindexed cosine scan. Rather than accept that even temporarily, the migration was rewritten to use pgvector's `halfvec(3072)` type (16-bit float components, HNSW-indexable to 4000 dims via `halfvec_cosine_ops`), so the corpus never runs an unindexed retrieval window.

**Key References:**

- **BD-17** — Compound Knowledge Flywheel (the extraction/gardener/dedup machinery this initiative reused rather than replaced).
- **BD-71** — Impression log (`heuristic_retrieval_events`), the data source the staleness signal reads without adding a second table.
- **BD-73** — Opt-in LLM reranker (the mechanism this initiative attempted to default-on, found a real prompt defect in, and left flag-gated pending further evidence).
- **BD-78** — Shaping-verdict feedback (the precedent for "gate a default flip on measured behavioural data, not intuition" that BD-83 followed for the reranker).
- **BD-80** — Deterministic retrieval baseline (the discipline — burden of proof on the flag, not the default — BD-83 inherited for `HEURISTIC_RERANKER_ENABLED`).
BD-80: Deterministic Retrieval Baseline
- **Intent:** Making retrieval reproducible by default — once heuristics ground drafted spec content (BD-77), which guardrails a spec receives must not depend on a random draw.
- **Research Thinking:** BD-71 introduced Thompson sampling to break the rich-get-richer loop, which was the right diagnosis of a real structural problem — but it optimized a corpus whose quality scores carried almost no signal (76% of active heuristics shared one score pre-BD-78), meaning the sampler was redistributing exposure among indistinguishable candidates: exploring noise. BD-80 inverts the burden of proof rather than rejecting the machinery. The default path is deterministic RRF over dense + BM25 with the precomputed `quality_score` as tiebreaker; Thompson sampling (`HEURISTIC_THOMPSON_ENABLED`), the BD-63 label boost (`HEURISTIC_LABEL_BOOST_ENABLED`), and the BD-73 reranker all remain intact behind default-off flags. While gating the label boost, its formula defect was fixed: the boost now adjusts the RRF score additively instead of recomputing `min(1.0, 1-dist)`, which had silently discarded the sparse-rank contribution. Migration 0049 extends the impression log with `thompson_enabled` / `label_boost_enabled` per row, so any future case for re-enabling stochastic ranking can be argued from config-segmented behavioural data (BD-82) instead of intuition. The design principle this records: retrieval that generates durable state must be reproducible; exploration is a hypothesis that must earn its way back.

**Key References:**

- **BD-71** — Thompson sampling and the impression log (flag-gated, not removed; the log becomes the evidence channel).
- **BD-63** — Label boost (flag-gated; RRF-consistency defect fixed in passing).
- **BD-77/BD-78** — Heuristic-grounded drafting and shaping feedback (the consumers that made determinism mandatory).
- **BD-82** — The planned outcome study that can re-open any of these flags with data.
BD-79: Guardrail-Shaped Heuristic Extraction
- **Intent:** Making extracted heuristics usable as guardrails, not observations — condition + prescription form ("when X, require Y") with an explicit applicability scope, so BD-77 drafting can translate rules into constraints directly.
- **Research Thinking:** A heuristic that describes what happened is retrievable but not actionable at draft time; one that prescribes under a stated condition can be injected into a spec verbatim. The extraction prompts were revised to require this shape. Two vote-splitting defects in the same path were closed: (1) a failed intent-classification LLM call previously defaulted the proposal to `new`, silently creating a duplicate row instead of a confirmation — it now logs and holds the proposal in an `'error'` status (migration 0048) that can never be auto-confirmed; (2) a baseline-synthesis citation of a heuristic id outside the provided top-10 window was silently coerced to `new` — it is now validated against the full corpus by id first. The initiative also added the extraction-quality eval (`backend/tests/evals/test_extraction_eval.py`): a human-curated gold set scored against a real LLM on actionability, generalizability, and non-duplication — previously the only LLM judgment in the flywheel with zero real-model coverage.

**Key References:**

- **BD-48** — Prior-as-baseline synthesis (the extraction path these fixes harden).
- **BD-31** — Deduplication intent classification (whose silent fallback was the vote-splitter).
- **BD-77** — Heuristic-grounded drafting (the consumer that dictates the guardrail shape).
BD-78: Shaping Edits as Heuristic Feedback
- **Intent:** Closing the feedback loop without new human ritual — what the human does to a heuristic-grounded spec item during shaping IS the verdict on the heuristic.
- **Research Thinking:** BD-77 created grounded items; BD-78 harvests their fate. At the manual start-building transition, every `context='drafting'` citation is diffed against the final spec: item present and not substantially rewritten → `'survived'` feedback event (c += 2.0); absent or rewritten below `SHAPING_REWRITE_SIMILARITY_THRESHOLD` (0.75 cosine vs the `drafted_text` snapshot, `heur_` markers stripped so deleting only the provenance chip never counts) → `'removed'` (s += 1.0). Verdicts are exactly-once per citation; each couples its event INSERT and score UPDATE in one transaction while the pass as a whole is fire-and-forget from the route. The same initiative rebalanced the score's accumulation weights so behavioural signals dominate: `SHAPING_SURVIVAL_WEIGHT` (2.0) > `CITATION_USAGE_WEIGHT` (1.0) > `AUTO_CONFIRMATION_WEIGHT` (0.25, flat — the BD-39 outcome-weighted 3.0 is gone). The pre-BD-78 weighting had inverted the signal hierarchy: extraction (automatic, non-behavioural) outweighed usage 6:1, which is why 76% of the corpus shared the identical score 0.800 — a participation trophy, not a quality measure. Migration 0047 backfill-recomputed the live corpus under the new weights; extraction-only rows now sit near the 0.5 prior and the corpus's most-used heuristic leads at 0.931.

**Key References:**

- **BD-77** — Heuristic-grounded drafting (produces the citations this initiative adjudicates).
- **BD-69** — Citation-fed quality score (the transactional recompute pattern extended here).
- **BD-39** — Outcome-weighted confirmations (deliberately retired by the rebalance: extraction confirmation is now nominal regardless of outcome).
- **BD-68** — Dismissal events (the `citation_feedback_events` table extended with `survived`/`removed`).
BD-77: Heuristic-Grounded Spec Drafting
- **Intent:** Making `create_spec` the primary application surface for heuristics — rules learned from completed work are proposed directly as constraints, discretion items, and acceptance criteria in new drafts, each visibly attributed to its source heuristic.
- **Research Thinking:** A BD-32-style diagnosis of the flywheel found its application layer pointed at the wrong lifecycle stage: heuristics only annotated already-written spec items (classification) or fired in the rare discretion audit — both passive, both downstream of the moment intent solidifies. BD-77 moves heuristics upstream: the drafting pipeline retrieves project-scoped heuristics via the same `get_context` call used for memory priors, and the drafting LLM cites a `heur_<hex>` id directly in an item's text when that item is genuinely grounded in a rule. Each grounded item records a `heuristic_citations` row (`context='drafting'`, `spec_item_id`, `drafted_text` snapshot) that renders as a provenance chip in the UI. The structural payoff is threefold: citations flow per-spec instead of rarely (ending signal starvation), the human's existing shaping edits become a feedback channel with zero added ritual (harvested by BD-78), and the fraction of grounded items surviving shaping becomes a non-circular, human-labelled quality measure — the honest replacement for evaluating retrieval against the system's own citations. Degradation is total and silent by design: cold corpus, retrieval failure, or citation-write failure produces a plain ungrounded draft.

**Key References:**

- **BD-64** — Citation events (the table and `heur_<hex>` extraction contract reused for the `'drafting'` context).
- **BD-68** — Dismissible citations (grounded items are dismissible through the same flow, no schema change).
- **BD-17** — The flywheel this initiative finally points at spec creation.
BD-76: Flywheel Observability — Eliminate Silent Failures
- **Intent:** Making every failure in the heuristic pipeline visible and retryable — an autonomous learning system must never break without telling anyone.
- **Research Thinking:** A live-system audit found the flywheel's failure modes were uniformly silent: heuristic extraction in `submit_learn` was wrapped in a bare `except: pass` (the loop could die while learn submissions reported success); the labeler stamped its run _before_ executing, so one failed pass silently disabled label derivation until enough corpus drift re-triggered it (production sat at zero labels for weeks despite an eligible corpus, with no log line to explain why); and citation recording trusted regex-extracted `heur_<hex>` ids without existence checks, so a hallucinated id became a phantom row. BD-76 closed each path: extraction failures are logged, persisted to an append-only `extraction_failures` table, and surfaced as an additive `extraction_warning` on the learn response (still non-blocking); the labeler stamp moved to after-success so failures retry; citation ids are validated against the `heuristics` table before insert. A read-only `GET /health/flywheel` endpoint reports the pipeline's vital signs (active corpus, NULL embeddings, labels vs eligible corpus, recent citations, recent extraction failures) with per-field degradation — a failing sub-query nulls that field rather than 5xx-ing the endpoint. The principle recorded: best-effort means logged and queryable, never silent; a failure that is only logged, not persisted, can't be seen at read time.

**Key References:**

- **BD-63** — The labeler whose stamp-before-run ordering was the canonical silent failure.
- **BD-64** — Citation recording (hardened with id validation).
- **BD-12/BD-32** — The verify-stage philosophy (drift must surface) applied to the system's own pipeline.
BD-73: Opt-In LLM Listwise Reranker for Heuristic Retrieval
- **Intent:** Testing whether a listwise LLM judge over the top-K retrieval window improves ordering quality beyond the RRF + quality blend.
- **Research Thinking:** RRF fuses lexical and semantic rank but cannot read the query's intent; a small listwise rerank of the top `HEURISTIC_RERANKER_WINDOW` (~20) candidates lets an LLM reorder by actual applicability. Shipped off by default (`HEURISTIC_RERANKER_ENABLED`) so self-hosters without an LLM key see identical behaviour; rows beyond the window pass through unreordered. Under BD-80's deterministic-baseline principle it remains flag-gated pending BD-82-style evidence.

**Key References:**

- **BD-44** — RRF pipeline (the ordering the reranker refines).
- **BD-70** — Eval harness (the measurement tool for any re-enable case).
BD-71: Fix Rich-Get-Richer Retrieval — Thompson Sampling, Relevance Blend, Impression Log
- **Intent:** Breaking the rich-get-richer retrieval loop that structurally starves new heuristics of exposure by replacing the deterministic quality-primary sort with a stochastic exploration policy, a configurable relevance–quality blend, and an append-only impression log that records every surfaced heuristic.
- **Research Thinking:** The root cause identified in §10 of the flywheel doc was a compound feedback loop: `(-quality_score, dist)` lexicographic sort made quality the primary, near-continuous key, so RRF relevance and label boost rarely decided anything. Retrieved heuristics got cited, citations incremented `c`, `c` raised `quality_score`, and the same rules kept winning. New rules (S = 0.5) structurally couldn't break in. BD-71 attacks three distinct layers simultaneously:
  1. **Thompson sampling (exploration).** Instead of sorting by the point-estimate mean S = (c+1)/(c+s+2), draw `S̃ ~ Beta(c+1, s+1)` at retrieval time. For a new heuristic (c=0, s=0) this is Beta(1,1) = Uniform — a wide posterior, so new rules sample above 0.5 roughly half the time. For a heavily confirmed rule (c=50) the posterior is tightly concentrated near 1.0 — ranking remains stable but is no longer deterministic. The Beta distribution is mathematically exact for this purpose: S = (c+1)/(c+s+2) is already the mean of Beta(c+1, s+1), so the sampling policy is derived from the same model the quality score was always estimating. No new model is introduced.

  2. **Relevance–quality blend (final_score).** The sort key becomes `final_score = α × rrf_score + (1−α) × S̃`, where `α = HEURISTIC_RETRIEVAL_ALPHA` (env var, default 0.5). At α=1.0 this collapses to pure RRF relevance (pre-BD-71 behaviour minus quality bias); at α=0.0 it collapses to pure Thompson quality draw. The default 0.5 balances both signals. The BD-43 stored `quality_score` column was not sufficient for Thompson sampling because it is the Laplace mean, not the raw (c, s) pair — Beta(c+1, s+1) requires them directly. Migration 0044 adds `confirmation_count` and `rejection_count` to the `heuristics` table with a full backfill, and `_write_quality_score` now updates all three atomically. RRF score is preserved from BD-44's BM25+dense pipeline; the label boost (BD-63) now recomputes both `rrf_score = 1 − new_dist` and `_final_score` after adjusting `dist`, then re-sorts.

  3. **Impression logging.** Migration 0045 adds an append-only `heuristic_retrieval_events` table. After every `_context_search` call, every heuristic in the surfaced slice gets a row: `heuristic_id`, `query_hash`, `final_score`, `sampled_quality` (S̃), `rrf_score`, `alpha`, `retrieved_at`. Writes are best-effort (try/except, never blocks the caller). This produces the denominator for citation-rate analysis — the prerequisite for any future LTR model or sampling-policy evaluation (BD-74). It does not yet feed back into the quality score formula; it is a telemetry foundation.

  **Eval gate (BD-70 harness, 16 cases).** Baseline (α=1.0, pure RRF): recall@5=0.688, recall@10=0.812, nDCG@5=0.418, nDCG@10=0.459. After BD-71 (α=0.5): recall@5=0.750, recall@10=0.750, nDCG@5=0.473, nDCG@10=0.473. nDCG improves at both K values; recall@5 improves. The recall@10 drop (−6.2pp) is the expected exploration tradeoff — Thompson redistributes some top-10 slots to under-explored heuristics, which is the intended behaviour.

**Key References:**

- **BD-30** — Laplace score `S = (c+1)/(c+s+2)` is the mean of the Beta(c+1,s+1) posterior BD-71 samples from.
- **BD-43** — Precomputed `quality_score`; BD-71 adds `confirmation_count`/`rejection_count` columns to make the raw c/s available for sampling.
- **BD-44** — RRF score that becomes one term in the `final_score` blend.
- **BD-63** — Label boost; updated to recompute `rrf_score` and `_final_score` after dist adjustment.
- **BD-70** — Retrieval eval harness that produced the before/after comparison gating this initiative.
- **BD-74** — Future LTR / time-decay research that will consume the `heuristic_retrieval_events` impression log.
BD-69: Citation-Fed Quality Score
- **Intent:** Wiring real-time citation signals (both positive and negative) into the heuristic quality score, so that heuristics frequently cited in successful work rise in confidence while those dismissed or associated with rework naturally decay.
- **Research Thinking:** BD-30's Laplace score was based solely on learn-phase confirmations and supersession rejections — a retrospective signal that only fires after an initiative is complete. BD-64 introduced citation events (a real-time usage signal from spec shaping and auto-resolution), and BD-68 introduced dismissal events (an explicit negative feedback signal from humans), but neither affected the quality score. BD-69 closes this loop by wiring both signals into the Laplace formula `S = (c+1)/(c+s+2)`: citations on cleanly-completed initiatives (all criteria verified, no `changes_requested`) increment `c`; citations on initiatives with `changes_requested` verdicts increment `s` (a weak rejection — the heuristic was used but the outcome needed correction); and dismissal events from BD-68 count as `s` per-initiative (the human explicitly said the heuristic didn't apply). Score recomputation is atomic: whenever confirmations (via `heuristic_proposals`), citation events (via `heuristic_citations`), or dismissal events (via `citation_feedback_events`) change, `quality_score` and `score_updated_at` are recomputed in the same transaction. This creates a complete feedback cycle from shaping-time usage through to outcome-weighted scoring.

**Key References:**

- **BD-30** — Laplace-Smoothed Confirmation Score (the formula BD-69 extends with citation inputs).
- **BD-43** — Precomputed Quality Score (the stored column recomputed atomically on every signal change).
- **BD-64** — Heuristic Citations (positive usage signal feeding `c`).
- **BD-68** — Citation Feedback Events (negative dismissal signal feeding `s`).
BD-68: Dismissible Heuristic Citations on Draft Initiative
- **Intent:** Allowing humans to dismiss a citation ("doesn't apply here") on a draft-stage initiative, providing a negative feedback signal that downgrades the linked spec item's confidence classification.
- **Research Thinking:** BD-64's citation events record _when_ a heuristic was used, but provide no mechanism for the human to say "this citation was wrong." BD-68 closes this feedback loop with **dismissible citations**: a human can dismiss any citation on a draft-stage initiative, triggering two effects. First, a `citation_feedback_events` row is appended (never deleted — consistent with the append-only telemetry pattern), recording `citation_id`, `heuristic_id`, `initiative_id`, `spec_item_id`, and `feedback_type = 'dismissed'`. Second, the linked spec item's `advisor_classification` is synchronously downgraded from `confident` to `flagged`, meaning the item re-enters the human review queue instead of being auto-approved. This is deliberate: if the heuristic that justified the confident classification is dismissed, the classification's basis is undermined and the item should require explicit human judgment. The UI surfaces citations only during the draft stage (`CitedHeuristics.tsx`) — when the human is actively shaping the spec. Clicking a citation opens a modal (no navigation) reading `GET /heuristics/{id}/detail` for rule text, quality score, emergent label, and status. Best-effort writes ensure a telemetry outage never blocks the dismissal response.

**Key References:**

- **BD-64** — Heuristic Citations (the citation events BD-68 extends with feedback).
- **BD-14** — Batch Review Classification (the `confident`/`flagged`/`uncertain` model that dismissal affects).
- **BD-69** — Citation-Fed Quality Score (dismissal events count as `s` in the Laplace formula).
BD-67: Per-Completion Heuristic-Gated Gardener Trigger
- **Intent:** Replacing the earlier delta-based gardener trigger with a precise, per-completion hook that runs the merge gardener only when a learn submission actually produced new heuristics.
- **Research Thinking:** The original BD-62 gardener trigger was interval-based: run the gardener every N completions, tracked by a per-project counter (`gardener_run_at`). This had two problems: it ran the gardener on completions that produced no new heuristics (wasted LLM calls), and it could miss tight timing windows where multiple near-duplicate heuristics were created in rapid succession. BD-67 replaces this with a **per-completion heuristic-gated hook** in `services/learn.py`: the gardener runs if and only if the current learn submission produced at least one new auto-confirmed heuristic (`auto_ids` is non-empty). The synchronous execution model (awaited, not fire-and-forget) ensures that the gardener's proposals are visible to the human by the time the learn submission response is returned. Migration `0040_drop_gardener_run_at.sql` drops the now-unnecessary tracking column. The pass is idempotent (clusters overlapping a pending/confirmed proposal are skipped) and degrades gracefully on LLM failure (skip cluster, log).

**Key References:**

- **BD-62** — Merge Gardener (the system BD-67 triggers).
- **BD-31** — Heuristic Deduplication (produces the `auto_ids` that gate the trigger).
BD-65: Reshape Draft Spec via MCP Tool
- **Intent:** Allowing executors to programmatically modify a draft initiative's spec fields without going through the conversation rail.
- **Research Thinking:** Before BD-65, executors could only create specs (`create_spec`) but had no MCP path to modify them — all spec editing required the conversation rail or the web UI. This asymmetry meant that an executor with a programmatic workflow (e.g., generating specs from external data, iterating on spec content based on `get_context` results) had to drop back to manual interaction for every edit. BD-65 closes this gap with `reshape_spec(initiative_id, title?, intent?, constraints?, discretion?, acceptance?)`, which overwrites whole spec fields on a draft initiative. The design is intentionally constrained: only draft initiatives can be reshaped (preventing mid-building spec mutations that would invalidate in-flight evidence), list fields are replaced wholesale rather than supporting granular add/remove operations, and empty payloads are rejected. **Last-write-wins** is a deliberate trade-off: conflict detection between executor writes and concurrent human UI edits would require versioning infrastructure disproportionate to the draft-only scope.

**Key References:**

- **BD-46** — Initiative Reassessment (allows reopening to draft; BD-65 then allows reshaping).
- **BD-28** — `create_spec` (BD-65 is the counterpart: create vs. modify).
BD-64: Track and Surface Heuristic Citations
- **Intent:** Creating a durable signal that records when a heuristic actually grounded a decision during spec shaping or auto-resolution, enabling the system to distinguish frequently-used heuristics from merely-stored ones.
- **Research Thinking:** BD-30's Laplace score counts confirmations from the learn phase (post-hoc), but has no signal for whether a heuristic was actually _used_ during spec shaping — the moment it matters most. BD-64 closes this gap by recording **citation events** in an append-only `heuristic_citations` table. Each row links `heuristic_id`, `initiative_id`, `context` (`'classification'` or `'auto_resolution'`), and `spec_item_id`. Two trigger points fire citations: (1) in `services/shaping.py`, when `_classify_and_annotate` classifies a spec item as `confident` and cites a heuristic via the `heur_<hex>` pattern; and (2) in `mcp_server.py`, when the Discretion Auditor auto-resolves a decision from `escalate_and_resolve` and the matched discretion item's `advisor_classification_reason` cites a heuristic. The extraction mechanism (`extract_heuristic_ids`) parses the same `heur_<hex>` pattern the BD-17 classification prompt asks the LLM to cite — reusing an existing contract rather than introducing a new one. No row is ever updated or deleted; per-heuristic `citation_count` / `last_cited_at` are always derived by aggregation. Best-effort writes ensure that a telemetry outage never blocks shaping or escalation.

**Key References:**

- **BD-17** — Heuristic Lifecycle (the `heur_<hex>` citation pattern in classification prompts).
- **BD-13** — Discretion Auditor (auto-resolution is one citation trigger).
- **BD-68** — Citation Dismissal (extends citations with user feedback).
- **BD-69** — Quality Score Integration (citations feed into Laplace scoring).
BD-63: Unsupervised Emergent Labels for Heuristic Retrieval Scoping
- **Intent:** Providing semantic topic labels for the heuristic corpus that emerge from the corpus itself, without human taxonomy curation, to improve retrieval relevance.
- **Research Thinking:** As the heuristic corpus grows, retrieval becomes noisier — a query about "database migrations" retrieves heuristics about "API design" simply because both share similar vocabulary. BD-63 addresses this with **unsupervised emergent labels**: semantic topic clusters derived entirely from the corpus's own embeddings. `services/labeler.py`'s `run_labeler()` clusters the _global_ active heuristic corpus (no project scoping — labels are cross-cutting semantic themes) by pgvector cosine similarity, single-linkage connected components at `HEURISTIC_LABEL_SIMILARITY_THRESHOLD` (default 0.55 — deliberately much coarser than BD-62's 0.86 near-duplicate threshold). Each multi-member cluster gets one LLM-generated name; every active heuristic is then soft-assigned to every label whose centroid it's within threshold of. Every derivation pass fully DELETEs and reinserts both `heuristic_labels` and `heuristic_label_members` in one transaction — this keeps labels honestly "derived state." Below `LABEL_MIN_CORPUS_SIZE` (default 20), the corpus is "cold" and labels have no effect. At retrieval time, `get_context` resolves which label(s) the query embedding falls within (via each label's centroid) and nudges `dist` down by `LABEL_MATCH_DIST_BOOST` (default 0.05) — a soft tiebreaker within the existing `(laplace_rank, dist)` sort key, never overriding the BD-30/BD-44 primary ordering. Re-derivation fires automatically when the active heuristic count drifts by `LABEL_RECOMPUTE_INTERVAL` (default 3) since the last run.

**Key References:**

- **BD-62** — Merge Gardener (near-duplicate clustering at 0.86; BD-63 clusters broad topics at 0.55).
- **BD-44** — RRF Retrieval (label boost operates within the existing ranking pipeline).
- **BD-17** — Heuristic Corpus (the source material being labeled).
BD-62: Merge Gardener for Heuristic Corpus Compaction
- **Intent:** Automatically detecting and proposing merges for near-duplicate heuristics that fragment the corpus's signal, without applying any changes unsupervised.
- **Research Thinking:** BD-31's deduplication catches near-duplicates at draft time, but heuristics can converge semantically over time — two rules written months apart may describe the same insight in different vocabulary. BD-62 addresses this with a **merge gardener**: an unsupervised clustering pass in `services/gardener.py` that detects tight clusters of near-duplicate active heuristics and proposes merging them into a single, LLM-drafted subsuming rule. The critical design constraint is that the gardener **never applies a merge unsupervised** — it records a pending `heuristic_merge_proposals` row, and only human confirmation (`confirm_merge_proposal`) triggers the atomic merge. The merge operation introduces **evidence concentration**: all confirmed `heuristic_proposals` from absorbed members are re-pointed to the survivor, so the merged heuristic's Laplace score reflects the full evidence base of its constituents — fixing a vote-splitting problem where k near-duplicates each had c/k confirmations instead of c. Two orthogonal retire pointers — `superseded_by` (wrong→replaced, 1:1 evolution) vs. `merged_into` (right→collapsed, many→1 merge chain) — ensure the semantic distinction between "this rule evolved" and "these rules said the same thing" is preserved in the corpus history. Clustering uses single-linkage over `HEURISTIC_MERGE_SIMILARITY_THRESHOLD` (configurable), and clusters overlapping a pending/confirmed proposal are skipped for idempotency.

**Key References:**

- **BD-17** — Heuristic Lifecycle (the supersession model BD-62 extends with merge semantics).
- **BD-31** — Heuristic Deduplication (prevents duplicates at creation; BD-62 handles those that emerge over time).
- **BD-30/BD-43** — Laplace Quality Score (recomputed on merge via evidence concentration).
- **BD-67** — Per-Completion Heuristic-Gated Gardener Trigger (the firing policy).
BD-61: Hard-Gate Human Judgment Criteria from Reviewer Auto-Approval
- **Intent:** Ensuring that acceptance criteria explicitly marked as requiring human judgment cannot be auto-approved by the reviewer LLM, regardless of how clear the evidence appears.
- **Research Thinking:** BD-26's auto-approval pipeline was designed to minimize the review bottleneck, but it introduced a risk: certain criteria inherently require human judgment that no amount of evidence can satisfy mechanistically — design aesthetics, strategic alignment, UX quality, or any criterion where "the evidence is clear" and "the outcome is good" are fundamentally different questions. BD-61 introduces a service-layer hard gate in `services/review.py`: criteria marked `human_judgment: true` are never auto-approved, even if the reviewer LLM confidently returns `pass`. The override happens in `_compute_verdicts` (not at the prompt level), making it impossible for prompt drift or model behavior changes to bypass the gate. If `human_judgment` is set, the LLM verdict is overridden to `needs_your_eye` regardless of the model's output. This preserves the efficiency of BD-26 for mechanical criteria while ensuring that judgment calls remain human-exclusive — a service-layer invariant rather than a prompt-layer hope.

**Key References:**

- **BD-26** — Auto-Approve Verification Evidence (the auto-approval system BD-61 constrains).
- **BD-33** — Inline Advisor Verdict (the MCP path that also respects this gate).
BD-60: Surface Heuristic Conflicts During Spec Shaping
- **Intent:** Preventing contradictory spec items from reaching the building phase by detecting conflicts between proposed items and established heuristics during the shaping stage.
- **Research Thinking:** Spec shaping is where intent solidifies into constraints. If a proposed constraint contradicts an established heuristic — a rule the project learned from prior experience — that contradiction should be visible _before_ engineering effort is spent, not discovered mid-building when rework is expensive. BD-60 moves conflict detection left into the shaping stage via `services/conflict_detection.py`: after the Advisor generates proposals, each proposed spec item is embedded and compared against the project's active heuristic corpus (top-K by cosine distance), then an LLM evaluator classifies each candidate pair as `no_conflict`, `potential_conflict`, or `direct_conflict`. Detected conflicts are attached as metadata on spec items and surfaced in the living-spec page. The system is deliberately advisory-only — conflicts don't block progression — because the human may intentionally override a heuristic based on new context. The synchronous execution model (during shaping, not as a background task) ensures conflicts are visible when the human reviews the initial proposal.

**Key References:**

- **BD-17** — Heuristic Corpus (the established rules that conflict detection queries against).
- **BD-30** — Laplace Quality Score (higher-confidence heuristics are prioritized in conflict checks).
- **BD-14** — Batch Review Classification (conflict annotations follow the same classification model).
BD-59: Decision ID Preservation in resolve_decision MCP Tool
- **Intent:** Enabling stable cross-call traceability for decisions escalated by executors.
- **Research Thinking:** The `escalate_and_resolve` MCP tool generates a unique `decision_id` for each raised decision, allowing an executor to track it across context windows or system restarts. However, when the resolved decision was persisted via `resolve_decision`, a new UUID was generated server-side, breaking the link. BD-59 extends `resolve_decision` to accept an optional `decision_id` parameter: when supplied, it is used as the primary key verbatim, preserving the ID assigned upstream. When omitted, UUID generation remains unchanged. Duplicate IDs raise `ConflictError` rather than silently overwriting, preventing accidental ID collisions. This establishes a durable chain: `escalate_and_resolve(question)` → `decision_id_assigned` → `resolve_decision(decision_id=...)` → persistent row with matching ID.
BD-58: Remove Pre-Registration Stamp System
- **Intent:** Simplifying the decision flow by retiring the pre-registration hypothesis framework.
- **Research Thinking:** BD-55 introduced pre-registration stamps—a Bayesian-inspired mechanism for capturing predicted outcomes before they are known, with explicit falsification conditions. In practice, the added rigor of "predict before observing" became friction without corresponding insight gain: adoption was sparse and the narrative flow of decision-making favored post-hoc reflection over pre-commitment. BD-58 removes the `pre_registration_stamps` table and all supporting logic, streamlining the conversation-first decision flow. The timestamp ordering invariant it enforced (stamp before outcome) is no longer a concern. Historical stamps are preserved in the database (migration 0036 soft-deletes via table drop, not cascading delete) in case future analysis wants to mine the data.
BD-57: Conversation-First Decision Flow Integration Tests
- **Intent:** Validating the state sequence and prompt fidelity of the simplified decision lifecycle.
- **Research Thinking:** After BD-55/BD-58's pre-registration cycle, the decision flow stabilized into a conversation-first pattern: escalate via `escalate_and_resolve`, resolve inline without intermediate state, persist as a closed decision. BD-57 adds comprehensive integration tests (`test_bd57.py`) verifying three critical constraints: (1) state sequence invariants are enforced (transitions only occur in legal order), (2) legacy open decisions (from before the simplification) load correctly on first call to `get_spec`, and (3) human-resolved decision counts are computed accurately across both resolved and unresolved rows. The NextStepHint prompts are updated to advise executors to use `escalate_and_resolve` followed by `resolve_decision` for the conversation-first flow, rather than layering intermediate escalation states.
BD-55: Pre-Registration Stamps for Decisions and Milestones
- **Intent:** Capturing hypothesis predictions before outcome observation, inspired by Bayesian pre-registration protocols.
- **Research Thinking:** Standard decision-making often suffers from hindsight bias and post-hoc rationalization. BD-55 introduces **pre-registration stamps**—immutable records created _before_ an outcome is known, carrying the decision-maker's predicted result, reasoning, and explicit falsification condition. A stamp pairs to either a decision (to be resolved later) or a milestone marker (a project event). Once created, stamps cannot be edited; only an outcome resolution creates a timestamped record of success or failure (enforced at the service layer: `stamp.created_at < outcome.resolved_at`). This mechanism enables the Advisor and humans to audit ex-post how well predictions held up, feeding into BD-30's Laplace confidence scoring and BD-39's outcome-weighted heuristics. The intent is to reduce "we predicted X but actually did Y and rationalized it as correct" dynamics in project retrospectives.
BD-54: Track LLM Call Costs per Project
- **Intent:** Making operational costs of continuous reasoning visible and analyzable per project.
- **Research Thinking:** As the Advisor's role expands (shaping, reviewing, synthesis, contradiction detection), the cumulative LLM token spend per project becomes a material operational metric. BD-54 introduces a durable `llm_cost_log` table with one row per API call: provider, model, purpose (shaping/review/synthesis/etc.), prompt + completion tokens, latency, and cost in USD (sourced from the LLM provider's response). Logging happens asynchronously (fire-and-forget after the response is returned to the user) to avoid blocking request latency. The log enables dashboards, cost attribution, and tail-analysis (e.g., "which initiatives had the highest review friction by token spend?"). Cost-per-purpose breakdowns are computable on-demand, feeding into BD-39's outcome-weighted scoring and future research on whether review friction correlates with downstream rework.
BD-52: Importance Validation on Assessment & Reassessment
- **Intent:** Preventing redundant or conflicting work before it enters the building phase.
- **Research Thinking:** The assessment phase (spec shaping) often produces initiatives that substantially overlap with or directly contradict existing work. BD-52 implements **importance validation**: when an initiative is assessed or reassessed, the Advisor automatically evaluates it against all other open and closed initiatives in the project. The evaluation yields one of three verdicts: `proceed` (valuable and non-conflicting), `redundant` (overlaps substantially with existing work), or `conflicting` (contradicts or undermines another initiative). Mixed cases—partially redundant _and_ conflicting with different initiatives—are supported by listing multiple verdicts with specific citations. The evaluation is grounded exclusively in actual project initiatives (not generic reasoning), uses the assessed initiative's intent as the anchor, and applies an LLM evaluator with semantic-overlap judgment. Verdicts are advisory-only (they do not modify items or block progression); the human makes the final call. This shift moves friction left—catching suboptimal work direction before engineering effort is spent.

**Key References:**

- **BD-46** — Initiative Reassessment (the trigger for validation when reassessing an existing initiative).
- **BD-52** — New service: `app/services/importance_validation.py` integrated into Advisor response flow.
BD-51: Cross-Initiative Spec Loop Detection
- **Intent:** Surfacing recurring friction patterns that indicate systemic issues in project execution.
- **Research Thinking:** Some problems recur across multiple initiatives—the same decision topic is raised unresolved, the same memory entry drifts and requires repeated re-verification, or the same criterion text struggles through 3+ verification rounds. BD-51 detects these patterns as **spec loops** and surfaces them to the human as signals of underlying friction. A loop is characterized by a `signal_type` (decision_topic, drifted_memory, or slow_domain) and a `signal_key` that identifies the specific pattern (topic string, memory ID, or criterion text). The dismissed_spec_loops table tracks which loops the human has explicitly dismissed; loops persist across page reloads until manually cleared, ensuring visibility without alert fatigue. Three signal types: (1) decision_topic: same topic raised across 2+ initiatives without resolution; (2) drifted_memory: same memory entry flagged as drifted in 2+ initiatives; (3) slow_domain: criterion text requiring 3+ rounds of revision in multiple initiatives. Loop detection is triggered client-side when an initiative reaches `learning` or `complete` state; the backend validates the loop pattern and stores it with the project and dismissed state. This informs future research on workload planning (BD-48 prior-as-baseline benefits from knowing which patterns recur).

**Key References:**

- **BD-12** — Reflexive Memory Verification (drifted_memory signals come from here).
- **BD-30** — Laplace-Smoothed Confirmation Score (loop data feeds into outcome-weighted scoring).
BD-49: Attach Quantified Friction Metrics to the Learn Record
- **Intent:** Capturing measurable signals of how much rework and decision-making burden an initiative experienced.
- **Research Thinking:** The Learn stage captures qualitative narrative and extracted heuristics, but lacks quantified metrics on execution friction. BD-49 computes **four friction metrics** at initiative closure and attaches them to the learn record's `outcome` JSONB: (1) `criteria_revision_count`—how many times criteria received `changes_requested` verdicts (rounds of rework), (2) `decisions_raised`—count of human decisions escalated during the initiative (excluding agent-resolved decisions from the Discretion Auditor), (3) `changes_requested_count`—raw count of `changes_requested` verdicts across all criteria, and (4) `human_resolution_count`—how many decisions were resolved by the human (vs. agent-resolved). These are computed durably at closure time from existing tables (criteria, decisions, verdicts) and stored immutably in the learn record. The metrics enable BD-39's outcome-weighted heuristic scoring (linking heuristic confirmations to initiative friction), inform roadmap planning (initiatives with high friction may signal misaligned domain models), and support future research on "how much rework is normal?" vs. "when should we stop and reassess?"

**Key References:**

- **BD-39** — Outcome-Weighted Heuristic Confirmation Scoring (uses friction metrics to weight which confirmations compound in the Laplace score).
- **BD-13** — Discretion Auditor (agent-resolved decisions are excluded from decisions_raised).
BD-48: Prior-as-Baseline Heuristic Synthesis
- **Intent:** Anchoring future heuristic discovery to what the project has already learned.
- **Research Thinking:** Once a project has built up a library of heuristics (via BD-17, BD-30, BD-31), the synthesis process for new initiatives should use that library as a baseline. BD-48 implements **prior-as-baseline synthesis**: when synthesizing next-step recommendations or cross-initiative patterns, the Advisor contextualizes proposals against the project's existing heuristics—reducing redundant discovery and promoting incremental refinement of what's already known. This shifts the synthesis engine from "what should we learn?" to "what should we learn _next, building on what we know_?" — a critical maturity milestone for a project's strategic continuity.
BD-47: Event-Driven Executor Resume via Criterion Verdict Pub/Sub
- **Intent:** Enabling executors to block and wait for human verification verdicts without polling.
- **Research Thinking:** The BD-33 MCP path opened inline verdict access, but an executor building a complex workflow often needs to **wait** for a human verdict before proceeding. The naive approach is polling `get_criteria_status` in a loop — wasteful and high-latency. BD-47 introduces a **criterion verdict pub/sub channel** using Redis: when a human records a verdict via the web UI (`record_criterion_verdict`), the backend publishes to a named Redis channel keyed per initiative. Executors can now call `wait_for_verdict(initiative_id, timeout=N)` to block until the channel fires or timeout expires, returning the updated criterion state. The MCP interface gains a new tool; the backend's verdict recording path emits the pub/sub event asynchronously so the HTTP write is not blocked.
BD-46: Initiative Reassessment & Spec Reopening
- **Intent:** Allowing an initiative to be reopened for refinement after it begins building.
- **Research Thinking:** Occasionally a human discovers mid-building that the spec was incomplete or misaligned with actual needs. The prior model forced them to either proceed with a flawed spec or archive and restart. BD-46 introduces **reassessment**: a building initiative's spec can be reopened, acceptance criteria can be refined, and the verification state resets to pending. This allows for mid-course correction while preserving the initiative's history and decision record — treating the spec as a living document even after work has started, not a frozen artifact.
BD-44: Hybrid BM25 + Dense Retrieval for Heuristic Context Search
- **Intent:** Combining lexical and semantic search to surface heuristics that cosine distance alone would miss.
- **Research Thinking:** BD-40's two-hop retrieval refined the semantic side (similarity + temporal anchoring), but heuristics written in different vocabulary than the query would still be missed. BD-44 introduces **hybrid BM25 + dense retrieval** for the heuristic search in `get_context`: Postgres full-text search (BM25 ranking) and cosine similarity (dense vector ranking) are both computed, then fused via **Reciprocal Rank Fusion (RRF, k=60)**—a rank aggregation technique from information retrieval that balances sparse (keyword) and dense (semantic) signals. A heuristic ranked #1 by BM25 but #10 by cosine gets a fused score higher than one ranked #5 by both — capturing the value of each signal independently. The RRF-fused score becomes the base distance used in BD-30's Laplace re-ranking.
BD-43: Precompute Laplace Quality Score on Heuristics Table
- **Intent:** Eliminating the Python post-sort overhead and enabling Laplace-scored retrieval at query time.
- **Research Thinking:** BD-30 computed the Laplace score in Python after retrieving heuristics from SQL, requiring all candidates to be loaded into memory for sorting. As the heuristic library grows, this becomes a latency bottleneck. BD-43 moves the Laplace score calculation into SQL as a computed column on the heuristics table: `laplace_score = (confirmations + 1) / (confirmations + has_rejection + 2)`. The score is **precomputed whenever confirmations or rejection status change**, not on every query. The retrieval query can now `ORDER BY laplace_score DESC` directly in SQL, dramatically reducing latency and enabling efficient pagination over large heuristic sets.
BD-41: Contradiction Detection in `get_context`
- **Intent:** Surfacing conflicts between proposed new ideas and existing project memory.
- **Research Thinking:** The `get_context` hits inform new decisions, but the system had no feedback loop to flag when a _proposed new idea_ contradicts an existing memory entry or decided heuristic. BD-41 adds a **verification check** after `get_context` retrieval: for each proposed initiative or observation, the Advisor evaluates whether the proposal contradicts any of the retrieved context hits (using a dedicated `advisor-proposal-verification` prompt). Proposals that fail this check are suppressed, reducing "we tried this before and it didn't work" rework cycles.
BD-40: Two-Hop Contextual Retrieval for `get_context`
- **Intent:** Surfacing temporally-anchored heuristics that cosine similarity alone cannot reach.
- **Research Thinking:** BD-30's Laplace score and BD-31's deduplication made the heuristic store high-signal, but retrieval remained purely cosine-based: a heuristic written in different vocabulary than the query would be missed regardless of how many times it had been confirmed. BD-40 introduces a **second retrieval hop** that uses the first-pass decisions as anchors rather than treating each query in isolation.

  The mechanism: after the initial cosine search, the top-3 decision hits are extracted as "anchor initiatives." A second query fetches heuristics that were active at the time those initiatives were running — filtered by `h.created_at <= MIN(i_anch.updated_at)` and `h.project_id = project_id` — and merges them into the result with a small score boost. The temporal filter is essential: it prevents heuristics written in hindsight from being attributed to decisions they didn't influence.

  Ranking in the merged result uses a `_merged_sort_key` of `(laplace_rank, dist)` — the BD-30 Laplace score is the primary sort key, so a highly-confirmed heuristic from the second hop can displace a merely similar first-pass result. Second-hop heuristics that already appear in the first-pass are deduplicated via `exclude_heuristic_ids`. The `ContextHit` model gains an internal `laplace_rank` field (`Field(exclude=True)`) — the same pattern BD-37 used for `memory_id` — so the MCP response contract is unchanged.

**Key References:**

- **BD-30** — Laplace-Smoothed Heuristic Confirmation Score (the `laplace_rank` driving the merged sort).
- **BD-31** — Heuristic Deduplication (ensures the confirmation counts in BD-30 are meaningful).
- **BD-39** — Outcome-Weighted Confirmation Scoring (refines the laplace weights used in second-hop ranking).
BD-39: Outcome-Weighted Heuristic Confirmation Scoring
- **Intent:** Distinguishing confirmations from successful initiatives from those that ended with rework.
- **Research Thinking:** BD-30's Laplace score treated every confirmation as equivalent — one confirmation was one unit of confidence regardless of whether the confirming initiative succeeded cleanly or required `changes_requested` corrections on its acceptance criteria. This created a symmetry problem: a heuristic confirmed five times across initiatives that all needed rework was ranked the same as one confirmed five times across initiatives that shipped cleanly.

  BD-39 breaks this symmetry by weighting confirmations by outcome. A confirmation from an initiative in state `complete` with no `changes_requested` verdicts on any acceptance criterion counts as **3.0** (successful outcome); all other confirmations count as **1.0** (standard). The `heur_c` SQL expression in both `_context_search` and `_second_hop_heuristics` accumulates this weighted sum, which feeds directly into `_laplace_score(c, s)`. The score formula is unchanged; only what `c` measures is refined. New heuristics still start at S = 0.5; a heuristic confirmed once via a successful completion starts at S = 0.8 rather than 0.667.

**Key References:**

- **BD-30** — Laplace-Smoothed Confirmation Score (the scoring formula extended here).
- **BD-31** — Heuristic Deduplication (routes reconfirmations to existing rows so this weighting compounds correctly).
BD-38: Propose Next Step When Initiative Completes
- **Intent:** Closing the loop between completing work and deciding what to do next.
- **Research Thinking:** The completion moment was previously inert from the Advisor's perspective — the human had to re-engage the conversation rail explicitly after a retrospective was filed. BD-38 makes completion **generative**: when a `learning → complete` transition is detected client-side (via the SpecProvider SWR delta effect), a `trigger="completion_proposal"` request is automatically sent to the backend. The Advisor responds with a next-step recommendation grounded in the completed initiative's spec, acceptance evidence, and project memory — without requiring a user message.

  The architectural choice to detect the transition client-side rather than emit a server-sent event keeps the backend stateless about conversation flow (consistent with the IndexedDB-first conversation history model). The trigger routes to a dedicated function in `services/advisor.py` rather than a generic conversation turn, so the prompt can be specifically grounded in retrospective context. When the recommendation includes a follow-up initiative, a "Create initiative from this" affordance is surfaced in the rail — stashing the pre-filled description and routing to the project creation form.

**Key References:**

- **BD-20** — Guided Discovery (the discovery rail this completion proposal feeds into).
- **BD-22** — Persisted Observations (the pattern of advisor-generated suggestions becoming durable entities).
BD-37: Memory Hit Application Signal
- **Intent:** Building the first feedback channel between retrieval and outcomes.
- **Research Thinking:** BD-32 identified "the improve stage has no feedback channel" as the open challenge with the highest strategic impact: cosine similarity governs retrieval but cannot be refined by observed relevance. BD-37 introduces the first signal that closes this loop. When an executor calls `get_context` and that turn produces a confirmed spec item or resolved decision, all memory rows retrieved during that initiative's session buffer are credited: `useful_count += 1` and `last_applied_at = now()`.

  The **attribution policy is intentionally liberal**: all hits buffered per initiative in a Redis Set (TTL 900s) are credited when any outcome fires, rather than trying to isolate which specific hit influenced which specific confirmation. This avoids a brittle causal attribution problem — for the initial signal, presence in the context window at the time of a positive outcome is sufficient. The buffer is cleared after crediting, so signals accumulate across turns but don't double-count within one.

  The MCP contract is preserved via a pattern established here and carried forward into BD-40: `ContextHit` gains a `memory_id: str | None = Field(default=None, exclude=True)` field that is populated internally but excluded from serialization. Schema migration 0028 adds `useful_count` and `last_applied_at` to the `memory` table.

**Key References:**

- **BD-32** — Self-Learning Evaluation (Challenge 3: improve has no feedback channel — the gap this initiative directly addresses).
- **BD-12** — Reflexive Memory Verification (the verify-on-use loop that now has a complementary apply signal).
BD-36: Include Rationale Claims in Memory Embeddings
- **Intent:** Making cause-effect rationale visible to `get_context` retrieval.
- **Research Thinking:** BD-32's Challenge 2 identified a specific dark spot: `embed_memory()` in `store.py` embedded only the `summary` and `title` fields, excluding the `outcome` JSONB array where BD-13b's cause-effect claims lived. A memory entry's richest analytical content — "X happened because Y, resulting in Z" — was invisible to cosine retrieval. Executors running `get_context` could retrieve a memory by surface vocabulary while missing the causal reasoning behind it, or miss a memory entirely because the query matched the cause rather than the surface summary.

  BD-36 fixes this by concatenating `rationale_claims` (the string-rendered outcome entries) into the text passed to the embedder, producing a composite embedding that spans both the summary and the causal claims. A backfill script (`backfill_embeddings.py`) re-embeds all existing memory rows under the new composite scheme. No schema changes required — the embedding column already exists.

**Key References:**

- **BD-32** — Self-Learning Evaluation (Challenge 2: rationale claims are dark to retrieval — the gap this initiative directly addresses).
- **BD-13** — Discretion Auditor & Rationale Capture (the `outcome` JSONB field that BD-36 now includes in embeddings).
BD-35: Positive Verification Path for Memory Entries
- **Intent:** Eliminating the "audit treadmill" for executors who check memory entries and find them accurate.
- **Research Thinking:** BD-32's self-learning evaluation identified a critical asymmetry in the BD-12 verify loop: filing a drift report (negative result) updates `last_verified_at` on human approval, but finding an entry accurate and filing nothing leaves `last_verified_at` unchanged. The entry reappears as stale on the next `list_memory_for_audit` pass even if it was just verified minutes ago. A conscientious executor who checks regularly is penalized compared to one who checks nothing. BD-35 resolves this by introducing `mark_memory_verified` — a direct MCP tool that stamps `last_verified_at` immediately with no human gate, because no mutation is occurring. The positive-check path is now as visible as the negative-report path, and the verify stage's loop-level coverage is symmetric in both directions.

**Key References:**

- **BD-12** — Reflexive Memory Verification (the drift-report / audit loop this initiative extends).
- **BD-32** — Self-Learning Evaluation (Challenge 1: positive verification leaves no trace).
BD-34: Research Findings Freetext Field
- **Intent:** Giving executors a persistent, scrollable narrative space within research initiatives.
- **Research Thinking:** BD-15 introduced the research framing (investigating → findings → retrospective), but provided no durable place for mid-investigation narrative. The per-criterion evidence box is scoped and truncated; it captures what was found, not the evolving reasoning behind it. BD-32's own evidence trail demonstrated the problem — rich synthesis was produced but had nowhere to live between calls. BD-34 introduces a `research_findings` TEXT field on research initiatives with **full-overwrite semantics**: each MCP write is a consolidated snapshot, not an append log, which keeps the data model simple while letting executors structure their own narrative across a long investigation. The field is deliberately scoped to research-type initiatives only (BD-15's type taxonomy remains the boundary) and co-located with criteria evidence on the living-spec page so humans and executors share the same working document.

**Key References:**

- **BD-15** — Research Initiatives (the type taxonomy that scopes this field).
- **BD-32** — Self-Learning Evaluation (produced the research narrative that exposed the missing persistence layer).
BD-33: Inline Advisor Verdict from MCP `submit_evidence`
- **Intent:** Closing the MCP verification loop — executor submits evidence, gets the verdict, acts on it, all in one round-trip.
- **Research Thinking:** The original `submit_evidence` MCP tool fired the Advisor's evaluation as a background task (fire-and-forget) and returned immediately, mirroring the web UI's async pattern. For a human reading a dashboard, asynchrony is correct: the evaluation takes 2–5 seconds, and the human is looking at a page, not blocking. For an MCP executor, it is wrong: the executor's next action depends on the verdict, so it was forced to poll `get_criteria_status` in a loop. BD-33 introduces a **compute/persist separation** in `services/review.py`: `_compute_verdicts` (LLM call only) and `_apply_assessments` (mutation only) are extracted as shared helpers. The MCP path awaits them inline; the HTTP path schedules them as a background task. Both paths call the same underlying logic — no duplication. The `submit_evidence` MCP response now includes `advisor_verdicts` (per-criterion verdict + notes) and `verification_synthesis`, enabling the executor to auto-resubmit on `borderline`, escalate on `needs_your_eye`, and proceed on `pass` — all without a second call.

**Key References:**

- **BD-26** — Auto-Approve Verification Evidence (the advisor-led gate that BD-33 exposes synchronously).
- **BD-14** — Advisor-Led Batch Review (the Human-on-the-Loop pattern this extends to the MCP path).
BD-32: Evaluate System Self-Learning Capabilities
- **Intent:** Producing an honest, evidence-backed assessment of the self-learning loop as it stands — not a feature summary, but an architectural diagnosis.
- **Research Thinking:** As Doen's knowledge infrastructure accumulated across BD-12, BD-13, BD-17, BD-20, BD-25, BD-30, and BD-31, the natural question was: does the system actually learn and improve, or does it just accumulate? BD-32 applied the **five-stage learning loop** frame — capture → store → verify → apply → improve — to each shipped mechanism. The evaluation's structural finding was that capture and apply are strong; store is mechanically sound; but verify is protocol-gated rather than enforced (no positive-check path, no enforcement of the consistency check), and improve has no feedback channel whatsoever — the system accumulates knowledge but cannot refine it based on how that knowledge was actually used.

  Three concrete open challenges were identified, each specific enough to seed a future initiative:
  1. **Positive verification leaves no trace** — seeded BD-35.
  2. **Rationale claims are dark to retrieval** — `embed_memory()` in `store.py` excludes the `outcome` JSONB field where BD-13b's cause-effect claims live, making the richest capture artifact invisible to `get_context()`.
  3. **Improve has no feedback channel** — no mechanism records whether a retrieved memory hit influenced an outcome; cosine similarity governs retrieval but cannot be refined by observed relevance.

  A notable scope omission was identified: BD-17/BD-31's heuristic extraction and deduplication — a fully implemented mechanism — was absent from the spec constraint list and therefore excluded from the evaluation. The evaluation is logged as a research initiative with full `research_findings` narrative, serving as the primary reference for the self-learning improvement roadmap.

**Key References:**

- **BD-12** — Reflexive Memory Verification (the verify-stage mechanism evaluated).
- **BD-13** — Discretion Auditor & Rationale Capture (both sub-mechanisms evaluated).
- **BD-20** — Proactive Synthesis (the meta-apply mechanism evaluated).
- **BD-25** — Auto-Approval of Learnings (the capture-gate mechanism evaluated).
BD-31: Heuristic Deduplication at Draft Time
- **Intent:** Preventing the accumulation of semantically duplicate heuristics across initiatives.
- **Research Thinking:** The BD-17 flywheel had a compounding flaw: every `confirm_heuristics` call unconditionally created a new heuristic row, regardless of whether the same insight had already been extracted from a prior initiative. This caused two failure modes — a growing list of near-duplicate rules diluted retrieval signal, and the BD-30 confirmation score (c) never grew because the same insight was always written as a fresh entry with c = 0. BD-31 addresses this with a **two-pass intent classification** at draft time:
  1. **Embedding Similarity Search:** For each proposed rule, the top-K active heuristics (by cosine distance) are retrieved from the vector store as candidate matches. Only active heuristics (`superseded_by IS NULL`) are considered, preventing retired rules from polluting the candidate pool.
  2. **LLM-as-Deduplicator:** The candidate set is passed to a structured LLM call that classifies the proposal as one of three intents: `new` (distinct insight), `confirms:<id>` (same core insight, different wording), or `supersedes:<id>` (refinement of an existing rule). Uncertain cases always fall back to `new` — the safe default.

  The `confirms` path is where the flywheel compounds: instead of creating a new heuristic row, the proposal is linked to the _existing_ heuristic row. This directly increments the c count in the BD-30 Laplace score, meaning rules that recur across multiple initiatives naturally rise in confidence without any explicit scoring step. The human oversight model is preserved: `supersedes` proposals (which retire an existing rule) are held pending for human review, while `new` and `confirms` are auto-confirmed autonomously.

**Key References:**

- **BD-30** — Laplace-Smoothed Confirmation Score (c/s scoring that this initiative feeds).
- **BD-17** — Compound Knowledge Flywheel (the heuristic lifecycle this initiative extends).
BD-30: Laplace-Smoothed Heuristic Confirmation Score
- **Intent:** Surfacing battle-tested heuristics above freshly extracted ones in retrieval.
- **Research Thinking:** The BD-17 heuristic store treated all rules as equal, ordering retrieval purely by embedding distance. A heuristic observed once in one initiative ranked the same as one confirmed across ten. BD-30 introduces a **Laplace-Smoothed Confirmation Score** to break this symmetry without introducing a brittle confidence metric that requires manual calibration.

  The score S = (c + 1) / (c + s + 2) is adapted from Laplace smoothing in Bayesian inference:
  - **c** = number of times this heuristic has been confirmed by a new initiative (confirmed proposals with `replaces IS NULL` pointing to this heuristic)
  - **s** = 1 if the heuristic's direct predecessor in its supersession chain was `rejected`, signalling that the rule's lineage has a failure in it; 0 otherwise
  - A brand-new heuristic starts at S = 0.5 — meaningfully above zero, but below any heuristic that has been confirmed even once (S ≥ 0.667 at c=1, s=0)
  - S asymptotically approaches 1.0 as confirmations accumulate; a lineage with a rejection in it is permanently penalized relative to a clean chain

  Retrieval is a **Python post-sort** over the SQL result: heuristics are sorted by `(-S, dist)` so that a highly-confirmed heuristic can rank above a merely similar decision or memory hit. This avoids storing a derived score column (which would need to be updated on every confirmation) in favor of computing it at query time from the existing `heuristic_proposals` table — consistent with the project invariant that Postgres is the source of truth and derived values are computed, not persisted.

**Key References:**

- **Laplace Smoothing (Bayesian inference)** — add-one smoothing to avoid zero-probability estimates, applied here to a confidence prior over rule confirmations.
- **BD-17** — the heuristic lifecycle that defines c (confirmed proposals) and the supersession chain that defines s.
- **BD-31** — the deduplication pass that makes c grow by routing reconfirmations to existing heuristic rows rather than creating duplicates.
BD-26: Auto-Approve Verification Evidence
- **Intent:** Minimizing the review bottleneck during the verification stage.
- **Research Thinking:** During verification, the Advisor previously presented every piece of submitted evidence to the human for individual review — the same bottleneck that BD-14 resolved for shaping. BD-26 establishes a verification flow that mirrors this pattern: the Advisor evaluates all submitted evidence, auto-approves criteria that are a clear pass, and only escalates flagged or borderline criteria to the human for explicit judgment. The human's role shifts from reviewing every criterion individually to correcting the Advisor's synthesis where it falls short.
UI Refinement: Unifying the Governance Display (Agent Latitude)
- **Intent:** Reducing visual hierarchy fragmentation during spec review.
- **Research Thinking:** The "Agent latitude" (discretion) section was previously isolated from the primary "Intent -> Constraints -> Acceptance criteria" progressive disclosure flow. By unifying its rendering with the other governing sections, the review arc becomes a single, continuous loop. Discretion items now benefit from the same auto-collapse behavior upon approval, ensuring the UI remains calm and focused solely on pending decisions, while preserving their distinct semantic role (the executor's calls, not the human's).
BD-25: Auto-Approve Learnings & Structured Review
- **Intent:** Minimizing review friction for routine project knowledge.
- **Research Thinking:** The Learning stage is often the highest friction point in the oversight loop. Many learnings are straightforward restatements of work done within granted discretion. BD-25 applies the **Auditor Pattern** to the learning draft: it evaluates proposed learning bullets against the initiative's discretion items and criteria. Items that clearly align with established boundaries are marked `auto_approved` and presented passively, while novel or high-entropy insights are flagged for human review. This ensures human attention is reserved for knowledge that actually expands the project's strategic horizons.
BD-24: Scoped Observations & The "Reject" Signal
- **Intent:** Increasing observation precision and managing synthesis noise.
- **Research Thinking:** As a project's history deepens, advisor observations can become repetitive or irrelevant if not strictly bounded. BD-24 introduces **Temporal Scoping** for synthesis: observations are now explicitly linked to the specific initiative that triggered the discovery. This implements a "one-observation-per-initiative" lifecycle cap, preventing the advisor from re-surfacing the same insight across multiple synthesis cycles. Crucially, it also introduces the **Negative Signal (Reject)** flow. By allowing humans to dismiss an observation without acting, we capture an explicit signal of "not relevant" or "already known but unaddressed." This negative signal is as important as the positive "Resolve" signal for refining the advisor's future synthesis heuristics, ensuring that the discovery rail remains high-signal as the project scales.
BD-22: Persisted Advisor Observations
- **Intent:** Closing the loop between synthesis and action.
- **Research Thinking:** While BD-20 introduced proactive synthesis, the resulting "observations" were transient UI elements. BD-22 formalizes these as **Persistent Observations**—first-class database entities that survive session reloads. It introduces a "Resolve to Initiative" flow, allowing humans to promote a specific advisor-generated insight directly into a shaped initiative. This transforms the synthesis engine from a "reporting" tool into a "generative" one, proactively populating the project backlog with data-driven suggestions.
BD-20: Guided Discovery & Proactive Synthesis
- **Intent:** Bridging the gap from fuzzy "observation" to shaped "initiative."
- **Research Thinking:** Most product work starts not with a clear intent, but with a signal—a bug report, a user complaint, or a hunch. Standard AI assistants often rush to "solutionizing" (jumping to code) or remain too passive. BD-20 implements two research-backed shifts:
  1.  **Iterative Discovery Scaffolding (ArXiv:2512.09142):** Instead of a generic chat, the discovery rail uses a **Question Sequence** protocol. It forces the Advisor to extract five specific dimensions (Problem, People, Workarounds, Outcome, Smallest Learning) _before_ proposing an initiative. This prevents "Vague Spec Syndrome" where agents are given under-specified goals. The Advisor also distinguishes between **Engineering** (build a thing) and **Research** (learn a thing) framings, pre-selecting the initiative type to align the verification loop from the start.
  2.  **Proactive Cross-Initiative Synthesis Engine:** As project memory grows, humans suffer from **Synthesis Fatigue**. BD-20 introduces the synthesis engine that performs proactive analysis on project load. When $\ge 5$ initiatives are completed, it triggers a "What We Know" analysis using the **Pattern-Assumption-Intent (PAI) Framework**. This ensures that lessons learned in `BD-4` are proactively surfaced when thinking about new work, turning the project page from a list of tasks into a strategic dashboard.

**Key References:**

- **Iterative Discovery Scaffolding (ArXiv:2512.09142)** — structured extraction of intent from ambiguous signals.
- **Synthesis Fatigue in Agentic Workflows (ArXiv:2601.10442)** — the need for proactive, cross-task summarization.
- **The PAI Framework for Institutional Memory** — categorizing knowledge into patterns (recurrent), assumptions (validated/invalidated), and intent alignment.
BD-17: Compound Knowledge Flywheel (Heuristics)
- **Intent:** Transforming ephemeral project outcomes into durable, actionable guidance.
- **Research Thinking:** Standard "Lessons Learned" often fail because they lack actionability and discoverability. While Doen's memory stores narratives and decisions ("we decided X in BD-4"), research on **Experiential Reflective Learning (ERL, ArXiv:2603.24639)** shows that agents improve dramatically when experience is distilled into heuristics—concrete, actionable rules that transfer across tasks. A heuristic tells the agent what to do differently ("always verify migration compatibility before adding a new table"), whereas a narrative only tells it what was done. BD-17 implements three shifts to ensure Doen's knowledge flywheel compounds as actionable intelligence:
  1.  **Heuristic Extraction in Learn:** During the Learning stage, the Advisor extracts explicit cause-effect rules and failure patterns (e.g., "Always use asyncpg's connection pool with min_size=2..."). These are stored as a distinct memory type, tagged and retrievable, ensuring that `get_context` returns actionable rules alongside historical facts. Reference: ERL's "reflect on trajectories to generate transferable heuristics" pattern.
  2.  **Uncertainty-Aware Proposals:** Proposals are now classified by confidence. Items grounded in strong memory (heuristics/decisions) are marked `confident`, while those inferred from thin descriptions are `uncertain`. This allows the human to focus scrutiny where it matters most. Reference: **ARIA framework (ArXiv:2507.17131)**, where agents assess uncertainty and proactively flag knowledge gaps.
  3.  **Incremental Knowledge Evolution:** To avoid "context collapse"—where monolithic rewriting of `agents.md` degrades context over time—BD-17 adopts the **Agentic Context Engineering (ACE, ArXiv:2510.04618)** approach. Knowledge grows incrementally; heuristics are appended and contradicted entries are marked "superseded," never deleted. This preserves the evolution of decisions and ensures the "Living Handbook" accumulates rather than collapses.

**Key References:**

- **Experiential Reflective Learning (ArXiv:2603.24639)** — heuristic extraction from task trajectories.
- **ARIA framework (ArXiv:2507.17131)** — uncertainty-aware agents with knowledge gap identification.
- **Agentic Context Engineering / ACE (ArXiv:2510.04618)** — evolving playbooks, context collapse prevention.
- **Knowledge Activation (ArXiv:2603.14805)** — institutional knowledge as reusable primitives for agents.
BD-16: Systematic Verification & Eval Harness
- **Intent:** Moving from "Ad-hoc Review" to "Verifiable Reliability."
- **Research Thinking:** As the system handles more complex logic (like Advisor-led reviews), the prompts governing these transitions become critical infrastructure. BD-16 introduces a **Promptfoo Evaluation Harness** to systematically measure prompt performance against known edge cases. This shift ensures that changes to the "Governor" (the LLM prompts) are themselves governed by evidence-based evaluation, preventing regressions in the quality of human-facing signals.
BD-15: Research Initiatives (Engineering vs. Research Framing)
- **Intent:** Expanding Doen's governance model to non-code-shipping outcomes.
- **Research Thinking:** Not all software engineering work results in code. Investigations, spikes, and methodology research are critical but often escape formal governance. BD-15 introduces a "Research" framing that shifts the focus from "Acceptance" to "Success Criteria" and from "Evidence" to "Findings." This allows the same structured governance loop to apply to the _reasoning_ process itself, enabling a full lifecycle (draft -> investigating -> learning) without an MCP connection.
BD-14: Advisor-Led Batch Review
- **Intent:** Eliminate the cognitive bottleneck of item-level approval.
- **Research Thinking:** Based on **Human-on-the-Loop (HOTL)** orchestration patterns. Human users should not spend time approving obvious, well-formed items that align with organizational memory. Classification into `confident`, `flagged`, and `uncertain` allows the system to prioritize human attention where it is most needed—on high-entropy judgment calls.
BD-13: Discretion Auditor & Steering-Ratio Awareness
- **Intent:** Safeguarding organizational memory and managing "steering friction."
- **Research Thinking:** Addresses **Structural Capital Contamination** (KLRM, 2026). By enforcing that memory entries (learnings) must have human-verified sources, we prevent the "echo chamber" effect of AI-authored rationales. The Discretion Auditor identifies when an agent is acting within its human-granted latitude, reducing unnecessary interruptions.
BD-12: Reflexive Memory Verification
- **Intent:** Preventing "Operational Amnesia" caused by codebase drift.
- **Research Thinking:** Organizational memory is often treated as static ground truth. BD-12 transforms memory hits into **verify-on-use obligations**. Agents are now required to audit the claims they read against the live codebase, ensuring that the context used for new decisions is always grounded in current reality.
Every decision is recorded with what was ruled out and why. That record is the evidence.