Skip to content

feat(risk): add Bayesian monitor, shadow ledger, and decision cards - #825

Open
Pigbibi wants to merge 2 commits into
mainfrom
feat/v2-closed-loop-governance
Open

Pigbibi wants to merge 2 commits into
mainfrom
feat/v2-closed-loop-governance

Conversation

@Pigbibi

@Pigbibi Pigbibi commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds three pure-offline, zero-I/O governance modules to quant_platform_kit.risk:

  • bayesian_confidence_monitor.py: quarterly source-separated (SHADOW / PAPER / LIVE) conjugate Normal-Normal + Beta-Binomial strategy decay monitor with immutable parameter_mutation_allowed=False and auto_execution_allowed=False.
  • multi_tier_shadow_ledger.py: simultaneous read-only multi-tier shadow ledger ($1.5k, $15k, $50k + modeled monthly contributions) built on bucket_capital_ladder and benchmark_dca_and_regime.
  • sentinel_decision_cards.py: read-only Layer 3 web-console decision-card builder with strict evidence sanitization, hard $50k Bucket D floor enforcement, and immutable requires_owner_signoff=True / auto_execute=False.

Risk & Rollback

  • Risk: Low (pure offline risk/reporting modules; zero broker, cloud, network, or live/paper execution side effects).
  • Rollback: Revert this PR cleanly; no runtime configuration or live service state is modified.

Verification

  • uv run ruff check passed with 0 issues across all new modules, exports, and tests.
  • uv run pytest tests/test_bucket_capital_ladder.py tests/test_bayesian_confidence_monitor.py tests/test_multi_tier_shadow_ledger.py tests/test_sentinel_decision_cards.py: 20 passed.
  • Local gpt-6.2-astra audit completed; all P1 and P2 findings fixed and covered by regression tests.

AI assistance

Drafted and audited with AI assistance (Antigravity + local gpt-6.2-astra review); all tests and lint checks verified locally.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-29T00:21:57.742810Z fe71dcf PR opened
🔒 Security Review ✅ Completed 2026-11-29T00:20:57.533416Z fe71dcf PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Pigbibi Pigbibi added the agent-approved An agent cleared this high-risk change on the current head; not an owner confirmation label Nov 29, 2026
@Pigbibi
Pigbibi enabled auto-merge (squash) November 29, 2026 00:19

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fe71dcfa21

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +262 to +263
elif holdings.get(sym, 0) > 0:
merged_targets[sym] = held_val

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve explicit zero-weight exits while expansion is paused

When expansion_paused=True, a held symbol explicitly assigned weight zero is restored to its current market value here because the earlier positive-weight filters omit it from merged_targets. Consequently, the order planner never receives the exit: buying 350 VTI shares in one step and setting bucket_a_weights={"VTI": 0.0} in the next paused step leaves all 350 shares held. Preserve explicit zero targets separately from missing targets so the pause blocks new buys without suppressing requested exits and distorting shadow results.

Useful? React with 👍 / 👎.

card_type=CARD_TYPE_BAYESIAN_DECAY,
severity=sev,
title=f"{rep.bucket_id} performance check: {rep.overall_status}",
summary=f"Recent {primary} quarters weakened. {action_hint} Strategy rules stay unchanged.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Attribute Bayesian alerts to the governing observation source

When an insufficient-sample LIVE channel is healthy but PAPER has a RED alert, evaluate_bucket_bayesian_confidence deliberately retains primary_source="LIVE" while taking the overall status, action, and reasons from PAPER. This summary then incorrectly tells the owner that LIVE quarters weakened, and the card includes no governing-source evidence to correct that attribution. This occurs with the observations already covered by test_insufficient_live_sample_does_not_mask_paper_red_alert; carry the governing source into the report/card or describe the alert without attributing it to the primary channel.

Useful? React with 👍 / 👎.

Comment on lines +249 to +251
raw_d_usd = budget_d * w
capped_d_usd = min(raw_d_usd, d_cap) if d_cap > 0.0 else raw_d_usd
merged_targets[sym] = merged_targets.get(sym, 0.0) + capped_d_usd

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve passive-breach handling when capping Bucket D targets

When a Bucket D-only holding appreciates above its 2% NAV cap, pre-capping its target dollars here turns the passive breach into an explicit trim before compute_merged_whole_share_orders can apply its existing block-adds-but-allow-holding behavior. For example, with $60,000 initial capital, a 10% Bucket D budget, and an unchanged 100% sleeve signal, the ledger initially buys 12 shares at $100 and then sells six when the price rises to $200; passing the uncapped signal target and the same cap directly to the planner retains all 12 shares and blocks additions. Preserve the original target for passive-breach evaluation while enforcing the cap on new purchases, otherwise the shadow ledger introduces unintended sales, fees, and return differences.

Useful? React with 👍 / 👎.

@qsl-gemini-reviewer

Copy link
Copy Markdown

AI Code Review (gemini / gemini-4-neon)

The PR adds three well-structured, offline risk governance modules with solid input validation and immutability guards, but contains two medium-severity logic bugs: expansion_paused in the multi-tier shadow ledger blocks all explicit exits (and can raise KeyError on missing target prices), and sentinel decision cards misattribute escalated Bayesian alerts to primary_source when a lower-fidelity channel triggered the alert.

Reviewed commit: 2450754c45 · Coverage: complete · Unresolved findings: true

Findings

  • [MEDIUM] src/quant_platform_kit/risk/multi_tier_shadow_ledger.py: In _build_sleeve_targets_and_caps, when expansion_paused=True, symbols omitted from target weights or explicitly set to 0.0 (filtered out by w > 0.0) hit elif holdings.get(sym, 0) > 0: merged_targets[sym] = held_val, which locks existing holdings in place and makes explicit exits impossible (contradicting the comment 'still permitting explicit trims/exits'). Also, step.prices_usd[sym] is indexed unconditionally for sym in merged_targets, raising an unhandled KeyError instead of ValueError if a target symbol has no price. Add a regression test in tests/test_multi_tier_shadow_ledger.py covering expansion_paused=True with non-empty existing holdings (new buys blocked, trims/exits permitted, and deactivated-sleeve holdings preserved only as intended).
  • [MEDIUM] src/quant_platform_kit/risk/sentinel_decision_cards.py: In _append_bayesian_cards, decision cards use rep.primary_source for card_id, summary ('Recent {primary} quarters weakened'), and evidence['primary_source']. However, in bayesian_confidence_monitor.evaluate_bucket_bayesian_confidence, when the highest-fidelity channel (e.g., LIVE) has insufficient samples and is GREEN, overall_status/recommended_action/reason_codes are escalated from a lower-fidelity channel (e.g., PAPER or SHADOW) while primary_source remains LIVE. This causes the decision card to misattribute a PAPER/SHADOW decay alert to LIVE. Expose the governing/triggering source on BayesianConfidenceReport and surface it accurately in OwnerDecisionCard.
  • [LOW] src/quant_platform_kit/risk/sentinel_decision_cards.py: In _append_safety_cards, cost_drift_report.breach_reasons is joined raw into evidence['breach_reasons'] without allowlist sanitization, unlike isolation_reason (_PUBLIC_ISOLATION_CODES) and bayesian_reports.reason_codes (_PUBLIC_BAYESIAN_REASONS). Apply a matching allowlist sanitizer for consistent defense-in-depth redaction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-approved An agent cleared this high-risk change on the current head; not an owner confirmation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant