# QuantumSpectra — Domain flowcharts & report

_This document is generated from `backend/architecture.py` (single source of truth) · content hash `14d0f0ab5979384a…`_

## Domains

1. [Identity, Wallet & Ledger backbone](#backbone) — Every domain plugs into the same account, custodial wallet, hash-anchor ledger and role model.
2. [Hyperspectral scans, certificates & Safety Registry](#spectral) — Upload a cube or scene → indices, pesticide/MRL fingerprint, carbon credit or TBDY 2018 risk → certificate → public registry.
3. [İmece Commons — farm-to-fork market](#commons) — Coops list provenance-backed lots inside fair price bands; orders, levies, inspections and anomalies are anchored and audited.
4. [Collective Farming Pilot · CSA · budget tracker](#pilot) — One parameterised model drives 19 programme documents, the CSA, pickups, reminders and the budget-vs-actuals tracker.
5. [3-stage Quality QR passport & stall scanner](#quality) — Soil → raw produce → processed product: three graded scans, safety blockers, one QR; shoppers verify, rate and rank hubs.
6. [God's Eye — Justice Index](#justice) — Evidence from every domain is scored into four fairness pillars per city; citizens attest or dispute; Claude explains.
7. [Renewal Finance — earthquake-safe rebuild bonds](#renewal) — Case → appraisal → ML risk → underwriting → tradable renewal bond → staged draws → monthly coupons → retrofit schemes.
8. [Social Housing & Sustainable Donations](#social) — Municipal sites funded by wallet donations and pledges, allocated by a transparent need score, leased with anchored rent.
9. [9D BIM Tender Feasibility](#tenders) — Parse the IFC, score nine BIM dimensions, publish an auditable, anchored feasibility PDF.
10. [Rural Health research screening](#health) — Hyperspectral screening → triage → referral → outcome; verification loop, cohort model, follow-ups and equity alerts.
11. [Sustainable Mining & Kastamonu province](#mining) — Satellite + hyperspectral surveys, tailings/AMD alerts, critical-raw-material engineering, drill plans and a province report.
12. [Micronutrients, seed registry & value chains](#micro) — Seed lots to TTSM criteria, MAP quality, hemp & saffron value-chain planning, buyer bids and live prices.
13. [AI assistants, quantum & external integrations](#ai) — Claude Sonnet 5.5 / Opus 5.5 via the Emergent Universal Key for streaming assistants, explainers and translations; keyless public data; optional IBM Quantum.
14. [Disaster Governance — extreme scenarios on updatable 3D terrain](#disaster) — Wildfire, flood and landslide scenarios on a live-fetched, municipality-patchable DEM; district risk tables, pond siting, comparative mitigation analysis, anchored decisions.

<a id="backbone"></a>
## Identity, Wallet & Ledger backbone

**Every domain plugs into the same account, custodial wallet, hash-anchor ledger and role model.**

Users register with a role (farmer, cooperative, public authority, inspector, health worker, collective executive, admin, public viewer…). A custodial wallet (TRY balance, carbon credits, certificates) is created at sign-up; JWT sessions ride an httpOnly cookie with a CSRF origin guard. Every consequential record — scans, lots, trades, inspections, pilot inputs, pickups, closes — is SHA-256 anchored and the ordered anchors form passport hashes anyone can recompute in the browser. The ledger, marketplace listings and portfolio optimiser (classical or IBM Quantum QAOA when a token is present) sit on top.

```mermaid
flowchart LR
  u(["User / role"])
  reg["Register · login (JWT cookie)"]
  w[("Custodial wallet")]
  csrf{"CSRF origin guard · roles"}
  dom["Domain actions (scan, lot, pilot, case…)"]
  anc>"anchor_hash (SHA-256)"]
  led[("Ledger · passport hashes")]
  mk["Marketplace · invest"]
  opt[["Portfolio optimiser (QAOA | classical)"]]
  ver("Browser re-verification (WebCrypto)")
  u --> reg
  reg --> w
  reg --> csrf
  csrf -->|allowed| dom
  dom --> anc
  anc --> led
  w --> mk
  mk --> opt
  led --> ver
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class u actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class reg,dom,mk process;
  classDef data fill:#8A2BE222,stroke:#8A2BE2,color:#F8FAFC;
  class w,led data;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class csrf decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class anc anchor;
  classDef external fill:#F472B622,stroke:#F472B6,color:#F8FAFC;
  class opt external;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class ver output;
```

**Actors:** All roles · Admin (seeded)

**Pages:** `/login` · `/register` · `/wallet` · `/ledger` · `/marketplace` · `/dashboard`

**Key endpoints:**
- `POST /api/auth/register · login · logout`
- `GET /api/auth/me`
- `GET /api/wallet`
- `GET /api/ledger`
- `GET/POST /api/marketplace`
- `POST /api/marketplace/{id}/invest`
- `POST /api/marketplace/optimize`
- `GET /api/quantum/status · /jobs`
- `GET /api/stats/public`

**Collections:** `users (wallet.try_balance, carbon_credits)`, `login_attempts`, `certificates`, `carbon_records`, `marketplace`, `investments`, `ledger`, `quantum_jobs`

**Integrations:** JWT + bcrypt (auth) · Fernet-encrypted custodial keys · IBM Quantum Runtime REST (optional token; simulator fallback) · Resend e-mail

**Anchored:** wallet creation · every mint (certificate / carbon credit) → tx hash · ledger entries · all domain records via anchor_hash()

<a id="spectral"></a>
## Hyperspectral scans, certificates & Safety Registry

**Upload a cube or scene → indices, pesticide/MRL fingerprint, carbon credit or TBDY 2018 risk → certificate → public registry.**

A project (agriculture or structural) receives an uploaded hyperspectral file or a live Sentinel-2 scene found through the Element84 STAC API. The spectral engine computes vegetation indices, crop health, SWIR residue fingerprints vs MRLs, nutrient passports (N·P·K via HVIs → variable-rate prescription), or — for buildings — material/soil/structural indicators scored against TBDY 2018. Clean farms mint zero-carbon credits; compliant buildings mint safety certificates; both land in the owner's wallet, the public Safety Registry and an anchored PDF. Lab assays and core tests calibrate the models. Spectral results are SIMULATED research-grade values until live sensors stream.

```mermaid
flowchart LR
  own(["Owner / coop"])
  prj["Project (agri | structural)"]
  src[["Upload cube | STAC scene"]]
  eng["Spectral engine (indices · SWIR · TBDY)"]
  dec{"MRL clean? / TBDY compliant?"}
  cc>"Mint carbon credit / certificate"]
  alert("Contamination alert e-mail")
  reg[("Safety Registry (public)")]
  pdf("Anchored report PDF · Claude narrative")
  cal["Lab / core calibration"]
  vra("HVI → VRA prescription · strip trials")
  own --> prj
  prj --> src
  src --> eng
  eng --> dec
  dec -->|yes| cc
  dec -->|no| alert
  cc --> reg
  eng --> pdf
  cal -->|calibrates| eng
  eng --> vra
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class own actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class prj,eng,cal process;
  classDef data fill:#8A2BE222,stroke:#8A2BE2,color:#F8FAFC;
  class reg data;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class dec decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class cc anchor;
  classDef external fill:#F472B622,stroke:#F472B6,color:#F8FAFC;
  class src external;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class alert,pdf,vra output;
```

**Actors:** Farmer / building owner · Cooperative · Inspector · Analyst · Public (registry)

**Pages:** `/dashboard` · `/projects/:id` · `/registry` · `/field`

**Key endpoints:**
- `POST /api/projects · /upload · /projects/{id}/run`
- `GET /api/scans/{id}/pdf`
- `GET /api/satellite/search`
- `GET /api/scans/{id}/hvi · prescription.geojson · taskdata.zip`
- `POST/GET /api/scans/{id}/trials`
- `POST /api/scans/{id}/nutrients/calibration · materials/calibration`
- `GET /api/registry`
- `POST/GET /api/field/captures`

**Collections:** `projects`, `scans`, `files (object storage)`, `certificates`, `carbon_records`, `registry`, `strip_trials`, `calibrations`, `field_captures`

**Integrations:** Element84 Earth Search STAC (Sentinel-2, no key) · Emergent object storage · Claude Sonnet 5.5 report narrative · Resend certificate / contamination alerts · IBM Quantum (optional)

**Anchored:** scan hash → scan_anchor · certificate tx hash · carbon credit tx hash · calibration records · registry entries

<a id="commons"></a>
## İmece Commons — farm-to-fork market

**Coops list provenance-backed lots inside fair price bands; orders, levies, inspections and anomalies are anchored and audited.**

Per city, a price board sets farmer-floor and consumer-ceiling bands from live reference prices. Cooperatives list lots (optionally linked to a hyperspectral scan → verdict verified clean / flagged / blocked), buyers order from their wallet, and a small levy feeds the collective treasury that auto-supports coops, forecasts and disburses by proposal. Inspectors file inspections; anomaly detection flags out-of-band prices and recalls; everything appears in the audit trail and the public lot passport (QR, stall label PDF, shopper ratings with photos). Farmer-linkage levers and the policy-evolution panel close the loop with municipalities.

```mermaid
flowchart LR
  pb[("Price board · bands")]
  coop(["Cooperative lists lot"])
  scan{"Linked scan verdict"}
  lot[("Lot (clean | flagged | blocked)")]
  buy["Buyer orders from wallet"]
  levy>"Levy → collective treasury"]
  insp["Inspection · anomaly"]
  audit[("Audit trail")]
  pass("Lot passport · QR · stall label")
  fb(["Shopper rating + photo"])
  pol("Treasury support · policy evolution")
  pb --> coop
  coop --> scan
  scan --> lot
  lot --> buy
  buy --> levy
  levy --> pol
  lot --> insp
  insp --> audit
  lot --> pass
  fb -->|anchored| pass
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class coop,fb actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class buy,insp process;
  classDef data fill:#8A2BE222,stroke:#8A2BE2,color:#F8FAFC;
  class pb,lot,audit data;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class scan decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class levy anchor;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class pass,pol output;
```

**Actors:** Cooperative · Buyer (any user) · Inspector · Collective executive · Public shopper

**Pages:** `/commons (tabs: prices, lots, coops, schedules, audit, treasury, linkage, policy)` · `/passport/:lotId`

**Key endpoints:**
- `GET /api/commons/prices · /policy`
- `GET/POST /api/commons/coops · /lots · PATCH /lots/{id}/price`
- `POST /api/commons/orders`
- `GET/POST /api/commons/inspections · GET /anomalies · /audit`
- `GET /api/commons/treasury · /forecast · /avoided-costs · POST /treasury/disburse`
- `GET /api/commons/passport/{lot} · qr.png · label.pdf · POST feedback`
- `GET/POST /api/commons/linkage/requests`

**Collections:** `coops`, `lots`, `orders`, `price_changes`, `inspections`, `anomalies`, `treasury`, `treasury_proposals`, `lot_feedback`, `linkage_requests`

**Integrations:** Live FX / reference prices (Frankfurter, no key) · Emergent object storage (feedback photos) · Claude Sonnet 5.5 explainers

**Anchored:** lot creation · price change · order (tx + levy) · inspection · anomaly · feedback (rating + photo SHA-256) · → passport hash

<a id="pilot"></a>
## Collective Farming Pilot · CSA · budget tracker

**One parameterised model drives 19 programme documents, the CSA, pickups, reminders and the budget-vs-actuals tracker.**

Planners edit pilot inputs (Kastamonu — Taşköprü: 120 ha from 45 plots, Siyez / onion / salep split, members, solar kWp…). compute() derives rotation, nitrogen balance, drip/solar sizing, capex, ROI/NPV and the CSA box economics, so all 19 documents (legal, agronomy, infrastructure, economics, implementation, community, governance) always agree; Claude tailors narratives and translates to Turkish (cached, anchored). Households join the CSA from the handbook: anchored agreement, three wallet instalments relative to the join date, welcome e-mail. The member dashboard shows the pickup calendar; day-before reminders carry a signed QR that confirms collection in one tap and links the box to its quality passports; work-exchange hours are logged and coop-confirmed. Planners and coops log actuals against the phased budget, close months (immutable, anchored), request Claude variance commentary and export the status-report PDF.

```mermaid
flowchart LR
  pl(["Planner edits inputs"])
  mdl["compute(): rotation · N · drip/solar · capex · ROI"]
  docs("19 documents · TR via Claude · PDFs")
  hh(["Household joins CSA"])
  agr>"Agreement · 3 wallet instalments"]
  dash["Member dashboard · pickup calendar"]
  rem[["Day-before reminder + QR (cron)"]]
  pick>"Collect / donate · link quality passports"]
  hrs["Work-exchange hours → coop confirms"]
  act["Actuals vs phased budget"]
  close>"Monthly close (immutable)"]
  rep("Claude commentary · status PDF")
  pl --> mdl
  mdl --> docs
  docs --> hh
  hh --> agr
  agr --> dash
  rem --> dash
  dash --> pick
  pick --> hrs
  mdl -->|budget| act
  act --> close
  close --> rep
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class pl,hh actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class mdl,dash,hrs,act process;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class agr,pick,close anchor;
  classDef external fill:#F472B622,stroke:#F472B6,color:#F8FAFC;
  class rem external;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class docs,rep output;
```

**Actors:** Public authority / collective executive (planner) · Cooperative · CSA member household · Public (docs)

**Pages:** `/commons → Pilot programme` · `/commons/member` · `/pickup/:token`

**Key endpoints:**
- `GET /api/pilot · PUT /inputs`
- `GET /api/pilot/docs/{id}?lang= · /pdf · /pack.pdf · POST /tailor · /ask (SSE)`
- `GET /api/pilot/projection · POST /narrative`
- `POST /api/pilot/members/join · GET /me · POST /me/pay/{n}`
- `GET /api/pilot/members/me/dashboard · POST /me/pickups/{week} · /me/hours · /me/brief`
- `GET/POST /api/pilot/members/pickups/confirm/{token} · reminders/run`
- `GET /api/pilot/actuals · POST /entries · /close/{month} · /commentary · GET /report.pdf`

**Collections:** `pilot_programme`, `pilot_versions`, `pilot_tailored`, `pilot_translations`, `pilot_members`, `pilot_csa_ledger`, `pilot_pickups`, `pilot_pickup_reminders`, `pilot_hours`, `pilot_member_briefs`, `pilot_actuals`, `pilot_actuals_closes`, `pilot_actuals_commentary`

**Integrations:** Claude Sonnet 5.5 (tailor, brief, commentary, doc Q&A) · Opus 5.5 (long docs, translation) · Resend (welcome, pickup reminders) · ECB FX (EUR capex) · Platform cron pickup-reminders (daily)

**Anchored:** inputs version · document anchor · translation · CSA agreement + instalment tx · pickup (collect/skip/qr) · hours + confirmation · reminder dispatch · actuals entry · monthly close · commentary

<a id="quality"></a>
## 3-stage Quality QR passport & stall scanner

**Soil → raw produce → processed product: three graded scans, safety blockers, one QR; shoppers verify, rate and rank hubs.**

Issuers (coop, inspector, farmer, executive) create a batch for Siyez, onion or salep from a pilot block. The spectral engine grades the block soil (SOC, pH, N/P/K, salinity, heavy metals), the raw produce (MRL, defects, maturity) and the processed product (moisture, purity/adulteration, mycotoxin proxy) A–E; any safety-limit breach blocks the batch regardless of score. Each stage and the batch are anchored into a passport hash. A shopper scans the QR at the stall (camera, manual code or photo), re-computes the hash in the browser, reads the Claude explainer, rates the batch (hub-tagged, offline-queued) — ratings join the chain and feed the weekly Bayesian leaderboard of batches, hubs and products. Scans are SIMULATED until sensor feeds exist.

```mermaid
flowchart LR
  iss(["Issuer creates batch"])
  soil["Soil scan (block)"]
  prod["Produce scan"]
  proc["Product scan"]
  blk{"Safety limit breached?"}
  grade>"Overall grade A–E | blocked"]
  qr("QR passport")
  shop(["Shopper scans at stall"])
  ver["Browser hash check · Claude explainer"]
  rate>"Rating (hub-tagged, offline queue)"]
  lb("Weekly leaderboard · batches · hubs")
  csa[("Linked to member's box pickup")]
  iss --> soil
  soil --> prod
  prod --> proc
  proc --> blk
  blk --> grade
  grade --> qr
  qr --> shop
  shop --> ver
  ver --> rate
  rate --> lb
  qr --> csa
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class iss,shop actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class soil,prod,proc,ver process;
  classDef data fill:#8A2BE222,stroke:#8A2BE2,color:#F8FAFC;
  class csa data;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class blk decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class grade,rate anchor;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class qr,lb output;
```

**Actors:** Issuer (coop / inspector / farmer / executive) · Shopper (anonymous) · CSA member

**Pages:** `/commons → Quality QR` · `/quality/:batchId` · `/quality/scan` · `/quality/leaderboard`

**Key endpoints:**
- `GET /api/quality/meta`
- `POST /api/quality/batches · /batches/{id}/scan/{stage}`
- `GET /api/quality/batches · /batches/{id} · qr.png`
- `POST /api/quality/batches/{id}/explain · /feedback · /scan`
- `GET /api/quality/leaderboard?window=`
- `GET /api/quality/hubs · /hubs/{hub}/poster.pdf · POST /hubs/poster-pack/run · GET /hubs/poster-packs`

**Collections:** `quality_batches`, `quality_explanations`, `quality_feedback`, `quality_scans`

**Integrations:** Claude Sonnet 5.5 explainer · jsQR camera decoding (browser) · WebCrypto SHA-256 (browser)

**Anchored:** batch creation · each stage scan hash · re-scan events · feedback events · → passport hash

<a id="justice"></a>
## God's Eye — Justice Index

**Evidence from every domain is scored into four fairness pillars per city; citizens attest or dispute; Claude explains.**

The Utopian-Revolutionary Justice Framework aggregates anchored evidence — clean food share, price-band compliance, building safety, housing allocation fairness, mining adoption attestations — into pillar scores (0–100), an index, a grade and a rank per city, with coverage flags for missing data. Anyone can file a claim (attest / dispute / allocation / mining) that becomes a legitimate signal; Claude Sonnet 5.5 renders a plain-language explanation of each verdict without authority voice.

```mermaid
flowchart LR
  ev[("Anchored evidence (all domains)")]
  pil["4 pillars 0–100"]
  idx>"Index · grade · rank per city"]
  cov{"Coverage / missing data"}
  cit(["Citizen claim (attest | dispute)"])
  exp("Claude explanation")
  ev --> pil
  pil --> idx
  pil --> cov
  idx --> exp
  cit -->|signal| idx
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class cit actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class pil process;
  classDef data fill:#8A2BE222,stroke:#8A2BE2,color:#F8FAFC;
  class ev data;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class cov decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class idx anchor;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class exp output;
```

**Actors:** Any citizen · Municipality · Planners

**Pages:** `/justice`

**Key endpoints:**
- `GET /api/justice/index`
- `GET/POST /api/justice/claims`
- `POST /api/justice/explain`

**Collections:** `justice_claims`, `(reads: lots, orders, inspections, registry, social_housing, mining_sites …)`

**Integrations:** Claude Sonnet 5.5 explainer

**Anchored:** claims (attest / dispute) · verdict hash

<a id="renewal"></a>
## Renewal Finance — earthquake-safe rebuild bonds

**Case → appraisal → ML risk → underwriting → tradable renewal bond → staged draws → monthly coupons → retrofit schemes.**

A building owner opens a renewal case; appraisers review, a transparent ML model scores risk (model card published), and the public authority underwrites. Investors buy bond units from their wallet on the primary and secondary market (orders book); contractors request staged draws that planners approve; a platform cron pays coupons monthly. Retrofit schemes (with Grasshopper JSON export) and anchored case/retrofit PDFs document each step; the pipeline map shows cases by city.

```mermaid
flowchart LR
  own(["Owner opens case"])
  app["Appraisal review"]
  ml["ML risk score (model card)"]
  uw{"Authority underwrites"}
  bond>"Renewal bond · primary & secondary market"]
  inv(["Investors buy from wallet"])
  draw["Staged draws (request → approve)"]
  cup[["Monthly coupons (cron)"]]
  ret("Retrofit scheme · Grasshopper JSON")
  pdf("Anchored case / retrofit PDF")
  own --> app
  app --> ml
  ml --> uw
  uw -->|yes| bond
  inv --> bond
  bond --> draw
  bond --> cup
  uw --> ret
  ret --> pdf
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class own,inv actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class app,ml,draw process;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class uw decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class bond anchor;
  classDef external fill:#F472B622,stroke:#F472B6,color:#F8FAFC;
  class cup external;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class ret,pdf output;
```

**Actors:** Building owner · Appraiser / inspector · Public authority (underwriter) · Investor · Contractor

**Pages:** `/renewal`

**Key endpoints:**
- `GET /api/renewal/pipeline · /cases · /map · /schemes`
- `POST /api/renewal/cases · /appraisal/review · /underwrite`
- `POST /api/renewal/cases/{id}/bond/invest · /bond/orders · /bond/orders/{id}/buy · GET /bond/market · /holdings`
- `POST /draws/{stage}/request · /approve`
- `GET /api/renewal/ml/model-card · POST /ml/refresh`
- `GET /cases/{id}/report.pdf · /retrofit · /retrofit/report.pdf`
- `POST /api/cron/coupon-run`

**Collections:** `renewal_cases`, `bond_orders`, `bond_holdings`, `coupon_runs`, `retrofit_schemes`, `cron_runs`

**Integrations:** Platform cron monthly-coupon-run (1st, 06:00 UTC) · numpy logistic model

**Anchored:** case · appraisal · underwriting · bond purchase / order fill · draw approval · coupon run

<a id="social"></a>
## Social Housing & Sustainable Donations

**Municipal sites funded by wallet donations and pledges, allocated by a transparent need score, leased with anchored rent.**

Planners create sites (TBDY 2018 standards, funding stack) and advance construction stages. Anyone donates from wallet or pledges (shareable QR cards and pages drive campaigns). Households apply to the waiting list with a need-based priority score (income, children, earthquake victim, disability…); allocation happens when a site is occupied, with appeals that planners resolve and Justice claims can contest. Tenants sign anchored leases, pay monthly rent from wallet; the rent roll tracks arrears, a cron sends reminders, and a site's rent can be linked to a renewal bond.

```mermaid
flowchart LR
  pl(["Planner creates site"])
  don["Donations (wallet | pledge) · share cards"]
  stg["Construction stages"]
  wl[("Waiting list · need score")]
  alloc{"Allocation (occupied?)"}
  appeal["Appeals · Justice claims"]
  lease>"Anchored lease · monthly rent"]
  roll[["Rent roll · arrears · reminders (cron)"]]
  bond("Link to renewal bond")
  pl --> don
  don --> stg
  stg --> wl
  wl --> alloc
  alloc -->|contest| appeal
  alloc -->|yes| lease
  lease --> roll
  roll --> bond
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class pl actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class don,stg,appeal process;
  classDef data fill:#8A2BE222,stroke:#8A2BE2,color:#F8FAFC;
  class wl data;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class alloc decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class lease anchor;
  classDef external fill:#F472B622,stroke:#F472B6,color:#F8FAFC;
  class roll external;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class bond output;
```

**Actors:** Public authority / executive (planner) · Donor (any user) · Household applicant / tenant · Public

**Pages:** `/social-housing` · `/campaign/:siteId`

**Key endpoints:**
- `GET/POST /api/social-housing/sites · POST /sites/{id}/stage · /donate`
- `GET /sites/{id}/share · qr.png · card.png`
- `POST/GET /sites/{id}/waitlist · /allocate · /appeal · /resolve`
- `POST /sites/{id}/lease/sign · /lease/pay · GET /rent-roll · POST /link-bond`
- `POST /api/cron/rent-reminders`

**Collections:** `social_sites`, `donations`, `waitlist`, `allocations`, `appeals`, `leases`, `rent_payments`, `rent_reminders`

**Integrations:** Platform cron rent-reminders (5th, 06:30 UTC) · Resend

**Anchored:** site · donation · stage · waitlist application · allocation · appeal · lease · rent payment · reminder

<a id="tenders"></a>
## 9D BIM Tender Feasibility

**Parse the IFC, score nine BIM dimensions, publish an auditable, anchored feasibility PDF.**

Public authorities upload an IFC model; the parser extracts quantities and systems, and the 9D engine scores geometry, time, cost, sustainability, facility management, safety, acoustics, lean/logistics and circularity. The tender record and its PDF are anchored so bidders and auditors see the same assessment.

```mermaid
flowchart LR
  auth(["Authority uploads IFC"])
  parse["IFC parse · quantities"]
  nine["9D scoring"]
  rec>"Anchored tender record"]
  pdf("Feasibility PDF")
  auth --> parse
  parse --> nine
  nine --> rec
  rec --> pdf
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class auth actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class parse,nine process;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class rec anchor;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class pdf output;
```

**Actors:** Public authority · Bidders / public

**Pages:** `/tenders`

**Key endpoints:**
- `GET/POST /api/bim/tenders`
- `POST /api/bim/ifc/parse`
- `GET /api/bim/tenders/{id}/pdf`

**Collections:** `bim_tenders`

**Integrations:** IFC parsing (ifcopenshell-style text parse)

**Anchored:** tender · PDF hash

<a id="health"></a>
## Rural Health research screening

**Hyperspectral screening → triage → referral → outcome; verification loop, cohort model, follow-ups and equity alerts.**

Health workers screen patients with VNIR/SWIR indices (SIMULATED research model, not a medical device), get a triage level and clinic routing, and send a tokenised referral the clinic confirms; outcomes close the loop. Flags (cross-track leakage, outliers, SWIR without cube) enter a review queue for the on-call clinician; a transparent logistic cohort model is trained per oncology track. Women's-health follow-ups and village trend alerts run on crons with e-mail (SMS is MOCKED until Twilio keys exist); equity checks compare women's vs men's loop closure. Field visits, referral PDFs and the weekly digest complete the workflow.

```mermaid
flowchart LR
  hw(["Health worker screens"])
  idx["VNIR/SWIR indices (simulated)"]
  tri{"Triage · clinic routing"}
  ref>"Tokenised referral → clinic confirms"]
  out["Outcome closes loop"]
  rq["Review queue · on-call"]
  mdl["Cohort logistic model"]
  fu[["Follow-ups · village alerts (cron)"]]
  eq{"Equity check women vs men"}
  sms("E-mail · SMS (mocked)")
  dig("Weekly digest · PDFs")
  hw --> idx
  idx --> tri
  tri --> ref
  ref --> out
  idx -->|flags| rq
  rq --> mdl
  out --> fu
  fu --> eq
  eq --> sms
  mdl --> dig
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class hw actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class idx,out,rq,mdl process;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class tri,eq decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class ref anchor;
  classDef external fill:#F472B622,stroke:#F472B6,color:#F8FAFC;
  class fu external;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class sms,dig output;
```

**Actors:** Health worker · Clinic (referral token) · On-call clinician · Admin

**Pages:** `/health` · `/health/visits/:id` · `/referral/:caseId/:token`

**Key endpoints:**
- `POST /api/health/screen · GET /cases · /cases/{id}/timeline · POST /outcome`
- `GET/POST /api/health/referral/{case}/{token}(/confirm) · GET referral.pdf`
- `POST /cases/{id}/cube · GET cube/verify · /sensors · /devices`
- `GET/POST /api/health/oncology/queue · /oncall · /digest/send`
- `POST /api/health/oncology/model/train · /cases/{id}/risk`
- `GET /api/health/followups · /equity · /villages/trends · POST /visits`
- `POST /api/cron/daily-ops · /weekly-ops (manual: /maternity-followups · /equity-check · /oncology-digest)`

**Collections:** `health_cases`, `health_referrals`, `review_queue`, `oncology_models`, `followups`, `equity_alerts`, `village_alerts`, `visits`, `sms_log (mocked)`

**Integrations:** Claude Sonnet 5.5 case explainer · Resend · Twilio SMS (MOCKED — keys pending) · Platform crons daily-ops · weekly-ops · Emergent object storage (case photos, cubes)

**Anchored:** screening · referral token · outcome · review decision · model training · follow-up / visit

<a id="mining"></a>
## Sustainable Mining & Kastamonu province

**Satellite + hyperspectral surveys, tailings/AMD alerts, critical-raw-material engineering, drill plans and a province report.**

Sites are surveyed with Sentinel-2 scenes (STAC) plus a SIMULATED spectral model for minerals, tailings and land use; AMD escalation e-mails planners. The CRM inventory (Cu, Co, Au, Mn, Fe, Cr, magnesite…) feeds deterministic engineering — kriged resource classes, NPV at live metal prices (metals.dev if keyed, else keyless Yahoo + reference), cut-off and a budgeted next-N drill plan. The Kastamonu table and map layer let planners build sites from occurrences, sweep surveys, attach geo-tagged field photos (object storage) and publish the anchored province report PDF; adopting a site files a Justice attestation.

```mermaid
flowchart LR
  pl(["Planner creates site / builds from Kastamonu table"])
  sat[["STAC Sentinel-2 scene"]]
  sur["Spectral survey (minerals · tailings · land use)"]
  amd{"AMD escalation?"}
  al("Alert e-mail to planners")
  eng["Engineering: kriging · NPV · cut-off"]
  px[["Metal prices (metals.dev | Yahoo) · cron"]]
  drill>"Budgeted drill plan"]
  photo[("Geo-tagged field photos")]
  rep("Province report PDF (anchored)")
  jus>"Adopt → Justice attestation"]
  pl --> sat
  sat --> sur
  sur --> amd
  amd -->|high| al
  sur --> eng
  px --> eng
  eng --> drill
  photo --> rep
  drill --> rep
  eng --> jus
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class pl actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class sur,eng process;
  classDef data fill:#8A2BE222,stroke:#8A2BE2,color:#F8FAFC;
  class photo data;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class amd decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class drill,jus anchor;
  classDef external fill:#F472B622,stroke:#F472B6,color:#F8FAFC;
  class sat,px external;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class al,rep output;
```

**Actors:** Planner (authority / executive) · Any user (survey, photos) · Public

**Pages:** `/mining`

**Key endpoints:**
- `GET /api/mining/meta · /sites · /stats · POST /sites · /sites/{id}/survey · /adopt · PATCH /alerts`
- `GET /api/mining/crm · /inventory · /prices · POST /prices/refresh`
- `POST /sites/{id}/engineering · GET /drill-plan?budget_musd=`
- `GET /api/mining/kastamonu-minerals · POST /{row}/site · /kastamonu/survey-sweep`
- `GET/POST /kastamonu-minerals/{row}/photos`
- `GET /api/mining/kastamonu/report.pdf · /sites/{id}/report.pdf`
- `POST /api/cron/daily-ops (manual: /metals-refresh)`

**Collections:** `mining_sites`, `mining_surveys`, `mining_engineering`, `mining_prices`, `mining_price_alerts`, `mining_sweeps`, `mining_photos`, `mining_province_reports`

**Integrations:** Element84 STAC (Sentinel-2) · metals.dev (key pending) · Yahoo Finance fallback · Frankfurter FX · Emergent object storage (photos) · Claude Sonnet 5.5 site explainer (SSE) · Resend tailings / price alerts · Platform cron daily-ops (metals refresh)

**Anchored:** site · survey · engineering version · drill plan · sweep · photo (SHA-256) · province report (content hash)

<a id="micro"></a>
## Micronutrients, seed registry & value chains

**Seed lots to TTSM criteria, MAP quality, hemp & saffron value-chain planning, buyer bids and live prices.**

Hybrid seed lots are registered against TTSM criteria with hyperspectral micronutrient panels, calibrated by lab assays, published to a public registry with a tokenised verification link and an anchored certificate PDF. For Kastamonu hemp and Safranbolu saffron the value-chain engine splits each lot into products, prices them from the live feed (ECB FX × reference quotes, overridable by community quotes) and recommends the highest value-added route; the saffron optimiser and Open-Meteo harvest window plan the season, district hemp quotas are tracked. Buyers post bids on registry lots and product splits; owners accept or decline.

```mermaid
flowchart LR
  f(["Farmer registers seed / MAP lot"])
  mn["Micronutrient panel (TTSM criteria)"]
  cal["Lab calibration"]
  pub>"Publish → registry · verify token · certificate"]
  vc["Value-chain split (hemp · saffron)"]
  px[["Live prices (ECB FX × quotes)"]]
  route("Best value-added route · plan PDF")
  bid(["Buyer bids → owner decides"])
  opt("Saffron optimiser · harvest window · hemp quotas")
  f --> mn
  mn --> cal
  cal --> pub
  px --> vc
  vc --> route
  route --> bid
  pub --> bid
  route --> opt
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class f,bid actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class mn,cal,vc process;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class pub anchor;
  classDef external fill:#F472B622,stroke:#F472B6,color:#F8FAFC;
  class px external;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class route,opt output;
```

**Actors:** Farmer / cooperative · Lab · Buyer (public bids) · Executive

**Pages:** `/micronutrients` · `/seed/:lotId/:token` · `/offers`

**Key endpoints:**
- `GET /api/micro/catalog · POST /lots · /lots/{id}/calibration · /publish · GET /registry · /verify/{lot}/{token} · certificate.pdf`
- `GET /api/micro/lots/{id}/value-chain · /plan · /plan.pdf`
- `GET /api/micro/prices · POST /quotes`
- `GET /api/micro/offers · POST /bids · /bids/{id}/{decision}`
- `GET /api/micro/saffron/optimize · /harvest-window · /hemp/quotas · /hemp/flow`

**Collections:** `micro_lots`, `micro_calibrations`, `micro_registry`, `price_quotes`, `bids`, `hemp_quotas`

**Integrations:** Frankfurter ECB FX (no key) · Open-Meteo weather (no key) · Resend bid notifications

**Anchored:** lot · calibration · publish · certificate · bid decision

<a id="ai"></a>
## AI assistants, quantum & external integrations

**Claude Sonnet 5.5 / Opus 5.5 via the Emergent Universal Key for streaming assistants, explainers and translations; keyless public data; optional IBM Quantum.**

All narrative AI runs through emergentintegrations with the Universal Key: Sonnet 5.5 for quick grounded narratives (İmece assistant with live context and persisted sessions, Ask-the-Analyst, document Q&A, quality explainer, member brief, variance commentary, projection narrative) and Opus 5.5 for long documents and Turkish translations (cached per inputs version, anchored). Keyless public feeds supply satellite scenes (STAC), FX (Frankfurter), weather (Open-Meteo) and metal prices (Yahoo fallback). Resend delivers all e-mail; Emergent object storage holds photos, cubes and files. IBM Quantum runs via the Qiskit Runtime REST API only when a valid token is configured (simulator fallback otherwise); Twilio SMS and metals.dev stay mocked / fallback until keys arrive. Five platform crons (max) drive the work: pickup reminders (daily), a daily ops bundle (women's-health follow-ups · metals refresh · seasonal trial reminders), a Monday ops bundle (equity + village checks · oncology digest · stall poster pack), monthly coupons and rent reminders.

```mermaid
flowchart LR
  usr(["User question / page context"])
  ctx[("Live context from Mongo (pilot, membership, passports, prices)")]
  son[["Claude Sonnet 5.5 (stream, SSE)"]]
  sess>"Session persisted · anchored outputs"]
  opus[["Claude Opus 5.5 — long docs · TR translation"]]
  cache[("Cache per inputs version")]
  pub[["Keyless feeds: STAC · FX · weather · Yahoo"]]
  q{"IBM Quantum (token?) → simulator fallback"}
  cron[["Platform crons (≤ 5) → /api/cron/*"]]
  mail("Resend e-mail · object storage")
  mock("Twilio SMS · metals.dev (mocked / pending)")
  usr --> ctx
  ctx --> son
  son --> sess
  ctx --> opus
  opus --> cache
  pub --> ctx
  q --> ctx
  cron --> mail
  cron --> mock
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class usr actor;
  classDef data fill:#8A2BE222,stroke:#8A2BE2,color:#F8FAFC;
  class ctx,cache data;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class q decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class sess anchor;
  classDef external fill:#F472B622,stroke:#F472B6,color:#F8FAFC;
  class son,opus,pub,cron external;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class mail,mock output;
```

**Actors:** Every user (assistant) · Planners (narratives) · Platform (crons)

**Pages:** `Floating İmece assistant on Commons / Quality / Member pages` · `/dashboard Ask the Analyst`

**Key endpoints:**
- `POST /api/assistant/chat (SSE) · GET/DELETE /sessions/{id}`
- `POST /api/chat/stream · GET /history`
- `POST /api/pilot/docs/{id}/ask (SSE) · /tailor · /translations/warm`
- `POST /api/quality/batches/{id}/explain`
- `POST /api/mining/sites/{id}/explain (SSE)`
- `POST /api/cron/* (Bearer WEBHOOK_CRON_SECRET)`

**Collections:** `assistant_sessions`, `chat_history`, `pilot_translations`, `pilot_tailored`, `quality_explanations`, `cron_runs`

**Integrations:** Claude Sonnet 5.5 & Opus 5.5 (Emergent Universal Key) · Resend e-mail · Emergent object storage · Element84 STAC · Frankfurter ECB FX · Open-Meteo · Yahoo Finance (fallback) · IBM Quantum Runtime REST (optional) · Twilio SMS (MOCKED) · metals.dev (pending key)

**Anchored:** translations · tailored narratives · explanations · commentary · cron run records

<a id="disaster"></a>
## Disaster Governance — extreme scenarios on updatable 3D terrain

**Wildfire, flood and landslide scenarios on a live-fetched, municipality-patchable DEM; district risk tables, pond siting, comparative mitigation analysis, anchored decisions.**

Planners pick a preset (Kastamonu province ≈ 1 km cells, Kastamonu city basin ≈ 115 m) or any Türkiye bounding box; elevation is fetched from free AWS Terrarium tiles (Copernicus GLO-30 derived), cached and stored as a versioned DEM that can be patched with an uploaded XYZ / ASCII-grid / GeoTIFF after earthworks. Deterministic engines run in the backend: wildfire minimum-travel-time spread with Rothermel-style wind/slope factors over a proxy fuel map; SCS curve-number runoff routed by a 2-D storage-cell scheme (e.g. 200 kg/m² over the whole province → flood risk by district); infinite-slope landslide factor of safety with D8 debris runout. Results are arrival-time grids and quantised depth keyframes, replayed on the 3D terrain with a scrubber — simulation decoupled from rendering. Firebreaks and artificial ponds are compared against a baseline; a pond-siting report ranks sites near agriculture for low-cost irrigation and firefighting water; every scenario, terrain version and governance decision is hash-anchored and exported as a council-ready PDF.

```mermaid
flowchart LR
  pl(["Planner / municipality"])
  dem[("DEM v1 (Terrarium) → vN (uploads)")]
  lay["Static layers: slope · HAND · TWI · fuel · FS"]
  sim["Engines: fire MTT · flood CN+routing · landslide FS"]
  fr[("Arrival grids · depth keyframes")]
  view("3D terrain + scrubber (GPU textures)")
  dist["District risk table"]
  pond["Pond siting (irrigation · fire water)"]
  cmp{"Baseline vs mitigation?"}
  dec>"Governance decision (anchored)"]
  pdf("Council PDF")
  pl --> dem
  dem --> lay
  lay --> sim
  sim --> fr
  fr --> view
  sim --> dist
  lay --> pond
  dist --> cmp
  pond --> cmp
  cmp -->|adopt| dec
  dec --> pdf
  dist --> pdf
  classDef actor fill:#FB923C22,stroke:#FB923C,color:#F8FAFC;
  class pl actor;
  classDef process fill:#00FFFF22,stroke:#00FFFF,color:#F8FAFC;
  class lay,sim,dist,pond process;
  classDef data fill:#8A2BE222,stroke:#8A2BE2,color:#F8FAFC;
  class dem,fr data;
  classDef decision fill:#F59E0B22,stroke:#F59E0B,color:#F8FAFC;
  class cmp decision;
  classDef anchor fill:#00FF7F22,stroke:#00FF7F,color:#F8FAFC;
  class dec anchor;
  classDef output fill:#94A3B822,stroke:#94A3B8,color:#F8FAFC;
  class view,pdf output;
```

**Actors:** Public authority / municipality · Inspector · Collective executive · Admin · Public (viewer)

**Pages:** `/disaster`

**Key endpoints:**
- `GET /api/disaster/presets · terrain · terrain/{id}`
- `POST /api/disaster/terrain · /terrain/{id}/upload`
- `POST /api/disaster/scenarios · GET /scenarios · /scenarios/{id} · /report.pdf`
- `GET /api/disaster/terrain/{id}/ponds · ponds.pdf`
- `POST/GET /api/disaster/decisions`

**Collections:** `disaster_terrains (versioned DEM)`, `disaster_scenarios (frames, districts, summary)`, `disaster_decisions`

**Integrations:** AWS Terrarium elevation tiles (no key) · Emergent object storage (optional DEM archive)

**Anchored:** terrain version · scenario run · pond siting · governance decision

---

Node kinds: `actor` · `process` · `data` · `decision` · `anchor` · `external` · `output`
