Skip to content

feat(sh2): FUSE-1 integration, US 23/5 close isolation, and Cloud Run job - #7

Closed
Pigbibi wants to merge 48 commits into
mainfrom
feat/sh2-live-engine
Closed

Pigbibi wants to merge 48 commits into
mainfrom
feat/sh2-live-engine

Conversation

@Pigbibi

@Pigbibi Pigbibi commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

AI assistance

Assisted by OpenAI Codex CLI (gpt-6.2-astra reasoning high pre-push blocker review) and Coordinator/subagent orchestration (shadow-sh2-engineer); all vendored checksums, unit/integration suites (185/185), design demos (SH2-D1..D10), sh2_acceptance, and gitleaks were independently verified on exact HEAD 0cddff241cc85aebfbb7a7de96e28d2bd6f08153.

What changed

Implements SHADOW-N SH-2 offline software slices on ShadowResearch main (20412087), integrating digest-pinned FuseControl fuse-eval-spec/v1 (46a86eed), csa22-v2 2026 XNYS calendar + US 23/5 16:00 ET close isolation (Roadmap v2.0 Item 13), and secret-free GCP Cloud Run Jobs (us-east1) runtime containerization (Item 18), with zero production unlock (production_chain_locked: true, clk01_active: false) and zero orders (orders_placed: 0, kelly_applied: false, H = "0", B0 = "50000"):

  • Digest-Pinned Read-Only FUSE-1 Vendoring & Entry Gates:
    • Vendors the 8 canonical .py files from QuantStrategyLab/FuseControl 46a86eed (0444, zero __pycache__/) under vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/ plus metadata/, verified against F1-A01/A03/A04/A10/A11 (docs/sh2-entry-gates.md).
  • Real Engine Adapter, Quarantine, Prior-Close Binding & Sizing Isolation (src/shadow/fuse_adapter.py, src/shadow/ledger.py, src/shadow/replay.py, src/shadow/sizing.py, src/shadow/scheduler.py):
    • VendoredFuseEvaluator re-verifies source SHA-256 digests, framed engine_hash, spec_version, and __pycache__ bytecode before load and before every evaluate(..., mode="shadow", ...) call with zero conformance shims.
    • Enforces caller-side explicit boolean hwm_adjusted on V2 reconciliation payloads (adjustment_complete is True), wires market_records[].corporate_action (split_ratio / cash_per_share_usd) into V2, preserves fund-level hwm_adjusted, fractional q_pre/broker_position quantities for O3, missing/invalid V1 modelled_fee/modelled_financing, V4 long_run_volatility, V5 shortfall_observed/shortfall_predicted, V6 carrying_cost_measured/excess_return_shrunk, and V7 quote_staleness/spread_width/trading_pause observations as None (emitting explicit missing_input instead of fabricating defaults; explicit long_run_vol_by_inst supported via scheduler.py / fuse_context / replay.py), derives L6 benchmark returns independently of missing fund returns (while still gating source_records["market_data"] on complete fund returns), five_session_history/sessions_window, O5 pre-trade order evidence, O7 explicit silence flags (o7_runtime_silent / o7_monitor_silent), and O9 change signals (tier_change_event / o9_change_descriptors), preserves list-form authorized_events, validates caller-supplied market_data/session_calendar source_records, rejects stale mismatched calendar_session["trade_date"], removes silent synthesis of missing broker_reconciliation or zero index_one_session_returns, scales derived joint_exposure/proposed_exposure into U-01 3x * beta / (1 + H/E*) units, derives split-adjusted returns & L4 one_session_loss, evaluates per-tier FUSE controls independently before sizing each tier (evaluator.by_tier & _by_tier, including explicit fuse_inputs / direct FUSE payloads via _apply_explicit_payload_tier), and structurally quarantines StubEvaluator / synthetic observations in production mode.
    • Strictly resolves the exact immediately preceding trading session via resolve_previous_trading_date() and target_prior_date (no stale-session fallback across skipped/rejected days), enforces _validate_tiingo_official_close_row across both current and prior-close Tiingo extraction (rejecting extended_overnight_open and off-close session_time), forwards non-empty partial index_one_session_returns into vendored FUSE-1 so single-benchmark L6 -10% crash latches still trigger even when another benchmark is missing/ineligible (O1 still enforces benchmark completeness), and requires complete fund returns before evaluate().
    • Enforces NO-NEW-RISK exposure clamping (q_ideal <= q_pre_i) and per-fund / per-tier control scopes in sizing.py & ledger.py.
  • Ledger-Bound State Integrity, Production History Authentication & Multi-Day Rejection Recovery (src/shadow/ledger.py, src/shadow/scheduler.py, src/shadow/cloudrun_job.py):
    • Embeds evaluator.next_row_state_sha256 inside RFC 8785 canonical record_body (bound by record_sha256 / OTS receipt) for all non-stub evaluators, and enforces load_row_state_snapshot(..., expected_state_sha256=...) verification with deterministic rebuild from OTS-verified replay_bundle.json on mid-commit crash recovery.
    • Requires external authentication (_authenticate_production_history) before reusing any persisted production ledger: expected_prior_head_sha256 (SHADOW_TRUSTED_HEAD_SHA256, verified via hmac.compare_digest) is mandatory on all advancing runs ("0" * 64 for one-time empty-bucket genesis) and same-session retries (bitcoin_merkle_roots corroborates only via assess_receipt_creditability(...), fail-closed exit 3, 0 writes), enforces external monotonic trusted_head_anchor_path (SHADOW_TRUSTED_HEAD_ANCHOR_PATH / --trusted-head-anchor-path, required outside SHADOW_DATA_DIR, updated under flock CAS with monotonic sequence/anchor_version, pre-persisted sequence=-1 genesis anchor in _stage_bundle_before_marker() before seq_000000.record.json commit, pending_rejected_session_date + pending_rejected_revision/pending_revision same-day anti-rollback ordering, plus authenticated forward interrupted-commit and interrupted-pending catch-up) to defeat synchronized ledger+head rollback attacks, hashes in-memory pending_payload directly (zero post-write TOCTOU re-read), and enforces mandatory SHADOW_TRUSTED_PENDING_STATE_SHA256 / expected_pending_state_sha256 (NO_PENDING_REJECTED_STATE_SHA256 = GENESIS_PREV_HASH when absent) continuity verification across all production cycles and post-evaluation OTS/deadline rejections.
    • Reconciles interrupted pre-marker snapshot staging (_reconcile_uncommitted_staged_snapshots), preserves unlatched cross-session O5 resets & exact_reconciliation_auto_clear on unlatched V2.pending_adjustments while locking latched V2/O5 states, allows verified terminal-status O4 order resolution (o4_resolved_symbols) and Q4-validated authorized_events latch clearing (normalize_pending_authorized_events, _has_authorized_pending_clear with scope isolation, session windowing, and L3 30-day cooling-off enforcement; forwarded through run_daily_drill_cycle, run_production_cycle, _persist_pending_rejected_state, fuse_context, and replay_window) in pending rejected snapshots, narrows native FUSE input detection cleanly without swallowing optional SHADOW high_water_mark/source_records, and passes prior-session lookback_days in live Tiingo fetches for seq=0 FUSE bootstrapping.
    • Allows same-session retries after O1/O2 rejections (including O1 clearing_period transitions under NO-NEW-RISK and legitimate 10th-session V4 clearing) without double-advancing counters, pins pending_rejected_state.json["base_prior_row_state"] strictly to the committed seq - 1 baseline across 2+ consecutive rejected sessions, enforces monotonic latch/counter bounds, and cleanly retires superseded pending_rejected_state.json on committed-session recovery (_retire_superseded_pending_rejected_state).
  • Production Lock, US 23/5 Isolation & Cloud Run Jobs us-east1 (config/production-scheduler.json, src/shadow/calendar_consumer.py, src/shadow/feeder.py, src/shadow/feeder_live.py, src/shadow/ots.py, src/shadow/http_limits.py, src/shadow/manifest.py, src/shadow/cloudrun_job.py, Dockerfile, deploy/cloudrun/job-spec.example.yaml, docs/sh2-cloudrun-runbook.md):
    • Default config/production-scheduler.json ships locked (production_chain_locked: true, clk01_active: false), switches treasury_endpoint to daily_treasury_yield_curve par yield dataset, validates strict booleans, checks loaded spec["spec_digest"] == cfg.calendar_spec_digest, forbids offline fixtures_dir in production mode, and rejects missing or non-production config_path overrides inside check_forward_clock_credit().
    • Enforces US 23/5 16:00 ET (13:00 ET half-day) Official Close isolation, rejects Tiingo bar timestamp midnight markers & Yahoo non-daily dataGranularity, separates core_session_open vs extended_overnight_open in O2, bounds text length, significant digits, exponents, and market-close value ranges ((0, 1e9]) in _parse_finite_decimal / canonical_decimal_str (fast-pathing 0 without fixed-point expansion and converting rejected numeric values into missing market records inside emit_market_records_from_payloads), and enforces bounded streaming + Content-Length + error-body byte caps and monotonic end-to-end connect/TLS/header/body deadlines + Cloud Run task_timeout_seconds reporting reserve across all upstream market (feeder_live.py: Tiingo/Yahoo 2 MiB, NYFed SOFR 1 MiB, Treasury/default 4 MiB, 15s default HTTP deadline) and OTS (ots.py: 256 KiB) HTTP fetches via src/shadow/http_limits.py (registered in RUNTIME_MODULE_FILES).
    • Ships secret-free Cloud Run Jobs (us-east1) entrypoint using driver: gcsfuse.run.googleapis.com and append-only lease epoch slots (.chain.lease.json at epoch 0 and immutable .chain.lease.epoch.<N>.json on reclamation via _latest_lease_slot() and atomic os.link _publish_exclusive_file() — zero os.unlink() calls on lease slot files) + 0-byte initializing guard + CAS stale-reclamation cross-instance mutex (ChainConcurrencyConflictError, pre-scan active higher-generation guard + generational exclusive .chain.lease.reclaim.<key>[.g<N>].lock claims up to _MAX_RECLAIM_GENERATIONS = 64 + reclaim_expires fence before epoch publish + 5s empty-claim initializing/abandonment recovery in _is_reclaim_claim_expired + background daemon immutable sidecar .chain.lease.renew.<lease_id>.<uuid>.json renewal (lease_ttl_seconds=300.0, _effective_lease_expiry(), post-publish slot/identity/expiry/active-reclaim verification) + immutable release tombstone .chain.lease.released.<lease_id>.json (_is_lease_released()) + assert_active_chain_lease() writer fencing across append_record/_stage_bundle_before_marker/anchor/pending-state persistence + re-entrant chain_lock(), dev/ino/digest verification, maxRetries: 0 template, --expected-pending-state-sha256 / SHADOW_TRUSTED_PENDING_STATE_SHA256, --trusted-head-anchor-path / SHADOW_TRUSTED_HEAD_ANCHOR_PATH) while preserving SH-1 drills/tests.
    • Preserves optional cash_per_share_usd alongside split corporate actions in src/shadow/fuse_adapter.py (_map_market_corporate_action() and _compute_ca_adjusted_fund_return()), gates feeder-derived corporate actions, derived fund returns, and benchmark returns on market-record validity (not bad_market_payload and instrument not in bad_market_insts), excludes unadjusted QQQ split prices from benchmark L6 index-crash derivation (_INDEX_RETURN_LABELS), preserves explicit invalid/null high_water_mark as missing for fail-closed O1 evaluation, and requires strictly positive sigma_forecast before marking volatility valid (vol_ok).
  • Design Demo (D1–D10), Acceptance & Regression Tests (demo/run_sh2_demo.py, src/shadow/sh2_acceptance.py, docs/sh2-acceptance-pack.md, tests/test_*.py):
    • Adds SH2-D1..D10, SH2-A01..A14, and full regression coverage (185 total tests).

