On this page
- Status: Accepted (2026-11-07, operator). Per-seam build status sits in each seam.
- Date: 2026-11-07
- Owners: Platform / decision-intelligence (
packages/metrics,packages/actions,packages/platform-contract); S5 lands through the AI work packages (packages/ai). - Related: ADR 0004 (off-take loop), ADR 0009 (causal service, deferred by this ADR, not superseded), ADR 0010 (RLS roles, outbox), ADR 0025 (PCNQ), ADR 0026 (metric layer), ADR 0027 (declared conversion), ADR 0053 (loop console), ADR 0057 (alert workflows); §60, §64, §65, §66, §82, §117, §171.
- Evidence: every
path:linebelow was read at commiteb676254on 2026-11-07.
Context#
The loop records decisions: append-only decision_episodes with selection propensity and receipt hash (packages/schema/src/tables/mso-episodes.ts:169, :266, :293; trigger packages/schema/sql/append-only-guards.sql:78), replay as a verify:rls leg (packages/metrics/src/decision-replay.ts:295, package.json:58), OPE that refuses below ESS 30 (packages/metrics/src/ope.ts:72, :232), owner-only promote and rollback (apps/web/src/server/routers/offtake.ts:2112, :2149). Evidence levels L3–L5 are beta and their missing pieces are listed in docs/status.md:138-146. It does not learn from outcomes yet:
| # | Gap | Evidence |
|---|---|---|
| G1 | The lever posterior is fit on correlation, not reward. fitPolicyModels reads offtake_; outcomes enter only as a count that shrinks variance, and the count includes unconfirmed outcomes although outcome_ is the only event learning may read. Rewards are already written. |
packages/; mso-; reward writes packages/ |
| G2 | The champion config is not served. The scan ranks with defaults; only the evaluation path passes a config. | offtake- vs :5332-; packages/ |
| G3 | The 10 % holdout is a payload literal. MSO approve inserts approved commands directly; arms are assigned only inside propose; observed_ has one writer, the sample generator. |
apps/; packages/; scripts/ |
| G4 | Few human labels. alert_ has two writers, neither a person acting on the alert; brief bullets and chat answers carry no reaction. |
packages/; apps/; scripts/; packages/; packages/ |
| G5 | Feedback weight reaches one path. weights is optional; only the dataset collector reads it; the catalog-domain collector has no production caller and passes none; workflow rows are excluded from signal_ (ADR 0057 D5). |
packages/; packages/; apps/; packages/ |
| G6 | Agent eval is not in a gate; prompts carry no version. | package. (absent from ., .); packages/; packages/ |
| G7 | Event contracts carry no shared id or schema version; lineage stops at bronze. | packages/; packages/; apps/; packages/; packages/; packages/; docs/ |
| G8 | AOV has two formulas. | apps/ vs :1020; fallback offtake- |
| G9 | The playbook runner proposes as org_, so its steps approve themselves. |
packages/ |
| G10 | Chat has no token cap: the budget map covers two purposes. | packages/ |
| G11 | No consent mechanism for cross-org learning. category_ has no reader or writer; the industry prior is a constant. |
packages/; packages/; policy- |
The signals work packages in flight own alert state and feedback UI: WP-SIG3 adds incident status, resolve and auto-resolve on alert_events (migration 0249), WP-SIG5 the ack, resolve, snooze and dismiss actions on the bell, brief and alert list, WP-SIG2 owns dataset-signal-collect.ts. S1 consumes their transitions as labels and does not redefine them.
Practice this ADR measures against (sources as cited in the 2026-11-07 architecture review, not re-fetched here):
| Source | Practice | Seam |
|---|---|---|
| Google, Rules of ML | Ship a heuristic, log serving-time features, join outcomes to them | S2 |
| Google Cloud, MLOps levels 0–2 | Level 1: validated pipeline with training triggers; target level 1 only | S2, S5 |
| Microsoft, MLOps maturity model | Registry with versioned lineage of what was served | S3, S5 |
| Netflix, Decision making at Netflix | Assignment and estimand stored before the readout | S2 |
| DoorDash, Dash-AB | Analysis as a service; guardrail metrics per test | S2 (guardrails later) |
| Uber, Michelangelo | One feature definition shared by training and serving | S3, G8 |
| Anthropic, Building effective agents | Workflows before agents; autonomy only with evals | S5 |
| OpenAI, A practical guide to building agents | Layered guardrails, eval-driven iteration | S5 |
| Shopify Engineering (Sidekick) | Merchant-grounded answers judged by user feedback | S1 |
Decision#
Five seams, each one module or one additive migration plus one guard in an existing gate. No new service, queue, table or framework.
S1 — Labels at the owning layer (G4, G5)
- Alerts: a label is a WP-SIG3 transition (acked, resolved manual or auto, dismissed). No alert columns here.
- Brief: no column on
briefings; a brief is one reader's rendering. A bullet's reaction writes the row it came from: the four §117 feedback columns onsignal_events, or the WP-SIG3 transition onalert_events. - Chat:
chat_messagesgainsrating(up | down, NULL),rating_reason,rated_at,rated_by; set onrole = 'assistant'rows by the conversation's own user throughorgProcedure. - Episode link: a label on a row linked to a decision (
packages/metrics/src/episode-signal-link.ts) appends adecision_episodesrow with a new event kindfeedback.EPISODE_EVENT_KINDSis a varchar union (mso-episodes.ts:64-99), so no migration;reducePlaybookStats(packages/metrics/src/decision-episodes.ts:1126) must ignore it. - One weight reader:
weightsbecomes required on the collector input (signal-binding.ts:346), so no caller can rank unweighted. The rule stays demote-only (§117 amendment C4). - Verification: type test (omitting
weightsfails typecheck); router test (rating refused for another user's message and another org);reducePlaybookStatstest (afeedbackrow changes no stat);append-only-ledger.tsandverify:rlsgreen. - Consequences: one migration (
chat_messages); labels become rows the reward join and prompt eval can read. - Rejected: rating on
chat_tool_calls(a person judges the answer, and that table has nois_sample,packages/schema/src/tables/chat-tool-calls.ts:30-52); abriefingscolumn (two labels for one event). - Isolation:
chat_messages(rls-policies.sql:343),signal_events(:400, worker-only insert, §117),alert_events(:129),decision_episodes(:390); a rating is writable only by the message's own user. - Status (2026-11-07): chat rating built. Migration
0254_chat_message_rating.sql(columns, CHECKs, partial index, frozen-column guard insql/append-only-guards.sql);chat.rateMessage(apps/web/src/server/routers/chat.ts, rate-limited, auditchat.message.rate); thumbs on/chatand the dashboard assistant tab; readerlistChatAnswerLabels(packages/metrics/src/chat-answer-labels.ts) on a worker column grant that excludesparts. Not built yet: thefeedbackepisode kind, requiredweights, and the deck assistant's thumbs.
S2 — Reward reaches the learner; the holdout is real (G1, G3)
- MSO approve keeps its own insert (its payload is not an
ActionProposalSchemapayload,packages/actions/src/index.ts:139-158) and calls the exportedassignExperimentArm(:738-741) withholdoutBp: 1000, the 10 % now written as a literal. It writes theexperiment_assignmentsrow in the same transaction; a control-arm command lands asholdout, neverapproved. Nothing starts executing that does not today; §64 gates stay in front. - Reward join in
offtake-loop.ts, the sole persister (§60b): at window close it writesobserved_lift_bpfrom the org's declared conversion throughresolveConversionActualScoped(offtake-loop.ts:4489). fitPolicyModelsfits each lever posterior on lift in bp from owner-confirmed outcomes (confirmed_atset):incremental_value × 10000 / (measured_value − incremental_value), the quantityobserved_lift_bpstores. A correlation is not a lift, soofftake_models.per_leverstops being an input: the cold-start prior becomes 0 bp withCOLD_START_VAR_BP2(packages/metrics/src/policy.ts:47), and a newpolicy_models.methodvalue marks lift-fit rows so a reader never mixes the two. Below 8 confirmed outcomes, the floor ranking already uses (playbook-stats-rank.ts:96), the brand keeps the prior.- Selection stays deterministic: S2 gives a control arm, not randomized choice among playbooks.
- Verification:
verify:dataassertion (observed lift reproduces fromordersover the window for sample orgs, anchored to the §55 oracle); unit test (an unconfirmed outcome moves no posterior);offtake-single-source.py. - Consequences: no migration;
observed_lift_bpgets a production writer besidesscripts/generate-sample-data.ts:1145; 10 % of approved MSO commands are withheld as control. - Rejected: routing MSO approve through
proposeAction(payload schema mismatch, and a newapprovedrow there auto-executes,packages/actions/src/index.ts:373); keeping the correlation as the lift prior (different quantity). - Isolation:
experiment_assignments(rls-policies.sql:147),decision_outcomes(:383),policy_models(:421); the fit reads one org (policy-loop.ts:178-186). - Status (2026-11-07): built, no migration (0252 unused). The arm unit is the decision:
sha256("mso_decision:<org>:<decision>")intoassignExperimentArmwithMSO_DECISION_HOLDOUT_BP(1000, rowmso-decision-holdoutindocs/architecture/reference/limits-and-budgets.md), so a cancel and re-approve keeps its arm; oneexperiment_assignmentsrow per command (subject_type = 'mso_decision',subject_key= decision id) in the claim transaction, a control arm inserts every command asholdout, and a decision with no command records no arm.assignExperimentArmnow buckets on 8 hex digits: 4 digits put 10.7 % in a 10 % arm. The baseline is the same conversion over the equal-length window before execution, read byresolveConversionActualScoped; the lift is pre/post per decision, written on both arms, and not yet control-adjusted. A control-arm decision was never run: its outcome is written with verdictabstain(no calibration bucket, nomeasuredepisode, soplaybook_stats, the OPE log and the confirm-due ping never see it) andconfirmOutcomerefuses it. The decision board tells the owner: the approve response's arm raises a notice not to run the decision by hand, and a control decision keeps one status line on its card and detail, read from its newestexperiment_assignmentsrow insideofftake.decisions(now narrowed by the caller's brand grant, §198); a control decision gets no lesson to approve. The fit readsobserved_lift_bpof treatment-arm, non-sample rows whose outcome is confirmed (policy_models.method = 'lift_normal';recommendPolicyand the champion/challenger card read only those rows);decision_outcomes.incremental_valuestays NULL on real rows, so no surface number changes.yng_workergains UPDATE onexperiment_assignments(observed_lift_bp, measured_at)only. Verification:verify:data#61 (fixture org: lifts equal the literals its orders imply, both arms; the control outcome abstains with no episode; the posterior folds the 8 confirmed treatment rewards and leaves out the unconfirmed one and the control) and #20 (every lift-fit row reproduces from an independent join); unit tests inpolicy-loop.test.ts,policy.test.ts,offtake-approve-ordering.test.ts,run-playbook-role.test.ts. Follow-up:recommendPolicyserves only a lever with confirmed positive lift (n_obsat the floor, mean > 0 bp) and abstains ascold_start("chưa đủ bằng chứng") otherwise, and a guardrail veto falls back only to such a lever that clears the floor itself;approveLessonrefuses a control decision in its UPDATE asconfirmOutcomedoes;markExecutedon aproposeddecision assigns the arm and writes the commands through the helpers approve uses, in its claim transaction. Not done:decision_episodes.source_watermark(S4) has no writer here.
S3 — Serving reads the champion; the runner uses the caller's role (G2, G9)
- The scan (
offtake-loop.ts:906) passes the championpolicy_versions.config, read once per org per scan with the query at:5164-5179. No champion meansTIER2_DEFAULTS, today's behaviour. - The episode pins the served
policy_versionsid and version in itsreceipt, whichreceipt_hashalready covers (mso-episodes.ts:290-293); replay ranks with that config.logging_policy_version(:275) keeps its meaning, the rule-DSL version (packages/metrics/src/decision-episodes.ts:647). runPlaybook(packages/actions/src/index.ts:659) takes the actor's role from its caller instead of the literal at:675. A system trigger (apps/worker/src/trigger-dispatcher.ts:142) proposes asviewer, so every step waits for a person.- Verification: unit test (a promoted challenger with a different prior changes the served order);
scripts/audit/decision-replay.tsreplays with the pinned version; test (a system-triggered step ispending_approval);decision-mutation-rbac.py. - Consequences: no migration; a promotion now changes what tenants see, so promote stays owner-only and audit-logged (§64); alert-triggered playbook steps stop approving themselves.
- Rejected: a second
logging_policy_versionmeaning (one column, two versions); keepingorg_adminfor system triggers (no person approved). - Isolation:
policy_versions(rls-policies.sql:425), read per org and brand (offtake-loop.ts:5164-5179).
S4 — One event envelope; lineage to gold (G7)
- One Zod
EventEnvelopeSchemainpackages/platform-contract:{id, type, org_id, brand_id?, occurred_at, source_system, source_ref, schema_version, data}. The eventbus envelope gainsidandschema_version; webhook ingest parses with it while the raw body still lands verbatim inraw_events(§44). - Additive migration: nullable
raw_event_id,source_batch_idonordersand the sync-written silver tables;source_watermarkjsonb onagg_*and ondecision_episodes(set at insert). NULL means "before lineage"; no backfill. Indexes only when a reader exists. - Verification: new audit event-envelope-single-schema.py in
audit:all(no envelope type outsideplatform-contract);scripts/audit/decision-replay.tscompares the watermark when present;verify:rlsanddrizzle-journal-monotonic.py. - Consequences: one migration; replay can say whether today's warehouse matches the inputs a decision saw (
docs/status.md:146); producers of the three contracts change once. - Rejected: a streaming platform or OpenTelemetry for lineage (columns answer the question; no consumer needs more); backfilling lineage for old rows (unrecoverable for rows ingested before it).
- Isolation: no learned state.
orders(rls-policies.sql:305) andagg_org_day(:329) are already org-scoped; the envelope carriesorg_id, and a mismatch with the authenticated connector's org is refused. - Status (2026-11-07): schema half built.
eventEnvelopeSchemainpackages/platform-contract/src/event-envelope.ts(contract 0.3.0), used by the webhook ingest route (the envelopeorg_idis the authenticated connector's org) and the eventbus publisher (id,schema_version). Migration 0253 addsraw_event_id/source_batch_idonordersandinventory_snapshots; the polling sync, Bronze replay and webhook writers set them, uploads clear them.creatorsis left out: it is a merged identity, not one Bronze record.source_watermarkis onagg_*anddecision_episodeswith no writer yet; the materialization refresh and the episode persister (offtake-loop.ts, owned by S2/S3) add it, anddecision-replay.tscompares it once it is written. Guard:event-envelope-single-schema.py(§205) inaudit:all. Reference: event contracts.
S5 — Eval and prompt versions in the gate; a chat cap (G6, G10)
ai_prompt_templatesgainsversionandbody_hash;ai_usage_loggainsprompt_hash,prompt_version. WP-AI1's columns merged as migration 0248 (6d39fc09).organizationsgains a nullable chat token budget (NULL = unlimited, today's behaviour) and one row inPURPOSE_BUDGET_COLUMN(packages/ai/src/server.ts:228-231); the chat route asksaiBudgetRemainingbefore streaming. No default cap: the operator sets it.- CI job in
.github/workflows/ci.yml:eval:agent --dry-run --baseline=<committed file>(scripted, no provider);--liveruns nightly and gates nothing. - Verification: the baseline diff fails CI on a regression;
limits-registry.pyrow for the cap;ai-resolver-single-source.py. - Consequences: one migration (
ai_prompt_templates,ai_usage_log,organizations); a prompt or model change that regresses a graded case fails CI; chat spend can be capped per org per month. - Rejected:
--liveeval as a merge gate (provider cost and nondeterminism per push); a default chat cap (no source for the number). - Status (2026-11-07, accepted by the operator): CI half merged (
9fc00c06). Schema half is migration 0255:ai_prompt_templates.version(N+1 per body change, computed in the router's one UPDATE) andbody_hash;ai_usage_log.prompt_hash/prompt_version, written by/api/chatas the hash of its system prompt rendered at a fixed clock (version NULL: chat reads no template row);organizations.chat_ai_budget_tokens, refused before streaming withchat_budget_exhausted(429, Retry-After to the next ICT month), set in the Admin CP org drawer, rowai-chat-budgetindocs/architecture/reference/limits-and-budgets.md. Other purposes record NULL until their call sites separate instructions from data;chat_deckstays uncapped. - Isolation:
ai_prompt_templates(rls-policies.sql:80) andai_usage_log(:78) are org-scoped.organizationsis outside RLS by design (:664-665; inventoryscripts/audit/rls-policy-inventory.ts:55); the budget column is written only where the two existing budget columns are (apps/web/src/server/routers/admin.ts:861) and read for the caller's own org.
Tenant isolation of learned state
No seam adds a table. Every learned-state and label table is in the attested org RLS arrays (packages/schema/sql/rls-policies.sql:548-590): ai_usage_log:78, ai_prompt_templates:80, alert_events:129, experiment_assignments:147, chat_messages:343, decision_outcomes:383, decision_episodes:390, playbook_stats:391, signal_stats:406, policy_models:421, policy_versions:425. S4 lineage columns land on org-scoped fact tables; the S5 budget column lands on organizations, the one table outside RLS (S5 above). Learned state is fit per org (policy-loop.ts:178-186) and pooled across brands inside one org only (:197); brand-carrying rows keep brand_id (§82). No code reads another org's outcomes. Cross-org learning (pooled priors, category_benchmarks) stays closed until a separate ADR defines consent: per-org opt-in, recorded and revocable, aggregated above a minimum org count.
Rollout order
| Step | Seam | Waits for | Rollback |
|---|---|---|---|
| 1 | S3 | nothing | revert; without a promotion the served order is unchanged |
| 2 | S2 | S3 (a promoted policy must be the one served) | revert; assignments already written stay as history |
| 3 | S4 | nothing; any time | revert code; nullable columns stay |
| 4 | S1 | WP-SIG1, SIG3, SIG5 merged | revert; rating columns stay NULL |
| 5 | S5 | AI work packages (packages/, chat route) |
drop the CI job; NULL budget = unlimited |
Rejected alternatives#
- A feature-store product: no second consumer; the catalog, Cube and dataset DSL already define features. G8 is a catalog fix (
packages/metrics/src/types.ts:185has no formula field), not a new store. - Cross-org priors now: no consent mechanism (G11).
- Production bandit now: needs S2 rewards for at least 2 months and an OPE ESS of 30 (
ope.ts:72) before randomized selection. - The causal service now (ADR 0009):
apps/ml/yng_ml/main.pyis a 68-line stub; deferred until S2 yields a control arm. 0009 stays Proposed. - A new alert incident table: the operator chose columns on
alert_events(WP-SIG3). - Seam-level alternatives are listed under each seam.
Consequences#
- Three additive, idempotent migrations: S1 (
chat_messages), S4 (lineage), S5 (prompt version, usage, org budget). Numbers are allocated at build time; 0249 and 0250 belong to the signals work. - One shared Zod schema, one CI job, one new audit, one
verify:dataassertion, one type-level guard. - Unchanged: a person approves every action (§64), and S3 removes the one path where a step approved itself; no machine write-back (
packages/connectors/tiktok-shop/src/index.ts:972-984returnsmanual_follow_up); the weight rule only demotes. - L3 can move on control-arm evidence (S2) and L5 on the watermark (S4);
docs/status.mdrows change only with that evidence. - Not addressed: G8 beyond S2 using the one conversion resolver; replay of
signal_eventsinputs.