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] Product Development, Precedent, and Groundedness (BD-107 → 2026-11-26)

Doen as a spec framework for product engineers — designers, software engineers, product

Recording work done without a spec (2026-10-12)
- **Intent:** Let work done outside any spec still leave its lessons for later work.

- **Research thinking:** Memory and decisions both hang off an initiative, and search only serves
  memory from completed initiatives, so a fix done outside Doen left no trace. Two shapes were
  weighed. Free-standing memory rows with only a project would mean a schema change plus a second
  path through search. Wrapping each record in a small initiative completed on the spot (no
  criteria, one learn record, which the existing state rule already calls complete) reuses every
  path and keeps every invariant. The second was built (`record_work`, migration 0069).

  Whether a record counts at once or waits for approval was a person's call: at once, with Undo.
  An approval queue is what made drift reports go unworked. The safeguards are a required
  reference (commit, PR or branch), `recorded: true` on every `get_context` hit from it (the item-level "past calls" view does not
  label it yet), executor
  decisions stored as the executor's (`resolver_type` "agent") so the count of human reasoning
  stays honest, a decision only with something ruled out, and Undo on the project page, which
  reverts the memory and retires the decisions without deleting anything. Executors learn about
  the tool from `setup_project`'s onboarding text. Whether records turn out useful or noisy is
  unmeasured. Counting how often they are retrieved would not show it (activity is not value); a
  person reading the records on the project page, and how many they undo, is the first signal.

- **Key references:** `backend/app/services/recorded_work.py`, `backend/app/store/recorded.py`,
  `backend/migrations/0069_recorded_work.sql`, `backend/app/mcp_server.py` (`record_work`),
  `web/app/[projectId]/RecordedWork.tsx`.
Iterating on a spec after draft (2026-10-12)
- **Intent:** Products are built by iterating, but a spec locked at the first evidence. Let it
  change in any state short of complete, keep it at the product level, and route feedback into
  it, without loosening who confirms what.

- **Research thinking:** Built in the order A → B → D → C → E.

  *A, changes after draft.* Three draft-only checks (reshape, the Advisor's edit and remove
  cards, accepting a rewording) and the page's draft-only controls made revert-to-draft the only
  way to change a spec. From learning that reset every verification. The rules that keep changes
  safe already existed, so the gates were the problem. Now a spec changes in draft, building and
  learning. A criterion with evidence or a verdict is retired and replaced, so evidence always
  describes the words it was given for. A new open criterion moves learning back to building
  through the existing state rule; only that case recomputes, so a build started by hand is never
  pulled back to draft. A completed spec stays closed, and the intent changes only in draft. An
  MCP reshape after draft needs `expected_version`, lands new items as proposals, and keeps
  confirmed items it leaves out. A person's own add is still their confirmation, and so is their
  accept on an Advisor card. The spec's open decision recommended this, and the alternative (a
  second confirm on their own change) is ceremony.

  *B, why it changed.* After draft, changing or retiring a confirmed item needs a reason. It is
  kept as a resolved decision, with the old wording as the ruled-out option. Adds may carry one.
  Required only for confirmed items, as the spec recommended: that is where the reason is a real
  product call, and optional everywhere else avoids filler.

  *D, product level.* The shaping prompt asks for item text a person can observe, puts technical
  checks in `verify.detail`, and makes implementation choices latitude. The reviewer then flags
  any proposed item that names a table, column, file, function or endpoint the description did
  not mention. Detection is by form (snake_case, a path, a file with an extension,
  lowerCamelCase, a backticked span), not vocabulary, because the keyword audit recorded in
  `audit_criteria_kinds.py` failed on English words like "endpoint". The flag overrides a
  confident rating, undoes an auto-confirm, and runs even when the rating call fails.
  `audit_criteria_kinds --named-internals` counts such items, so drift can be watched. The
  prompt change is unmeasured; the shaping eval needs live models and was not run.

  *C, redraft with a direction.* "Redraft: <direction>" in the conversation asks the Advisor for
  edit, remove and add cards across the whole spec, leaving untouched items alone. It writes
  nothing. Rather than a second redraft path beside the Advisor, it reuses the cards, the
  suggestions-on-items view and the accept rules already in place.

  *E, feedback.* After draft the Advisor sorts feedback into one of three suggestions: changes
  requested on an existing criterion, a spec change, or a decision only. Executors get
  `propose_spec_change`: a proposed item, or a replacement for one, with their reason; a person
  confirms it, and confirming a replacement retires the old item. An executor may also propose a
  removal, in draft only: the item carries the reason until a person removes it or keeps it.
  After draft, dropping what governs work under way stays a person's call.

- **Key references:** `backend/app/services/authoring.py` (`_CHANGEABLE`, `_save_and_settle`,
  `_record_change`, `propose_item`, `_only_propose`), `backend/app/services/product_level.py`,
  `backend/app/services/classification.py` (`flag_named_internals`),
  `backend/app/prompts/advisor-redraft.txt`, `backend/app/mcp_server.py` (`propose_spec_change`).
The conversation: faster turns, one accept, and suggestions on the items they change (2026-10-09)
- **Intent:** Make changing a spec through the Advisor conversation quick and direct. It was
  slow, every change needed two accepts, and the conversation sat in a narrow side column away
  from what it changed.

- **Research thinking:**

  _A hidden second call._ Every turn ran `importance_validation` after the Advisor's reply: one
  more large-model call over the intents of every other initiative in the project (BD-52). Its
  result went into a field the endpoint never sent, and nothing in the web app read it. The
  Advisor's own output format also asked the model to write an `importance_recommendation` that
  nothing parsed. Both are gone. This is likely the largest single latency cut, but it is not
  measured. `llm_cost_log` latency by `purpose`, before and after, on the instance the MCP server
  points at, would show it.

  _One accept._ Accepting a card used to add the item as _proposed_, to be accepted again in
  the document. A person's accept on the card is already the confirmation of that exact
  wording. So it now confirms in one step, with provenance `ai_confirmed_by_human`, the same
  value confirming a proposed item records. Invariant 9 holds: the Advisor never confirms
  anything; the person's click does. The Advisor can also suggest an `edit`, rewording an item
  in place. Before, a rewording was remove-and-add, which lost the item's id, rating and past
  calls.

  _Where suggestions show._ While drafting, a suggestion aimed at an item shows on that item in
  the document, as a rewording or a removal with its own accept. A suggested new item shows as a
  dashed entry at the end of its section. The conversation keeps one line ("3 suggested changes,
  shown on the spec items they change"); title and intent suggestions stay as cards. Each item
  has _Ask about this_, which starts a message about it. Pages now run up to 1340px: from
  1280px the spec keeps a fixed 720px reading width and the conversation (or, on the project
  page, the new-initiative form) takes the rest. A manual "widen" switch was tried first and
  dropped: the layout should give the room, not a setting. The conversation fills the window
  height, and its input grows with the text.

  _The wait._ The initiative conversation now streams: the step under way, the time so far,
  then the reply text as the model writes it. Proposals arrive with the final message. The
  model still answers through one forced tool call, so the provider streams the call's JSON
  arguments, and a small incremental parser pulls the `reply` string out as it grows.
  Providers without streaming fall back to one final event. The project conversation keeps the
  plain request.

  _Cheaper turns._ With an Anthropic model, the fixed instructions and the spec-and-project part
  of the request are marked for prompt caching (`LLM_PROMPT_CACHE`). Older turns beyond the
  latest six go in shortened to 600 characters. `ADVISOR_MODEL` lets the conversation use a
  different model from drafting. It defaults to the same one: a faster model needs
  `eval/suites/advisor` run first, which this change did not do. None of these effects is
  measured yet.

- **Key references:** `backend/app/services/advisor.py` (`advise_stream`, `_converse_call`),
  `backend/app/providers/llm.py` (`stream_structured`, `ReplyExtractor`, `_payload`),
  `backend/app/services/authoring.py` (`add_item`, `edit_item`),
  `web/app/[projectId]/[initiativeId]/ConversationRail.tsx`, `DocSuggestions.tsx`,
  `RailLayout.tsx`.
A new initiative shows its draft before the draft is rated (2026-10-09)
- **Intent:** Cut the wait between describing an initiative and reading its spec, and make the
  wait that remains legible.

- **Research thinking:** Creating an initiative returned at once, but the page showed only a
  spinner until three model calls had run one after another: the draft, Jev's rating of every
  item, and the reasons shown with each rating. The rating is a review of the draft, yet it was
  holding back the draft itself. Background drafting now saves twice. First the draft, with
  `shaping_status = "classifying"`, so the items are readable after one model call. Then the
  ratings. Accept, reject and edit stay locked on the page until the ratings land ("Still being
  reviewed…"), so nobody acts on an item a moment before its rating changes how it is shown.
  The rating runs on a fresh read and is merged by item id, only onto items still proposed with
  unchanged text, retrying on a stale write. A person who acts anyway, through the rail or an API,
  keeps what they did. A failed rating still completes the draft, unrated, which the page already
  handled.

  Two form bugs went with it. The form re-enabled itself before the page changed, with the text
  still in it, so a second click made a second initiative. And the type the rail suggested was
  dropped. The two buttons ("Shape", "Research") gave way to one choice, Build or Research, with
  a line saying what each produces, the suggested one preselected, and a single "Draft the spec".
  The page now names the step under way and the time so far, instead of "Advisor is drafting…".
  It gives no estimate, because no step durations have been measured. `llm_cost_log.latency_ms`
  by `purpose` is where to measure them, on the instance the MCP server points at.

- **Key references:** `backend/app/services/shaping.py` (`fill_spec_from_description`,
  `_rate_draft`, `_merge_ratings`), `web/app/NewInitiative.tsx`,
  `web/app/[projectId]/[initiativeId]/DraftingSteps.tsx`.
Memory corrections can be accepted, and lead with a two-sentence summary (2026-10-09)
- **Intent:** Let a person settle a correction either way, and decide it from the summary alone.

- **Research thinking:** The panel had only _undo_, so a correction a person agreed with stayed
  at the top of the project page for good. Accepting is now the other half (`accepted_at`,
  migration 0068, on the correction row like `reverted_at`). It changes nothing in retrieval: the
  correction was already in use. It only takes the correction out of the queue and out of
  review. Both actions ask once for confirmation inline, because each changes what every later
  executor is told. The panel now shows only corrections still waiting. Each reads like a
  proposed spec item: the summary, the recommendation as a callout, Accept and Undo. The three
  texts are behind _Show details_. The summary prompt now asks for two sentences, at most 35
  words: what changed in everyday words, then what to check, starting with a verb, or a "Careful:"
  when the correction outruns its reason. The earlier summaries ran to three sentences and
  restated the texts the person could already open. 0068 deleted the stored reviews so they
  regenerate with the new prompt. The 35-word cap is a prompt instruction, not enforced, and not
  yet read against live output.

- **Key references:** `backend/migrations/0068_memory_correction_accept.sql`,
  `backend/app/store/memory.py` (`accept_memory_correction`),
  `backend/app/prompts/memory-correction-summary.txt`, `web/app/[projectId]/MemoryCorrections.tsx`.
Memory corrections get a summary and a suggestion, and move above the initiatives (2026-10-09)
- **Intent:** Make reviewing a correction cheap enough that people actually do it, since a
  correction grounds new work from the moment it is written.

- **Research thinking:**

  _Where it sits._ The panel was in the right column under the new-initiative form, below the
  fold on most screens. A live correction is already shaping every later draft and build, so it
  now sits above the initiatives, in the page's text flow rather than as a card.

  _What it adds._ Each live correction gets two things. The review LLM writes two or three
  sentences: what the memory said, what it says now, why, and anything the correction claims
  beyond its reason. Jev answers one Choice question, keep or undo, from the original, the
  correction and the reason. Jev cannot see the code, so the rubric asks something it can judge:
  does the reason describe a concrete check that contradicts the original, and does the
  correction change only what that check covers? A correction can be right and still get "undo"
  when its reason does not show it. That is useful to the person, not a mistake.

  _Fail toward the person._ The suggestion never acts. It is shown only at confidence 0.7 or
  above (`CORRECTION_RECOMMEND_CONFIDENCE`); below that, or if Jev is down, the panel says to
  compare the texts. 0.7 is not measured: there are no labelled corrections yet. It errs high
  because a missing suggestion costs a read and a wrong one invites a careless click. The raw
  call and confidence are stored, so the threshold can be moved later without re-running.

  _Existing corrections._ Listing a project's corrections starts a background review for any live
  one without a review, which covers everything written before this. The panel polls until each
  lands. A review that fails, whether the LLM or Jev was unreachable, is stored as failed and
  retried at the next listing after ten minutes. A Jev outage is therefore never shown as Jev
  being unsure, and a brief outage on first open does not stick. A pass keeps going until
  nothing is left, so a correction written mid-pass is not skipped.
  `app/backfill_correction_reviews.py` does every project in one pass, and `--retry-failed`
  retries every failed review at once. Undone and replaced corrections are not
  reviewed, because a suggestion on whether to undo them answers nothing. Reviews live in their
  own table (migration 0067) because `memory` is the append-only record and this is commentary
  on it.

- **Key references:** `backend/migrations/0067_memory_correction_reviews.sql`,
  `backend/app/services/correction_review.py`, `backend/app/prompts/memory-correction-summary.txt`,
  `backend/app/prompts/memory-correction-jev.txt`, `backend/app/backfill_correction_reviews.py`,
  `web/app/[projectId]/MemoryCorrections.tsx`.
Memory corrections: the executor fixes it, a person can take it back (2026-10-09)
- **Intent:** The owner, after resume-builder's RB-9: `get_context` served an entry claiming a
  "scores table" that does not exist. The executor caught it only because it read the schema.
  Leaving a wrong entry unstamped was the designed behaviour since drift reports went
  (2026-10-07), so nothing could correct it. Every later executor would have to re-derive the
  same correction.

- **Research thinking:**

  _The harm was retrieval, not the queue._ An unstamped entry stays in the audit backlog, which
  is harmless. It also stays embedded, which is not: it keeps coming back as grounding, and
  nothing ever retired it. The audit loop already produces exactly what a fix needs (an entry
  checked and found wrong, and the reason), and that output had nowhere to go.

  _Why this is not drift reports again._ Drift reports were a workflow: an executor filed an
  essay, a person triaged it, and the person then had to write the replacement into a blank box.
  The removal note said that if this came back, it should start from a replacement the agent
  writes. `amend_memory` is that replacement, written as a single step by whoever just checked
  the code. Three gates were considered:
  - an approval queue first: rejected, because it rebuilds the queue nobody worked while the
    wrong entry stays live;
  - no review at all: rejected as further than any rule here goes, because every other
    executor-removed human check is gated or reversible;
  - live at once, with a person able to undo it: chosen.

  _Append-only kept._ The owner's two requirements were a required reason and keeping the
  original, because "a memory entry that can be silently rewritten is worse than one that's
  wrong". An in-place `UPDATE` with an `amended_from` column would have broken the memory
  append-only invariant. Instead a correction is a new row on the same initiative that
  `supersedes` the old one. The old row keeps its text and gets `superseded_at`. Retrieval, the
  audit and `list_memory` read only live rows. The pattern mirrors `decisions.retired_at`. Undo
  sets the correction's `reverted_at` and puts the original back with its existing embedding.
  Corrections cannot fork: amending an already-replaced entry is refused and names the current
  one. Same project only: the executor checked the claim against its own project's code.

  _Embedded before it is written, unlike `create_memory`._ The obvious version would end with a
  background `embed_memory`, the way `create_memory` does. Review caught that this is wrong here.
  The original leaves retrieval in the same write, so a background embed that failed would leave
  the claim served by neither row until someone ran a backfill. The correction is embedded inside
  the transaction instead, and an embedder failure refuses it.

  _A gap, closed in a follow-up._ `get_context` hits did not carry a memory id (BD-37 kept it out
  of the contract), so an executor could only find the id through `list_memory_for_audit`, which
  shows stale entries only. A recently stamped entry that was wrong, including a correction
  (stamped when written), could not be amended until its window lapsed. Memory hits now carry
  `memory_id` (null on decision hits). It is an additive field on the `get_context` response;
  nothing else that reads hits serialises them whole, so no prompt gains an id.

- **Key references:** `backend/migrations/0066_memory_amendments.sql`,
  `backend/app/store/memory.py` (`amend_memory`, `revert_memory_correction`),
  `backend/app/mcp_server.py` (`amend_memory`), `backend/app/routers/memory.py`,
  `web/app/[projectId]/MemoryCorrections.tsx`, `backend/tests/test_memory_corrections.py`,
  `docs/design-principles.md` ("The human / AI boundary").
Decisions at the centre of drafting, and a lighter path for small work (2026-10-08)
- **Intent:** Make captured human reasoning visible where specs are written and reviewed, and cut
  the cost of reviewing a draft that is mostly fine.

- **Research thinking:**

  _Precedent beside the item._ `get_precedent` had no reader. It now has one: each draft item shows
  "Past calls on this", the closest resolved decisions from other initiatives above a similarity
  floor (`PRECEDENT_MIN_SIMILARITY`, 0.48 — the score below which hits on the build-doen corpus
  stopped reading as related; a judgment on a small sample, not a measured cut, so it is a
  setting). Each one can be retired from where it is shown, because the corpus is known to hold
  misleading decisions and the moment a bad one is seen is the moment to remove it. This reverses
  "wire retrieval to nothing yet" for one surface only; no prompt reads it.

  _Asking why at the point of disagreement._ Rejecting or rewriting an AI-proposed item is the
  clearest product call a person makes on a draft, and it was thrown away. It now prompts once for
  a reason and stores it as a decision (the rejected version is the ruled-out alternative). The
  prompt can be skipped; capture that is forced gets filler.

  _What the drafter saw._ A draft records the hits it was given (`drafted_from`), shown under the
  draft with a retire control on decisions. Before this, a bad precedent could shape drafts
  invisibly. Text is stored with internal ids stripped.

  _A lighter path._ Projects showed 29–45 items waiting to be confirmed. Two changes. Within each
  draft section, the items the reviewer classified as confident fold under one line ("N look
  settled") with a single confirm, scoped to that section (`batch-approve-confident` takes an
  optional `section`), so the page shows what was flagged or uncertain. This replaces the
  spec-wide "approve as a batch?" banner, which offered to confirm items in sections the person
  had not opened. And the shaping prompt now gives the full structure a ceiling (about five
  constraints, four latitude items, six criteria) and says larger work is more than one
  initiative. The ceiling is unmeasured: the shaping eval needs live models and was not run.
  Watch item counts on new drafts before treating it as working.

- **Key references:** `services/precedent.py` (`precedent_for_item`), `services/shaping.py`
  (`drafted_from`), `services/authoring.py` (`batch_approve_confident`), `prompts/shaping.txt`;
  web `PastCalls.tsx`, `RecordWhy.tsx`, `DraftedFrom.tsx`, `SpecDocument.tsx`.
A cleanup pass: what nothing reads, and a contract nobody had checked (2026-10-08)
- **Intent:** Remove fields, endpoints and code paths nothing uses, so the codebase says only what
  the system does.

- **Research thinking:**

  _How the candidates were found._ Mechanically, not by memory: every model field counted against
  its writers and readers in the backend and the web; every HTTP route checked for a caller in the
  web app; vulture over the backend, ts-prune over the web. A field written but never read counts
  as unused as much as one never written — the two spec synthesis fields were produced on every
  classification and review and shown nowhere.

  _What went:_ four spec fields and one decision field (`references`, `memory_links`, the two
  synthesis texts, `emitted_item_ids`; migration 0064 strips them from stored documents, because
  `Spec` rejects unknown keys); three MCP response values that were empty on every call and an MCP
  parameter that was silently dropped; the project "what we know" synthesis, an LLM feature with no
  reader (migration 0065, a human decision); the cost-summary endpoint; a handful of dead helpers,
  web utilities and components; and the whole open-decision path.

  _The contract nobody had checked._ `agents.md`, the spec contract and the design principles all
  said `escalate_and_resolve` "blocks until the human resolves" via Redis pub/sub, with a 600 s
  timeout, and that this made waiting mandatory "by design". The code had stopped doing that at
  some point: it resolves within discretion or returns the question unsaved, and the answer is
  stored by `resolve_decision`. Its own module docstring said so — "there is no open DB state". So
  for some time every executor was told to expect a blocking call that returned immediately, and
  the dashboard counted open decisions that nothing could create. The general lesson matches the
  one BD-101 and BD-105 already taught: a statement about behaviour that no test pins drifts from
  the code silently, and docs are statements about behaviour.

  _A bug the old tests hid._ The spec-loop dismissal tests asserted only `if loops:`, so with no
  loop present they passed vacuously. Rewritten around a real slow-criterion loop, the first run
  showed that dismissing a loop never hid it: asyncpg returns JSONB as text, and the stored key was
  dumped as a quoted string that could never equal the live one. A conditional assertion is not an
  assertion.

- **Key references:** `backend/migrations/0064_drop_unused_spec_fields.sql`,
  `backend/migrations/0065_drop_project_synthesis.sql`, `backend/app/mcp_server.py`
  (`escalate_and_resolve`), `backend/app/store/signals.py::get_dismissed_spec_loops`,
  `backend/tests/test_spec_loops.py`.
Retiring a decision from precedent, and a token in front of the API (2026-10-07)
- **Intent:** Two things the framework review left open: precedent that is known to mislead, and
  a backend and executor surface with no authentication at all.

- **Research thinking:**

  _Precedent needs a way out, not a delete._ `agents.md` already recorded that six of build-doen's
  nineteen resolved decisions describe the heuristic system removed on 2026-10-02, so a third of
  the corpus the product calls its guidance was actively misleading. Every reader of precedent
  (`get_context`, `get_precedent`, shaping priors, the Advisor's sibling summary,
  `measure_precedent`) served them, and the only lever was deleting rows from an append-only
  table. A retired decision now keeps its row and its place in the initiative's log, dimmed with
  the reason, and every precedent read skips it. A reason is required because the record outlives
  everyone's memory of why. Only a person retires one, over HTTP, like capture: judging which
  guidance has gone stale is not an executor's call. Retiring the six is left to the owner on
  production; this change makes it a click rather than a migration.

  The measurement consequence is worth stating: `measure_precedent` now skips retired decisions
  both as questions and as answers, so its rate after retiring the six is not comparable with the
  76.5% recorded before. That is the point (it was measuring against guidance known to be wrong),
  but a before/after comparison must say so.

  _A shared token, deliberately small._ The docs warned not to expose port 8000 and named the
  network boundary as the only protection, while `agents.md` described the MCP server pointing at
  a public deployment. `DOEN_API_TOKEN` puts one shared secret in front of every route and the
  `/mcp` mount, with `/health` left open for platform probes. It is off when unset, so local dev
  and the test suite are unchanged. It is not user accounts and it puts no login on the web UI;
  the docs say both, so it is not mistaken for more than it is. The web server holds the token
  server-side, and one helper (`web/lib/backend.ts`) is now the only way the web reaches the
  backend, so a new call site cannot forget it.

- **Key references:** `backend/migrations/0063_decision_retirement.sql`,
  `backend/app/store/decisions.py::retire_decision`, `backend/app/auth.py`,
  `web/lib/backend.ts`, `DEPLOYMENT.md`.
Auto-confirm off by default, an opt-in lock on reshape, and words instead of enums (2026-10-07)
- **Intent:** Close the remaining gaps from the same framework review, each as a human decision
  taken in the session: the unevaluated auto-confirm gate, the one write path that bypassed the
  optimistic lock, and engineer vocabulary on a page designers read.

- **Research thinking:**

  _Auto-confirm, reversed in part._ The 2026-10-05 entry below turned on a gate that confirms spec
  items nobody has read, and stated its cost plainly: no eval, a threshold chosen rather than
  measured. Two days later it is off unless a deployment opts in. Nothing new was measured in
  between. What changed is that the earlier fix to the criteria lifecycle showed how this gate
  composes: an auto-confirmed criterion becomes something evidence can be submitted against, and
  then something the reviewer can approve. Two judges, neither evaluated end to end, can then carry
  a criterion from drafted to verified. The project's own rule (BD-105) says a gate that removes a
  person fails toward the person until it is measured. The threshold and the provenance value stay,
  so turning it back on is one environment variable once an eval exists. **Deployments that relied
  on the old default stop auto-confirming.**

  _The lock on reshape._ `reshape_spec` was documented as last-write-wins, contradicting invariant 5
  in the same document. Making the version mandatory would break every executor calling it today,
  so it is optional: given `expected_version`, a spec a human changed since is refused with nothing
  written. Invariant 5 now names the version-less call as its one exception, and the tool, the
  contract and the spec skill all tell executors to pass it.

  _Enums on screen._ Criteria showed `[human_judgment]` and badges read CONFIDENT / FLAGGED /
  UNCERTAIN. `web/lib/labels.ts` now maps them to what they mean ("checked by your judgment",
  "has a concern"); stored values are untouched. Doing this turned up a real bug: the research
  form offered five kinds (literature review, interview, and so on) that the backend's enum
  rejects, so picking any of them failed the save. The form now offers the four real kinds and the
  research method goes in the detail.

- **Key references:** `backend/app/config.py` (`SPEC_ITEM_AUTO_CONFIRM_ENABLED`),
  `backend/app/services/authoring.py` (`reshape_spec`), `web/lib/labels.ts`,
  `web/app/[projectId]/[initiativeId]/SpecDocument.tsx`.
Closing the criteria lifecycle's no-human path, and prompts that outlived their systems (2026-10-07)
- **Intent:** A review of the framework found three holes in the criteria lifecycle, prompts still
  instructing the model about the heuristic system and work units, and a learn-stage gate whose
  prompt contradicted the drafter's. Fix the holes, clean the prompts, and settle the contradiction
  without making any judge bolder.

- **Research thinking:**

  _The no-human path._ `submit_evidence` checked that a criterion id existed, never that it was
  confirmed, and the reviewer judges anything in `evidence_submitted`. Put together with
  `create_spec`, an executor could draft a spec, submit evidence against its own AI-proposed `test`
  criteria, and have Jev verify them: an initiative from creation to verified with no person having
  accepted a word. Invariant 9 held to the letter, since the executor never approved itself, but
  "proposed items do not govern" did not. Evidence is now refused against anything not confirmed,
  and the reviewer withholds auto-approval from an unconfirmed criterion either way. That second
  gate exists because evidence stored before the first one may already be sitting there.

  _The stuck lifecycle._ `_recompute_state` counted retired criteria, so retiring one that was
  never verified left the initiative in `building` with no way out. That mattered more after
  2026-10-05: retiring is the documented undo for an auto-confirmed item, so the safety valve on
  the auto-confirm gate broke the lifecycle. Retired criteria are now ignored by the pure
  `derive_state()`, while proposed ones still count, because an unconfirmed criterion is an open
  question about the spec. Retire and reject now advance the state when they complete
  verification. They advance it _only_ then: a full recompute would pull an initiative started by
  hand, with no evidence yet, back to draft, which is a regression the new tests pin.

  _The learn gate._ `learn-draft.txt` tells the model to drop learnings that only restate what
  happened and keep transferable rules. `learning-eval-jev.txt` auto-approves only learnings that
  restate one spec item. So the drafter is told to cut exactly what the gate can approve. The first
  instinct, which the owner also picked, was to loosen the gate so a transferable lesson anchored in
  one item auto-approves. That was dropped once the committed safety data was checked:
  `learning_eval_negatives.jsonl` holds 8 curated must-never-approve cases at a hard 0% bar, and
  several are precisely transferable lessons anchored in one item ("migration scripts should always
  be idempotent" against "the migration is idempotent"). Loosening would have meant relabelling the
  gold to fit the gate, which is the circularity this project has already paid for once. And with
  no model key in the session, the live eval could not run to show otherwise.

  The resolution keeps the gate's semantics and makes both prompts say it: a generalised lesson
  claims the rule holds beyond this initiative's record, only a person can endorse that, so it goes
  to the human. Most well-written learnings will. The cost is human review at the learn stage; the
  alternative's cost was unverified claims entering durable memory, which nothing downstream would
  catch.

  _Prompt residue._ The Advisor base prompt still carried a full HEURISTIC CONFLICTS instruction for
  a context block that stopped existing on 2026-10-02. The classification rubric pointed the judge
  at `state["superseded_heuristics"]`, which the service never sends. Shaping asked for a
  `[HEADLINE]` suffix that nothing parsed, so it reached people as a literal token. All gone;
  shaping strips a trailing marker if a model still writes one. Stored criteria that already carry
  it are untouched.

- **Key references:** `backend/app/store/specs.py` (`derive_state`, `submit_evidence`),
  `backend/app/services/authoring.py` (`_save_removing_criterion`),
  `backend/app/services/review.py` (`_apply_assessments`),
  `backend/app/prompts/learning-eval-jev.txt`, `backend/app/prompts/learn-draft.txt`,
  `backend/tests/evals/data/learning_eval_negatives.jsonl`, `backend/tests/test_invariants.py`.
Removing drift reports: a human queue nobody could act on (2026-10-07)
- **Intent:** The owner saw the first drift report ever filed in production — in resume-builder,
  after two initiatives — and asked what it was for: "very difficult to understand, non actionable,
  usefulness questionable. Should we remove drift reports entirely, because this is just noise?"

- **Research thinking:**

  _Measured on the instance the MCP server actually points at_ (BD-101's rule): the Railway
  production backend held **one** drift report, filed 2026-10-07 against the only memory entry
  resume-builder has. `build-doen` — four months, 100+ initiatives, 82 memory entries — had filed
  **zero**.

  _Three defects, and only the first is about verbosity._ The panel rendered the agent's evidence
  and never the memory entry it corrected, so you read a correction to an invisible original.
  "Approve update" opened a blank textarea asking the human to compose the replacement summary from
  scratch — in a product where every other such moment is drafted-then-edited — and leaving it blank
  closed the report, changed nothing, and stamped `last_verified_at`. And since `create_drift_report`
  already stamped on filing, and resolving either way cleared `has_pending_drift`, the human actions
  available were: do nothing, or restore trust in an uncorrected entry. A feature whose default
  action launders a known-wrong memory as checked is worse than one nobody uses.

  _The argument that decided it was not usage, it was redundancy._ The report's central claim was
  that a future initiative reading the memory would never learn the variant-drift columns exist.
  Running the retrieval for exactly that question against production returned
  `dec_538d0a67fe55` — the decision, its chosen option, its rejected timestamp alternative — at
  **0.696**, with the memory entry it was correcting last at **0.312** and already flagged
  `has_pending_drift: true`. The decision corpus holds the content; memory summaries restate it;
  the drift mechanism was policing the restatement. Precedent retrieval had already done the work
  the human queue was asking a person to do by hand.

  _What survives, and what the right shape would be._ The staleness audit is untouched —
  `list_memory_for_audit`, `mark_memory_verified`, and the `memory_audit` backlog `get_spec`
  carries. An entry found wrong is now simply left unstamped, so it stays in the queue, and is
  reported in the handoff. If this needs a mechanism again, it should be a _proposed replacement
  summary_ the agent writes and the human edits, shown next to the current entry — not an essay
  about it. The agent that files the report already knows the correct text; the old contract just
  never asked for it.

  _One thing worth keeping from the wreckage._ The only measurement in the feature was an
  LLM-as-judge scoring drift evidence on Specificity and Actionability. It gave this report
  **100%, Actionability 5/5**, on the artifact the owner called unactionable. It was graded against
  no gold data, and it was grading the evidence prose rather than whether the handoff could be
  acted on. `app/services/evaluation.py` existed only for that rubric and went with it.

  _Scope of the removal:_ the `drift_reports` table (migration 0062), the `report_memory_drift`
  MCP tool (17 tools → 16), the router and its proxy route, five store methods,
  `ContextHit.has_pending_drift`, the `drift_reports` attention count and its dashboard tier, the
  `DriftReportsPanel`, the `drifted_memory` spec-loop signal and its Advisor messaging (it could
  only ever fire on that table), the judge framework, and `JUDGE_MODEL`.

- **Key references:** `backend/migrations/0062_drop_drift_reports.sql`,
  `docs/design-principles.md` ("Deliberately rejected", memory drift reports),
  `README.md` ("Validation — the staleness audit").
The verification card is read by a designer, so stop showing them a test transcript (2026-10-07)
- **Intent:** The evidence blob an executor submits is the thing a human is asked to judge, and it
  is written engineer-to-engineer: parameterised test names, file paths, payload dumps, incidental
  fixes made along the way, routinely a full screen of monospace. The audience of this product is
  product engineers — designers and product owners included. They are being asked one question,
  _did this do what we asked_, and could not answer it from what the card showed.

- **Research thinking:**

  _Why presentation alone was not enough._ The obvious fix is to clamp the blob and render it
  nicely. That makes it shorter, not understandable: the vocabulary is the problem, not the length.
  So `review.summarize_evidence` writes two fields alongside the evidence — `evidence_summary`
  (what was done, in product vocabulary) and `evidence_check` (the single thing this person should
  look at before approving). The card shows those. The raw evidence is not hidden from the record;
  it appears verbatim, unaltered, the moment someone opens the review flow, which is the point at
  which an engineer who wants it is asking for it.

  _Why it cannot be Jev._ Same reason `draft_change_request` is not: `JevChoiceAnswer` carries a
  choice, a confidence and a probability spread, and no free text. The preliminary notes can say
  how sure the reviewer was and can never say what the evidence showed. A summary needs prose, so
  it needs its own `StructuredLLM` call — one batched call per evaluation, keyed by criterion id.

  _The failure direction._ This is drafting, not judgment, so it is advisory everywhere: a failed,
  garbled, empty or slow summarization leaves the fields `None` and the card falls back to the raw
  evidence, and in the inline MCP path the summary runs under its own deadline so it can never be
  the reason a verdict call times out. `tests/test_evidence_summary.py` pins each of those; the
  `garbage` case found a real crash on a non-dict body during the first run.

  _The one thing to watch._ A summary is a second-hand account of the evidence, and the human now
  decides on it. The prompt therefore forbids claiming a pass the evidence does not claim and
  forbids softening a gap it admits to — an invented pass here is the unrecoverable error, because
  nothing downstream re-reads the blob. If that shows up in practice, the answer is the eval this
  does not yet have, not a longer prompt.

  _Second pass, same day: shorter, and no ids._ The first summaries were still hard to follow —
  two or three sentences that kept too much of the executor's vocabulary. The prompt now asks for
  ONE sentence under 30 words (a second only when the evidence admits something the reader must
  know), with worked before/after examples rather than adjectives about tone.

  The sharper problem was the internal id. "Constraint item_9e81c9ddf249 specified
  `server_default=text(...)`" was real text on a real card. Nothing in this product resolves an id
  to the item it names — no link, no lookup — so to the reader it is a dead token in the middle of
  the sentence they must act on, and the item behind it can be reworded or retired independently.
  Ids are now forbidden in every generated-prose path and allowed only in structured fields, where
  they are machinery: a remove-proposal's `item_id`, a rationale claim's `source_id`, Jev's
  per-item answers. `plain_language.strip_internal_ids` is the deterministic backstop, applied to
  evidence summaries, change-request drafts, classification reasons, ambiguity questions and learn
  drafts — cheap to run, and the alternative is noticing a leaked id by eye. The same reasoning
  took ids out of the memory embedding text: `Rationale (decision): <claim>` rather than
  `Rationale [decision dec_abc123]`, because an opaque token is noise in a vector nothing can
  resolve it from.

  _The rows already written._ A survey of all 108 production specs found 146 id-carrying fields
  across 49 of them, and the distribution settled a design question: **102 were in `evidence`**,
  with the rest in classification reasons (16), preliminary notes (13) and the two synthesis
  fields (15). Evidence is what the review flow shows verbatim — the exact text the complaint
  quoted — so treating the submission as an untouchable record would have left the problem in
  place. `app/strip_spec_ids.py` repairs the stored documents (dry-run by default,
  `--keep-evidence` to opt out), and `store.submit_evidence` now strips ids on the way in, so the
  rule holds without relying on the executor to follow it. Item `id` fields themselves are never
  touched — that is identity, not prose.

  _One bug the repair found._ The tidy pass that closes the gap left by a removed id was turning
  "a ::jsonb cast" into "a::jsonb cast" — it matched any whitespace before punctuation. It now
  requires the punctuation to end a clause, which also protects "12:30". Pinned by a test.

- **Key references:** `backend/app/services/review.py::summarize_evidence`,
  `backend/app/prompts/evidence-summary.txt`,
  `web/app/[projectId]/[initiativeId]/CriteriaVerification.tsx` (`EvidenceReadout`),
  `backend/tests/test_evidence_summary.py`.
The left-hand gate: letting the reviewer confirm spec items (2026-10-05)
- **Intent:** Close the asymmetry the owner described: specs generated by an LLM, verified and
  potentially approved by Jev and otherwise by a human — at BOTH ends, shaping and verification.
  Only the verification end existed.

- **Research thinking:**

  _The asymmetry, stated precisely, because I got it wrong first._ At verification time Jev
  genuinely auto-approves: `review.py` sets `verdict="approved"`, `approved_by="advisor"`, no human,
  gated by `JEV_AUTO_APPROVE_CONFIDENCE` with BD-61 forbidding it on `human_judgment`. At shaping
  time Jev approved **nothing**. All three writes of `status = "confirmed"` lived in `confirm_item`,
  `confirm_all` and `batch_approve_confident`, every one reachable only from `routers/specs.py` —
  an HTTP call a person makes — and the provenance written was literally `ai_confirmed_by_human`.
  So `confident` bought a bulk-accept shortcut, not an approval. I had described the shaping
  classifier as an auto-approve mechanism earlier in the same session; it never was one.

  _The decision, and the cost that was stated before it was taken._ Three options were offered:
  mechanical criteria only (`test`/`metric`), anything above the gate, or leave the boundary alone.
  The owner chose the broadest — **any section, constraints and discretion included** — with the
  consequence named at the time: an AI-drafted constraint can now govern a build without a person
  having read it, and constraints are exactly what an executor is held to. Recorded here as a
  deliberate accepted cost, not something to rediscover.

  _What makes it auditable rather than merely permitted._ Three things, each chosen because a person
  will eventually need to undo or account for this:
  1. **The threshold is 0.90 and is NOT a measured value** — unlike every other Jev gate in
     `config.py`, which cite sweeps against evals. No gold set of "spec items a human would have
     accepted unchanged" exists, so the gate sits far above the 0.50 the evaluated gates settled
     on. BD-105's rule applies: fail toward keeping the human, never move a threshold to hit an
     automation target. Lower it against a measurement, not before.
  2. **The provenance is honest.** `ai_confirmed_by_jev` is its own enum value. Reusing
     `ai_confirmed_by_human` would have recorded an endorsement that never happened and made
     "which governing items did nobody read" unanswerable. The UI labels it "auto-confirmed, not
     reviewed", deliberately unreassuring, because it renders beside items labelled "you
     confirmed" and the contrast is the point.
  3. **It is undoable.** A confirmed item cannot return to proposed, so `retire_item` is the
     escape hatch — it stops governing while staying in the document for history.

  _The boundary with BD-61, which is the easiest thing to get wrong._ Confirming an acceptance
  criterion accepts its **wording**; approving evidence says the **work** satisfies it. Two gates,
  two objects, two questions. A `human_judgment` criterion may therefore be auto-confirmed and still
  never auto-approved — both are true at once, and two tests pin the pair so the gates cannot
  silently merge.

  _A consequence found by a failing test rather than by reasoning._ With the gate on,
  `batch_approve_confident` loses most of its work: items at or above 0.90 are already confirmed
  before it runs, so it only ever handles the band between "classified confident" and "confident
  enough to confirm unread". `test_bd14`'s batch-vs-individual equivalence test began failing on
  provenance for exactly that reason. The equivalence is still a real invariant, but only observable
  on items that reach batch-approve, so the test now disables the gate and says why. Worth noting
  the test did its job: a behavioural consequence of a new gate surfaced as a specific failure
  rather than as a surprise in production.

  _One fail-safe worth its own test._ The caller passes `confidence_by_id.get(item.id, 0.0)`, so an
  item whose confidence goes missing — a partial Jev response, a later refactor dropping the field —
  arrives as 0.0 and stays proposed. A default that read as "sure enough" is the dangerous version
  of that line.

- **Key references:** `backend/app/services/shaping.py::_maybe_auto_confirm`,
  `backend/app/config.py` (the unmeasured-threshold note),
  `backend/tests/test_spec_item_auto_confirm.py`, `agents.md` invariant 9 (amended with the
  evidence-only boundary).
BD-107: giving the "a person should decide this" half a mechanism (2026-10-05)
- **Intent:** The shaping classifier's two verdicts were not symmetric. `confident` had a consumer
  — `batch_approve_confident` reads it and the human accepts the lot in one click. `flagged` and
  `uncertain` had none anywhere in the codebase: they rendered as a coloured callout and stopped.
  So the judgment that says "no person needed" produced an action, and the judgment that says "a
  person should decide" produced a paragraph.

- **Research thinking:**

  _The correction that reframed the work._ Mid-assessment the owner pointed out that "auto-approve
  by Jev" means assessing whether criteria can be approved **without a human** — and that is a
  different mechanism from the one I had been describing. There are two, and conflating them had
  made the earlier analysis wrong in a way worth recording. `review.py` genuinely auto-approves:
  on submitted _evidence_ it sets `verdict="approved"`, `approved_by="advisor"`, no human, gated by
  `JEV_AUTO_APPROVE_CONFIDENCE` and the BD-61 hard gate. The draft-time classification approves
  **nothing** — every caller of `batch_approve_confident` is the HTTP endpoint a human hits, and
  the provenance it writes is literally `ai_confirmed_by_human`. So before BD-107 the product had
  no draft-time judgment that decided anything, and BD-107 is the first one that does.

  _Composition, not new machinery._ The only judge is `discretion_auditor.audit_decision`, which
  already applies its own confidence gate and is already covered by a false-suppression eval. The
  genuinely new step is drafting the ambiguity as a question with candidate answers, which is
  unavoidable: Jev's `ask_choices` can only _select_ among options, never generate them. Keeping
  drafting and judging as two calls is also the point — the thing proposing the options is not the
  thing deciding between them.

  _The failure direction is the whole safety argument, and it is asymmetric on purpose._ A drafting
  failure **raises**: with no question there is nothing to ask and nothing to resolve, so a caller
  that swallowed it would report success having done nothing. An auditor failure is **swallowed
  into "ask the human"**: `audit_decision` guards only `JevError` internally, so a timeout or a
  malformed payload propagates, and that must become a question for a person rather than an error
  or — far worse — something that looks like a within-discretion pass. Nothing in the module can
  write a Decision on a failure path.

  _Two mutation tests, because the guarantees are the feature._ Breaking the auditor-outage path to
  auto-resolve instead of asking, and making resolution also confirm the item, each failed exactly
  one test and no others. That is worth doing on a feature whose value is entirely in what it
  refuses to do: a passing suite over safety properties proves nothing until you have seen it fail.

  _One test I had to weaken to make honest._ The criterion asked that the drafted question and
  options carry no identifiers. With a fake provider that is unassertable — the output is whatever
  the fake was handed, so checking it has no ids checks the fixture. What _is_ under this code's
  control is the input, so the test now pins that the service never sends the item's id to the
  drafter, and that the prompt carries the instruction for ids appearing in the concern text. The
  model-behaviour half belongs in an eval. Submitting the weaker-but-real check with that stated is
  better than a green assertion about my own fixture.

  _Discretion calls worth recording._ Three options (middle of the permitted 2-4), with free text
  so the human is never boxed in. No second endpoint for the human's answer — it lands on the
  existing `POST /initiatives/{id}/decisions`, which already requires a rationale and a rejected
  alternative; a parallel write path would mean two places creating human precedent and two places
  to keep those requirements in. No back-reference to the originating item: `emitted_item_ids`
  means the inverse relationship, and a new field was out of scope, so traceability is by the
  question's content — weaker, and consistent with the constraint forbidding identifiers in it.

- **Key references:** `backend/app/services/ambiguity.py`,
  `backend/app/prompts/ambiguity-question.txt`, `backend/tests/test_bd107.py`,
  `web/app/[projectId]/[initiativeId]/ResolveAmbiguity.tsx`, `agents.md` → "A flagged spec item is
  a decision, not a label".
Dropping the flywheel's schema, and the dead code the strip left behind (2026-10-05)
- **Intent:** Answer "have you cleaned all the unnecessary database columns and removed any obsolete
  code" honestly. The answer was no on both counts, and the audit found more than expected.

- **Research thinking:**

  _The code audit found work the strip itself had created._ Scanning every definition under `app/`
  for references, checking the store Protocol against its implementations, and running ruff
  F401/F811/F841 (not previously installed in the venv) surfaced 67 findings. The one worth naming:
  removing BD-69's quality-score refresh from `store/specs.py` left behind the `SELECT state FROM
initiatives` that fed it — **a database round-trip on every `_recompute_state` call whose result
  nothing read**. Deleting a block and deleting what fed the block are two separate acts, and lint
  does not flag the second one; only `F841` on the orphaned local did, indirectly. `store/base.py`
  also still declared `count_recent_extraction_failures` in the Protocol with no implementation
  anywhere, which pyright does not catch because a Protocol stub is not a call.

  _Two pre-existing finds were more interesting than the flywheel leftovers._
  `routers/projects.py::DismissLoopRequest` is a bare class — not a `BaseModel` — that looks exactly
  like a request schema and validates nothing; the route it appears to describe takes `body: dict`.
  And `exceptions.py::InvalidTransition` raises for work-unit state transitions, a concept that does
  not exist anywhere in the codebase. Both had been dead long enough to read as real.

  _On the schema: the previous entry's reasoning was reversed on purpose, not corrected._ The strip
  kept the seven flywheel tables read-only because reversing a data deletion is not cheap. Asked
  directly, the owner chose to drop everything. The split that made the question answerable was
  separating **valueless scaffolding** (`dream_sweeps` and `projects.last_swept_at`, added by
  migration 0058 three days earlier for a scheduler that no longer exists, zero code references;
  `extraction_failures`, empty) from **irreplaceable record** (209 heuristics, 265 proposals, 105
  citations, 13 merge proposals — ~4.3 MB). Presenting those as one choice would have made whichever
  answer came back partly accidental.

  _What the drop actually costs, stated rather than discovered._ Any future question about which
  rules were extracted, which were cited, and which were merged into which is now unanswerable from
  the database. That is acceptable because the questions worth asking were already answered and
  written down — 228 rules produced 5 usable ones, max pairwise similarity 0.7774 against a 0.78
  merge threshold, 42 of 44 citations stranded by BD-101 — and a corpus nothing reads cannot answer
  new ones anyway. A data-only dump was taken before the drop and handed over; it is deliberately not
  in the repository, so nothing depends on it.

  _One migration became un-rerunnable, which is worth knowing about._ Migration 0053 says
  `ALTER TABLE heuristics DROP COLUMN IF EXISTS ...`, and `IF EXISTS` guards the column, not the
  table — so once 0059 dropped `heuristics`, re-executing 0053 raises `UndefinedTableError`. Fresh
  databases are fine (0053 runs before 0059) and production never re-runs an applied migration, so
  the only casualty was `test_cleanup_0053.py`'s idempotency test, which replayed the file
  deliberately. It now checks the migration's _statements_ for `DELETE`/`TRUNCATE`/`DROP TABLE`
  instead of executing them. That is a weaker check, and the weaker check that still holds beats a
  stronger one that passes only while a six-migrations-old schema happens to survive.

  _CASCADE was chosen over dropping in dependency order._ Three tables carry foreign keys into
  `heuristics` and `citation_feedback_events` references two of them. Hand-ordering the drops would
  work and would silently depend on that order staying correct; `CASCADE` states the actual intent,
  which is that nothing referencing these is being kept either.

- **Key references:** `backend/migrations/0059_drop_heuristic_flywheel.sql`,
  `backend/tests/test_cleanup_0059.py` (absence from the live schema AND from any query under
  `app/`), `docs/data-model.md` (seven table sections, the entity map, 20 FK rows and 3 invariants
  removed).
Capture before retrieval: giving human product reasoning somewhere to go (2026-10-05)
- **Intent:** Act on the first of the two gaps the reframe named. Doen recorded how _executors_
  got stuck and never recorded how _people_ decided, which is the half the product thesis depends
  on.

- **Research thinking:**

  _The corpus, classified rather than counted._ `build-doen` is the only active project left: 78
  initiatives, all complete, 19 resolved decisions, 79 memory entries. Reading all 19 by hand:
  **6 are genuine product/UX calls** (should the learn module be hidden or visibly disabled; what
  happens when a human edit races an MCP write; surface spec loops on the dashboard or inline too),
  7 are internal engineering or threshold tuning, and **6 are about the heuristic flywheel deleted
  three days earlier**. So the retrievable precedent for product work is six decisions in five
  months, and a third of the corpus is now actively misleading — retrieval will happily return
  BD-78's "cosine threshold for substantially rewritten" as precedent for a future product call.
  `measure_precedent.py` scores this corpus at 76.5%, which is exactly the circularity its own
  docstring warns about: it measures that a comparable question was asked, not that the answer
  helps. On this corpus, similarity mostly finds other flywheel-threshold decisions.

  _The finding that made the work obvious._ `Decision.raised_by: Literal["agent", "human"]` has
  been on the model since BD-13. It is serialised into every row's payload. **Nothing in the
  codebase has ever set it** — all 20 rows read `agent`, because the only way a decision could come
  into being was an executor calling `escalate_and_resolve`. The field was a correctly-designed
  affordance for a path nobody built, and it had been silently describing the gap for five months.
  Worth noting how it stayed invisible: `resolver_type` _is_ set to `"human"` on most rows, so a
  glance at the data suggests humans are involved — they are, as resolvers of questions agents
  raised. The two fields mean different things and only one of them was ever the gap.

  _Where capture lives, and why not on the MCP surface._ `POST /initiatives/{id}/decisions` →
  `services/precedent.py::capture_decision`, born resolved because nobody is blocked (the open
  state in `escalate_and_resolve` exists so an executor can wait on it; here the human has already
  decided). Deliberately **not** an MCP tool: `raised_by` exists to answer "is any product
  reasoning being captured by people", and an executor able to write `"human"` would make that
  answer report the agent's own work as a person's — worse than reporting nothing. The UI is a
  `DecisionLog` panel on the initiative page, not in the conversation rail, because a decision is
  part of the durable record and the rail explicitly is not (browser-local since spec uvama, which
  is the mechanical reason this reasoning was being lost in the first place).

  _The friction is the feature._ Capture requires a rationale **and at least one rejected
  alternative**. A chosen option with no reason is a note, and the reason cannot be reconstructed
  later. More importantly, "did we already rule that out, and why" is the question precedent is
  uniquely able to answer, and a record with nothing rejected cannot answer it — so the frictionless
  version of this endpoint would be easier to use and would rebuild the thin corpus it exists to
  fix. The tests are mostly refusals for that reason, including a pin that whitespace-only
  alternatives do not satisfy the rule, since an untouched empty form row is the likeliest client
  bug and would bypass the requirement by accident.

  _Deliberately left unwired._ `SpecStore.get_precedent` — which returns the rejected alternatives
  `get_context` drops — still has no caller. Wiring retrieval over six usable decisions would
  produce a demo, not a capability, and would invite tuning a number before the corpus can support
  one. That is the mistake the flywheel made for twenty initiatives; the ordering is the lesson.

  _One known limitation, recorded rather than fixed._ `_decision_text` embeds a decision as
  question + chosen + rationale, so the rejected alternatives are **not** searchable even though
  they are now captured and returned. Fixing it means re-embedding every decision, and it should be
  done when retrieval is actually wired, against a corpus worth re-embedding.

- **Key references:** `backend/app/services/precedent.py`, `backend/app/routers/decisions.py`,
  `backend/tests/test_precedent_capture.py`, `web/app/[projectId]/[initiativeId]/DecisionLog.tsx`,
  `agents.md` → frontier gap 1.
The suite was paying for live models, and nobody could see it (2026-10-04)
- **Intent:** Make the default test suite offline and fast. Found while verifying the flywheel
  removal: full-suite runs swung between 12 and 30+ minutes, and two runs never finished. The cause
  was not the change under test.

- **Research thinking:**

  _The measurement._ `backend/.env` carries a real `LLM_API_KEY`, and five tests reached
  `openrouter.ai` on every run. Suite runtime was therefore set by network latency and OpenRouter
  rate limiting, not by the code — which is why repeated runs got progressively slower as the
  limit bit. Pointing the providers at a dead port dropped the same 324 tests from 12-30+ minutes
  to **25 seconds**, with 319 passing and exactly the five live-calling tests failing. After fixing
  those five: **324 passed in 22 seconds**, at zero cost, stable under random ordering.

  _The finding that matters is which provider leaked._ Not one of the five was testing a model.
  Each already passed a `FakeLLM` for the call it was about, then slipped out through a provider
  nobody was thinking about — **embeddings behind `get_context` were 10 of the 14 live calls**, with
  Jev's BD-96 proposal check and the learn-stage draft making up the rest. The mental model "I
  patched the LLM, so this test is offline" is wrong in a system where retrieval, classification,
  type inference, review and learn each reach a different provider. A per-test opt-in is only ever
  remembered by the test that happens to fail.

  _So the fix is a gate, not a convention._ `tests/conftest.py` now patches
  `httpx.AsyncHTTPTransport` to refuse any request leaving the machine, with an error that names the
  host and says what to patch. It is deliberately at httpx rather than at the provider factories:
  services import their factories by name (`from app.providers.llm import get_shaping_llm`), so a
  default installed on the factory module misses every consumer that already bound the name, and
  there is no list of those that stays correct. Loopback and `testserver` stay open — the ASGI
  TestClient and the MCP streamable-HTTP transport are in-process, and `test_bd65` exercises the
  latter for real.

  _Where a default double is safe, and where it is a trap._ `FakeEmbedder` is now the session
  default: it is deterministic and L2-normalised, so cosine ranking still behaves and every
  retrieval assertion stays meaningful — a real vector buys the suite nothing. Jev and the LLMs are
  deliberately **not** defaulted. Their answers are the thing under test, and a blanket "always
  confident" double would turn real assertions green while testing nothing. That asymmetry —
  infrastructure may have a safe default, judgments may not — is the rule to carry forward.

  _The two tests that needed real doubles got the honest one._ Both were given a `FakeJev` that
  raises, because that is the contracted path: `_classify_and_annotate` leaves items unclassified
  rather than raising, and the reviewer falls through to the human queue on an outage (invariant 9's
  safe direction). Neither test was asserting on the judgment, and both now say so in a comment.

  _A process note on how this was found, which is the uncomfortable part._ The slow runs were first
  attributed to the flywheel strip, then — after one 131s baseline sample on pre-strip code — to the
  strip definitively. Both were wrong: the same test on post-strip code ran in 76s, faster than the
  baseline. The real variable was unbounded third-party latency, invisible in every green run that
  preceded it. **A single timing sample is not a baseline when the dependency is someone else's
  network**, and a suite whose runtime depends on a paid external service hides exactly this class
  of mistake.

- **Key references:** `backend/tests/conftest.py` (the gate and the two session defaults),
  `backend/tests/evals/conftest.py` (`DOEN_LIVE_LLM=1` opt-in, skip-with-instructions otherwise),
  `agents.md` → "The default suite runs offline, and that is enforced".
Removing the heuristic flywheel: what a 228-rule corpus actually cost (2026-10-02)
- **Intent:** Act on the reframe above rather than only documenting it. The flywheel had been
  measured and found not to serve its purpose; leaving the machinery in place would have kept
  paying its maintenance cost and kept inviting the next initiative to extend it.

- **Research thinking:**

  _What came out, and the one thing that stayed._ Deleted: learn-time extraction (the whole second
  half of `services/learn.py`, 26.9 KB), `services/{dream_phase,dream_scheduler,gardener,
admission,heuristic_citations,citation_feedback,conflict_detection}.py`,
  `store/{heuristics,dream_phase}.py`, the `heuristics` routes on `routers/projects.py`, the
  learn-stage confirm route, the `run_dream_phase` MCP tool (18 tools → 17), `/health/flywheel`
  and `routers/observability.py`, `app/eval_harness.py`, eleven heuristic prompts, the
  `tests/bench/` harness with its cassettes, and 19 test modules. **No table was dropped in this
  commit** — the 228 rules, their proposals, citations and merge proposals were kept readable, on
  the reasoning that reversing a code deletion is cheap and reversing a data deletion is not.
  _That held for three days._ Migration 0059 (2026-10-05) dropped all seven tables plus
  `projects.last_swept_at`, as a human decision taken with the cost stated: the schema is clean and
  the record of what the flywheel learned is gone from the database. See the 2026-10-05 entry.

  _Two removals that look incidental and are not._ **RRF + BM25 went with the heuristics.** The
  hybrid ranking existed only to order rules against each other — decisions and memory were always
  ranked by plain cosine, and `_merge_by_cosine` existed solely to reconcile the two incompatible
  scales. `store/retrieval.py` went from 378 lines to 117 with no behaviour change for the corpora
  that remain. **`quality_score` went too**, along with `_laplace_score` and the 60-line
  correlated-subquery SQL that computed it; it only ever broke ties among heuristics.

  _`detect_conflicts` is the removal most likely to be mourned, and it is not the thing people
  mean._ BD-60's conflict detection compared _retrieved heuristics_ against each other — with the
  rule corpus gone it has no inputs. The contradiction-finding that has actually earned its place
  is a different mechanism: the shaping classifier's rubric requires each item to be compared
  against the rest of its own batch, which is what caught the discretion-vs-constraint contradiction
  in BD-99 and BD-105. That stays. If you want conflict detection, the spec-item comparison is the
  one that works; do not restore the heuristic-pair version to get it.

  _The suite says what was load-bearing and what was self-referential._ 546 passing before, 321
  after — but only 3 of the ~225 removed tests covered behaviour anything outside the flywheel
  depends on. 19 whole modules (BD-17, 30, 31, 39, 41, 43, 44, 48, 60, 64, 68, 69, 70, 76, 77, 79,
  89, 91, plus the bench) tested the subsystem against itself. The incidental fixes were small and
  telling: `test_bd90` and `test_bd93` each kept an "out of scope for this spec" tuple naming
  modules by filename, which fails loudly when a module is deleted — a better outcome than a stale
  assertion passing vacuously, and worth copying.

  _One methodological note, because it cost an hour._ Two pytest runs overlapping on the shared
  `doen_test` database produced 95 failures where the uncontended run produced 24, all of them
  shaped like unrelated 404s on basic endpoints. A suite that shares a database is not safe to run
  concurrently with itself; if a failure list suddenly widens and looks nothing like the change,
  check for a second run before believing it.

- **Key references:** `docs/design-principles.md` ("Retiring the heuristic flywheel" — the
  measurement and the three reasons), `agents.md` invariant 8 (rewritten: guidance comes from
  precedent), `backend/app/store/retrieval.py`, `backend/app/measure_precedent.py`.
The reframe, and the three measurements behind it (2026-10-02)
- **Intent:** The goal shifts from "the system learns engineering rules" to "the system records how
  comparable product calls were made, and the artifact it produces can be trusted." Three
  measurements forced it, each of which contradicted something the project believed.

- **Research thinking:**

  _The flywheel's metric was circular, which is why nothing caught it for twenty initiatives._ Its
  purpose is better specs; every number used to judge it measured activity instead. A citation is
  written when the drafting model mentions a rule id in text it generated, and the retrieval bench
  harvested "citations for relevance" as ground truth — so the eval was scored against labels the
  thing under evaluation produced. 228 rules, 5 usable. BD-89 had already stripped the subsystem
  once and it regrew into the same shape. The deciding detail is BD-101's own accepted cost: 42 of 44
  citations landed on rules the change made unusable, meaning the rules people actually used were the
  standalone ones BD-97 had argued for all along.

  _Precedent is the asset, and it was sitting underneath._ From the same history: 24 resolved
  decisions, 23 carrying both a rationale and the rejected alternatives — 96% complete, each
  authored by a human choosing between stated options. A heuristic is a lossy compression of a
  decision that discards the situation making it true; precedent keeps it. A first retrieval
  prototype (`store.get_precedent`) was built and measured in a day: it surfaces what `get_context`
  drops — `_decision_text` embeds question + chosen + rationale and omits the rejected options, which
  for precedent is most of the value.

  _Then the measurement invalidated itself, usefully._ `app/measure_precedent.py` scored 76.5% of
  decisions as having relevant prior art. Reading the 17 pairs, the real figure is ~18%: the top
  scores were artefacts of shared boilerplate prefixes ("Work Unit 1 (type-inference Jev
  migration):") rather than related questions. Two genuine signals survived — BD-97 retrieving the
  prior decision that established Jev auto-admission, and a BD-52 → BD-78 → BD-51 cluster of three
  initiatives separately deciding what cosine threshold means "substantially similar". That
  recurrence is exactly what the reframe wants surfaced.

  _And then the corpus composition invalidated the whole exercise._ The 24 decisions are almost
  entirely meta-work on Doen's own internals — thresholds, Jev migrations, flywheel mechanics. So
  the measurement answered "does precedent help with flywheel maintenance", which is close to
  worthless for the vision. Worse, scoped properly: **all 25 decisions were raised by an agent, none
  by a human. 83 completed internal initiatives produced 24 decisions; 9 completed product
  initiatives produced 0.**

  _The real bottleneck is capture, not retrieval._ A decision exists only when an executor hits an
  intent gap and escalates. A human making a product call during shaping writes nothing down — the
  reasoning lives in a conversation that has been browser-local since spec uvama, so the backend
  cannot read it and `stated_priorities` degrades to empty. The precedent corpus for product work is
  therefore empty and will remain so however good retrieval becomes. Capture precedes retrieval; the
  retrieval prototype and its harness are kept, and 18% is the baseline to beat once there is
  something to retrieve.

  _A fourth finding, independent of all of the above._ Doen verifies the executor rigorously and its
  own generated artifacts not at all. In one session, drafted specs referenced a `tier` column, a
  `resolution_reason` column, a `call_site` column, a "metric store" and a dashboard — none existing —
  plus stale baselines; and a learn record asserted three proposals "reached a terminal state in the
  first post-deploy sweep" when they were still pending and the step had never executed. Both ends of
  the loop fabricate. An engineer survives that; the designers and product owners this reframe
  targets cannot see it. Groundedness is a precondition of the audience shift.

  _What the numbers say about where the time went._ 83 of 93 completed initiatives were spent on
  Doen's own internals, most of that maintaining the flywheel, against 9 on product. The flywheel's
  largest cost was never the code — it was the product capacity it consumed.

- **Key references:** `docs/design-principles.md` (Product thesis, and "Retiring the heuristic
  flywheel" under Deliberately rejected), `backend/app/store/decisions.py::get_precedent`,
  `backend/app/measure_precedent.py`.
Every decision is recorded with what was ruled out and why. That record is the evidence.