How verified

Independently verified on exact HEAD 0cddff241cc85aebfbb7a7de96e28d2bd6f08153 (185/185 OK in 353.610s, production_chain_locked=true, clk01_active=false, engine_hash=12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45, csa22_v2_spec_digest=2ba8cd7684c361209df68bfa2e10004c1f9922a645c7ec55d421fda520561798, production_code_version_sha=b6f677a8113058120499fcacb03d63728635aa6cae57ea66e8ff215fe2c822bd, production_policy_config_hash=23d8f3d42fd15a285b4dbef67c4a2b7a2372ca9c58a9e2f2af1ed2f3a2a43e8c):

  • PYTHONPATH=src python3 -m unittest discover -s tests: PASS (185/185 OK in 353.610s)
  • PYTHONPATH=src python3 -m shadow.sh2_acceptance: PASS (overall_status="PASS_OFFLINE", demo_cases_passed="10/10", oa_sh2_2_locked=true, hygiene_violations=[])
  • gitleaks (85 commits, 0 leaks), git diff --check; vendored files 0444 with zero __pycache__/.
  • Remediated all Codex Code & Security Review and OpenCode (qsl-ai-reviewer[bot]) findings across 6691b079..cedaf69e, d43db216 (PRRT_kwDOV2RNAc67nx2K/Q/U/Z), 57a442db (PRRT_kwDOV2RNAc67n1S7), f1423a13 (PRRT_kwDOV2RNAc67oei4/i_/jF/jO), 7c153394 (PRRT_kwDOV2RNAc67o8zW/d/j), 88ff3282 (PRRT_kwDOV2RNAc67pU3Y/e/m/q), be0a9317 (PRRT_kwDOV2RNAc67pqv1, PRRT_kwDOV2RNAc67pqv7), 8136ff76 (PRRT_kwDOV2RNAc67qGz1), c4bb9d95 (PRRT_kwDOV2RNAc67qYmN/S/U, PRRT_kwDOV2RNAc67qas6), 2e8d559c (PRRT_kwDOV2RNAc67rQES, PRRT_kwDOV2RNAc67rRKq, PRRT_kwDOV2RNAc67rRKY, PRRT_kwDOV2RNAc67rRKc, PRRT_kwDOV2RNAc67rRKh, PRRT_kwDOV2RNAc67rRKk), 3bc694f6 (PRRT_kwDOV2RNAc67sDWf, PRRT_kwDOV2RNAc67sDWs), e1dd173b (PRRT_kwDOV2RNAc67sgT5), 36ecc1a9 (PRRT_kwDOV2RNAc67tITU), ddb89b0b (PRRT_kwDOV2RNAc67tin_, PRRT_kwDOV2RNAc67tioE, PRRT_kwDOV2RNAc67uDPn), ca05cbef (PRRT_kwDOV2RNAc67t_7Y, PRRT_kwDOV2RNAc67t_7d), 8c8ae695, a45f7644 (PRRT_kwDOV2RNAc67uZos, PRRT_kwDOV2RNAc67uZxP), 7ef5f910 (PRRT_kwDOV2RNAc67u2Rh, PRRT_kwDOV2RNAc67u6aV), 5aed8309 (PRRT_kwDOV2RNAc67vD5g), c407d1f7 (PRRT_kwDOV2RNAc67zG1k), a41a3b61 (PRRT_kwDOV2RNAc67zkEJ, PRRT_kwDOV2RNAc67zkEX), 5fcd4d3d (PRRT_kwDOV2RNAc670YfQ, PRRT_kwDOV2RNAc670YfW, PRRT_kwDOV2RNAc670Yfa), 79a77c39 (PRRT_kwDOV2RNAc671Lqz), c48e4290 (PRRT_kwDOV2RNAc671w9t, PRRT_kwDOV2RNAc671w94), 583ac1d3 (PRRT_kwDOV2RNAc672bN8, PRRT_kwDOV2RNAc672bOF), a8c13900 (PRRT_kwDOV2RNAc673Exc, PRRT_kwDOV2RNAc673ExU), ad970e5d (PRRT_kwDOV2RNAc673qT5), 472a6c42 (PRRT_kwDOV2RNAc674gAl, PRRT_kwDOV2RNAc674gAg, plus half-day prior-close extraction & run_production_cycle direct-config guard), b8de8ae3 (PRRT_kwDOV2RNAc674l91: monotonic total connect/TLS/header/body/error-body HTTP deadlines & Cloud Run reporting reserve), 8f3fba55 (PRRT_kwDOV2RNAc675CO1 lease/byte-fenced transaction rollback & PRRT_kwDOV2RNAc675CPD multi-tier O1/O2 fail-closed guard before sizing), 291573de (PRRT_kwDOV2RNAc675yIQ: crash-safe partial fallback lease/reclaim cleanup and grace-window CAS recovery), 9f7cec1a (PRRT_kwDOV2RNAc676Dwj signal s [0,1] O1 validation & PRRT_kwDOV2RNAc676Dwo _DeadlineSocketProxy per-socket-read deadline enforcement), 5ffcea0b (PRRT_kwDOV2RNAc676aSQ: exclusive seq_NNNNNN.record.json and detached .ots/.receipt publication via _publish_exclusive_file), and 0cddff24 (PRRT_kwDOV2RNAc676zyT: exclusively published append-only <anchor>.v<N>.json trusted-head anchor history slots protecting external rollback defense across separate hosts).
  • Note: docker build did not run locally (no Docker daemon in local environment; Dockerfile and Cloud Run job spec verified statically + direct module execution).

Why

Delivers the complete SHADOW-N SH-2 offline software layer on ShadowResearch main binding FuseControl FUSE-1, csa22-v2, US 23/5 close isolation, ledger-bound state & authenticated production history integrity, and secret-free Cloud Run Jobs containerization ahead of owner-gated cloud deployment (OA-3) and CLK-01 unlock (OA-SH2-2).

