-
-
Freight Rerouting Manifest — Afterlife AI turns surplus inventory into a traceable rescue plan, then reconciles what actually happened.
-
Afterlife AI turns one inventory workbook into a constrained rescue plan, while keeping final approval with the human operator.
-
Operators upload one XLSX file and set the objective, logistics budget, rescue ratio, and deadline before analysis.
-
Triage protects healthy stock first, then shows rescue scope, expected rescue, waste, and economic value.
-
CP-SAT selects feasible allocations under shared constraints, with model estimates and expected recovery shown per action.
-
Feasible and blocked alternatives stay visible, including why each candidate was not carried into the final allocation.
-
Afterlife AI stays advisory: uncertain inventory is held for review, and physical execution requires human approval.
-
Model, partner-registry, ruleset, and optimizer provenance are shown directly beside the decision evidence.
-
Operators record only confirmed rescued and waste quantities; anything unconfirmed remains unresolved.
-
Reconciliation compares expected and confirmed outcomes, reports deltas, and excludes unresolved units from realized diversion.
Afterlife AI
Give surplus inventory another useful life.
Afterlife AI helps retail and F&B operators decide what to do with inventory that still has usable value but no longer fits its original selling path. It combines deterministic triage, safety and feasibility rules, HGB-E rescue-success scoring, global CP-SAT allocation, sustainability reporting, and operator-confirmed outcome reconciliation.
Inspiration
I grew up around a family-run neighborhood store, so surplus inventory never looked like a clean spreadsheet problem.
A slow-moving product could still be sold one by one, bundled, repurposed, moved through another channel, or kept because the apparent “surplus” was still normal stock. Sometimes the store had enough information to make a confident decision. Sometimes it did not.
One early case involved Nutrisari Es Rujak that was moving slowly in the family store. The product still had several possible uses and selling paths. The incident record was incomplete, and that limitation shaped the project as much as the rescue idea itself. If the evidence is incomplete, the system should say so.
I expanded that initial observation during preproduction. The discovery set included 16 retrospective family incidents and 16 external incidents from retail, food service, hospitality, supermarkets, restaurants, bakeries, and food-rescue contexts.
I did not use those 32 incidents as ML training data. I used them to identify recurring decision questions:
- which inventory should stay untouched;
- which inventory only needs monitoring;
- which quantity belongs in rescue planning;
- which rescue routes exist for the business;
- which constraints can block an otherwise attractive route;
- when the system should stop and ask for review.
The incidents pointed to a decision problem under constraints.
A partner can run out of capacity. A bundle can consume companion stock needed elsewhere. Repurposing can require labor, equipment, ingredients, or cold storage. A transfer can exceed the logistics budget. A route can take longer than the remaining safe-use window.
That changed the project from “find another place for surplus” into a planning problem with explicit authority boundaries.
The name reflects the product idea. An item can fail its first commercial path and still have another useful path if safety, time, capacity, demand, and economics support it.
What it does
The production system accepts one structured .xlsx inventory workbook plus request-level decision context.
The analysis flow:
- validates the workbook, worksheet, schema, datatypes, row semantics, and request context;
- runs deterministic inventory triage;
- protects healthy and monitored stock;
- isolates the quantity that belongs in rescue planning;
- builds planning lots;
- generates rescue candidates from the active runtime capability profile and partner evidence;
- applies deterministic safety and feasibility hard gates;
- sends gate-eligible rescue candidates to HGB-E scoring;
- calculates expected economic and physical outcomes;
- uses OR-Tools CP-SAT to allocate quantity across the full request;
- produces a traceable Rescue Decision Report;
- derives a Sustainability Summary from the same plan;
- accepts operator-confirmed rescued and waste quantities after external execution;
- reconciles those confirmed outcomes against the original planning scope.
Runtime triage states include:
HEALTHY_STOCKMONITORSURPLUS_CANDIDATEEXPIREDNEEDS_REVIEW
The active Technical MVP rescue profile includes:
INTERNAL_REPURPOSEBUNDLELOCAL_DISCOUNTEXTERNAL_PARTNERSAFE_DISPOSAL
The domain contracts contain a broader rescue-action vocabulary. I kept the production profile narrower so the submission only claims actions that the runtime supports and tests.
Afterlife AI produces advisory decisions. A human approves any physical action outside the system.
Core rescue and impact flow

