Skip to content

About

LangGraph sUAS Open Source Intelligent Mission Plannter

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

sUAS Intelligent Mission Planner. Advisory only, not a clearance. Operational mode is unreachable.

sUAS Intelligent Mission Planner

Deterministic energy and performance feasibility for small unmanned aircraft. The language model writes prose; the calculator writes every number. Advisory only: today operational mode is unreachable.

CI Release v0.4.0-eval License: MIT Python 3.11, 3.12, and 3.13

What it is. Deterministic energy and performance feasibility for small unmanned aircraft. The language model writes prose; the calculator writes every number.

What it is not. It is explicitly not an airspace, NOTAM, or regulatory clearance tool. A GO means only that the energy budget and airframe envelope close. Today operational mode is unreachable.

Eval. The frozen mission pack and generated leaderboard live in eval/. One failure trace, Qwen no_tools on pack_procedure pp-01 from the 2026-11-14 run, is in eval/traces/. The writeup of both local-model runs is in eval/WRITEUP.md. The advisory demo and this frozen pack are pinned at tag v0.4.0-eval.

Warning

Advisory only, not a clearance. This is an energy and performance feasibility calculator. It is explicitly not an airspace, NOTAM, or regulatory clearance tool, and a GO means only that the energy budget and airframe envelope close. Today operational mode is unreachable: every plan comes back advisory, with blockers naming what is missing. See Advisory and operational.

An async AI orchestration and deterministic physics engine for small unmanned aircraft system (sUAS) flight planning. A LangGraph state machine coordinates validation, live weather, deterministic safety math, and a language-model safety brief. A Next.js dashboard drives it. The reference data covers a set of DIU/DCMA Blue UAS (NDAA-compliant) multirotor platforms.

62-second demo: catalog, an advisory plan, review, signature, brief, and a NO-GO when the energy budget does not close. No operational claim.

Full demo recording (62 seconds, WebM): catalog, an advisory plan, review, signature, brief, and a NO-GO when the energy budget does not close. No operational claim. Every on-screen number comes from the committed fixtures and the calculator. The GIF above is a compact copy of that recording.

Contents

Quickstart

Docker Compose, from the repository root.

Demo, no keys

cp .env.example .env
DEMO_MODE=true docker compose up --build

Open http://localhost:3000. Demo mode needs no model key, no API key and no weather provider. Every plan uses a fixed fixture reading tagged fixture, so the gate blocks operational (WEATHER_NOT_LIVE) and every plan is advisory. Never fly on a demo plan. With the stack up, python3 scripts/compose_smoke.py checks the catalog through the frontend against the frontend's types and walks plan, acknowledge and read-back. scripts/e2e.sh brings the stack up, runs the smoke and then a Playwright browser test of the same path, and tears it down. Both run locally; neither is a CI job.

Live weather

  1. Copy .env.example to .env and set at least POSTGRES_PASSWORD. Add OPENAI_API_KEY to enable the model narrative (optional).
  2. Run docker compose up --build.
  3. Open http://localhost:3000.

Without an OPENAI_API_KEY, the app still runs. The report node returns a deterministic go/no-go summary instead of a model narrative.

Architecture

  • Frontend. Next.js 15 (App Router, standalone output), React 19, TypeScript strict, TailwindCSS.
  • Backend. FastAPI on Python 3.11 to 3.13, fully async request path.
  • Orchestration. LangGraph 1.x StateGraph with a conditional edge and durable checkpointing.
  • Language model. langchain-openai ChatOpenAI, called with ainvoke, timeout, and bounded retries.
  • Database. PostgreSQL 16 via async SQLAlchemy 2.0 (SQLite for local and tests).
  • Migrations. Alembic, async-aware, verified against the ORM models in CI.
  • Persistence of graph state. AsyncPostgresSaver in production, InMemorySaver otherwise.
  • Observability. request correlation, JSON logs, Prometheus metrics, split liveness and readiness.
  • Deployment. Docker Compose with health checks and non-root images.

Graph design

The graph is defined in backend/suas/graph/. Nodes are built by factories that receive dependencies explicitly, so no node relies on global state and each is unit testable. The flow is a single column, so it stays readable on a phone:

  • START → validate
  • validate → weather when the setup is viable, otherwise straight to report
  • weather → calculations → cite_limits → human_ack
  • human_ack → report on confirm, back to calculations on edit, or END on abort
  • report → END

human_ack interrupts the run and waits for a person. The order is a security control rather than a workflow preference: the operator signs an assessment that neither retrieved text nor generated prose has touched, so nothing a model produces can change what was signed. See ADR-004. The report node has no tools bound, for the same reason. Both are pinned by tests that fail if the invariant is removed.

The dashboard holds the same line. While a plan awaits its signature there is no brief on screen, even if a response carried one; the review card shows only the sealed verdict, mode, limiting factors, calculator version and the full inputs hash it will sign. Editing any mission input after the assessment disables the confirm until the mission is analyzed again (frontend/src/lib/review.ts).

State and checkpoints

State holds only JSON-native values. Pydantic models are dumped to dictionaries before entering state, which keeps checkpoint serialization simple and safe. The container sets LANGGRAPH_STRICT_MSGPACK=true to restrict checkpoint deserialization to known-safe types.

Every request supplies a thread_id, or gets a server-generated UUID. A client-chosen id must match ^[A-Za-z0-9_-]{1,128}$ (else 422): : is reserved for the server's replan children, <id>:<n>, which belong to their parent's operator. GET, ack and replan accept any id up to 255 characters, so ids stored before that rule still resolve. The checkpointer persists state per thread, so GET /api/plan/{thread_id} can retrieve a prior assessment and a follow-up request can resume the same conversation. Checkpoints are written with durability="sync", so a crash between the assessment and the signature loses neither.