Risk

Tier: R2 / High-rigor shadow risk-engine integration & fail-closed forward-clock scaffolding (production_chain_locked=true, orders_placed=0, live=OFF, kelly=OFF, H="0").

  • Default config/production-scheduler.json keeps production_chain_locked: true and clk01_active: false, guaranteeing zero production ledger writes or clock activation until explicit owner OA-SH2-2 sign-off in a separate gated change.
  • Rollback: Revert the PR merge commit on main; existing SH-1 drill chains and csa22-v1/csa22-v2 specs remain unchanged and backward-compatible.

Pin read-only FuseControl main engine (46a86eed) by content digest
12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45 with
spec/bundle/freeze metadata, provenance, and SH-1 entry-gate record.
- Add VendoredFuseEvaluator with runtime hash, spec_version,
  __pycache__ verification, and V2 boolean hwm_adjusted gate
- Enforce structural StubEvaluator quarantine and OA-SH2-2 default lock
- Add atomic state_snapshots/ restart continuity across runs
- Isolate US 23/5 16:00 ET close and post-21:00 ET boundary (Item 13)
- Add secret-free GCP Cloud Run Jobs us-east1 entrypoint (Item 18)
- Add D1-D10 demo, SH2-A01..A14 acceptance suite, and full unit tests
- Remove unlock_production_override and forbid fixtures_dir in prod.
- Require strict booleans and yahoo_symbol_map XSOX in prod config.
- Lock check_forward_clock_credit defaults for SH-2 production chains.
- Drop fabricated sources/returns in build_fuse_validated_inputs; wire
  live corporate_action events into FUSE-1 V2 and enforce NO-NEW-RISK
  and per-fund sizing isolation.
- Persist pending O1/O2 rejected-day row state and fuse_context for
  bit-for-bit replay across rejected and normal sessions.
- Reject Tiingo row.timestamp midnight markers, non-daily Yahoo charts,
  and mismatched calendar spec_digest overrides.
- Stage state snapshots inside atomic ledger commit hooks with
  rollback and deterministic reconciliation, and add .chain.lease.json
  cross-instance fencing (CLI exit 4, Cloud Run maxRetries: 0).
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 24, 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-25T22:01:02.165170Z c862105 New commits
🔒 Security Review ✅ Completed 2026-11-25T22:09:23.072881Z c862105 New commits

Security findings

Advisory findings (14)

ℹ️ 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.

@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: 6691b07910

ℹ️ 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 thread src/shadow/scheduler.py Resolved
Comment thread src/shadow/ledger.py Resolved
Comment thread src/shadow/ledger.py Resolved
Comment thread deploy/cloudrun/job-spec.example.yaml Resolved

@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 Security Review · Automatically triggered

Here are some automated security review suggestions for this pull request.

Reviewed commit: 6691b07910

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread src/shadow/ledger.py Resolved
- Require exact immediately preceding trading session close via
  resolve_previous_trading_date and target_prior_date.
- Allow same-session O1 clearing_period retries without double
  advancing counters while preserving base_prior_row_state.
- Reject non-production or missing config_path in
  check_forward_clock_credit.
- Switch Cloud Run CSI driver to gcsfuse.run.googleapis.com.
- Bind evaluator.next_row_state_sha256 into canonical ledger records
  and enforce ledger-digest + monotonic latch checks on snapshots.
Pin pending_rejected_state.json base_prior_row_state strictly to the
committed seq-1 state across 2+ consecutive O1/O2-rejected days so
intervening rejected runs do not overwrite base_prior_row_state with
uncommitted intermediate state.

Pass expected_base_session_date into
load_pending_rejected_state_snapshot and bound monotonic counter steps
(L5, O1, V4, V5) by elapsed calendar days from the committed baseline
while keeping un-committed latch downgrades and arbitrary counter jumps
fail-closed.

Refresh pinned production code/policy hashes in
docs/sh2-acceptance-pack.md and add multi-day V4 clearing regression
coverage in tests/test_sh2_pipeline.py.
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@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: 0dc148a208

ℹ️ 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 thread src/shadow/ledger.py Resolved
Comment thread src/shadow/scheduler.py Resolved
Comment thread src/shadow/feeder.py Resolved

@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 Security Review · Automatically triggered

Here are some automated security review suggestions for this pull request.

Reviewed commit: 0dc148a208

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread src/shadow/scheduler.py Resolved
Address all four Codex review findings on ShadowResearch#7:

- ledger: allow valid 10th-session V4 clearing inside
  pending_rejected_state.json when elapsed days reach >=10 while
  blocking premature clearing and invalid counter >=10.
- scheduler: add _retire_superseded_pending_rejected_state and call it
  across every return path of committed snapshot reconciliation so
  interrupted post-commit unlinks clean up on retry.
- feeder: share _validate_tiingo_official_close_row between
  select_tiingo_row and extract_prior_close_from_tiingo_bytes to reject
  extended/overnight markers and off-close session_time values.
- scheduler/cloudrun_job/docs: require external history authentication
  (expected_prior_head_sha256 / SHADOW_TRUSTED_HEAD_SHA256 or
  bitcoin_merkle_roots / SHADOW_BITCOIN_MERKLE_ROOTS_PATH) before
  reusing non-empty production ledger history (CLI exit 3 on failure).
- docs/tests: refresh pinned production code/policy hashes and add
  positive and negative regression tests across all four fixes.
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: a5599c5af8

ℹ️ 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".

@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 Security Review · Automatically triggered

Here are some automated security review suggestions for this pull request.

Reviewed commit: a5599c5af8

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread src/shadow/scheduler.py Resolved
Fail closed with production_genesis_unauthenticated on empty

SHADOW_DATA_DIR unless expected_prior_head_sha256 matches

GENESIS_PREV_HASH (Codex Security PRRT_kwDOV2RNAc67knPD), blocking

wiped-bucket replay and updating acceptance hashes and tests.
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@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: 0800291e30

ℹ️ 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 thread src/shadow/fuse_adapter.py Resolved
Comment thread src/shadow/scheduler.py Resolved
Comment thread src/shadow/scheduler.py Resolved

@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 Security Review · Automatically triggered

Here are some automated security review suggestions for this pull request.

Reviewed commit: 0800291e30

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread src/shadow/scheduler.py Resolved
@qsl-ai-reviewer

Copy link
Copy Markdown

AI Code Review (opencode / google/gemini-4-hydrogen)

Batch 1: Reviewed Batch 1/6 (Dockerfile, production-scheduler.json, Cloud Run job entrypoint, US 23/5 calendar consumer extensions, SH-2 demo, deployment templates, and runbooks). No high or medium severity defects were identified in this batch; one low-severity edge case was noted in classify_us_equity_session_window. Batch 2: Review of Batch 2/6 (src/shadow/feeder.py and src/shadow/fuse_adapter.py) found two medium correctness bugs: an early-return condition in build_fuse_validated_inputs that shadows high_water_mark and source_records handling, and prior-close extraction validating historical session bar times against the current session's calendar close time (breaking across half-day/regular-day boundaries), plus minor timestamp validation edge cases in feeder.py. Batch 3: Reviewed Batch 3/6 (src/shadow/ledger.py, src/shadow/manifest.py, src/shadow/replay.py). Found medium-severity concurrency, state-continuity verification, and fail-closed config-guard gaps. Batch 4: Reviewed Batch 4/6 (scheduler.py, sh2_acceptance.py, sizing.py). Found two medium-severity fail-closed/correctness bugs: run_sh2_acceptance() ignores demo pass/fail results and hardcodes PASS_OFFLINE for SH2-A03..A12, and sizing.py silently downgrades unrecognized control states to rank 0 (NORMAL) while letting J1_TRIM suppress a fund-level NO-NEW-RISK clamp due to equal rank. Batch 5: Reviewed tests/test_cloudrun_job.py, tests/test_fuse_adapter.py, and tests/test_sh2_acceptance.py. All three test suites thoroughly cover fail-closed security guards, lease concurrency conflicts, production history authentication, tamper detection, V2 schema enforcement, stub quarantine, per-fund sizing isolation, and offline acceptance gates with no bugs, secret leaks, or silent error swallowing. Batch 6: Reviewed Batch 6/6 (tests/test_sh2_pipeline.py, truncated at line ~780 of +1716). The visible test suite thoroughly exercises SH-2 invariants including production chain lock enforcement, fail-closed snapshot/ledger digest binding, US 23/5 official close isolation, rejected-session V4 clearing state persistence without double-advance, atomic rollback/recovery, and production history authentication using synthetic fixtures and mocked transports/clocks. No correctness, security, or boundary issues were observed in the provided diff.

Reviewed commit: 0800291e30 · Coverage: partial · Unresolved findings: true

