Engineering documentation. This repository is the implementation companion to the portfolio: the portfolio explains the business problem, this repository shows how the system is designed, why the tradeoffs were made, and how it is tested. It assumes the reader already understands the problem and is here to evaluate the engineering.
This repository implements one vertical slice of an Operational Intelligence Operating System. The thesis it proves technically: organizations already have experts making good local decisions; the failure mode is that each department optimizes its own objective without a shared view of how one business event ripples through the rest of the organization. The supply chain use case is the first proof point, a multi-site internal operations network where local decisions across planning, inventory, supply, operations, finance, and leadership must be coordinated against shared constraints. The engineering question this code answers is concrete: local optimization versus enterprise optimization, and how to make a recommendation that is best for the whole network rather than just one department.
The current implementation focuses on one decision family: inventory rebalancing. It is a decision layer above a WMS, not a WMS. Given a multi-site network it computes inventory policy, detects positioning risk, recommends explainable transfers, and evaluates each recommendation by its measurable enterprise impact (units and labor moved, capacity consumed, risk reduced, shortfall left, and a local-versus-global score), then isolates what-if scenarios from committed state and lets a business priority (an objective profile) reshape the plan. The decision families this repository originally designed but did not build, demand forecasting and an inbound container engine, have since been built as standalone engines, and are composed by a decision-pipeline umbrella. This repository is the product layer of that larger system.
This repository is the flagship product layer of a three-layer system: the product here, a decision-pipeline core that composes five engines, and the five component engines beneath it. Two of those engines are refined rebuilds of the policy and transfer logic prototyped here; the other three fill out decision families this product designed. The full map, the repo links, and the integration seam are in docs/SYSTEM_MAP.md. Status of every capability, here and across the system, is tracked in the roadmap.
app/
db.py SQLAlchemy 2.0 engine + session, bound from MSDN_DATABASE_URL (default sqlite:///msdn.db)
models/ 20 ORM tables across core, inventory, scenario, planning, platform
engines/ pure decision logic (no I/O, no HTML): state, strategy, position, transfers, runner, report, history
view/ render.py + base.css + three HTML templates (presentation only)
security.py capability model: propose / approve / commit are separate
cli.py report and scenario commands
integration/ consume MSDN's decision record into OS state (msdn_core.py)
scripts/ create_db, seed, build_views, run_from_msdn (+ thin per-view builders)
docs/SCHEMA.md full schema, ERD, and table reference
tests/ test_schema (4), test_engines (7), test_views (9), test_enterprise (8), test_cli (3), test_integration (5)
Single runtime dependency: SQLAlchemy >= 2.0. Python 3.10+. Standard library only for the math (statistics.NormalDist) and for consuming the pipeline's decision record (json). Regenerating that record runs the separate engine stack; consuming it here does not. Run commands are in Running it.
The system is a one-directional pipeline. Data is read into a plain-dict state, pure engines compute a plan, the report layer reshapes that plan into role-specific view models, and renderers emit static HTML. Nothing downstream writes back upstream, which is what makes the compute layer trivially testable.
flowchart LR
DB[(SQLite / SQLAlchemy)] --> ST[state.py<br/>load_prod_state]
ST --> EN[strategy / position / transfers]
EN --> RU[runner.py<br/>run_plan, compare_prod_stage]
RU --> RP[report.py<br/>role view models]
RP --> RND[view/render.py]
RND --> HTML[exec / planner / positions .html]
RU --> CLI[cli.py report/scenario]
The layering rule is strict: models know nothing about engines, engines know nothing about HTML, and view knows nothing about the database. The engines operate on dictionaries, not ORM objects, so they can be unit-tested without a database session and the persistence layer can change without touching decision logic.
The compute layer is stateless and deterministic. load_prod_state(session) materializes the network (warehouses, SKUs, policies, positions, capacities) into a nested dict; every engine is a pure function of that dict. There is no clock and no simulation loop. This is a decision snapshot, not a time-stepped model: re-running with the same inputs produces byte-identical output, which is a deliberate design choice (see tradeoffs).
Two environments share one schema. PROD is the committed operating state. STAGE is not a copy: it is a frozen snapshot pointer plus a set of overrides applied in memory at read time. A scenario never writes a PROD row. This is enforced structurally, not by convention (see scenario isolation).
Twenty tables across five modules. The core entities and their relationships:
erDiagram
NETWORK ||--o{ CAMPUS : contains
CAMPUS ||--o{ WAREHOUSE : contains
WAREHOUSE ||--o{ INVENTORY_POSITION : holds
SKU ||--o{ INVENTORY_POSITION : "stocked as"
SKU ||--|| INVENTORY_POLICY : "has Min/OHQ/Max"
SNAPSHOT ||--o{ SCENARIO : "frozen base for"
SCENARIO ||--o{ SCENARIO_OVERRIDE : "delta set"
PLAN ||--o{ TRANSFER_RECOMMENDATION : produces
INVENTORY_POSITION is the operationally sensitive hot table: it contains the per-SKU, per-warehouse state that drives every recommendation. SCENARIO_OVERRIDE rows are the deltas that define a STAGE world without mutating PROD. The full column-level reference, including the platform and planning tables, is in docs/SCHEMA.md.
Each engine is a pure module with a single responsibility:
strategy.py(compute_policy): Min, OHQ, and Max per SKU from demand and lead-time variability.position.py(position_metrics): days of supply, stockout probability over the lead time, and under/over/correct classification per SKU-warehouse.transfers.py(recommend_transfers): the explainable greedy network solve that decides what moves and from where.runner.py(run_plan,compare_prod_stage): orchestration; runs the engines for a state and diffs STAGE against PROD.report.py(build_brief): reshapes one plan into three role-specific view models (build_executive_brief,build_planner_review,build_inventory_diagnostics) plus arender_textCLI summary. This layer carries semantic tone, never colors or HTML.history.py: a deterministic synthetic-history generator (seed 42). It is dormant: not surfaced in any view and never read by the engines or tests. It exists as scaffolding for the forecasting work and is intentionally inert.
Min/OHQ/Max from a service-level target, using a z-score safety stock over combined demand and lead-time variability:
z = invCDF(clamp(service_level, 0.5, 0.9999))
sigma_LT = sqrt(LT * demand_sd^2 + demand_mean^2 * LT_sd^2)
safety = z * sigma_LT
Min = roundToLPN(demand_mean * LT + safety) # reorder point
OHQ = roundToLPN(Min + demand_mean * coverage_days) # preferred target
Max = roundToLPN(OHQ + demand_mean * buffer_days) # upper planning limit
OHQ is the reorder point plus a configurable coverage cycle, rounded to whole license-plate quantities, not a bare midpoint between Min and Max. The function returns a method_note string for explainability, and explicitly records that an EOQ-optimized OHQ is deferred.
Each position's stockout probability is computed against the lead-time demand distribution with statistics.NormalDist, giving a real probability rather than a heuristic flag, and days of supply at current on-hand. Positions are classified under, over, or correctly positioned relative to their band.
An explainable greedy network solve, chosen over an exact optimizer on purpose (see tradeoffs). Candidate moves are scored against a weighted objective and committed against shared, decrementing capacity budgets:
weights = service 0.45, positioning 0.25, cost 0.20, labor 0.10
score = w.service*urgency + w.positioning*positioning - w.cost*friction - w.labor*labor
feasible = min(remaining_need, source_surplus, destination_transfer_capacity, destination_cbm_room)
flowchart TD
A[Under-positioned demand] --> B[Enumerate source candidates]
B --> C[Score against weighted objective]
C --> D[Pick best feasible source]
D --> E[Clamp to min of need / surplus / capacity / cbm]
E --> F[Commit and decrement shared budgets]
F --> G{Need remaining<br/>and budgets left?}
G -- yes --> B
G -- no --> H[Emit move with binding_constraint + reason]
Two properties make the output reviewable. Same-campus sources outscore cross-campus ones, so the solve prefers local moves. And every recommendation reports the binding_constraint that limited it (destination_transfer_capacity, source inventory, or cbm room), so a planner sees not just the move but why it was not larger, and why some shortfalls were left unresolved.
A third property is the destination-need budget. The solve keeps a remaining_need budget per (sku, destination) alongside source surplus, transfer capacity, and storage. Feasible quantity is the minimum of all four, and remaining_need is decremented on every commit, so when several sources target the same shortage they cannot collectively push the destination past OHQ. This is enforced by a regression test (test_optimizer_does_not_overfill_destination).
This is where the slice expresses the thesis: a recommendation is a decision object that explains why it is best for the whole network, not just a locally valid departmental action.
Enterprise impact (enterprise_impact.py) turns each raw move into a structured object that is data-backed, not templated. It carries a metrics block computed entirely from the optimizer's own output: units and LPNs moved, labor hours, source surplus consumed, destination capacity consumed and remaining, the shortfall the move leaves, whether it crosses a campus, and the destination stockout risk before and after (so service_risk_reduced is a real delta). The prose impacts and tradeoffs are generated from those numbers, for example "Cuts Buda Primary stockout risk 99% to 90%" or "Leaves 443 units short at Buda Primary." Two scores summarize the tension: local_score is the destination's own view (how urgent, how fully covered); global_score discounts it by cross-campus friction, labor, unmet need, and scarce-capacity consumption. When a move is locally strong but globally constrained, local_vs_global_note names the dominant driver ("Locally strong (score 0.39) but globally lower (score 0.16) because of leaving 443 units short").
The recommendation contract (contract.py) is the source of truth for recommendation content, not an afterthought. The data flow is: engine output produces a recommendation, the contract wraps it (with its enterprise impact) into a decision object, the report layer builds role-specific view models from contract fields, and the renderers format those view models. The renderer authors no decision language of its own; the planner card reads business_question, recommended_action, the enterprise impact, alternatives_considered, selected_because, confidence, and status straight from the contract. That is what lets a second decision family plug into the same structure without touching the report or view layers. See docs/DECISION_CONTRACT.md.
Planner cards stay concise. Each expanded card shows the business question, the recommended action, at most three network-impact bullets, and a single tradeoff line (a second only when a material shortfall remains), plus the local and network scores, affected domains, and the top alternatives. No paragraphs. A test enforces the three-bullet cap.
Alternatives considered answers the reviewer's first question, why this move and not another. Each recommendation carries at least two alternatives with the reason each was rejected: the other candidate sources (rejected for lower objective score, cross-campus friction, or insufficient surplus) plus the standing strategic alternatives (wait for inbound, accept the shortfall).
Objective profiles (objectives.py) make decision hierarchy a first-class input. A profile is a named weighting of the four objective terms (service, positioning, cost, labor): balanced, service_first, cost_first, capacity_protection. A scenario's ObjectiveProfile is wired through execution, so changing the business priority changes the plan's scoring. python -m app.cli objectives prints the same network scored under every profile. To be precise about what this proves: in the seeded demo network the committed order does not change, because source proximity and capacity constraints dominate; the scores change under each profile, and the command says so explicitly. That order can flip is proven by a unit test (test_objective_profile_changes_recommendation_order) on a crafted state where two moves contend for shared capacity. The local-vs-global thesis itself is demonstrated by python -m app.cli local-global; see docs/LOCAL_VS_GLOBAL_OPTIMIZATION.md. That artifact computes the inventory decision from the engine and labels the other departments as illustrative, since those engines are not built.
The dashboards are implementation artifacts: they demonstrate the output of the decision engine, they do not introduce the project. The same build_brief output is rendered into three non-redundant views, one role per view:
exec_view.html(decide): the recommended moves, the result, and the cost of inaction.planner_view.html(validate): source and destination before/after, with each move's binding constraint and approve/modify/override controls.positions_view.html(explain): where the network is short, which sources can cover it, and how each position sits in its band.
Rendering is a pure view_model -> template -> HTML fill. Templates are commented skeletons with {{TOKEN}} slots and no logic; render.py builds the fragments (SVG flows, bands, tables) and fills them. All three link one shared base.css rather than inlining styles, so there is no duplicated style block across the generated output. Build with scripts/build_views.py.
STAGE-cannot-write-PROD is enforced by the data model, not by discipline. A scenario is a Snapshot (a frozen read of PROD) plus a set of ScenarioOverride rows. resolve_scenario_state reads the snapshot and applies the overrides in memory:
flowchart LR
PROD[(PROD rows)] -->|capture_snapshot| SNAP[Snapshot, frozen]
SNAP --> RES[resolve_scenario_state]
OV[ScenarioOverride deltas] --> RES
RES --> STAGE[STAGE state, in memory]
STAGE --> CMP[compare_prod_stage]
PROD --> CMP
CMP --> DIFF[what changed]
There is no code path from a scenario to a PROD write. The regression in test_schema asserts exactly this: after resolving a scenario that overrides a position, the STAGE state reflects the override while both the PROD state and the underlying PROD row are unchanged. security.py reinforces the same separation at the action level: propose, approve, and commit are distinct capabilities, so the role that drafts a recommendation cannot also push it to PROD.
These are the choices a reviewer is here to interrogate.
- Snapshots over live mutation. Scenarios read a frozen snapshot and layer deltas in memory. This buys reproducibility (a scenario always re-resolves to the same state), auditability (the override set is the complete diff), and a hard isolation guarantee, at the cost of not modeling continuous live updates. For decision support, reproducibility was worth more than freshness.
- STAGE cannot write PROD, structurally. The alternative, a flag on a shared row, fails the moment a code path forgets to check it. Modeling STAGE as snapshot-plus-overrides means there is no PROD row for a scenario to corrupt, so isolation does not depend on every author remembering a guard.
- Explainability as a first-class output. Every transfer carries its binding constraint and a reason string; every policy carries a method note. A black-box optimizer that emits only quantities is not reviewable, and an unreviewable recommendation does not get committed. Explainability was treated as a requirement, not a nicety.
- Deterministic recommendation generation. No randomness in the decision path. This makes the engines testable with exact assertions, makes the demo stable to talk through, and makes a recommendation defensible (the same inputs always justify the same move). The only seeded RNG, in
history.py, is deliberately quarantined from the decision path. - Greedy over exact optimization. The transfer solve is a scored greedy heuristic, not a MILP. Greedy is explainable step by step, fast, and good enough for daily rebalancing; the binding-constraint reporting gives most of the value an exact solver would. A MILP is on the roadmap as a bounded challenger to measure the greedy gap, not as a default.
- What was deferred here, and then built. XGBoost demand forecasting and the inbound/container engine were designed but unbuilt in this repository. Shipping one decision end to end with honest seams was chosen over five half-built engines. Those engines were then built out fully as their own tested, standalone repositories and composed by the decision-pipeline umbrella (see docs/SYSTEM_MAP.md). Decision memory, EOQ-optimized OHQ, and a live WMS sync remain designed.
Six suites mirror the layers, 36 tests total:
test_schema.py(4): persistence and the isolation invariant. Includes the explicit assertion that a scenario override never mutates PROD.test_engines.py(7): decision logic. Policy ordering, risk math, the greedy solve, capacity exhaustion and the resulting binding constraint, and PROD/STAGE comparison.test_views.py(9): the presentation contract. The suite builds the views into a temp directory via a tempMSDN_DATABASE_URL, then asserts each view has no unresolved{{TOKEN}}, carries its role-specific content, exposes the correct active nav, surfaces concise network-impact language (with the three-bullet cap enforced), and never leaks raw warehouse codes.test_enterprise.py(8): the thesis, not just the mechanics. Every recommendation carries enterprise impact, the metrics are data-backed (they equal the optimizer's own output), the optimizer cannot overfill a destination, the objective profile changes decision order under contention, alternatives are recorded, the global score penalizes cross-campus moves, a locally attractive move that hurts the network scores lower globally, and the local-vs-global artifact is well-formed.test_cli.py(3): every demo command (scenario,objectives,local-global) is safe to run twice and produces deterministic output.
The testing philosophy follows from the architecture: because the compute layer is pure and deterministic, tests assert exact numbers rather than ranges, and because the engines take dicts rather than ORM objects, most tests need no database at all.
The current solve is in-memory and single-process, sized for one network snapshot. The relevant scaling axes: the greedy solve is roughly O(under-positions x candidate-sources) per pass and is the first thing a MILP or a candidate-pruning pass would replace at large SKU-by-site counts; state materialization is a small number of indexed reads and would move to per-campus partitioning before it became a bottleneck; and the renderers are stateless, so view generation parallelizes per role. SQLite is the development binding; the persistence layer is isolated behind db.py and the dict-based state contract, so a managed Postgres swap touches one module.
Status is tracked honestly. Implemented means it runs in this repository; partially implemented means the spine exists but a component is stubbed or seeded; designed means specified but not built.
| Capability | Status |
|---|---|
| Inventory policy (Min/OHQ/Max), positioning, stockout risk | Implemented |
| Explainable greedy transfer optimizer with binding constraints and destination-need budget | Implemented |
| Enterprise-impact layer (data-backed metrics, local vs global scoring) | Implemented |
| Recommendation contract as source of truth; view models built from it | Implemented |
| Alternatives considered on every recommendation | Implemented |
| Objective profiles wired through scenario execution | Implemented |
| Snapshot + override scenario isolation, PROD/STAGE compare | Implemented |
| Three-view dashboard renderer | Implemented |
| Local-vs-global demo artifact | Partially implemented (inventory computed; other departments illustrative) |
| Capability model (propose/approve/commit) | Partially implemented |
| Demand forecasting (XGBoost) feeding policy inputs | Implemented as standalone engine (demand-forecasting-engine) |
| Inbound/container engine (effective cube, opportunity cost) | Implemented as standalone engine (container-network-engine) |
| Refined inventory policy and transfer engines (standalone) | Implemented (inventory-policy-engine, transfer-replenishment-engine) |
| Home assignment / slotting engine (new decision family) | Implemented as standalone engine (home-assignment-engine) |
| Five-engine decision pipeline over a shared catalog | Implemented as the umbrella (multi-site-network-decision-system) |
| Adopt the umbrella pipeline as this product's decision core | Implemented (app/integration/msdn_core.py; the OS runs its engines on a pipeline-derived network, see docs/SYSTEM_MAP.md) |
| Cross-department coordination engines (planning, finance, operations) | Designed |
| Decision memory (outcome capture, confidence update) | Designed |
| MILP transfer solver as a bounded challenger | Designed |
| EOQ-optimized OHQ, multi-method forecast backtesting | Designed |
| WMS sync and data-trust boundary | Designed |
pip install -r requirements.txt PYTHONPATH=. python -m scripts.create_db # create the schema (20 tables) PYTHONPATH=. python -m scripts.seed # seed the demo network PYTHONPATH=. python -m app.cli report # executive summary on PROD (text) PYTHONPATH=. python -m app.cli scenario # STAGE override vs PROD compare (uses the scenario's objective profile) PYTHONPATH=. python -m app.cli objectives # the same network scored under each objective profile PYTHONPATH=. python -m app.cli local-global # local-vs-global demo artifact (writes local_global_demo.json) PYTHONPATH=. python -m scripts.build_views . # build the three dashboard artifacts PYTHONPATH=. python scripts/run_from_msdn.py # run the engines on a network from MSDN's decision record PYTHONPATH=. python -m tests.test_schema # persistence + PROD isolation PYTHONPATH=. python -m tests.test_engines # decision logic PYTHONPATH=. python -m tests.test_views # presentation contract PYTHONPATH=. python -m tests.test_enterprise # enterprise behavior (impact, overfill, profiles) PYTHONPATH=. python -m tests.test_cli # demo commands are idempotent
All data in this repository is fictional and generated for demonstration.