The complete lifecycle is:
Inventory Workbook + Decision Context
↓
Validation
↓
Deterministic Inventory Triage
↓
Planning Lots
↓
Rescue Candidate Generation
↓
Safety and Feasibility Hard Gates
↓
HGB-E Rescue-Success Scoring
↓
Expected-Value Calculation
↓
Global CP-SAT Allocation
↓
Rescue Decision Report
↓
Sustainability Summary
↓
Human Review
↓
Physical Execution Outside Afterlife AI
↓
Operator-Confirmed Outcome
↓
Outcome Reconciliation
↓
Human-Readable Markdown Report
Planning, physical execution, and confirmed outcomes stay separate throughout the flow.
Operational flowchart

The flowchart shows the branches that shape runtime behavior:
- invalid input stops before planning;
- inventory with no rescue-planning quantity bypasses rescue candidate generation;
- blocked candidates never reach HGB-E;
- model loading failure uses a deterministic neutral scoring fallback for eligible rescue candidates;
- a definitive infeasible CP-SAT result leaves quantity unallocated for human review;
- incomplete package-weight evidence withholds full-batch mass claims;
- physical action remains advisory until a human approves it;
- Outcome Reconciliation runs only when an operator provides confirmed results.
The system can finish with a recommendation, a review state, an infeasible result, or unresolved outcome quantity.
System architecture
Judge-facing architecture

The simplified architecture keeps the responsibility chain visible:
Inventory + Decision Context
↓
Validation
↓
Deterministic Triage
↓
Rescue Option Generation
↓
Safety & Feasibility Hard Gates
↓
HGB-E Scoring
↓
Expected Value
↓
Global CP-SAT Allocation
↓
Rescue Decision Report
↓
Sustainability Summary
↓
Human Review
↓
External Physical Action
↓
Operator-Confirmed Outcome
↓
Outcome Reconciliation
↓
Markdown Report
The Runtime Capability Profile, Partner Demand Registry, HGB-E model, optimization objective, budget, and deadline feed the stages that need them.
Full technical architecture