Findings

  • [LOW] src/shadow/calendar_consumer.py: In classify_us_equity_session_window, the local_t >= time(20, 0) or local_t < time(4, 0) check runs before checking is_trading_day, blocks_eligibility, and local_date_str != trade_date, causing non-trading weekend/holiday or out-of-date timestamps between 20:00 and 04:00 local time to be classified as extended_overnight_open instead of closed or next_trade_date_window.
  • [MEDIUM] src/shadow/fuse_adapter.py: In build_fuse_validated_inputs, the early-return check if any(k in session_inputs for k in ("bankroll", "high_water_mark", "source_records", "session_calendar_status")): return direct triggers whenever "high_water_mark" or "source_records" is present in session_inputs. This makes session_inputs.get("high_water_mark", ...) and the entire caller_sources = session_inputs.get("source_records") block (lines 700-729) unreachable dead code, and causes any ShadowResearch payload containing E/funds/market_records together with high_water_mark or source_records to skip translation and pass untranslated keys straight to FUSE-1.
  • [MEDIUM] src/shadow/feeder.py: extract_prior_close_from_tiingo_bytes and extract_prior_close_from_yahoo_bytes pass the current session_date's calendar_session into _validate_tiingo_official_close_row(row, row_d, calendar_session) and _official_close_time_for_calendar(calendar_session) when validating historical bars (row_d / bar_date < session_date). When session_date is a half-day (13:00 close) following a regular 16:00 session, valid 16:00 prior-close bars will be rejected as extended_hours_overnight_rejected, causing prior-close extraction to return None (and conversely a half-day prior session would be checked against 16:00 on a regular day).
  • [LOW] src/shadow/feeder.py: In _validate_tiingo_official_close_row, session_time values containing a negative UTC offset (e.g. "16:00:00-04:00") bypass the full-timestamp branch ("T", " ", "+", "Z") and are parsed by dt_time.fromisoformat, producing an offset-aware time that raises an unhandled TypeError when compared against naive dt_time(21, 0). Additionally, _validate_core_rth_bar_timestamp silently returns None if row["timestamp"] is an empty string or non-string instead of raising tiingo_invalid_timestamp.
  • [MEDIUM] src/shadow/ledger.py: In _acquire_cross_instance_lease, os.open(..., O_CREAT | O_EXCL) publishes a 0-byte .chain.lease.json before os.write() completes, and the FileExistsError handler silently swallows read/parse exceptions (except Exception: existing = {}) and treats missing/unparseable expires_at_utc as immediately stale. A concurrent writer in another instance (where flock is not shared) reading the empty or mid-write file will replace the active lease and run concurrently. Write and fsync a unique temp file first and publish it atomically via os.link(), and fail closed on unreadable/corrupt lease files.
  • [MEDIUM] src/shadow/replay.py: In replay_window, fuse_context['prior_row_state_used'] unconditionally overrides the chained prior_state without checking isinstance(..., dict) or verifying monotonic breaker/latch preservation against prior_state (such as _assert_pending_state_preserves_committed_breakers). A tampered bundle or writer bug that resets latched breakers in prior_row_state_used between committed records will pass replay_window with bit_for_bit_match=True.
  • [MEDIUM] src/shadow/ledger.py: In check_forward_clock_credit, when config_path is None and is_sh2_prod_chain is True, the fallback read of config/production-scheduler.json only checks production_chain_locked is False and clk01_active is True, omitting the mode == 'production' and production_mode_forbidden guards enforced when config_path is provided. Also is_sh2_prod_chain should check body.get('mode') == 'production' directly.
  • [LOW] src/shadow/manifest.py: compute_code_manifest_hash labels any custom config_path as f'config/{cfg_file.name}' regardless of parent directory, which conflates configs in different directories that share a filename.
  • [MEDIUM] src/shadow/sh2_acceptance.py: run_sh2_acceptance() runs run_sh2_demo.run_all_demos() and records demo_cases_passed and demo_summary, but never checks demo_out['passed'] == demo_out['total'] or individual case statuses when computing overall_status. Checks SH2-A03 through SH2-A12 unconditionally hardcode status='PASS_OFFLINE', SH2-A02 does not gate on gates['pycache_verified'], and SH2-A13 hardcodes status='PASS_OFFLINE' even when detail is 'FAILED'. Failing demo or gate checks can therefore still exit 0 with overall_status='PASS_OFFLINE'.
  • [MEDIUM] src/shadow/sizing.py: _most_restrictive_sizing_state() uses _CONTROL_STATE_RANK.get(..., 0), which silently treats any unrecognized active_control_state or fund_control_states[inst] value as rank 0 (NORMAL) instead of failing closed. Additionally, 'NO-NEW-RISK' and 'J1_TRIM' share rank 1, so when active_control_state=='J1_TRIM' and a fund has 'NO-NEW-RISK', _most_restrictive_sizing_state returns 'J1_TRIM' and bypasses the eff_state=='NO-NEW-RISK' clamp when q_ideal > q_pre_i.
  • [LOW] src/shadow/scheduler.py: In _reconcile_committed_state_snapshot_if_missing(), the initial load_row_state_snapshot() validation is wrapped in a broad 'except Exception: pass' before falling back to replay_bundle rebuild, masking snapshot corruption/identity errors if replay_bundle is valid; and in _run_daily_drill_cycle_locked(), a non-None cfg.fuse_engine_hash that differs from PINNED_FUSE_ENGINE_HASH silently falls back to StubEvaluator() in drill mode instead of raising an EngineIdentityError.

Require explicit current record_sha256 or external BTC roots on

same-session retries, fetch prior trading close via live Tiingo

lookback for FUSE genesis, reconcile uncommitted staged state

snapshots, and narrow native FUSE input detection.
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 2639145d8b

ℹ️ 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".

@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 Security Review · Automatically triggered

Here are some automated security review suggestions for this pull request.

Reviewed commit: 2639145d8b

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread src/shadow/scheduler.py Resolved
Comment thread src/shadow/ledger.py Resolved
Require SHADOW_TRUSTED_HEAD_SHA256 on all recurring and retry

production runs (even when BTC roots are provided, closing

PRRT_kwDOV2RNAc67m4A-), and pin pending_rejected_state.json with

SHADOW_TRUSTED_PENDING_STATE_SHA256 (closing PRRT_kwDOV2RNAc67m4BM).
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@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: cedaf69e3b

ℹ️ 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 thread src/shadow/scheduler.py Resolved
Comment thread src/shadow/fuse_adapter.py Resolved
Comment thread src/shadow/fuse_adapter.py Resolved
Comment thread src/shadow/fuse_adapter.py Resolved

@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 Security Review · Automatically triggered

Here are some automated security review suggestions for this pull request.

Reviewed commit: cedaf69e3b

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread src/shadow/ledger.py Resolved
@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 926550db68

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@Pigbibi

Pigbibi commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 926550db68

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 926550db68

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@qsl-ai-reviewer

Copy link
Copy Markdown

AI Code Review (opencode / google/gemini-4-hydrogen)

Batch 1: Batch 1/6 adds the secret-free Cloud Run Jobs container/entrypoint (Dockerfile, config/production-scheduler.json, deploy/cloudrun/job-spec.example.yaml, src/shadow/cloudrun_job.py), US 23/5 close-isolation helpers in src/shadow/calendar_consumer.py, SH-2 acceptance/runbook docs, and the SH2-D1..D10 design demo. No high or medium severity issues found in these files; standing safety locks and production-chain guards remain intact. Batch 2: Reviewed Review Batch 2/6 (src/shadow/feeder.py and src/shadow/feeder_live.py). The US 23/5 core RTH Official Close isolation, bounded numeric parsing, Yahoo granularity check, prior-close extraction helpers, and bounded-size/deadline-enforced HTTP fetch logic are solid and fail-closed, with only two low-severity edge cases noted. Batch 3: Reviewed src/shadow/fuse_adapter.py and src/shadow/http_limits.py. Found two medium-severity correctness issues: mid-read deadline expirations in read_bounded_http_body let raw TimeoutError escape instead of raising error_cls, and _map_market_corporate_action silently drops corporate actions when optional fields are present as None. Batch 4: Reviewed manifest, OTS transport/deadline bounds, and ledger replay changes in batch 4/6. Found a medium-severity replay integrity issue where replay_window trusts fuse_context.prior_row_state_used on every session without verifying continuity against the replayed prior_state. Batch 5: Reviewed Review Batch 5/6 (truncated diff of src/shadow/scheduler.py). Production lock checks (OA-SH2-2), pinned FUSE-1/csa22-v2 validation, atomic session staging/rollback, external trusted head anchor monotonic versioning, and state snapshot reconciliation are fail-closed and consistent. Only minor low-severity observations remain. Batch 6: Reviewed batch 6/6 (src/shadow/sh2_acceptance.py and src/shadow/sizing.py). Found two medium-severity correctness bugs: sh2_acceptance hardcodes PASS_OFFLINE for SH2-A01..A12 and ignores demo pass counts/digest checks in overall_ok, and sizing.py uses active_control_state instead of per-tier/per-fund state for J1_TRIM and handles fund-level DE-RISK cap reservation inconsistently across branches.