Authentication and the API key

The browser never holds a credential. It calls this app's own origin, and server-side Next.js route handlers under frontend/src/app/api/ proxy each request to the backend, attaching X-API-Key from BACKEND_API_KEY. That variable is deliberately not prefixed NEXT_PUBLIC_, so Next.js will not inline it into the client bundle.

This replaces an earlier arrangement where the key was read from NEXT_PUBLIC_API_KEY and shipped inside the JavaScript bundle, which meant enabling auth published the key to every visitor. Only the Next.js server needs network reach to the backend now; the backend does not have to be exposed to browsers at all.

Keys are per operator (#81). SUAS_API_KEYS=alpha:key-a,bravo:key-b gives each key an operator id; the older single SUAS_API_KEY still works as operator default. Each mission records the id of the key that planned it, and only that key can read, acknowledge or replan it. Asking with another key gets exactly the answer an unknown thread gets (found: false on GET, 404 elsewhere), so holding someone's thread id tells you nothing. A key list that repeats an id or a key refuses to start.

Each browser is its own operator (#82). The Next.js server gives every new browser a random 256-bit session id in an HttpOnly, SameSite=Strict cookie (Secure over HTTPS), and sends the backend session.<id>.<HMAC-SHA256(secret, id)> instead of a shared key. The backend checks the MAC with SUAS_SESSION_KEY_SECRET and scopes missions to that session, so two browsers cannot read, acknowledge or replan each other's threads. Neither the secret nor any derived key reaches the browser, and a POST whose Origin is not this app's is refused with 403 before it reaches the backend. The session is anonymous: clearing cookies loses that browser's threads, and there are still no accounts or roles.

Default Compose ships a public, demo-only secret so this works with no setup; the backend logs a warning while it is in use. Set SESSION_KEY_SECRET (32 or more random characters) before anyone else can reach the stack. Without BACKEND_SESSION_SECRET the proxy falls back to the single BACKEND_API_KEY.

Quality gates

Every job in .github/workflows/ci.yml, as of main today. A blocking job turns the run red when its rule fails; changes merge only on a fully green run. That is project practice: the branch ruleset does not yet list required status checks. Rules and rationale for each gate are in docs/engineering-practices.md.

  • backend (blocks). On Python 3.11, 3.12 and 3.13: ruff lint (including the bandit S rules), ruff format, mypy --strict, pytest with coverage at 80% or more, and migrations that apply and match the models.
  • postgres-integration (blocks). Real Postgres: migrations apply, the app boots end to end, /ready refuses an unmigrated database, and concurrent startup seeds all succeed.
  • calculator-version (blocks, pull requests only). A change to backend/suas/calculations/ must bump CALCULATOR_VERSION.
  • ub-mode (blocks). CRAP below 10 for every function in backend/suas, and no unlisted duplicate pair at 0.8 or above.
  • frontend (blocks). tsc, ESLint (cyclomatic complexity 10 or less, plus @next/eslint-plugin-next), the UI standard scan (docs/ui-standard.md), Prettier, Vitest (which includes axe-core over the planner page and a keyboard-only acknowledgment), production build.
  • docker (blocks on the build). Both images build. Its trivy scan of HIGH and CRITICAL findings is report-only (job summary).
  • workflow-lint (blocks). actionlint and zizmor over .github/: actions pinned to commits, no template injection, least-privilege tokens.
  • secrets-scan (blocks). gitleaks, a checksum-verified pinned release, over the full history.
  • mutation (report-only). Surviving mutants (mutator) in the changed backend modules, or the safety core on main.

Outside ci.yml, both report-only: audit.yml runs pip-audit and npm audit every Monday and on demand, and sbom.yml writes CycloneDX SBOMs of both images on each v* tag.

Run the gates locally

Backend:

cd backend
ruff check suas tests alembic scripts ../eval   # lint
ruff format --check suas tests          # formatting
mypy suas                               # strict type check
pytest -q --cov=suas --cov-fail-under=80
alembic upgrade head && alembic check   # migrations apply and match models
python scripts/smoke_check.py           # boots the real lifespan end to end

Frontend:

cd frontend
npm run typecheck
npm run lint
npm run lint:ui                       # UI standard scan (docs/ui-standard.md)
npm run format                        # prettier --check
npm test                              # vitest, covers the server-side proxy
npm run build

npm run lint includes @next/eslint-plugin-next 16.4.6 (recommended and core-web-vitals) under the existing ESLint 10 flat config. The app runs Next.js 15.5 and React 19; route-handler params are awaited. The plugin was already compatible with this stack, so it stays as enabled in #217.

Dependency audit, report-only (as audit.yml runs it weekly):

pip install -e ".[dev]"
pip-audit                             # runtime + dev, advisory

The performance model

The deterministic engine is an energy and performance feasibility calculator. It is explicitly not an airspace, NOTAM, or regulatory clearance tool: it knows nothing about controlled airspace, TFRs, or Part 107 altitude limits. A GO here means the energy budget and airframe envelope close, nothing more.

What the model accounts for:

  • Payload mass. All-up mass scales induced power by (m/m_ref)^1.5 (momentum theory).
  • Air density. Power scales by 1/sqrt(rho/rho_0), with density from the ISA relation at the mission's density altitude.
  • Density altitude. Computed at the operating altitude, surface temperature extrapolated up at the ISA lapse rate.
  • Wind. Cruise is flown at cruise_speed - wind_speed. Heading is unknown, so the full wind is assumed to be a headwind.
  • Climb. Hover power for the climb duration, plus mgh / efficiency.
  • Descent. Hover power for the descent duration. No credit for recovered energy.
  • Gusts. Checked against the airframe wind limit independently of sustained wind.
  • Temperature. Two-sided against the airframe envelope, and battery capacity is derated when cold.

Battery capacity derates linearly from 100% at 20 C to 65% at -10 C, flat outside that range. This is representative of the chemistry, not a measured curve for any specific pack.

Every one of these was absent in an earlier revision, and each omission biased the result toward GO. The choices above are deliberately conservative where the model is uncertain: worst-case headwind, no descent energy recovery, and the momentum-theory power law applied to cruise as well as hover.

Data provenance

Every numeric field in backend/suas/data/*.json carries its value, unit, source, confidence, and notes. The full inventory is generated into backend/suas/data/CITATIONS.md and a test fails if it drifts from the data.

  • datasheet. Read from the manufacturer's own published document. Good enough to fly on: yes.
  • flight_log. Measured from recorded flight telemetry. Good enough to fly on: yes.
  • secondary. Published figure from a specification summary, not the primary document. Good enough to fly on: no.
  • derived. Computed from other fields by a formula in the notes. Good enough to fly on: no.
  • estimate. An engineering estimate. Good enough to fly on: no.
  • unknown. Provenance not recorded. Nobody vouched for this number. Good enough to fly on: no.

As of this writing: 85 numeric fields across 8 airframes and 6 payloads; 51 are good enough to fly on (50 datasheet, 1 flight_log). The rest stay non-operational: 13 derived (for airframes still without a measured power log, hover_power_w = battery_wh / no_payload_endurance_hours and cruise_power_w = 0.90 * hover_power_w), 10 estimate, 5 secondary, and 6 unknown. The operational gate still refuses the lab pair because cruise power remains derived and cruise_speed_mps remains an estimate, and Blue-list snapshot checks still apply — see backend/suas/data/CITATIONS.md.

secondary is not a hedge. The figures below were gathered from published specification summaries rather than retrieved from the manufacturers' own documents, and recording them as datasheet would overstate what this project knows. The remaining non-operational fields, bucketed by source, are listed in CITATIONS.md. That inventory's durable ticket is #74, which stays open until those fields are promoted or a flight log settles them.

Operating temperature limits are published manufacturer figures:

  • Skydio X10D min_temp_c -20. Published range -20 to 45 C. Source: Skydio X10 specifications.
  • Skydio X2D min_temp_c -10. Published range -10 to 43 C. Source: Skydio X2 support documentation.
  • Parrot ANAFI USA min_temp_c -36. Published range -33 F (-36 C) to 122 F (50 C). Source: ANAFI USA product sheet 2023-02.
  • Teal Golden Eagle min_temp_c -35.6. Published range -32 F to 110 F (-35.6 to 43.3 C). Source: Teal Golden Eagle Operators Manual.
  • Freefly Astro Max min_temp_c -20. Published range -20 to 50 C. Source: Freefly Astro pilot's operating handbook.
  • Freefly Alta X min_temp_c -20. Published range -20 to 50 C. Source: Freefly Alta X specifications.
  • Inspired Flight IF1200A min_temp_c -10. Published range -10 to 40 C. Source: IF1200A Information Sheet v1.0.

Freefly_Astro_Max additionally carries pack_min_takeoff_c at 10 C.

Where the four documented conflicts stand

  • IF1200A max_temp_c. Promoted to datasheet 40 C (IF1200A Information Sheet v1.0).
  • ANAFI USA max_temp_c. Promoted to datasheet 50 C (2023-02 product sheet; resolves the prior 43/49/50 circulation).
  • IF1200A battery_wh. Promoted to datasheet 1420.8 Wh system energy: 2 x 710.4 Wh per-pack figure; airframe flies two packs.
  • Alta X power figures soft. Kept, discrepancy recorded. The stored hover figure implies ~20 minutes of endurance, which matches the published figure at a 20 lb load rather than the no-payload figure its own formula names. It is conservative, so it stays until a flight log settles it.

None of these became datasheet. Every figure above was obtained from a web search summary of the manufacturer's page, not by opening the page, so they are recorded as secondary with the URL and the caveat attached. The operational gate is unmoved, which is correct: a citation nobody has read is not evidence.

Freefly documents a separate battery procedure of 10 C minimum at takeoff for the Astro, well above the airframe's -20 C limit. That is modeled as pack_min_takeoff_c and checked as its own safety flag rather than folded into min_temp_c: they are different limits with different owners, and an airframe rated to -20 C can still have a pack that must not launch below +10 C. Ambient temperature stands in for pack temperature, which is conservative for the cold-soaked aircraft the procedure is written for.

The power fields are engineering estimates, not measurements. Replace them with real power logs before operational use, which POST /api/logs now makes possible. All payload power_draw_w values are estimates. For the authoritative live roster, cross-check bluelist.dcma.mil.

Degraded inputs

Weather has six explicit states, because "we could not reach the provider", "the provider answered with nonsense", and "this is a reading from forty minutes ago" are different situations an operator would act on differently.

  • live. Fetched now, parsed, complete. Operational: yes.
  • cached_fresh. A recent reading, still inside its freshness window. Operational: yes.
  • cached_stale. Past its window, used because the live fetch failed. Operational: no.
  • fallback. Defaults; the provider could not be reached. Operational: no.
  • error. Defaults; the provider answered and the answer was unusable. Operational: no.
  • fixture. A fixed demo-mode reading, never fetched (#97). Operational: no.

The rule the service exists to keep is narrow and absolute: a degraded reading must never be indistinguishable from a live one. Anything short of the top two sets degraded: true, names the state in warnings, and blocks operational mode. The dashboard shows the state as a chip in the weather table, each state in a treatment no other shares (green only for the two operational states, dashed for any reading not fetched now), and an amber banner.

Parsing is strict. A missing, non-numeric, NaN or infinite field makes the whole payload unusable rather than being quietly replaced with a default — substituting defaults is how a reading nobody measured ends up labeled live.

Timeouts are bounded twice: SUAS_WEATHER_TIMEOUT_S (default 3s) per request, and SUAS_WEATHER_DEADLINE_S (default 6s) across the whole operation including retries. Without the second, per-request timeouts multiply by the retry count and the endpoint hangs far longer than any single setting suggests.

Live readings are cached for SUAS_WEATHER_CACHE_TTL_S (default 600s) per ~1 km cell. With SUAS_WEATHER_CACHE_SHARED=true (the Compose default) the cache is a database table every worker shares, so a reading one worker fetched is cached_fresh in all of them (#85). Left off, each worker keeps its own cache in memory, which is the local default. Only live readings are cached; a degraded answer is never reused, and freshness is always judged from the reading's own fetched_at. A cached reading answers an outage as cached_stale only until SUAS_WEATHER_STALE_MAX_AGE_S (default 10800s, 3 h); past that the outage gets the same fallback or error reading an empty cache gives, and the retention pass deletes the shared row (a worker's own cache drops it on its next store).

Platforms and payloads

Reference data is bundled at backend/suas/data/ and is reconciled into the database on every startup. The bundled JSON is the source of truth: rows are matched by id and updated in place, so a corrected performance figure reaches an existing deployment on the next restart. Rows you add yourself that are not in the JSON are left untouched. Edit the JSON (or mount your own) to change the catalog; direct database edits are overwritten on the next boot.

The frontend fetches the catalog from the API at runtime, so the dropdowns cannot drift from the data the backend actually holds.

Aircraft: Skydio_X10D, Skydio_X2D, Parrot_ANAFI_USA, Teal_Golden_Eagle, Teal_2, Freefly_Astro_Max, Freefly_Alta_X, Inspired_Flight_IF1200A.

Payloads: None, FLIR_Hadron_640R, Sony_ILX_LR1, Nextvision_Raptor, Workswell_WIRIS_Ent, Trillium_HD40_LV.

The X10D carries an integrated sensor suite, so its external payload capacity is 0; pairing it with any payload other than None yields a negative payload margin and a NO-GO, which is the correct result. For a combination with real payload headroom, select Freefly_Astro_Max.

API

  • GET /health. Liveness. Touches no dependencies.
  • GET /ready. Readiness: database reachable, schema at the code's alembic revision, checkpoint store readable. Returns 503 otherwise; a missing model key does not count. See ops.
  • GET /metrics. Prometheus text exposition: request counts, latency, plan outcomes by granted mode, weather provenance, seal violations, lock contention (practices).
  • GET /api/aircraft. Selectable airframes. Drives the client dropdown.
  • GET /api/payloads. Selectable payloads. Drives the client dropdown.
  • POST /api/plan. Assess a mission; pauses for a person with awaiting_ack: true.
  • POST /api/plan/{thread_id}/ack. Confirm, edit, or abort the assessment the operator was shown.
  • GET /api/plan/{thread_id}. Persisted state of a prior mission thread.
  • POST /api/replan. Compare live telemetry against the briefed plan. No language model.
  • POST /api/logs. Ingest a CSV flight log; apply=true writes measured power figures.

Advisory and operational

assessment_mode is what you ask for. The backend decides what you get, and it fails closed: a gate condition it cannot verify counts against the plan. Today that means operational mode is unreachable on the public demo — every plan returns 200 with mode: "advisory" and blockers naming what is missing. Operational mode is off by default (assessment_mode defaults to advisory) and is only considered for one lab configuration, Freefly Astro Max + Sony ILX-LR1 (CONFIGURATION_NOT_LAB_OPERATIONAL otherwise). Even that pair cannot be granted operational on the bundled seed: cruise power is derived (POWER_NOT_OPERATIONAL_GRADE), cruise_speed_mps is an estimate (FIELD_NOT_OPERATIONAL_GRADE), and unless a snapshot has been pinned with refresh_blue_list.py, no Blue UAS snapshot is stored (BLUE_LIST_SNAPSHOT_UNAVAILABLE). A pinned snapshot older than SUAS_BLUE_LIST_MAX_AGE_S (default 7 days) is BLUE_LIST_SNAPSHOT_STALE. Advisory still runs. A fixture test pins the exact inputs that would clear the gate; the gate was not loosened to make the seed pass. An ungrantable mode is a downgrade with reasons attached, not a 409; see ADR-005. A mode that is not a valid value is still a 422.

The dashboard says so where it cannot be missed: whenever the sealed mode is advisory, or a replan since has raised any alert, a strip between the top bar and the panels reads "Advisory, not a clearance" with the mode and the weather source. It sits outside every scrolling panel, so scrolling the figures never takes it off screen, and a clean replan never removes it from an advisory plan.

Once a plan is signed, the review panel offers a live telemetry form (state of charge, remaining leg and hover, outside air, optional wind, payload attached; the payload box starts from what was briefed). Replanning puts a panel at the top of the assessment with each briefed figure beside its live one and the change between them: margin after mission, energy available, required and reserve, wind, and state of charge against the full pack the brief assumed. Its findings list each alert by code, label and message, and its verdict is advisory whenever the replan raised anything, whatever the plan was.

The planner needs no model key. Without one (or when the model fails) the backend writes a short deterministic brief, and the dashboard's "Safety officer brief" says so: "Deterministic: no language model wrote this brief." A brief a model did write is marked as one to check against the figures. The label comes from the response's report_source: model only for prose the model wrote and the seal kept, and deterministic for every brief written by code (no key, a failed model call, a brief the seal withheld for contradicting the assessment or stating an unsupported number, an abort, or no brief yet). While a plan is computing nothing claims a model is at work, a plan or acknowledgment that fails says what was not done (nothing computed, or the signature not recorded) with the raw reason beneath, and a plan with no figures says so instead of showing empty tables.

GET /api/plan/{thread_id} returns the persisted state for a prior mission thread, or found: false when the thread is unknown.

The shape of /api/plan, /api/plan/{thread_id}/ack and /api/replan is frozen in backend/tests/fixtures/api_contract.json. CI fails if a response field disappears or changes type, or a request gains a required field; adding an optional field does not. After a deliberate break, run python scripts/api_contract.py --write from backend/ (#115).

Every response carries an X-Request-ID header. Supply your own to correlate a client trace with server logs; one is generated when absent.

Planning: request, acknowledgment, and the assessment

POST /api/plan accepts a validated mission request and returns the go/no-go result, weather, deterministic calculations, a report, the thread_id, and any degraded-input warnings.

{
  "aircraft_id": "Skydio_X10D",
  "payload_id": "None",
  "mission_params": {
    "distance_m": 5000,
    "hover_time_s": 600,
    "target_altitude_m": 120,
    "elevation_m": 0,
    "latitude": 34.0,
    "longitude": -80.0
  },
  "thread_id": null,
  "assessment_mode": "advisory"
}

elevation_m is the launch point's elevation above sea level and target_altitude_m is the planned operating height above that launch point (AGL). Density altitude is reported for the operating altitude, not the field: the surface temperature is extrapolated upward with the ISA lapse rate before the deviation from standard is applied. Under a standard lapse rate that means planning h meters higher raises reported density altitude by exactly h.

POST /api/plan now returns with awaiting_ack: true and no brief. The run is paused at the review step until a person acts:

POST /api/plan/{thread_id}/ack
{ "action": "confirm", "actor": "dispatcher-1", "inputs_hash": "<from the plan response>" }

action is confirm, edit, or abort. inputs_hash is the assessment the operator was actually shown; if it no longer matches, the acknowledgment is refused with 409 rather than applied to numbers that changed underneath it. An edit (altitude, hover time, or payload) re-runs the calculator and pauses again, because a revision is a new thing to sign. An abort ends the run without calling the model at all. Confirmations are recorded against the thread with the actor, timestamp, assessment hash, and calculator version.

The response carries an assessment object, which is the authoritative decision: decision (go, no_go, or insufficient_data), the reasons behind it, the mode granted, any blockers, plus inputs_hash and calculator_version identifying exactly which numbers produced it. It is written by suas/calculations/ and never by the language model. is_viable remains as a derived alias for decision == "go".

Beside calculations, provenance says what each watt and watt-hour rests on. It has one entry per W or Wh figure, keyed by its path (effective_hover_power_w, energy_breakdown.cruise_wh, battery_check.margin_wh, and so on), with the weakest source and lowest confidence among the reference fields the figure was computed from, operational_grade (true only when every one of them is datasheet or flight_log), and those inputs. A figure computed from even one estimate is labeled as one, and the dashboard shows the label beside the number. Weather's own provenance is weather.source.

Each entry also carries basis: one record per input field, with the catalog's value, unit, source, confidence, source_url, retrieved_at and notes (value and unit are null when the catalog keeps no record, and the source is then unknown). In the dashboard, the basis label beside a figure opens a provenance drawer under the figures listing those fields: estimates are labeled "Estimate", unrecorded fields "Not recorded", a cited field links out to its document (http and https only), and retrieval times show in UTC. Escape or Close shuts it and puts focus back on the figure.

The acknowledgment can be done without a mouse. Tab reaches the advisory checkbox (Space ticks it), then Acknowledge and Abort (Enter activates them). Once a decision is recorded, focus moves to the note saying what happened, not to the page body. Once there is an assessment, the next Tab after Analyze is a "Skip to sign-off" link, hidden until focused, in the assessment header: Enter moves focus to the review panel, so the advisory checkbox and Acknowledge are the next two stops instead of every figure's provenance button. In Vitest, axe-core checks the page while an assessment awaits its signature, after signing, and with the drawer open. jsdom cannot measure color, so the NO-GO treatment's WCAG AA contrast is computed from the tokens in both themes (src/lib/contrast.test.ts).

Replanning in flight

POST /api/replan takes a telemetry snapshot from an aircraft already flying and compares it against the plan that was briefed.

{
  "thread_id": "<the briefed thread>",
  "ts": "2026-09-14T14:03:11Z",
  "latitude": 34.0, "longitude": -80.0, "alt_m": 100.0,
  "soc_fraction": 0.42,
  "remaining_leg_m": 1800.0,
  "remaining_hover_s": 60.0,
  "oat_c": 4.0,
  "wind_mps": 6.0,
  "payload_attached": true
}

remaining_leg_m is required rather than inferred from the briefed distance. An aircraft that has deviated, held, or been retasked is no longer flying the route it was briefed on, and assuming otherwise computes a residual for a mission nobody is flying.

The response carries the live energy picture, the briefed margin, and a list of alerts, each with briefed, live, and delta blocks so the recommendation can be checked rather than taken on faith:

  • ENERGY_BELOW_RESERVE (abort): land now.
  • ENERGY_NEAR_RESERVE (warning): land soon.
  • WIND_EXCEEDS_LIMIT (abort): land now.
  • SOC_STALE (watch): advisory only.
  • WEATHER_DEGRADED (watch): advisory only.
  • PAYLOAD_MISMATCH (watch): advisory only.

Three properties worth knowing. The briefed plan does not move: a replan runs on a child thread ({parent}:{seq}), so the assessment an operator signed stays addressable and unchanged. No language model is involved — this runs while an aircraft is airborne, which is the worst moment to wait on one or to let one influence what the operator is told. And any alert at all, including a watch, makes the replan advisory: an alert means something could not be confirmed, and an unconfirmed replan is advice rather than clearance.

Remaining capacity is derated for the temperature the aircraft reports, not the one it was briefed for, and the reserve is measured against that same derated capacity — a reserve computed on nameplate watt-hours is not a reserve on a cold day.

Flight logs

POST /api/logs?airframe_id=<id> takes a CSV flight log as the request body and derives measured hover and cruise power from it. This is the only way a figure in the reference data can become source: flight_log, which is one of the two sources the operational gate accepts.

curl -X POST "http://localhost:8000/api/logs?airframe_id=Freefly_Astro_Max&apply=true" \
  -H "Content-Type: text/csv" -H "X-API-Key: $SUAS_API_KEY" \
  --data-binary @your-flight.csv

timestamp and alt_m are required; power_w, or voltage_v and current_a together, supply the power figure. The full column list, units, and what gets rejected are in backend/tests/fixtures/logs/README.md.

Ingesting is not applying. An upload always stores the log and reports the estimates. apply=true additionally writes them into the airframe's reference row, and only for fields with at least 30 selected samples. Changing a number that plans are built on should be a deliberate act, not a side effect of uploading a file.

What a hover window means. A sample counts toward hover power only if it is not labeled climb, descent, or cruise, and its measured vertical rate is within ±0.5 m/s, and its speed is at or below 1.5 m/s. The label alone is not enough: a row marked hover while the aircraft was climbing is excluded on its measured rate, because averaging climb power into a hover figure understates hover draw, which understates the energy budget, which biases the decision toward GO. Cruise is the mirror image — level within ±1.0 m/s and at or above 3.0 m/s.

The estimator reports the median rather than the mean, with the interquartile range and a sample count beside it, because a log routinely contains brief spikes that a mean would let move the figure.

PX4 .ulg logs are converted first, on a workstation, with backend/scripts/ulog_to_csv.py. The script sums every battery pack, prefers vehicle_local_position, and falls back to barometric altitude plus EKF velocity when that topic is missing. Pack serials and vehicle identifiers are left in the ULog; they never appear in the CSV. Install the optional ulog extra (pip install -e '.[ulog]' or .[dev]) to get the pinned pyulog and numpy the script needs.

Citations

After the calculator runs and before the operator signs, cite_limits attaches evidence for the limits the assessment used. Citations explain a decision; they never change one. The assessment is already sealed by the time retrieval runs, and retrieval being unavailable leaves the plan unconfirmed rather than blocked — the corpus is not the oracle (ADR-003).

Queries are built from the field being cited and the airframe configuration, never from the operator's free text. Both retrieval legs carry the same filter, so fusion cannot mix airframes: returning the Astro's pack limit as evidence for an ANAFI would be worse than returning nothing, because a plausible wrong limit reaches a human as evidence.

Evidence reaches the model inside a per-request nonce fence, and is cited by chunk id — the model never sees or emits a URL. A static delimiter would be guessable by anyone reading this repository.

The embedding model is pluggable. SUAS_EMBEDDING_PROVIDER=http points at a service such as services/embeddings/, which is deployable as its own Railway service; the default is a lexical hashing projection that runs anywhere and understands nothing. Deployment is documented in docs/railway.md.

The document corpus

Manufacturer documents that back a citation live in corpus/, and nothing enters it because it happens to be on disk. A file is ingested only if corpus/manifest.json names it, its bytes hash to the recorded sha256, and its source_url host is in the allowlist. Adding a source is a reviewed commit, not a file copy.

python3 backend/scripts/ingest_corpus.py --corpus corpus

Ingest is offline by design. The API process never parses a document, and a test asserts the request path does not import the ingest code.

Every chunk is screened before it is stored. Invisible characters are stripped, the text is NFKC-normalized, and HTML and markdown link syntax is removed — in that order, before the content is matched against anything. Zero-width joiners and bidirectional overrides exist to make two different strings look identical to a person and different to a matcher, so a screener that runs after hashing can be walked straight past.

A chunk carrying something that reads as an instruction to a model is quarantined, never dropped:

datasheets/freefly-astro-pack-limits.txt: 4 chunks, 1 quarantined (20.0%)
    tripwire: 'Ignore previous instructions'

Discarding it silently would remove a paragraph of a manufacturer's document without anyone knowing a limit had gone missing. The paragraph is kept with the pattern that caught it, and the configuration it belongs to gains the CORPUS_QUARANTINED blocker: paperwork containing something that reads as an attack is not paperwork to fly on until a person has looked at it. Other configurations are unaffected.

GET /metrics reports suas_corpus_quarantine_open. The tripwire is a heuristic and will occasionally fire on an innocent sentence in a real manual — that is why it quarantines rather than deletes, and why the rate is worth watching. A tripwire nobody trusts gets switched off, which is worse than not having one.

Configuration

Backend variables use the SUAS_ prefix. Compose maps friendly names to them.

All variables
  • SUAS_DATABASE_URL (default sqlite+aiosqlite:///./suas_local.db). Async SQLAlchemy URL. Postgres enables the durable checkpointer.
  • SUAS_OPENAI_API_KEY (default empty). Enables the model-generated report.
  • SUAS_DEMO_MODE (default false). Fixture weather instead of the live provider; every plan advisory. Compose: DEMO_MODE.
  • SUAS_OPENAI_MODEL (default gpt-4o-mini). Chat model name.
  • SUAS_LANGSMITH_TRACING (default false). Opt-in LangSmith tracing; needs SUAS_LANGSMITH_API_KEY. Coordinates and all text are redacted unless SUAS_LANGSMITH_REDACT=false (local only). See docs/ops.md#tracing.
  • SUAS_API_KEY (default empty). When set, planning endpoints require header X-API-Key. Known as operator default.
  • SUAS_API_KEYS (default empty). Per-operator keys, id:key,id:key. A mission is visible only to the key that planned it.
  • SUAS_RETIRED_API_KEYS (default empty). Rotation overlap, id:old-key@expiry: the old key keeps working until the expiry, only from the client IP that last used it. See docs/ops.md, Key rotation.
  • SUAS_RETIRED_KEY_MAX_GRACE_S (default 3600). Latest allowed expiry for a retired key, in seconds from startup.
  • SUAS_TRUSTED_PROXIES (default empty). Peer IPs whose X-Forwarded-For is believed. Empty trusts none.
  • SUAS_SESSION_KEY_SECRET (default empty). Enables per-browser operators: verifies the proxy's signed session keys. 32+ characters. Compose defaults to a demo-only value.
  • SUAS_CORS_ORIGINS (default http://localhost:3000). Comma-separated allowed origins. Only needed for non-browser clients now that the UI proxies server-side.
  • SUAS_LOG_LEVEL (default INFO). Root log level.
  • SUAS_JSON_LOGS (default true). Emit structured JSON logs. Set false for readable local output.
  • SUAS_BATTERY_RESERVE_PERCENT (default 20). Reserve withheld from usable battery capacity.
  • SUAS_VERTICAL_SPEED_MPS (default 3). Assumed climb and descent rate.
  • SUAS_CLIMB_EFFICIENCY (default 0.6). Propulsive efficiency for the climb energy term.
  • SUAS_CHECKPOINT_RETENTION_DAYS (default 30). Age at which graph checkpoints are purged. 0 disables retention.
  • SUAS_RETENTION_INTERVAL_S (default 3600). How often each worker repeats retention after startup.
  • SUAS_RATE_LIMIT_REQUESTS (default 30). Requests allowed per window, per client (per worker unless shared). At least 1; limiting cannot be switched off.
  • SUAS_RATE_LIMIT_WINDOW_S (default 60). Rate limit window in seconds.
  • SUAS_WEATHER_STALE_MAX_AGE_S (default 10800). Oldest cached reading an outage may fall back to as cached_stale; older is answered as no cache and pruned. At least SUAS_WEATHER_CACHE_TTL_S.
  • SUAS_BLUE_LIST_MAX_AGE_S (default 604800). Age of the pinned Blue UAS snapshot at which operational clearance would describe the past (7 days). Advisory still runs.
  • SUAS_BLUE_LIST_SNAPSHOT (data dir default). Path to the hashed snapshot written by backend/scripts/refresh_blue_list.py. A missing file is unavailable, not stale.
  • SUAS_WEATHER_CACHE_SHARED (default false). Keep weather readings in the database so all workers share one cache. Compose sets true.
  • SUAS_RATE_LIMIT_SHARED (default false). Keep the budget in the database so all workers share one ceiling. Compose sets true.
  • BACKEND_API_URL (default http://localhost:8000). Backend URL as reached by the Next.js server, not the browser.
  • BACKEND_API_KEY (default empty). Sent upstream as X-API-Key by the server-side proxy. Never exposed to the client.
  • BACKEND_SESSION_SECRET (default empty). Same value as SUAS_SESSION_KEY_SECRET. When set, each browser gets its own session cookie and operator, taking precedence over BACKEND_API_KEY. Server-only.

Local development

Backend:

cd backend
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
alembic upgrade head                 # optional locally; the app can self-create schema
uvicorn suas.main:app --reload        # serves on :8000, defaults to local SQLite

Frontend:

cd frontend
npm install
npm run dev                           # serves on :3000

Optional git hooks:

pre-commit install

Documentation

The 90-day plan for taking this from a working demo to a system whose numbers can be defended lives in docs/PLAN-90.md. Supporting specifications:

To add a mission to the frozen eval pack, open a Good first fixture issue from .github/ISSUE_TEMPLATE/good-first-fixture.yml. Expected values are regenerated with python3 backend/scripts/generate_eval_fixtures.py --write; never hand-edit eval/fixtures/missions.jsonl.

The organizing rule across all of it: the language model writes prose, and backend/suas/calculations/ writes every number that can keep an aircraft in the air.

Operations and limitations

Known limitations

  • Python 3.10 is not supported. The floor is 3.11, which is what makes enum.StrEnum and datetime.UTC available to this codebase. The production image still pins python:3.11-slim, the floor of the supported range, so CI exercises a wider range than the container runs.
  • No dependency-audit gate. pip-audit --strict failed regularly on transitive advisories outside this project's control, so it does not block a merge. audit.yml runs pip-audit and npm audit every Monday and on demand, report-only; run pip-audit before a release as well.
  • Some practices are not gates yet. The Aspirational list says which. The branch ruleset lists no required status checks, so "merge only on green" is held by people. No job holds calculations/ at 95% coverage (only the repo-wide 80%), graph tests run on SQLite rather than Postgres, nothing enforces the second reviewer the review bar asks for on safety code, and the frontend's CRAP is not measured. Mutation, image scan, dependency audit and SBOM are report-only.
Operational notes
  • One rate-limit ceiling across workers, when shared. With SUAS_RATE_LIMIT_SHARED=true (the Compose default) every worker draws on one budget kept in the database, so the ceiling is SUAS_RATE_LIMIT_REQUESTS whatever the worker count (#84). Left off, each worker keeps its own budget in memory and the ceiling is that times the worker count; that is the local default, where one process needs no shared state.
  • Resuming an interrupt is not per process. Two workers handed the same acknowledgment serialize on a per-thread mutex and a FOR UPDATE row lock; one proceeds, the other gets 409. Measured, not assumed: see docs/ops.md.
  • Load and crash-recovery figures are recorded in docs/ops.md, including the concurrency at which this service stops keeping up and the kill -9 drill transcript. Reproduce with python3 backend/scripts/load_plan.py --requests 100 --concurrency 100.
  • Metrics are per process too. Scrape every replica and aggregate in Prometheus rather than assuming one endpoint reports the whole fleet.
  • Migrations are a deploy step, not a restart side effect (#87). The image's entrypoint (backend/scripts/docker-entrypoint.sh) serves without touching the schema. Compose runs a one-shot migrate service (docker-entrypoint.sh migrate) before the backend, Railway runs preDeployCommand from railway.json, and anywhere else runs docker-entrypoint.sh migrate once per release. MIGRATE_ON_START=true upgrades before serving, for a single local container only. Upgrades hold a Postgres advisory lock, so concurrent ones serialize, and /ready stays 503 until the schema is at the code's revision. See ops: Migrations for rollback.
  • Reference power figures are estimates. See Data provenance. Swap in measured values before relying on the energy budget operationally. Edit backend/suas/data/*.json; the change is applied on the next restart.
  • Retention runs at startup and then every SUAS_RETENTION_INTERVAL_S (default 3600s) in every worker, so no restart or external scheduler is needed (#86). Threads older than SUAS_CHECKPOINT_RETENTION_DAYS are purged with their replan children through the checkpointer's own API, capped at 1000 threads per pass; each thread is claimed by one worker. Idle shared rate-limit rows and weather readings past SUAS_WEATHER_STALE_MAX_AGE_S are pruned too. Failures are logged and never stop the app.
Coding standards

All Python, JavaScript, and TypeScript follows a strict, safety-critical style adapted from NASA's Power of Ten: simple control flow, minimal shared state, no unsafe features, tight scoping, static analysis with no suppressions in domain code, no deep recursion, small single-purpose functions, explicit data shapes, standardized error handling, and no builtin or prototype mutation. Configuration lives in backend/pyproject.toml (ruff + mypy strict) and frontend/eslint.config.mjs plus frontend/tsconfig.json.

Narrow, documented exceptions: two thin LangGraph wiring modules relax specific mypy generic-interop codes, Alembic's generated migration environment is excluded from strict typing, and CI scripts may write to stdout. All domain logic (calculations, schemas, services, database, API) stays fully strict.

Project structure
backend/
  alembic/          async migration environment and versioned migrations
  scripts/          entrypoint, smoke check, backup and restore, corpus ingest, load test, generators, CI helpers
  suas/
    api/            routes, security, rate limiting, observability, error handlers
    calculations/   pure physics, battery, and assessment functions
    data/           bundled Blue UAS aircraft and payload reference data
    db/             async engine, ORM models, repository, seed
    graph/          state, nodes, checkpointer, workflow
    schemas/        pydantic domain, request, and response models
    services/       async weather and report clients
    config.py       typed settings
    logging_config.py  JSON formatter and request-id correlation
    main.py         app factory and lifespan
  tests/            unit, service, graph, observability, and API tests
frontend/
  src/
    app/
      api/          server-side route handlers that proxy to the backend
      components/   UI components
    lib/            typed API client, catalog hook, geolocation, shared types
      server/       backend proxy; the only reader of the API key
corpus/             manifest-listed manufacturer documents for citations
attic/              earlier repositories that fed this one, and what they contributed
docs/               plan, practices, threat model, ADRs, runbooks
eval/               frozen mission pack, retrieval evaluation, committed 2026-11-14 and 2026-11-15 local-model results, one published failure trace, and the eval writeup (offline by default; a real model is optional via `--provider openai` and `SUAS_EVAL_BASE_URL`; scored decision, mode, and figures come from the sealed calculator)
scripts/            Compose smoke test, pinned trivy installer, backlog filer
services/
  embeddings/       optional embedding service for retrieval
docker-compose.yml

License

MIT © 2026 Matthew K.

Blue UAS names in the bundled reference data identify published platforms. They are reference data, not an endorsement by those programs, the manufacturers, DIU, or DCMA. A GO from this calculator is not a flight authorization.

About

LangGraph sUAS Open Source Intelligent Mission Plannter

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages