Formal Architecture Design · Version 1.1

Stable Income Generator Platform

A bounded, auditable architecture for deterministic signal generation, constrained LLM review, defined-risk option planning, independent preflight, and Alpaca paper execution.

Implementation aligned Fail-closed Hash-bound contracts PostgreSQL source of truth No live-trading path

Document control

Document ID
RS-ARC-001
Status
Implementation-aligned baseline
Effective date
30 August 2026
Scope
Hackathon paper runtime
Architecture style
Modular monolith, isolated roles
Primary platform
Docker Compose / Linux ARM64
System of record
PostgreSQL 18
Authority boundary
Execution worker only

Executive architecture view

The platform separates public visibility, deterministic decisioning, LLM advice, economic-context collection, durable control, and credentialed execution into distinct process and network boundaries. Every permitted order originates as a deterministic semantic signal and remains unchanged through both advisory gates.

Deterministic authority

Strategy, planning, risk, and execution preflight own executable fields. LLM output is never order authority.

Two constrained vetoes

The market thesis and economic assessment may return only ALLOW_UNCHANGED or VETO.

Fail-closed operation

Missing, stale, mismatched, unavailable, uncertain, or unreconciled state ends in refusal without broker mutation.

Auditable effects

Canonical hashes, immutable commands, transactional outbox/inbox, and broker-event projections preserve decision lineage.

Scope boundary. This design has no LIVE mode, live hostname, or live credential route. Alpaca economic inputs are market/news proxy context, not official CPI, employment, GDP, or central-bank release data.

Physical architecture

The implemented deployment uses hardened role-specific containers, file-mounted secrets, private bridge networks, and one internal PostgreSQL service. Solid lines are implemented paths; dashed lines identify external scheduling or a controlled future read-model connection.

Physical deployment and trust zones

Container, network, secret, and external-service boundaries

deterministic/public advisory data execution
RegimeSwitch physical architecture External users, scheduler, model provider, Alpaca data and paper endpoints connect to isolated Docker services and an internal PostgreSQL database. EXTERNAL SERVICES / ACTORS Judge / Operator HTTPS · private control CLI Session Scheduler 08:45 ET one-shot trigger Pinned LLM Provider Structured JSON · no tools Alpaca Data + News IEX bars · headline metadata Alpaca Paper Trading authenticated paper access only DOCKER COMPOSE · ALPACA-HACKATHON-PAPER · DEFAULT LINUX/ARM64 PUBLIC NETWORK api Credential-free Read-only replay/status host port :8000 DECISION ZONE decision-worker strategy · resolver · economic gate planner · risk · outbox producer secret: database DSN only ADVISORY ZONE agent-worker thesis + economics assessment ALLOW_UNCHANGED | VETO secret: provider key only DATA COLLECTION economic-context one immutable capture/day market/news client only secrets: data key + DB DSN EXECUTION ZONE execution-worker preflight · broker adapter submit · reconcile paper key + account + DB DSN DATABASE-INTERNAL · PRIVATE CONTROL AND EVIDENCE PLANE PostgreSQL 18 · regimeswitch events · jobs · outbox/inbox · risk/control daily_economic_context_v1 · signal_decision_audit_v1 non-superuser runtime role · no host port postgres_data named persistent volume retained audit evidence sanitized HTTP daily cache transactional claims target read-model feed

Container hardening

  • Read-only root filesystem; bounded writable tmpfs.
  • All Linux capabilities dropped; no-new-privileges enforced.
  • CPU, memory, and process-count limits declared per service.
  • Role-specific images exclude forbidden packages and credentials.

Network intent

  • Agent and database networks are internal Docker bridges.
  • Public API, model egress, data egress, and broker egress are separate.
  • Bridge names express trust intent; production still requires FQDN egress enforcement.
  • PostgreSQL publishes no host port.

Logical architecture

The logical design keeps strategy semantics, advice, exact order construction, authorization, and external effects in separate modules joined by versioned contracts. The central invariant is that advisory output can veto but cannot transform executable intent.

Layered component model

Responsibilities, dependency direction, and authority boundaries

RegimeSwitch logical architecture Five logical layers show inputs, decisioning, authorization, execution, and evidence with one-way dependency flow. L1 · NORMALIZED INPUTS AND CONTRACTS Market / Account State FeatureVectorV1 DailyEconomicContextV1 Registry + Config L2 · SEMANTIC DECISION AND ADVISORY Strategy Runnerisolated deterministic plug-in Thesis AdapterALLOW_UNCHANGED | VETO Resolversemantic TradeIntentV1 Economics Adaptersupport | veto only Economic Gateoriginal intent or refusal NO_TRADE is a complete, durable decision L3 · EXACT PLANNING AND AUTHORIZATION Order Planner Risk Kernel Approved Command Bundle L4 · CREDENTIALED EXECUTION Outbox Consumerlease + deduplication Independent Preflightrecompute hard invariants Paper Broker Portsubmit + reconcile L5 · DURABLE EVIDENCE AND READ MODELS Event Ledgeroutbox · inbox · jobs Audit Projectionsignal + placement state

Data-flow architecture

Two coordinated flows operate at different cadences: one pre-market economic-context capture per trading date, and a per-signal decision/execution flow. Every refusal converges on the durable signal audit without producing an order.

End-to-end data flow with refusal branches

Morning context lane, per-signal lane, and broker evidence loop

RegimeSwitch end-to-end data-flow architecture Alpaca data is captured once each morning. Each strategy signal passes through advisory, economic, planning, risk, and execution gates with no-trade branches recorded in PostgreSQL. A · PRE-MARKET CONTEXT FLOW · ONCE PER TRADING DATE · 08:45–09:25 ET Alpaca Data + Newsdaily IEX bars + headlines Claim Dateatomic one-row collection lock Normalize + Hashbounded proxy observations daily_economic_context_v1READY | FAILED · immutable daily payload 1 call windowCLAIMEDcanonical V1 B · PER-SIGNAL DECISION AND AUTHORIZATION FLOW Frozen Inputsmarket · feature · state 1 Strategy Evaluationsemantic candidate / refusal 2 LLM Thesis Gateallow unchanged / veto 3 ResolverTradeIntentV1 4 Economic Assessmentdaily context + semantic signalallow unchanged / veto 5 Economic Gatebinding + TTL checks 6 cached context reused all day Order Plannerexact legs · qty · debit 7 Risk Kernelhash-bound approval 8 Transactional Outboxreserve + enqueue atomically 9 Execution Preflightlatest broker state replay 10 Alpaca Papersubmit · reconcile 11 NO_TRADE / RISK_REJECTED / PREFLIGHT_REJECTED durable reason code · zero broker mutation C · EVIDENCE PROJECTION signal_decision_audit_v1 broker_events_v1 + reconciliation

Data architecture and contract ownership

All decision and execution payloads are strict V1 contracts with canonical content hashes. PostgreSQL stores operational truth; JSON Schema snapshots are committed for integration and replay.

Information objectAuthoritative producerPersistence / cadencePrimary binding or invariantConsumers
MarketSnapshotV1Execution-zone ingress or frozen exporterPer decision snapshotFeed identity, timestamps, quality flags, content hashFeatures, planner, risk, replay
StrategyEvaluationV1Isolated registered plug-inPer signalRegistry-pinned plug-in/config/content identityResolver, advisory, audit
AgentThesisV1Agent workerPer signal, TTL-boundContext, evaluation, model-input, model and prompt hashesDeterministic resolver
DailyEconomicContextV1Economic-context workerOnce per trading dateCollection config, source request, causality, expiryEconomics advisory gate
EconomicAssessmentV1Agent workerPer semantic intent, TTL-boundDaily context, evaluation, trade intent, model-input hashEconomic gate, audit
TradeIntentV1Deterministic resolverPer allowed signalOriginal semantic tuple; advisory may not alter itOrder planner
OrderPlanV1Order plannerPer exact order proposalExact legs, quantity, debit, TIF, deterministic client IDRisk, preflight, execution
RiskInputV1 / RiskDecisionV1Decision worker / risk kernelPer plan, short TTLPlan plus all market/account/control/release hashesOutbox, execution preflight
ExecuteApprovedPlanV1Decision workerTransactional outboxImmutable command and identical risk-input bindingExecution worker inbox
BrokerEventV1Execution workerAppend-only per observed transitionClient order ID, broker state, occurrence timeReconciler, reservations, audit projection
SignalDecisionAuditV1Decision worker; execution projectionOne logical row per signalDecision reason, economic lineage, conservative placement stateOperators, read models, evidence review

Security and authority boundaries