Reviewed commit: 926550db68 · Coverage: partial · Unresolved findings: true

Findings

  • [LOW] src/shadow/calendar_consumer.py: In classify_us_equity_session_window and is_official_close_bar_timestamp, datetime.fromisoformat(iso_norm).astimezone(tz) interprets a naive timestamp string (missing 'Z' or explicit UTC offset) using the host OS local timezone rather than rejecting it or treating it as UTC. Rejecting dt.tzinfo is None in is_official_close_bar_timestamp would ensure consistent behavior across non-UTC environments.
  • [LOW] src/shadow/cloudrun_job.py: Explicit empty-string arguments for expected_prior_head_sha256, expected_pending_state_sha256, or trusted_head_anchor_path bypass the '.strip() or None' normalization applied to environment variables (e.g., passing trusted_head_anchor_path='' could be treated as non-None and resolve Path('') to '.'). Normalizing empty/whitespace strings consistently for both kwargs and env vars avoids this edge case.
  • [LOW] src/shadow/feeder.py: In _validate_core_rth_bar_timestamp and _validate_tiingo_official_close_row (publicationTimestamp), calling datetime.fromisoformat(...).astimezone(_NY_TZ) on a naive timestamp without a timezone offset or Z suffix implicitly interprets it in the host OS local timezone; consider rejecting timezone-naive timestamps with tiingo_invalid_timestamp for host-independent determinism.
  • [LOW] src/shadow/feeder.py: In extract_prior_close_from_tiingo_bytes and extract_prior_close_from_yahoo_bytes, calendar_session is only passed through when calendar_session.get('trade_date') == row_d/bar_date, which is always false for prior dates; as a result, prior-close bar timestamp checks fall back to 16:00 ET even if the prior trading session was a 13:00 ET half-day.
  • [MEDIUM] src/shadow/http_limits.py: In read_bounded_http_body, deadline checks before and after read_fn() raise error_cls(f"{error_prefix}:deadline_exceeded"), but if the deadline expires during read_fn() (via _DeadlineSocketProxy raising TimeoutError or a socket timeout), TimeoutError is not caught and escapes instead of error_cls. Callers handling error_cls can miss mid-stream deadline failures.
  • [MEDIUM] src/shadow/fuse_adapter.py: In _map_market_corporate_action, mca.get("split_ratio", "1") and mca.get("cash_per_share_usd", "0") return None when the key exists with value None (e.g., null in JSON). Decimal(str(None)) raises InvalidOperation, which is swallowed by except Exception: return None, silently dropping valid splits or cash distributions from V2 reconciliation and CA-adjusted return calculations.
  • [MEDIUM] src/shadow/replay.py: In replay_window, when fuse_context.prior_row_state_used is present, eff_prior_state unconditionally overrides the running prior_state for every session without asserting continuity against the prior_state derived from the preceding replayed record. A bundle with tampered or mismatched prior_row_state_used values between consecutive sessions would still pass bit_for_bit_match without detecting broken state transitions; prior_row_state_used should only seed the initial session (if needed) or be verified against the deterministically carried-forward prior_state.
  • [LOW] src/shadow/scheduler.py: load_production_scheduler_config parses JSON with json.loads instead of parse_json_no_duplicates, which is used elsewhere in the module to reject duplicate JSON keys.
  • [LOW] src/shadow/scheduler.py: check_no_unconsumed_pending_rejected_reports silently skips completeness*.json files on any Exception when reading or parsing; while the external trusted head anchor still enforces pending state integrity, logging or failing on malformed completeness reports in production mode would avoid masking local report corruption.
  • [MEDIUM] src/shadow/sh2_acceptance.py: run_sh2_acceptance() hardcodes "status": "PASS_OFFLINE" on checks SH2-A01 through SH2-A12 and never verifies demo_out["passed"] == demo_out["total"], individual demo case statuses, or spec_v2["spec_digest"] == PINNED_CSA22_V2_DIGEST in overall_ok. If run_sh2_demo.run_all_demos() records failed cases without raising, run_sh2_acceptance() and main() still report "overall_status": "PASS_OFFLINE" and exit 0.
  • [MEDIUM] src/shadow/sizing.py: Line 733 evaluates breaker_forced_reduce using active_control_state == "J1_TRIM" rather than t_acct_state / eff_state, so a J1_TRIM state supplied via tier_control_states or fund_control_states fails to enable mandatory_bypass. Additionally, when frozen_insts is empty (lines 590-620), a fund in DE-RISK is still included in Step 7/8 cap allocation (consuming joint-cap and w_ceil headroom) before being zeroed at line 714, whereas the else branch (line 631) excludes DE-RISK from active_insts.
  • [LOW] src/shadow/sh2_acceptance.py: Several imported symbols (resolve_session, StubEvaluator, StubProductionForbiddenError, V2PayloadSchemaError, VendoredFuseEvaluator, GENESIS_PREV_HASH, build_record_body, run_production_cycle) are unused, and sys.path is mutated without restoration when importing run_sh2_demo.

@Pigbibi

Pigbibi commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@Pigbibi

Pigbibi commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 6d29a7fc96

ℹ️ 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".

@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 Security Review · Automatically triggered

Here are some automated security review suggestions for this pull request.

Reviewed commit: 6d29a7fc96

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread src/shadow/http_limits.py Resolved
@Pigbibi

Pigbibi commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 1f860435a5

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 1f860435a5

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@Pigbibi

Pigbibi commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 1f860435a5

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 1f860435a5

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@qsl-ai-reviewer

Copy link
Copy Markdown

AI Code Review (opencode / google/gemini-4-hydrogen)

Batch 1: Batch 1/6 looks well-structured and adheres to the safety locks, secret-free Cloud Run deployment requirements, and FUSE-1 entry-gate isolation; two low-severity issues were noted in session-window classification ordering and Cloud Run config/exit handling. Batch 2: Reviewed the feeder and live feeder diffs (src/shadow/feeder.py, src/shadow/feeder_live.py): bounded numeric parsing, US 23/5 official-close isolation, prior-close extraction, and HTTP response/deadline budgets are sound, with two minor timestamp-validation edge cases. Batch 3: Reviewed src/shadow/fuse_adapter.py (Review Batch 3/6). The vendored FUSE-1 integrity/bytecode verification, F1 entry-gate checks, V2 reconciliation schema validation, and fail-closed input translation are solid and preserve safety invariants, with only minor defensive edge cases noted. Batch 4: Reviewed Batch 4/6 (src/shadow/http_limits.py, src/shadow/manifest.py, src/shadow/ots.py, src/shadow/replay.py). Found one medium-severity input-verification bypass in replay_window where sess['inputs']['market_records'] can shadow verified sess['market_records'], plus two low-severity issues in ots.py and manifest.py. Batch 5: Reviewed the partial diff of src/shadow/scheduler.py (production config loading, atomic session/snapshot commits, trusted head anchor monotonic versioning, interrupted commit/pending catch-up, and fail-closed production history authentication). No high or medium severity bugs, security leaks, or fail-closed safety regressions were found in the reviewed hunks. Batch 6: Reviewed the visible diff for src/shadow/sh2_acceptance.py and src/shadow/sizing.py. Found two medium-severity risk-gate bugs in src/shadow/sizing.py where NO-NEW-RISK can be bypassed when combined with J1_TRIM and unknown control states silently fail open to NORMAL, plus one low-severity unchecked dictionary access in src/shadow/sh2_acceptance.py.

Reviewed commit: 1f860435a5 · Coverage: partial · Unresolved findings: true

