GEstimator

Backend architecture and command contracts

Current contract, checked against source on 2026-11-23. Navigation: index · architecture · database format · frontend · MCP.

Ownership and module map

The backend is headless Python. Calculations, input validation, numbering, placement and persistence are not frontend responsibilities. Desktop commands and MCP adapters reuse the same service/editor operations.

Concern Owner
JSON Lines transport and error envelopes __main__.py
Owner thread, bounded queue and document routing runtime.py
Project lifecycle, analysis draft, revisions and orchestration service.py
Project transactions, compound operations and snapshot undo project.py
Read-only library attachment, catalog and notes libraries.py
Library import policies, staging and dependencies library_import.py
Measurement list/detail and item operations measurements.py
Record edits and record identities measurement_records.py
Records draft history and acceptance measurement_draft.py
Mapped worksheet helpers/import importing.py
Analysis workbook parsing/import analysis_import.py
Rate dependencies and recalculation rates.py
Ordered insertion and dependency-category placement insertion.py
Versioned row-transfer payloads clipboard.py
Search, notes and optional enrichment search.py, metadata.py
Saves, fingerprints, backups and recovery locks persistence.py
Reporting changes/deltas editor_changes.py
Analysis rules and template/settings validation analysis_rules.py, program_settings.py
ORM, analysis/measurement models and workbook output estimator/data/

Service and ProjectEditor are already large. A new domain concern belongs in a named handler with explicit editor/service context, not another unrelated branch in a router. Helpers must not create their own commit/history system. See the quality audit for remaining extraction work.

Library attachment/import methods on ProjectEditor are compatibility forwards. The editor retains attachment handles, selection helpers and transaction/history ownership. library_import stages the complete batch before placement and final rate policy; its dependency helper preserves prefixed, zero-quantity SUB ANALYSIS copies even when the corresponding source item is explicitly selected too.

Runtime and document sessions

One Runtime owns a queue (capacity 128) and a worker thread. Each open document has a separate Service, working database, drafts, revision and recovery identity. The runtime supports up to 32 sessions and keeps at least one open. Desktop requests identify their session. MCP dispatch selects the runtime’s active session; switching the active document advances the MCP project epoch.

HTTP request threads may parse/authenticate transport messages and serve static skill files. They must not call the ORM directly. Reads and writes that access projects join the owner queue. A queued timeout can cancel a request that has not started; an already executing write may still finish. Clients must read state before retrying after an uncertain transport result.

Desktop JSON Lines protocol

The sidecar accepts UTF-8 JSON objects, one per line. For example:

{"id":"request-1","method":"state","params":{},"session":"main"}

Responses contain the same id and either result or error: {code, message}. Long commands can emit {id, event: "progress", message} before their final response. Progress is not completion. Protocol errors use INVALID_REQUEST, file errors FILE_ERROR and unexpected failures BACKEND_ERROR; diagnostics go to stderr, not JSON stdout. Input lines are limited to 2,000,000 characters and request IDs to 100 characters.

Session methods (session.open/list/activate/close) are routed by Runtime. Project/analysis/library methods are routed by Service.call, with project operations forwarded to ProjectEditor.call. shutdown closes the runtime. There is no second public desktop RPC implementation or frontend calculation API.

Revisions and write boundaries

Desktop edits require the latest revision where checked by the service/editor. Read-only state and preview operations have their own routing and must stay read-only. Do not bypass revision checks to make stale UI edits appear to work. MCP’s optional if_revision is a separate public contract; its adapters inject current desktop revisions when they invoke application methods.

State being changed Boundary Acceptance/history
Analysis draft model/resources Service draft mutation/history Apply writes it to the working project; draft undo is separate from project undo
Working project rows ProjectEditor.mutate SQL transaction plus snapshot; bounded project history
Related multi-step project/MCP edits ProjectEditor.compound One outer transaction and project undo entry; preview restores transient state too
Open measurement records/properties/links MeasurementDraft.mutate Draft model and record IDs; Apply accepts as one project operation
Source project file Service save plus persistence helpers Conflict checks, staged file and backup; no live database write-through

Compound rollback restores more than SQL: analysis state, revision, dirty flags, clipboard, measurement IDs, draft state and histories matter. Keep nested operations inside their existing owner boundary. Use existing preview helpers or compound(..., preview=True) rather than editing and manually undoing.

Dirty analysis/record drafts protect navigation and conflicting mutations. discard intent and MCP discard_draft are explicit actions; a stale/failed write must retain the user’s typed value and recoverable work. Save/recovery can include pending drafts while preserving their live edit histories until success. Read database persistence before modifying any save path.

Calculation authority

ScheduleItemModel.evaluate_results remains the analysis authority. Row order matters:

Currency uses Decimal HALF_UP and supports the existing fractional-place rounding convention. Do not replace it with ordinary round, JavaScript money arithmetic or SQL floating-point totals. Rate dependency changes belong in rates.py and reuse the engine’s sub-analysis semantics. Batch related reads and writes; source databases and the SUB ANALYSIS dependencies are not editable UI copies to be changed opportunistically.

Numeric evaluation

NumericExpression owns the shared bounded AST syntax. numbers.decimal evaluates under a 40-digit Decimal context, keeps literal precision (at most 12 decimal places), and rounds computed entries to six places. evaluate_number retains legacy integer/float arithmetic for measurement templates and worksheet helpers. Trigonometric approximations are converted back to Decimal in modern entry; ordinary Decimal arithmetic and native Decimal math remain Decimal.

Supported functions, constants, positional arguments, angle units and limits are maintained once in the numeric-expression guide. Do not add eval, Python namespaces, object attributes or a parallel frontend parser. Distinguish named round() entry math from Currency/rate rounding. loose_number handles worksheet grouping and currency marks while preserving commas that separate function arguments.

Measurements and templates

The shared engine’s Measurement and trusted installed meas_templates own template calculations. template_loader validates names/paths and caches by content; each measurement still receives independent mutable template state. Do not load a project-supplied Python path. Presentation metadata lives in measurement_templates.py.

Preserve declared columns, read-only computed cells, dimensions, labels and raw expression strings. NLBH ignores zero factors; electrical point counts truncate toward zero; duct/steel templates have their own retained rounding. These are compatibility contracts, not opportunities to standardize all templates during an unrelated refactor. Serialization and link cleanup are described in the database format.

Extending a backend workflow

  1. Identify the domain handler and choose draft/project/compound ownership.
  2. Validate field types, bounds, selection and revision at the existing boundary. Keep request-specific limits with their schema/validator, not a generic limit copied from another command.
  3. Apply changes with the engine and existing handlers. Keep external libraries read-only; do not introduce a new ORM connection/thread for convenience.
  4. Return authoritative decimal strings, row IDs and warnings. Let the frontend render them; let MCP reuse the same operation.
  5. Test success and the relevant failure invariants: no partial writes, stable IDs, stale rejection, preview rollback, draft conflicts, undo/redo and save/reopen.

Start with calculation baselines, analysis parity, math expressions, project editors, records drafts, batch additions and document sessions, choosing tests for the changed concern. The testing guide defines the full checks and evidence to record.