The detailed architecture separates seven implementation layers:
- Presentation Layer
- Shared Intake & Validation
- Canonical Rescue Planning Pipeline
- NextStep Sustainability Extension
- Outcome Reconciliation
- Human-Facing Output
- Runtime Artifacts
The production interface uses FastAPI, Jinja2, semantic HTML, vanilla CSS, and vanilla JavaScript.
The canonical rescue pipeline still returns RescueDecisionReport. The NextStep layer wraps that report in NextStepDecisionReport and adds a typed sustainability_summary.
The current reconciliation endpoint is stateless. Physical execution stays outside Afterlife AI.
Why the system separates rules, AI, optimization, and human review
Each stage answers a different decision question.
Deterministic inventory triage
Triage decides which inventory may enter rescue planning.
Healthy stock stays protected. Monitored stock stays outside intervention. Expired inventory follows different semantics from recoverable surplus. Ambiguous or incomplete cases can enter NEEDS_REVIEW.
HGB-E never overrides this stage.
Safety and feasibility hard gates
Candidate generation creates possible rescue routes. The gate layer decides which routes remain eligible.
The gates can evaluate:
- safety;
- verification sufficiency;
- remaining safe-use and commercial-sale windows;
- rescue deadline;
- storage compatibility;
- action compatibility;
- partner demand;
- partner capacity;
- candidate minimum order quantity;
- logistics feasibility;
- shared operational capacity;
- supported-domain coverage.
A failed hard gate removes the candidate before model scoring.
HGB-E rescue-success scoring
HGB-E uses HistGradientBoostingClassifier.
The model estimates rescue-success evidence for candidates that already passed the deterministic gates.
HGB-E does not control triage, safety, feasibility, final allocation, or human approval.
SAFE_DISPOSAL uses terminal action semantics and does not pass through the rescue-success model.
Expected-value calculation
The value layer combines the rescue-success estimate with action economics and physical-outcome semantics.
The report can expose:
- expected cash recovery;
- expected future branch recovery;
- expected avoided purchase cost;
- direct action cost;
- logistics cost;
- handling cost;
- expected net recovery;
- expected physical rescue quantity;
- expected waste quantity.
For SAFE_DISPOSAL, physical rescue remains zero and allocated disposal quantity contributes to waste.
Global CP-SAT allocation
A per-item ranking can pick several candidates that cannot coexist.
Two candidates can compete for the same logistics budget, labor, equipment, ingredients, companion stock, cold storage, action capacity, partner capacity, or time.
OR-Tools CP-SAT resolves those conflicts across the complete request.
The local question is “Which action looks best for this item?”
The planning question is “Which combination of feasible actions can coexist under the shared constraints?”
The optimizer answers the second question.
The deterministic fallback also preserves those constraints. A definitive INFEASIBLE result does not become a successful fallback allocation.
How I built it
I used an evaluation-first, contract-driven process.
The project began with:
Discovery
↓
Problem Brief
↓
Evaluation Contracts
↓
Domain Rules
↓
Feature Schema
↓
PRD
↓
Implementation
↓
Verification
Before production coding, the preproduction work defined which stock stays protected, when the system should abstain, which constraints outrank model scores, which quantities must be conserved, what partner evidence the planner can trust, which solver outcomes allow fallback, what counts as rescue or waste, and which claims each evidence source can support.
I froze the preproduction package before production implementation.
The production speedrun then built one vertical slice:
- Day 1: repository foundation, XLSX intake, validation, and deterministic triage;
- Day 2: planning lots, candidate generation, hard gates, expected value, CP-SAT, fallback, and Rescue Decision Report;
- Day 3: synthetic dataset generation, grouped splitting, baselines, candidate-model training, AI Value Gate, and HGB-E selection;
- Day 4: production integration, FastAPI + Jinja2, API, Docker, and the Technical MVP release candidate.
The post-speedrun work audited that MVP against the frozen preproduction contracts. I restored high-value missing behavior, compared frontend approaches, polished the selected interface, aligned claims with evidence, and ran a repo-wide correctness reconciliation.
That correctness pass fixed issues that a working demo could hide:
- destination-aware candidate IDs for multiple external partners;
- candidate-level MOQ enforcement;
SAFE_DISPOSALrescue and waste semantics;- logistics-feasibility versus logistics-budget semantics;
- safe-use and commercial-sale time-window derivation;
- train-serving feature parity;
- optimizer and report economic semantics;
- runtime error boundaries;
- numeric hardening around allocation.
The production story includes both implementation and correction. A passing happy-path demo was not the finish line.
Evidence strategy
I kept three evidence classes separate because they answer different questions.
1. Incident-based discovery evidence
The discovery set contains:
- 16 family incidents;
- 16 external incidents.
I used them for problem framing, constraint discovery, rescue-action vocabulary, failure modes, and evaluation-case design.
They do not serve as model training rows.
2. Evaluation contracts
The evaluation layer contains deterministic triage fixtures, 30 planner cases, integration cases, fallback cases, and explicit expected behavior.
These cases test:
- safety overrides;
- timing;
- stale or incomplete demand evidence;
- partner capacity;
- budget;
- quantity conservation;
- fallback;
- manual review;
- allocation semantics.
They work as executable specifications.
3. Synthetic candidate benchmark
The controlled synthetic benchmark contains:
| Split | Scenario groups | Candidate rows |
|---|---|---|
| Train | 1,680 | 8,435 |
| Validation | 360 | 1,805 |
| Locked final test | 360 | 1,780 |
| Total | 2,400 | 12,020 |
The split unit is scenario_group_id.
Recorded split evidence:
- group leakage:
false; - group leakage count:
0; - final-test policy:
LOCKED_FINAL_EVALUATION.
The benchmark supports model development and technical evaluation. It does not represent merchant transaction history.
How I evaluated the AI component
I kept a learned model only after it beat the registered simpler baseline under the synthetic evaluation protocol.
The selected model is HGB-E. The primary baseline is B1, a train-only action-prior baseline.
I froze model selection before opening the locked final-test outcomes.
Validation and AI Value Gate
The frozen selection record reports:
- selected model:
HGB-E; - family:
HistGradientBoostingClassifier; - selection status:
FROZEN_BEFORE_FINAL_TEST; - final test accessed during selection:
false; - validation PR-AUC:
0.853664; - validation Brier score:
0.155145.
The robustness protocol used seeds 42, 137, and 2026.
Recorded robustness results:
- mean HGB-E PR-AUC:
0.856632; - mean B1 PR-AUC:
0.834086; - mean PR-AUC delta:
0.022546; - aggregate bootstrap 95% CI for the delta:
0.012832to0.032417; - consistency:
3/3.
One individual robustness seed produced a confidence interval that crossed zero. I therefore avoid claiming significance on every individual seed.
Selected Model vs B1 Baseline
Locked synthetic final-test evidence:
| Metric | HGB-E | B1 action-prior baseline |
|---|---|---|
| PR-AUC | 0.874229 | 0.834923 |
| Brier score ↓ | 0.151383 | 0.156801 |
| MRR | 0.930093 | 0.915972 |
| NDCG@3 | 0.890749 | 0.869309 |
| Top-1 success rate | 0.872222 | 0.844444 |
| Pairwise accuracy | 0.663004 | 0.596337 |
Downstream synthetic allocation diagnostics
| Diagnostic | HGB-E | B1 action-prior baseline |
|---|---|---|
| Mean allocation regret ↓ | 9454.805111 | 20545.045250 |
| Oracle value retained ↑ | 0.998591 | 0.996938 |
Recorded locked-evaluation safety checks:
- quantity conservation:
PASS; - hard-constraint violations:
0.
The AI Value Gate passed.
These results support one bounded claim: HGB-E beat B1 on the frozen synthetic benchmark under the registered evaluation protocol.
The benchmark does not establish field-calibrated rescue probabilities, verified merchant waste reduction, real-world financial impact, merchant adoption, or universal optimizer superiority.
Rescue Decision Report
The planner returns more than one recommendation score.
RescueDecisionReport can expose:
- inventory and triage results;
- selected allocations;
- feasible alternatives that the optimizer did not select;
- blocked candidates and reason codes;
- allocated and unallocated quantity;
- binding constraints;
- expected economic-value components;
- expected rescue and waste quantities;
- model provenance;
- schema and ruleset provenance;
- optimizer status;
- partner-registry provenance;
- warnings;
- limitations;
- manual-review items;
- human approval state.
The report describes the plan and the evidence behind it. Physical execution requires human action outside the application.
What changed during NextStep Hacks 2026
I tagged the pre-hackathon state as:
nextstep-prehackathon-baseline-2026-08-30
That baseline already contained:
- XLSX intake;
- deterministic triage;
- rescue candidate generation;
- hard safety and feasibility gates;
- HGB-E scoring;
- expected-value calculation;
- CP-SAT allocation;
- Rescue Decision Report;
- human review;
- FastAPI + Jinja2 production UI.
For NextStep, I extended the system into measurable impact reporting and outcome reconciliation.
The NextStep work added:
- typed Sustainability Summary;
COMPLETE,PARTIAL, andNONEmass-evidence coverage;- source-lot mass accounting from
package_weight_g; NextStepDecisionReport;POST /api/analyze-nextstep;- stateless
POST /api/outcomes/reconcile; - operator-confirmed rescued and waste quantities;
- explicit unresolved quantity;
- realized diversion ratio;
- expected-versus-confirmed rescue and waste deltas;
- reconciliation UI;
- human-readable Markdown report export.
The original HGB-E model and CP-SAT planner stayed in place.
NextStep did not add a second model, retrain HGB-E, replace the optimizer, invent CO2 estimates, or add outcome persistence.
The hackathon delta closes a missing lifecycle step: the original system could plan expected rescue, while the NextStep version can also record and reconcile what an operator later confirms.
Sustainability Summary
The Sustainability Summary derives expected impact from the canonical rescue plan.
It can report:
- reconciled planning quantity;
- expected rescued quantity;
- expected waste quantity;
- expected rescue ratio;
- expected rescue mass when weight evidence covers the full relevant batch;
- expected waste mass under the same evidence condition.
Mass evidence uses three states:
COMPLETEPARTIALNONE
The runtime never fills missing package weights with invented defaults.
For mixed-weight inventory, the impact layer applies each source lot's package_weight_g before aggregation.
When evidence is incomplete, the report withholds complete batch-mass claims.
The current MVP does not calculate CO2 avoided, trees saved, meal equivalents, or similar environmental proxies.
Outcome Reconciliation
The original rescue plan contains expected outcomes. The reconciliation layer handles confirmed observations after physical execution.
An operator supplies:
- actual rescued quantity;
- actual waste quantity.
The reconciliation result derives:
- confirmed quantity;
- unresolved quantity;
- realized diversion ratio from confirmed outcomes;
- rescue delta;
- waste delta.
Example:
100 units in reconciliation scope
70 confirmed rescued
10 confirmed waste
20 unresolved
The 20 unresolved units remain unresolved.
The reconciliation call does not mutate the original rescue plan and does not claim persistence.
Why FastAPI + Jinja2 is the primary interface
After the Technical MVP stabilized, I built a thin Streamlit challenger over the same canonical pipeline.
The comparison used the same fixture, model artifact, runtime configuration, decision context, and report contract.
Recorded comparison:
| Presentation layer | Score |
|---|---|
| FastAPI + Jinja2 | 42 / 50 |
| Streamlit | 38 / 50 |
FastAPI + Jinja2 won six comparison dimensions. Streamlit won four.
I kept FastAPI + Jinja2 as the production presentation layer because it gave the project more control over information hierarchy, warnings, alternatives, provenance, limitations, and the human-review flow.
Streamlit remains a challenger and reference adapter. It reuses the same core pipeline.
The production frontend uses:
- FastAPI;
- Jinja2;
- semantic HTML;
- vanilla CSS;
- vanilla JavaScript.
Challenges
Incomplete evidence
The first family incidents exposed missing variables.
I carried that limitation into the product contract. Missing or ambiguous evidence can trigger validation errors, warnings, withheld metrics, or NEEDS_REVIEW.
Protected stock
A slow-moving item can still belong to normal inventory.
Deterministic triage protects that stock before rescue planning starts.
Model authority
A model can assign a high score to a candidate that violates a safety or feasibility rule.
The hard-gate layer removes that candidate before HGB-E sees it.
Shared constraints
Two good candidates can compete for the same budget, capacity, ingredients, equipment, or time.
CP-SAT solves those conflicts across the full request.
Correctness after the demo worked
The Technical MVP exposed an end-to-end flow, then the correctness reconciliation found semantic bugs underneath that flow.
MOQ, candidate identity, disposal semantics, timing, logistics budgets, and report calculations all needed tighter end-to-end alignment.
Sustainability evidence
Expected rescue quantity does not prove realized impact.
The NextStep layer separates planning estimates from operator-confirmed outcomes and withholds unsupported mass claims.
Hackathon scope
The pre-NextStep rescue engine already worked.
I used the hackathon period to close the missing measurement and reconciliation step instead of replacing working parts for novelty.
Accomplishments
The current system combines:
- structured XLSX intake;
- deterministic validation and triage;
- protected-stock handling;
- planning-lot construction;
- capability-aware candidate generation;
- partner-demand evidence;
- hard safety and feasibility gates;
- frozen HGB-E scoring;
- registered baseline comparison and locked final evaluation;
- expected economic and physical-value calculations;
- OR-Tools CP-SAT allocation;
- candidate MOQ handling;
- quantity conservation;
- deterministic fallback semantics;
- action-specific
SAFE_DISPOSALtreatment; - selected and unselected alternatives;
- manual-review states;
- model and optimizer provenance;
- Sustainability Summary;
- evidence-bounded mass accounting;
- operator-confirmed Outcome Reconciliation;
- unresolved outcome quantity;
- realized diversion ratio;
- expected-versus-confirmed deltas;
- Markdown report export;
- typed APIs;
- FastAPI + Jinja2 production UI;
- a separate Streamlit challenger;
- unit, integration, API, acceptance, and regression tests;
- final architecture and claim-boundary documentation.
The current recorded NextStep regression checkpoint reports:
419tests passed;0failed;- full-repository Ruff check:
PASS; - JavaScript syntax checks for
app.js,impact-ui.js, andreport-markdown.js:PASS.
That checkpoint covers the repository regression state. Deployed-app smoke verification remains a separate submission check.
What I learned
I ended up treating prediction, planning, physical execution, and outcome measurement as separate responsibilities because the system behaved more cleanly when each boundary had its own evidence.
HGB-E estimates rescue success for an eligible candidate. Hard gates control eligibility. CP-SAT controls constrained allocation. A human approves physical action. Outcome Reconciliation only uses quantities that an operator confirms afterward.
The project also changed how I think about uncertainty in product design.
NEEDS_REVIEW, INFEASIBLE, unresolved, and withheld mass metrics are useful outputs. They preserve information that a forced answer would destroy.
The AI component had to earn its place as well. HGB-E stayed because it passed the registered value gate against B1 on the frozen synthetic benchmark. Its role remains narrow.
What's next
The next phase needs real-world evidence more than another model.
Priorities include:
- merchant pilot evaluation;
- real partner-demand integrations;
- persistent outcome history with provenance;
- stronger package-weight evidence;
- long-term expected-versus-confirmed calibration;
- field evaluation of HGB-E probability calibration;
- operational integrations for partner and internal rescue workflows;
- broader runtime rescue capabilities backed by tests;
- sustainability metrics backed by defensible source data;
- evaluation of real rescue and waste outcomes.
Afterlife AI started with a store-level observation: an item can fail its first selling path and still have useful value.
The current system plans that second path, records the evidence behind it, and lets the operator compare the plan with what happened afterward.
Afterlife AI
Give surplus inventory another useful life.
Built With
- css3
- fastapi
- github
- html5
- javascript
- jinja
- numpy
- openpyxl
- or-tools
- pandas
- pydantic
- python
- scikit-learn
- vercel

Log in or sign up for Devpost to join the conversation.