Findings

  • [LOW] src/shadow/calendar_consumer.py: In classify_us_equity_session_window(), the overnight window check (local_t >= 20:00 or local_t < 04:00) runs before checking is_trading_day, blocks_eligibility, and local_date_str vs trade_date, so timestamps on weekends, holidays, or mismatched dates in that time range are classified as 'extended_overnight_open' instead of 'closed' or 'next_trade_date_window'.
  • [LOW] src/shadow/cloudrun_job.py: run_cloudrun_job() reads eff_config_path with json.loads() instead of the imported parse_json_no_duplicates(), and main() returns exit code 0 even when out['fail_closed'] is True (e.g., O1/O2 or OTS fail-closed outcomes that do not raise an exception), which can cause Cloud Run Jobs to report a failed cycle as a succeeded execution.
  • [LOW] src/shadow/feeder.py: In _validate_core_rth_bar_timestamp, checking "+" in txt for midnight-UTC markers accepts non-UTC positive offsets (e.g. YYYY-MM-DDT00:00:00+09:00) as midnight-UTC markers and skips RTH time/date validation; restrict this to txt.endswith(("Z", "+00:00", "-00:00")) and validate row_d format.
  • [LOW] src/shadow/feeder.py: In _validate_tiingo_official_close_row, publicationTimestamp calls .astimezone(_NY_TZ) without verifying tzinfo is not None (unlike _validate_core_rth_bar_timestamp), so a naive timestamp silently uses the host local timezone instead of raising tiingo_invalid_timestamp.
  • [LOW] src/shadow/fuse_adapter.py: _finite_number checks dec.is_finite() before calling float(dec), but does not verify math.isfinite(val) afterward, so an oversized finite Decimal (>= 1e309) would overflow to float('inf').
  • [LOW] src/shadow/fuse_adapter.py: _map_calendar_statuses only validates trade_date == session_date when 'trade_date' is present in calendar_session; an omitted trade_date silently bypasses session-date matching.
  • [LOW] src/shadow/fuse_adapter.py: In _apply_explicit_payload_tier, if session_inputs overrides 'tier' on an explicit fuse_inputs payload and _derive_default_max_loss_cap returns None (e.g., partial bankroll fields in session_inputs), any pre-existing payload['max_loss_cap'] from the original tier is retained rather than cleared.
  • [MEDIUM] src/shadow/replay.py: In replay_window, if "market_records" in sess and "market_records" not in replay_inputs: allows sess["inputs"]["market_records"] (and similarly required_series / fuse_context keys) to shadow the verified top-level sess["market_records"]. Because raw archive integrity, official-close validation, and computed_mkt_digest are verified against sess["market_records"], letting sess["inputs"]["market_records"] take precedence allows build_record_body to evaluate unverified market records while archived_inputs_ok and market_records_digest still pass.
  • [LOW] src/shadow/ots.py: In urllib_ots_transport, read_bounded_http_body is passed error_prefix="ots_response_too_large", so deadline or incomplete-body failures emit misleading errors like ots_response_too_large:deadline_exceeded. Also, http.client.HTTPException raised while streaming the response body is not caught by (urllib.error.URLError, TimeoutError, OSError) and will escape urllib_ots_transport unwrapped rather than raising OtsSubmitError.
  • [LOW] src/shadow/manifest.py: In compute_code_manifest_hash, cfg_rel = "config/drill-scheduler.json" if config_path is None else f"config/{cfg_file.name}" hardcodes a config/ prefix using only cfg_file.name, which mislabels non-config/ paths and aliases distinct config paths that share a filename.
  • [MEDIUM] src/shadow/sizing.py: _CONTROL_STATE_RANK assigns rank 1 to both 'NO-NEW-RISK' and 'J1_TRIM'. When the tier/account state is 'J1_TRIM' and a fund's state is 'NO-NEW-RISK', _most_restrictive_sizing_state('J1_TRIM', 'NO-NEW-RISK') evaluates 1 > 1 as False and returns 'J1_TRIM'. Unlike breaker_forced_reduce (which explicitly checks t_acct_state and t_fund_states for 'J1_TRIM'), the NO-NEW-RISK clamp only checks if eff_state == 'NO-NEW-RISK' and q_ideal > q_pre_i, allowing positions to increase despite the fund being in NO-NEW-RISK.
  • [MEDIUM] src/shadow/sizing.py: _most_restrictive_sizing_state uses _CONTROL_STATE_RANK.get(..., 0) without validating state names. An unrecognized or misspelled control state in fund_control_states/tier_control_states (or active_control_state) silently receives rank 0 and falls back to 'NORMAL' (or behaves as 'NORMAL' in downstream equality checks) instead of failing closed or raising SizingInputError.
  • [LOW] src/shadow/sh2_acceptance.py: run_sh2_acceptance guards demo_all_passed with isinstance(demo_out, dict) and .get(...), but later constructs 'demo_cases_passed': f"{demo_out['passed']}/{demo_out['total']}", which will raise KeyError/TypeError instead of returning a FAILED acceptance report if run_all_demos() returns a malformed structure.

Pigbibi added a commit that referenced this pull request Nov 26, 2026
Vendor the FuseControl FUSE-1 engine package (fuse-eval-spec/v1,
engine_hash 12e9b502...) with its provenance, freeze, spec, result
bundle and disposition register metadata. No runtime code consumes it
yet; the adapter lands in a follow-up part of the SH-2 split of #7.


Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Pigbibi added a commit that referenced this pull request Nov 26, 2026
…5) (#9)

* feat(fuse): add vendored FUSE-1 adapter and per-tier sizing isolation

Add VendoredFuseEvaluator, which re-verifies the vendored engine digests
before each evaluate() call, plus FUSE input translation, NO-NEW-RISK
clamping and per-tier sizing controls. Register fuse_adapter in the code
manifest, hash explicit scheduler config paths by their relative path,
and record the SH-2 entry gates. Part 2 of the SH-2 split of #7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): honor O5 settled-cash alias, V7 session time, pyc flags

Resolve o5_settled_cash before defaulting settled_cash to the bankroll,
keep a missing V7 session_time as missing instead of asserting a
regular session, and compile vendored source with dont_inherit=True so
legitimately compiled __pycache__ bytecode verifies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): keep O5 counter aliases, forward H, drop return-as-loss

Default the canonical O5 session counters only when no alias carries
evidence, forward H so O9 can match authorized H change descriptors,
and stop substituting one_session_loss (a return fraction) for the
cumulative dollar loss L when re-tiering explicit FUSE payloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* docs(fuse): document O3 model self-reconciliation in Stage N

Stage N has no broker evidence in any mode, so absent broker_*
observations are substituted with modelled values and O3 is a model
self-reconciliation, not reconciliation evidence. Comment only; no
change to validated inputs or record hashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): preserve explicitly null O5 session counters

Default session_order_count and session_turnover only when the key is
omitted; an explicitly null counter is unknown evidence and is passed
through as None so evaluate_O5() fails closed on turnover/order limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): compare pyc code structurally and keep null settled cash

Compare cached vendored bytecode by code-object equality instead of
marshal encoding, which differs between py_compile and compile() on
CPython 3.11/3.12, while still rejecting altered constants. Preserve an
explicitly null settled_cash or o5_settled_cash as unknown evidence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra P1s in adapter inputs and engine loading

Validate every market record (including optional SPX) for eligibility,
calendar digest and effective session, apply corporate actions to V1
returns only when the ex-date is the decision session, pass explicit
null policy hashes and heartbeats through uncoerced, leave absent
settled cash unknown, pin the complete metadata digest set in code, and
execute only verified engine source bytes via a dedicated finder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): label adapter self-heartbeat with heartbeat_source

Record heartbeat_source="adapter_self" when the adapter defaults the
O7 heartbeat to as_of, and "caller" when session inputs supply it, so a
self-attested heartbeat is never mistaken for liveness evidence. The
ledger-supplied heartbeat follows in part 4 (#13).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* docs(fuse): document EOD half-day O2 mapping and pin it with a test

SH-2 decisions are end-of-day, so every trading day, half days
included, maps to `open`; FuseControl's half_day_cutoff is a pre-trade
rule. Pin that the 2026-11-27 14:30 ET half-day decision maps to open
with O2 clear, and that late runs are the scheduler cutoff's job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra round-2 P1s and default substitutions

Apply the feeder's exact rate freshness rule, reject records retrieved
after the decision instant, reject the ineffective kill_switch_tripped
flag, fail closed on conflicting corporate actions and on caller closes
that disagree with the validated market close, and pass explicit nulls
(broker, cash, exposures, tolerance, proposal) through as missing.
Unknown tiers and missing high-water marks no longer fall back to
balanced or bankroll defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): compare caller and market closes by decimal value

The close-mismatch guard must compare values, not the strict sizing
parser (which rejects floats by design), so a float and a canonical
decimal string for the same close are treated as equal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra round-3 safety P1s in adapter and evaluator

Reject conflicting corporate actions before any successor state,
never let current_index_closes override a validated record, propagate
unknown held-position values into reconciliation and aggregates,
reject kill_switch_tripped on the effective payload at the evaluator
boundary, drop source records dated after the decision instant, and
compare timestamps as aware instants rather than strings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): guard source dates at evaluator, keep unknown shares None