Decision boundary

  • No Alpaca package or competition credential in the decision container.
  • Strategy plug-ins receive no network, filesystem, database, account, model, or broker object.
  • LLM requests exclude account, exact contract, quantity, price, risk, and execution state.
  • Only the unchanged deterministic intent can pass an advisory gate.

Execution boundary

  • Only the execution worker receives the competition paper key and expected account ID.
  • Preflight revalidates hashes, TTLs, quotes, control mode, release, allowlist, and reconciliation.
  • Uncertain submission is reconciled by deterministic client order ID before retry.
  • Unknown broker state retains conservative risk reservation.

Data-collection boundary

  • A separate Alpaca data key is mounted only into the one-shot collector.
  • The collector image has no planner, risk kernel, execution core, or broker adapter.
  • One claim is made before any provider call; same-day retry is prohibited after failure.
  • Market/news proxies are never represented as official economic releases.

Persistence boundary

  • PostgreSQL is internal, has no host port, and uses a non-superuser runtime role.
  • Risk reservation and outbox enqueue are committed atomically.
  • Decision job completion and signal audit persistence are atomic.
  • Public read models must use a separately provisioned SELECT-only identity.

Operations, resilience, and observability

Quality attributeDesign mechanismSafe degraded behaviorEvidence
SafetyClosed operating modes, bounded-risk templates, hash-bound approvals, independent preflightReject or NO_TRADE; no live fallbackRisk and security tests; decision tape
AvailabilityDurable jobs, leases, outbox/inbox, deterministic client IDsRetry only internal work; reconcile uncertain external effectsJob/outbox state and broker events
ConsistencyPostgreSQL transactions, compare-and-swap versions, advisory locksFail conflicting approval or lease claimVersioned snapshots and reservation rows
AuditabilityCanonical hashes, frozen V1 artifacts, supplemental reason metadataPreserve refusal as a first-class resultsignal_decision_audit_v1
PerformanceEconomic context fetched once each morning and reused all dayMissing cache produces no order rather than intraday refreshDaily context status and request hash
RecoverabilityPersistent PostgreSQL volume, append-only broker events, reconciliation-first restartHold reservation and remain non-entry-capable until knownReconciliation state and terminal event

Failure-mode policy

Before outbox enqueue

  • Strategy, model, economic context, binding, TTL, planning, or risk failure produces a durable refusal.
  • No exact broker command is created for semantic or economic vetoes.
  • Failed morning collection remains terminal for the date.

After outbox enqueue

  • Execution replays independent preflight against latest reconciled state.
  • Submission-start fencing prevents blind duplicate broker effects.
  • Terminal broker evidence updates the same signal audit and is not rewritten by stale events.

Key architecture decisions

Modular monolith with role-specific deployment imagesPreserves delivery speed while enforcing process and credential boundaries.
Adopted
PostgreSQL transactional outbox and inboxCoordinates risk reservation, command publication, deduplication, and durable retries.
Adopted
LLM as veto-only advisorUses model synthesis without delegating executable order authority.
Adopted
One immutable economic proxy context per dateReduces latency and provider calls while preventing intraday context drift.
Adopted
Independent execution-side preflightRejects stale or tampered commands even after decision-side approval.
Adopted
Separate paper broker and data credentialsLimits credential propagation; external egress policy remains required.
Deployment control
No equity-plus-option protective-put workflow in V1Alpaca does not provide atomic mixed equity/option multi-leg submission; orphan exposure is not accepted.
Deferred

Architecture acceptance criteria

Control objectiveRequired evidenceStatus
Advisory output cannot alter direction, template, horizon, size, contract, price, or riskContract validation and resolver/economic-gate testsImplemented
Economic veto occurs before order planning and outbox publicationDeterministic veto fixture and durable-worker testImplemented
Every generated signal records decision and actual-placement stateSignal audit schema, atomic persistence, broker-event projection testImplemented
Daily economic input is captured once and reusedOne-claim storage invariant and cache behavior testsImplemented
Execution is restricted to paper endpoint and expected accountDeployment configuration and execution preflight testsImplemented
Production FQDN egress allowlists match logical network intentDeployment firewall policy and connectivity evidenceOperator-owned
Public read API uses SELECT-only projections from PostgreSQLRead-model DB identity and negative mutation testsTarget
Container topology executes successfully in DockerCompose build, migration, health, and role-connectivity runEnvironment pending