Drop source records dated after the decision instant at the evaluator
boundary so nested fuse_inputs and direct payloads are covered, and
pass an unknown ledger quantity as share_count None (0 only for an
explicitly flat position) so O3/V2 cannot clear on an invented zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Pigbibi added a commit that referenced this pull request Nov 26, 2026
…2 3/5) (#14)

* feat(fuse): add vendored FUSE-1 adapter and per-tier sizing isolation

Add VendoredFuseEvaluator, which re-verifies the vendored engine digests
before each evaluate() call, plus FUSE input translation, NO-NEW-RISK
clamping and per-tier sizing controls. Register fuse_adapter in the code
manifest, hash explicit scheduler config paths by their relative path,
and record the SH-2 entry gates. Part 2 of the SH-2 split of #7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* feat(feeder): isolate US 23/5 official close and bound upstream HTTP

Consume the csa22-v2 calendar to classify core RTH vs extended and
overnight windows, reject non-official-close and T+1 bars, resolve the
immediately preceding trading date, and bound decimal inputs. Add
http_limits with streaming byte caps and monotonic total deadlines for
market and OTS fetches. Part 3 of the SH-2 split of #7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): honor O5 settled-cash alias, V7 session time, pyc flags

Resolve o5_settled_cash before defaulting settled_cash to the bankroll,
keep a missing V7 session_time as missing instead of asserting a
regular session, and compile vendored source with dont_inherit=True so
legitimately compiled __pycache__ bytecode verifies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): keep O5 counter aliases, forward H, drop return-as-loss

Default the canonical O5 session counters only when no alias carries
evidence, forward H so O9 can match authorized H change descriptors,
and stop substituting one_session_loss (a return fraction) for the
cumulative dollar loss L when re-tiering explicit FUSE payloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* docs(fuse): document O3 model self-reconciliation in Stage N

Stage N has no broker evidence in any mode, so absent broker_*
observations are substituted with modelled values and O3 is a model
self-reconciliation, not reconciliation evidence. Comment only; no
change to validated inputs or record hashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): preserve explicitly null O5 session counters

Default session_order_count and session_turnover only when the key is
omitted; an explicitly null counter is unknown evidence and is passed
through as None so evaluate_O5() fails closed on turnover/order limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): compare pyc code structurally and keep null settled cash

Compare cached vendored bytecode by code-object equality instead of
marshal encoding, which differs between py_compile and compile() on
CPython 3.11/3.12, while still rejecting altered constants. Preserve an
explicitly null settled_cash or o5_settled_cash as unknown evidence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra P1s in adapter inputs and engine loading

Validate every market record (including optional SPX) for eligibility,
calendar digest and effective session, apply corporate actions to V1
returns only when the ex-date is the decision session, pass explicit
null policy hashes and heartbeats through uncoerced, leave absent
settled cash unknown, pin the complete metadata digest set in code, and
execute only verified engine source bytes via a dedicated finder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): label adapter self-heartbeat with heartbeat_source

Record heartbeat_source="adapter_self" when the adapter defaults the
O7 heartbeat to as_of, and "caller" when session inputs supply it, so a
self-attested heartbeat is never mistaken for liveness evidence. The
ledger-supplied heartbeat follows in part 4 (#13).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* docs(fuse): document EOD half-day O2 mapping and pin it with a test

SH-2 decisions are end-of-day, so every trading day, half days
included, maps to `open`; FuseControl's half_day_cutoff is a pre-trade
rule. Pin that the 2026-11-27 14:30 ET half-day decision maps to open
with O2 clear, and that late runs are the scheduler cutoff's job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra round-2 P1s and default substitutions

Apply the feeder's exact rate freshness rule, reject records retrieved
after the decision instant, reject the ineffective kill_switch_tripped
flag, fail closed on conflicting corporate actions and on caller closes
that disagree with the validated market close, and pass explicit nulls
(broker, cash, exposures, tolerance, proposal) through as missing.
Unknown tiers and missing high-water marks no longer fall back to
balanced or bankroll defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): compare caller and market closes by decimal value

The close-mismatch guard must compare values, not the strict sizing
parser (which rejects floats by design), so a float and a canonical
decimal string for the same close are treated as equal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra round-3 safety P1s in adapter and evaluator

Reject conflicting corporate actions before any successor state,
never let current_index_closes override a validated record, propagate
unknown held-position values into reconciliation and aggregates,
reject kill_switch_tripped on the effective payload at the evaluator
boundary, drop source records dated after the decision instant, and
compare timestamps as aware instants rather than strings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): guard source dates at evaluator, keep unknown shares None

Drop source records dated after the decision instant at the evaluator
boundary so nested fuse_inputs and direct payloads are covered, and
pass an unknown ledger quantity as share_count None (0 only for an
explicitly flat position) so O3/V2 cannot clear on an invented zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(feeder): address SH-2 part 3 Astra review findings

* fix(feeder): reject post-cutoff or future-published market records

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Pigbibi added a commit that referenced this pull request Nov 26, 2026
… Run job (SH-2 4/5) (#15)

* feat(fuse): add vendored FUSE-1 adapter and per-tier sizing isolation

Add VendoredFuseEvaluator, which re-verifies the vendored engine digests
before each evaluate() call, plus FUSE input translation, NO-NEW-RISK
clamping and per-tier sizing controls. Register fuse_adapter in the code
manifest, hash explicit scheduler config paths by their relative path,
and record the SH-2 entry gates. Part 2 of the SH-2 split of #7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* feat(feeder): isolate US 23/5 official close and bound upstream HTTP

Consume the csa22-v2 calendar to classify core RTH vs extended and
overnight windows, reject non-official-close and T+1 bars, resolve the
immediately preceding trading date, and bound decimal inputs. Add
http_limits with streaming byte caps and monotonic total deadlines for
market and OTS fetches. Part 3 of the SH-2 split of #7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* feat(ledger): bind FUSE row state to ledger and authenticate history

Embed next_row_state_sha256 in record bodies, authenticate persisted
production history against an external trusted head and monotonic
anchor, and recover pending rejected state across multi-day rejections.
Wire FUSE into scheduler and replay, add the locked production config,
the Cloud Run job module, and the SH-2 demo used by the pipeline tests.
Part 4 of the SH-2 split of #7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): honor O5 settled-cash alias, V7 session time, pyc flags

Resolve o5_settled_cash before defaulting settled_cash to the bankroll,
keep a missing V7 session_time as missing instead of asserting a
regular session, and compile vendored source with dont_inherit=True so
legitimately compiled __pycache__ bytecode verifies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): keep O5 counter aliases, forward H, drop return-as-loss

Default the canonical O5 session counters only when no alias carries
evidence, forward H so O9 can match authorized H change descriptors,
and stop substituting one_session_loss (a return fraction) for the
cumulative dollar loss L when re-tiering explicit FUSE payloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* docs(fuse): document O3 model self-reconciliation in Stage N

Stage N has no broker evidence in any mode, so absent broker_*
observations are substituted with modelled values and O3 is a model
self-reconciliation, not reconciliation evidence. Comment only; no
change to validated inputs or record hashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): preserve explicitly null O5 session counters

Default session_order_count and session_turnover only when the key is
omitted; an explicitly null counter is unknown evidence and is passed
through as None so evaluate_O5() fails closed on turnover/order limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): compare pyc code structurally and keep null settled cash

Compare cached vendored bytecode by code-object equality instead of
marshal encoding, which differs between py_compile and compile() on
CPython 3.11/3.12, while still rejecting altered constants. Preserve an
explicitly null settled_cash or o5_settled_cash as unknown evidence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra P1s in adapter inputs and engine loading

Validate every market record (including optional SPX) for eligibility,
calendar digest and effective session, apply corporate actions to V1
returns only when the ex-date is the decision session, pass explicit
null policy hashes and heartbeats through uncoerced, leave absent
settled cash unknown, pin the complete metadata digest set in code, and
execute only verified engine source bytes via a dedicated finder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* test(ledger): give hand-built market records an effective session

Market records are now validated against the decision session, so the
ledger-integration and pipeline fixtures that build records by hand
carry the effective_session the feeder always sets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): label adapter self-heartbeat with heartbeat_source

Record heartbeat_source="adapter_self" when the adapter defaults the
O7 heartbeat to as_of, and "caller" when session inputs supply it, so a
self-attested heartbeat is never mistaken for liveness evidence. The
ledger-supplied heartbeat follows in part 4 (#13).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* docs(fuse): document EOD half-day O2 mapping and pin it with a test

SH-2 decisions are end-of-day, so every trading day, half days
included, maps to `open`; FuseControl's half_day_cutoff is a pre-trade
rule. Pin that the 2026-11-27 14:30 ET half-day decision maps to open
with O2 clear, and that late runs are the scheduler cutoff's job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra round-2 P1s and default substitutions

Apply the feeder's exact rate freshness rule, reject records retrieved
after the decision instant, reject the ineffective kill_switch_tripped
flag, fail closed on conflicting corporate actions and on caller closes
that disagree with the validated market close, and pass explicit nulls
(broker, cash, exposures, tolerance, proposal) through as missing.
Unknown tiers and missing high-water marks no longer fall back to
balanced or bankroll defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* test(ledger): align hand-built records with session validation

Ledger and pipeline fixtures that build market records by hand now
carry a T-1 SOFR effective date, a retrieval time before the decision
instant, and per-fund closes that match the fund payload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): compare caller and market closes by decimal value

The close-mismatch guard must compare values, not the strict sizing
parser (which rejects floats by design), so a float and a canonical
decimal string for the same close are treated as equal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra round-3 safety P1s in adapter and evaluator

Reject conflicting corporate actions before any successor state,
never let current_index_closes override a validated record, propagate
unknown held-position values into reconciliation and aggregates,
reject kill_switch_tripped on the effective payload at the evaluator
boundary, drop source records dated after the decision instant, and
compare timestamps as aware instants rather than strings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): guard source dates at evaluator, keep unknown shares None

Drop source records dated after the decision instant at the evaluator
boundary so nested fuse_inputs and direct payloads are covered, and
pass an unknown ledger quantity as share_count None (0 only for an
explicitly flat position) so O3/V2 cannot clear on an invented zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* test(fuse): restore part 4 test_fuse_adapter additions after main merge

* feat(ledger): wire O7 previous-record heartbeat and L0 two-pass

* fix(sh2): resolve Astra Round 1 P1s for retry, receipts, L0, Cloud Run, lock

* fix(sh2): harden default prod lock, nested O7, evidence staging, and CLK-01

* fix(sh2): recover drill evidence, propagate nested L0, guard _by_tier

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Pigbibi added a commit that referenced this pull request Nov 26, 2026
…-2 5/5) (#16)

* feat(fuse): add vendored FUSE-1 adapter and per-tier sizing isolation

Add VendoredFuseEvaluator, which re-verifies the vendored engine digests
before each evaluate() call, plus FUSE input translation, NO-NEW-RISK
clamping and per-tier sizing controls. Register fuse_adapter in the code
manifest, hash explicit scheduler config paths by their relative path,
and record the SH-2 entry gates. Part 2 of the SH-2 split of #7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* feat(feeder): isolate US 23/5 official close and bound upstream HTTP

Consume the csa22-v2 calendar to classify core RTH vs extended and
overnight windows, reject non-official-close and T+1 bars, resolve the
immediately preceding trading date, and bound decimal inputs. Add
http_limits with streaming byte caps and monotonic total deadlines for
market and OTS fetches. Part 3 of the SH-2 split of #7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* feat(ledger): bind FUSE row state to ledger and authenticate history

Embed next_row_state_sha256 in record bodies, authenticate persisted
production history against an external trusted head and monotonic
anchor, and recover pending rejected state across multi-day rejections.
Wire FUSE into scheduler and replay, add the locked production config,
the Cloud Run job module, and the SH-2 demo used by the pipeline tests.
Part 4 of the SH-2 split of #7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* feat(cloudrun): add Cloud Run job packaging and SH-2 acceptance pack

Add the secret-free Cloud Run Job Dockerfile and example job spec, the
Cloud Run runbook, the SH-2 acceptance pack (sh2_acceptance) and its
docs, the Cloud Run job test suite, and deprecation notes for the SH-1
host templates. Part 5 of the SH-2 split of #7; the tree now matches
feat/sh2-live-engine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): honor O5 settled-cash alias, V7 session time, pyc flags

Resolve o5_settled_cash before defaulting settled_cash to the bankroll,
keep a missing V7 session_time as missing instead of asserting a
regular session, and compile vendored source with dont_inherit=True so
legitimately compiled __pycache__ bytecode verifies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): keep O5 counter aliases, forward H, drop return-as-loss

Default the canonical O5 session counters only when no alias carries
evidence, forward H so O9 can match authorized H change descriptors,
and stop substituting one_session_loss (a return fraction) for the
cumulative dollar loss L when re-tiering explicit FUSE payloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* docs(fuse): document O3 model self-reconciliation in Stage N

Stage N has no broker evidence in any mode, so absent broker_*
observations are substituted with modelled values and O3 is a model
self-reconciliation, not reconciliation evidence. Comment only; no
change to validated inputs or record hashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): preserve explicitly null O5 session counters

Default session_order_count and session_turnover only when the key is
omitted; an explicitly null counter is unknown evidence and is passed
through as None so evaluate_O5() fails closed on turnover/order limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): compare pyc code structurally and keep null settled cash

Compare cached vendored bytecode by code-object equality instead of
marshal encoding, which differs between py_compile and compile() on
CPython 3.11/3.12, while still rejecting altered constants. Preserve an
explicitly null settled_cash or o5_settled_cash as unknown evidence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra P1s in adapter inputs and engine loading

Validate every market record (including optional SPX) for eligibility,
calendar digest and effective session, apply corporate actions to V1
returns only when the ex-date is the decision session, pass explicit
null policy hashes and heartbeats through uncoerced, leave absent
settled cash unknown, pin the complete metadata digest set in code, and
execute only verified engine source bytes via a dedicated finder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* test(ledger): give hand-built market records an effective session

Market records are now validated against the decision session, so the
ledger-integration and pipeline fixtures that build records by hand
carry the effective_session the feeder always sets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): label adapter self-heartbeat with heartbeat_source

Record heartbeat_source="adapter_self" when the adapter defaults the
O7 heartbeat to as_of, and "caller" when session inputs supply it, so a
self-attested heartbeat is never mistaken for liveness evidence. The
ledger-supplied heartbeat follows in part 4 (#13).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* docs(fuse): document EOD half-day O2 mapping and pin it with a test

SH-2 decisions are end-of-day, so every trading day, half days
included, maps to `open`; FuseControl's half_day_cutoff is a pre-trade
rule. Pin that the 2026-11-27 14:30 ET half-day decision maps to open
with O2 clear, and that late runs are the scheduler cutoff's job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra round-2 P1s and default substitutions

Apply the feeder's exact rate freshness rule, reject records retrieved
after the decision instant, reject the ineffective kill_switch_tripped
flag, fail closed on conflicting corporate actions and on caller closes
that disagree with the validated market close, and pass explicit nulls
(broker, cash, exposures, tolerance, proposal) through as missing.
Unknown tiers and missing high-water marks no longer fall back to
balanced or bankroll defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* test(ledger): align hand-built records with session validation

Ledger and pipeline fixtures that build market records by hand now
carry a T-1 SOFR effective date, a retrieval time before the decision
instant, and per-fund closes that match the fund payload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): compare caller and market closes by decimal value

The close-mismatch guard must compare values, not the strict sizing
parser (which rejects floats by design), so a float and a canonical
decimal string for the same close are treated as equal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): resolve Astra round-3 safety P1s in adapter and evaluator

Reject conflicting corporate actions before any successor state,
never let current_index_closes override a validated record, propagate
unknown held-position values into reconciliation and aggregates,
reject kill_switch_tripped on the effective payload at the evaluator
boundary, drop source records dated after the decision instant, and
compare timestamps as aware instants rather than strings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(fuse): guard source dates at evaluator, keep unknown shares None

Drop source records dated after the decision instant at the evaluator
boundary so nested fuse_inputs and direct payloads are covered, and
pass an unknown ledger quantity as share_count None (0 only for an
explicitly flat position) so O3/V2 cannot clear on an invented zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq

* fix(sh2): harden acceptance checks, offline OTS, Cloud Run volume UID

* fix(sh2): resolve Astra Round 2 P0 group name, remove image data dir, harden A13

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@Pigbibi

Pigbibi commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Superseded and completed via 5 clean stacked PRs merged into main:

  1. SH-2 1/5: chore(vendor): vendor digest-pinned FUSE-1 engine (SH-2 part 1/5) #8 (13faed23743a7dfe8370c1ad2f5769f14bfe6e1a)
  2. SH-2 2/5: feat(fuse): add vendored FUSE-1 adapter and sizing isolation (SH-2 2/5) #9 (ccc8b6d2e6a368d955cf4eed375757e2feeb0ea9)
  3. SH-2 3/5: feat(close): add US 23/5 close isolation, feeder limits, and OTS (SH-2 3/5) #14 (bbdddcb438f426d38de50be20ab5bba367a25d29)
  4. SH-2 4/5: feat(ledger): add SH-2 ledger integrity, scheduler, replay, and Cloud Run job (SH-2 4/5) #15 (4cbbb3425ce7b57fdeee46c50b2957aacc549cbe)
  5. SH-2 5/5: feat(sh2): add Cloud Run deployment spec and SH-2 acceptance pack (SH-2 5/5) #16 (ac8aff55a8ab45f8a3aca1edab50fab95ea117f1)

Offline SH-2 acceptance (python3 -m shadow.sh2_acceptance) passes PASS_OFFLINE (14/14 checks, 10/10 demos), full unit suite passes (220 tests), and config/production-scheduler.json retains production_chain_locked: true and clk01_active: false pending OA-SH2-2.

@Pigbibi Pigbibi closed this Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant