Architecture Decisions
See ROADMAP.md for versioned milestone planning. This file records decisions
and rationale after architecture direction is chosen.
2026-08-25
Base Launch Control leases grant permission to perform optional work. Enhancement leases are a separate binary, bounded allocation of additional work quality available only to an already-admitted subsystem. Enhancement never creates independent authority. Launch Control consumes the existing Resource Governor snapshot, ranks cheap owner-published demand, and allocates at most two enhancements; domain managers still define and execute the work.
Enhancement capacity is zero unless the CPU governor is open with at least a
moderate work horizon and a healthy/abundant commanded tier. Moderate abundance
provides one slot; abundant CPU with an extended horizon provides two. Memory
critical forces zero capacity. Memory elevated still permits the current
bounded compute work and fixed-size conclusions because no consumer adds
long-lived historical resolution. This preserves a future
compute-versus-retention distinction without introducing retention leases now.
Part 2 derives enhancement participation from the canonical six
cpuWorkClasses rather than a second hard-coded owner list. Existing
Infrastructure and Logistics records and lifecycle counters migrate in place;
the four new current-state records initialize empty. Intelligence may process
at most four strategically relevant early reassessments after 25 ticks while
its ordinary 50-tick refresh remains unchanged. Scouting compares at most four
already-authorized targets and never enlarges its four-room/16-candidate
frontier or population. Remote Development may reconsider at least two
existing candidates after 25 rather than 50 ticks, without changing active
room or workforce caps. Mineral Development may inspect at most 32 existing
planning entries to retain one fixed summary of at most four changed
Extractor/Container prerequisite records; Infrastructure approval and
execution remain authoritative.
All existing Launch Control work classes can compete for enhancement capacity, but only while independently base-admitted and only when the owning manager publishes real marginal work. Enhancement improves bounded work quality; it never creates strategic or execution authority. Scouting enhancement explicitly preserves the bounded frontier policy.
Leases last 25 ticks, require a request no more than one tick old, and end immediately when their base lease, useful request, or resource capacity disappears. Existing base priority, urgency, bounded wait, least-recent grant, and fixed class order provide deterministic ranking and rotation. Capacity may remain unused. Infrastructure raises dirty-domain analysis from two to four and local route path calculations from one to two; every existing approval, revision, legality, placement, and safety gate remains authoritative. Logistics may perform a material-evidence-triggered network reevaluation after at least 10 ticks, still on the existing deterministic room stagger; its ordinary full evaluation interval remains 25 ticks.
CPU and Memory are sibling resource signals beneath a lightweight Resource Governor coordinator. The existing CPU policy remains unchanged and Launch Control remains the sole allocator of optional-work leases. Resource governors describe pressure and capacity; they do not own strategic policy. Domain owners retain sole authority over the meaning of their persistent state and over which parts, if any, are safely reconstructible.
The Memory Governor samples the incoming serialized RawMemory length every
250 ticks. It retains the last evaluation tick and byte sample, normalized
bytes-per-tick growth, a 0.2 growth EWMA, the current pressure state, and
compact reclamation counters/timestamps. Pressure is healthy below 1,500,000
bytes, elevated from 1,500,000 bytes, and critical from 1,800,000 bytes.
Evaluation performs one raw-string length read and no recursive Memory scan;
stats and debug surfaces only project the persisted result.
CIA is the first reclamation participant. During an elevated evaluation it may
inspect at most four dossiers and reclaim at most four ciaEvents entries at
least 5,000 ticks old; critical pressure raises both bounds to eight and shortens
event grace to 1,000 ticks. CIA owns a single continuation cursor. The governor
does not know the Memory.rooms path. Current observations, ownership,
assessments, confidence, hostile facts, resource surveys, operations, operator
overrides, and all other dossier state are authoritative or conservatively
protected. CPU recovery or emergency never expands the scan.
Screeps Memory retains historical information only when autonomous decisions
need it. Human-oriented operational history is projected through
Memory.stats and retained downstream in Graphite/Grafana instead of growing
indefinitely in game Memory. Enhancement allocation retains only six fixed
current class records plus cumulative grant/revocation counters; time series
remain downstream in Graphite/Grafana.
Milestone 0.4.3 introduces DepositOperationsManager as a dedicated transient
runtime authority rather than expanding RemoteOperationsManager into a
universal executor. The MVP admits one exact operator-approved opportunity and
one globally live deposit operation, owned under its home room. Approval only
creates preparing state; current CIA/live deposit, route, risk, economy,
essential-workforce, CPU, lifetime, cooldown, yield, and actual-body economics
must still pass before Spawn Manager commits energy.
The first workforce is one bounded self-hauling depositHarvester. Three small
deterministic WORK/CARRY/MOVE templates cover short, standard, and longer routes;
the selected parts derive the persisted cost, spawn ticks, carry capacity,
replacement lead time, and admission economics. Replacement is requested only
after the same actual-body investment remains repayable. No Containers, highway
Road construction, builders, escorts, Market execution, or permanent
infrastructure are authorized.
Deliberate economic abandonment is successful operation behavior. A still-live
deposit may enter winding-down when cooldown, lifetime, yield, demand/value,
economy, CPU, or risk evidence no longer supports another cycle or replacement.
The worker stops harvesting, evacuates typed cargo to owned Storage or Terminal,
and only then allows completion and bounded retirement.
Deposit transport is represented by the shared resource-typed logistics route
contract while the MVP worker executes both production and carrying. Generic
carry/capacity aggregates may include all resources, but energy-named aggregates
now filter for RESOURCE_ENERGY; mist, biomass, metal, and silicon can no longer
inflate demandEnergy. General multi-operation allocation and competition remain
deferred to 0.4.4.
As an interim step before the broader external-operation allocator, deposit
admission has a persistent global operator-approved / autonomous authority
mode. Autonomous mode is the default and may create only the existing
one-operation pilot from the highest-value currently viable opportunity.
Admission runs only with a fresh cadence-bounded deposit assessment and an
active remoteDevelopment Launch Control lease. The lease authorizes the new
external investment decision; its later expiry does not revoke a committed
operation or prevent safe cargo evacuation. Manual exact-opportunity approval
remains available in either mode, and the retained last outcome prevents
immediate readmission of that exact deposit.
Launch Control reopening authority is numeric capacity rather than the former
closed / single / full state. The current horizon still supplies the
autonomous target (brief=0, moderate=1, extended=4), proven reopening
capacity advances or retreats one observed level at a time, and the admission
cap is the lesser of proven capacity and the effective target. A bounded global
operator override may temporarily replace that target for smoke testing, but it
does not alter work-class horizons, selection policy, governor state, or active
lease lifetime. Experimental proof above the autonomous ceiling is discarded
when the override ends. Extended capacity now progresses through three to four
under the same evidence model; no other admission policy changes.
Normal governor completion remains distinct from experimental expansion.
Capacity four now means autonomous reopening is complete for commanded tier and
unrelated CPU-throttled cadence even while an override progressively tests five
or six Launch Control slots. Legacy closed, single, and full
Memory maps once to capacities zero, one, and two respectively; legacy full
never inherits a higher experimental or future target.
Milestone 0.4.2 extends the normalized external-operation contract with
transient highway-deposit opportunities, but deliberately assigns them
advisory-only runtime authority. CIA remains the only source of deposit facts;
the opportunity evaluator reads existing economy, logistics, defense, Industry,
and cached Market evidence and owns no execution state. Eligible advice has no
admitted objective, route, workforce demand, construction intent, resource
commitment, or Market command. 0.4.3 must explicitly introduce and revalidate
each of those permissions before any deposit is harvested.
Highway scouting is a separate exception to ordinary one-room adjacency. It is rooted only at an eligible owned room, bounded by route distance, candidate and edge-work caps, cached in heap, and persisted on a scout only as a compact waypoint mission. The scout's current room never becomes a new search root. Completed highway missions reserve the next pending assignment for ordinary adjacent refresh, preserving baseline intelligence coverage.
2026-08-23
Milestone 0.4.1 keeps one RemoteOperationsManager-owned room operation while
representing each known remote energy source as its own persisted objective.
Safety, hostile suspension, reservation, CIA context, and home-room economic
authorization remain room-scoped. Marginal economics, harvester coverage,
container identity, hauling demand/capacity/performance, and road support are
source-scoped.
Marginal admission amortizes source workforce, its Container, transport, and only the road tiles not already justified by an admitted sibling. Reservation is deliberately not charged to every source. Shared road coordinates remain infrastructure overlap; they do not merge source route identities. Ordinary haulers remain a shared fleet, but each live assignment belongs to exactly one source route and therefore contributes capacity to exactly one route summary.
This is an incremental extension of the existing runtime authority, not a new external-operation executor or a remote-room portfolio allocator. Multiple simultaneous remote rooms and broader allocation remain later 0.4.x work.
Milestone 0.4.0 introduces ExternalOperation as a typed, read-only normalized
view over the existing remote-energy pilot. Operation identity is
remote-energy:<home>:<target> and a selected source objective is
<operation-id>:source:<source-id>. The contract contains an objective array,
the generalized lifecycle vocabulary, persistence, resource, and associated
existing logistics route IDs, but it stores no new Memory and runs no gameplay
cadence.
RemoteOperationsManager remains the runtime policy authority and source
selector. Its candidate and pilot states map deterministically into the wider
lifecycle vocabulary; unreachable states remain vocabulary only. CIA remains
authoritative for intelligence, logistics for routes and transport state,
economy for readiness and spending, infrastructure for construction support,
spawn planning for workforce demand, and existing roles and workflows for
execution. This milestone activates no new opportunity types and creates no
control path back from the normalized view.
2026-08-22
Milestone 5 completes the colony-layout infrastructure migration as a clean
cut. Colony layout is the only fixed-local geometry authority, logistics owns
persistent local arterial Roads, unified local-road intent is the only local
Road construction input, and focused local construction is the only migrated
local execution path. Manual local placement accepts only exact
localConstructionApprovals fingerprints.
The generic planned-structure/build-order lifecycle is retained solely for remote source Containers and defensive Walls/Ramparts; remote Roads retain their dedicated route lifecycle. Work packages, local order mirrors, package approval aliases, rollout gates, Extension migration automation, and their debug/stats/serialization support are deleted rather than left dormant.
Existing Memory is filtered once under
infrastructureCutoverCleanupVersion = 1. Purpose-aware cleanup preserves
remote and defense records plus colony layout, local-construction state,
logistics road planning, and remote-road state. This bounded migration replaces
permanent compatibility readers; deleted local legacy records cannot
regenerate.
2026-08-21
Milestone 4 replaces generic local build-order/package execution with
managers/localConstruction. Colony layout supplies fixed desired coordinates,
unified local-road intent supplies Road coordinates, and the executor decides
only whether a currently eligible exact site can be placed safely. Matching
live structures/sites satisfy intent; future-RCL slots remain pending; no
geometry or per-structure lifecycle copy is persisted.
Infrastructure authority remains global. Autonomous mode authorizes desired items directly. Manual mode uses exact compact desired-item fingerprints, with approved legacy records accepted temporarily only as compatibility approval tokens. Fixed-local orders are excluded from generic execution and local packages are no longer executed. Remote source Containers, remote Roads, Walls/Ramparts, and destructive Extension migration retain their existing owners and behavior until later milestones.
Colony layout is the sole geometry authority for fixed local owned-room structures. It persists exact core, Lab, Extension, natural-anchor Container, Extractor, and operational Link slots. InfrastructureManager remains a bounded construction adapter during migration: legacy plans and packages may mirror and execute those coordinates, but may not score an alternative fixed-local tile. Unbuilt competing legacy coordinates are invalidated; completed structures and tracked sites remain conservative live-world facts.
Lab reaction roles and resource operations remain with the Lab subsystem, while Lab package geometry comes only from colony-layout slots. The legacy Lab reservation may still be read and mirrored until later compatibility cleanup. Road geometry and scoring, defensive Walls/Ramparts, and remote Containers and Roads retain their existing owners. This authority transfer does not authorize build-order removal, migration cleanup, demolition, or deployment.
Desired local Roads are exposed through a derived read contract rather than a new persistent copy. Colony layout contributes its designed lane geometry; active local creep-route intents contribute their already-calculated arterial geometry. One result tile represents each coordinate, with an independent layout-support flag and sorted unique route IDs so overlap does not erase either reason. The view is computed on demand, excludes remote routes, and stores no third full geometry copy.
Logistics owns local arterial route selection, value/evidence, endpoint and
topology fingerprints, cached geometry reuse/invalidation, and the bounded
Room.findPath refresh in logistics/localRoadPlanning. Milestone 3C moves its
single persisted cache to RoomMemory.logisticsRoadPlanning, deletes the
legacy infrastructure keys after a one-way move, and keeps the unified merge
non-persistent.
Local Roads no longer use planned-structure or work-package authority. Construction, logistics support, strict retention, and debug inspection consume unified local-road intent; maintenance and performance use the same logistics-owned arterial cache when route-specific provenance is required. InfrastructureManager retains only cadence orchestration and a temporary road-only placement adapter with live validation, duplicate suppression, site bounds, retry pacing, and layout rollout/RCL phasing. This adapter stores no geometry or lifecycle. Manual local-road authorization is intentionally deferred to Milestone 4's replacement executor; the adapter places only under autonomous infrastructure authority. Path costs/bounds and all remote-road behavior remain unchanged.
2026-08-14
The CPU bucket governor uses three persisted postures: open, recovery, and
emergency. The former managed posture duplicated the graduated control now
owned by Launch Control and the full / single / closed reopening stages,
and its 9,000-point exit could keep a stable colony throttled indefinitely.
Open posture therefore remains active above the 5,000 recovery boundary while
runway-aware leases and stage backoff regulate optional work.
The stage is also the operating-tier command within open posture: full
commands abundant, single commands healthy, and closed commands
constrained. A stage tracks its latest bucket peak and backs down after more
than 100 points of loss, so recovery from an older low baseline cannot hide a
later drain. Recovery still holds until 9,000, emergency still enters at 1,500
and exits to recovery at 3,000, and reopening remains progressive. Persisted
legacy managed state is converted once to the equivalent open stage (or
recovery at the recovery boundary) and its obsolete admission record is
removed.
2026-08-12
Colony layout becomes a persistent advisory layer above existing infrastructure authority. The first patch stores a stable RCL8 reservation but does not create work packages, approve construction, or place sites. Developed rooms adopt their completed Storage; pre-Storage rooms derive the future Storage origin from the deterministic primary spawn. Once an established structure anchors a plan, its loss invalidates the plan for operator review rather than silently moving the colony.
The layout doctrine uses a hybrid core: exact core-service geometry, the existing exact Lab reaction footprint, compact five-Extension pods around shared lanes, and terrain-adaptive connectors. A pod may relocate at most one Extension by at most two tiles while preserving lane adjacency. Core and Lab slots do not distort. Candidate selection uses the agreed weighted balance of 50% logistics, 30% complete RCL8 buildability, and 20% defensive compactness; hard terrain and access constraints remain blockers regardless of score.
Planning runs inside the existing cadence-bounded infrastructure CPU section. Full geometry is generated only when absent or when its version, anchor, or Lab recommendation changes. Cheap blocker validation runs no more often than every 100 ticks. Patch 2 will decide how existing extension and road work packages consume accepted reservations; Patch 1 deliberately leaves their behavior unchanged.
2026-08-11
Launch Control generalizes bucket-governor work admission from scouting and remote development to CIA assessment, local logistics, local infrastructure, and mineral development. Subsystems publish one bounded current request with an urgency and reason; no queue or history is introduced. Moderate runway permits one active lease and extended runway permits two. Local logistics and infrastructure share the highest optional baseline, scouting, intelligence, and minerals form the prerequisite/mid-tier group, and remote development remains lowest. Extended admission preserves one priority lane and one rotation lane. The rotation lane favors never-admitted and longest-waiting eligible work; moderate admission gives an overdue same-priority peer precedence after 100 eligible ticks. Recovery does not accumulate eligible wait or phase applicants with deferral timestamps because no lease can be granted there.
Remote development no longer implies scouting. Adjacent intelligence must first be recent, then have a CIA assessment whose observation tick matches the latest dossier. Missing or stale evidence requests scouting; unmatched evidence requests intelligence; only current evidence allows remote development to apply. Existing remote creeps retain safe reduced-cadence continuity outside a lease.
Population admission happens in createPopulationPlan(), not creep roles. One
local service hauler is protected when a container economy exists. Additional
local haulers require a logistics lease and persistent performance evidence: a
deficit, low idle capacity, usable destination, sufficient sample confidence,
and sustained production or consumption. That pressure must survive two fresh
network evaluations at least 25 ticks apart. A successful commitment authorizes
one count increase, colony-wide authorizations are separated by 150 ticks, and
the committed count provides replacement continuity only while a logistics
lease is active. Lease expiry lets living optional haulers finish but returns
spawn demand to the protected floor; a fresh evaluation can still withdraw the
stored need. Ordinary builders require
an infrastructure lease; one critical-defense repair builder and active colony
bootstrap pioneers are the only automatic exceptions. Mineral miner demand and
policy evaluation require mineral-development admission. The existing minimum
controller upgrader remains protected during optional-work suppression.
Workforce recovery uses the same one-hauler essential floor rather than raw optional economy demand. Otherwise an unleased second hauler would keep the room permanently in recovery and prevent logistics evaluation from producing the evidence needed to apply for that capacity.
InfrastructureManager retains one implementation but accepts independent local and remote permissions. Local leases cannot consume the remote dirty domain or place remote work, and remote leases cannot consume local domains or place local packages/orders. This preserves existing infrastructure authority, validation, and bounded placement behavior without creating a second manager. Stable infrastructure publishes a low-urgency refresh request after 100 ticks without a pass so completed-structure loss and other world invalidations cannot remain undetected indefinitely.
Lab development uses a reusable relative reaction topology rather than independent nearest-Storage plans or room-specific coordinates. Each RCL 6+ room translates, rotates, and reflects the same two-input/eight-output footprint and reserves all ten Lab plus service positions before Extension planning. Current RCL capacity remains the placement gate. Candidate generation is a bounded dirty-industry pass with no pathfinding or every-tick discovery.
Storage access is a direct placement invariant: only walkable Roads, Ramparts,
and Containers, one designated Storage Link, and one Tower may be newly placed
adjacent. Existing matching structures are grandfathered, but replacement must
obey current policy. Valid Lab geometry blocked only by Labs or Extensions is
reported as relocation-required; an exact operator reservation protects the
footprint and pauses conflicting builder work but never destroys or removes
world objects. A Lab candidate that overlaps authoritative core, Extension, or
operational fixed geometry is structurally invalid instead of relocatable. The
colony-layout planner rejects it with bounded conflict metadata while preserving
relocation-required for historical live and legacy Lab/Extension obstructions.
2026-08-08
Normal infrastructure endorsement is now an operator policy rather than a
mandatory lifecycle stage. Persistent authority is manual or autonomous,
with existing and new Memory defaulting to autonomous. Manual mode retains
revision-specific tickets. Autonomous mode stamps a compact policy marker on
the current build-order or work-package record and omits duplicated console
approval metadata.
Build orders remain the immutable execution snapshot because comparing them to the current plan is a useful safety boundary, not merely approval-era duplication. Work packages remain the durable exact geometry for aggregate local roads and extension clusters. Both paths continue through live-world ownership, revision, structure-limit, coordinate, tile, anchor, topology, and existing-site revalidation before placement. Remote source containers retain their remote-operation gates; remote-road routes remain explicitly manual because their cross-room authority is a separate risk boundary.
Mode transitions are event-driven. Entering autonomous authority releases pending canonical records without recreating them; returning to manual affects future proposals while already-authorized work remains stable. Autonomous active plans discard proposal-only candidate arrays, and autonomous records do not allocate approval references. This reduces serialization and avoids adding a new every-tick authority scan.
Colony-layout Extension migration now follows the same global authority policy. Manual mode retains the exact propose/approve boundary. Autonomous mode selects and authorizes one exact source/replacement pair per room only after the prior replacement completes. The destructive pass is unchanged: it still drains and revalidates the source, target, topology, capacity, workforce, threat state, and immediate replacement capacity before removal. Post-removal recovery remains authoritative, and room-scoped rollout gates still bound where autonomy applies.
2026-08-06
Bucket recovery governs execution as well as population. The bot intervenes at 7,000/5,000/1,500 bucket on descent, remains in emergency until 3,000, and holds recovery until 9,000. During recovery, optional managers pause and nonessential local, remote, and bootstrap creeps use deterministic staggered cadences. Local harvesters and haulers, spawning, towers, links, economy assessment, and controller work retain continuous eligibility so austerity does not disable the colony's energy engine or downgrade protection. Full reopening advances only one population tier per 100 ticks.
This favors reserve restoration after an observed bootstrap-related bucket collapse. It accepts slower expansion, construction, upgrading, telemetry, and remote throughput while constrained instead of relying on spawn caps to reduce the CPU of creeps that already exist.
2026-08-04
The CPU bucket governor is the colony's sole strategic operating authority.
Persisted postures are open, managed, recovery, and emergency, with
asymmetric 7,000/5,000 descent thresholds and a 9,000 recovery exit. Downward
restrictions are immediate; recovery exit reopens the existing commanded tiers
one step per configured delay. This treats the bucket as a renewable reserve
that may be deliberately spent without removing existing per-tick bounds.
Calculated engine-charged CPU, reported-CPU fallback, the discrepancy offset, EWMA, thresholds, and CPU grade remain a lower-level observer. They may tighten the recovery tier but never command managers independently. Managers continue to consume one four-level tier, keeping bucket interpretation and reopening state inside the governance layer.
2026-08-03
Native mineral inventory policy remains room-owned by mineralOperation rather
than becoming a general resource solver. A completed extractor, its exact
adjacent container, and completed primary Storage activate a protected target
equal to the current MINERAL_DENSITY cycle amount. Mineral lifecycle events
own density and regeneration refresh; economy policy consumes the allocation to
derive effective energy capacity, and logistics alone decides whether inventory
is physically movable now.
The allocation is total protected native occupancy, not extra empty space on top
of minerals already stored. Other non-energy occupancy also reduces safe energy
capacity. Energy reserve counts remain actual energy, while Storage fill pressure
and deposit permission use the effective ceiling. A single resource-typed
transport-mineral job lets ordinary local haulers finish collected mineral
before returning to energy service. New collection is below established energy
acquisition and urgent delivery, is actual-capacity-gated, and creates neither a
role nor an unconditional population increase.
2026-07-28
Mature colonies primarily scale useful body capacity rather than creep count. CPU pressure limits optional population, while essential recovery, one harvester per source, controller downgrade protection, and local container service floors remain protected.
CPU population policy is a small process-wide layer rather than part of
EconomyManager, logistics, SpawnManager, or creep roles. The current bucket
is the sustained-budget signal and an EWMA consumes only the previous completed
tick's CPU utilization. Modes are abundant, healthy, constrained, and
critical; worsening must persist for 20 ticks, recovery for 50 ticks, and
recovery thresholds include bucket/utilization hysteresis. EconomyManager
continues to own economic demand and permissions, logistics continues to own
required carry capacity, createPopulationPlan() applies RCL then CPU caps,
and SpawnManager only executes the plan.
At RCL4+, ordinary builders and upgraders default to one. A second builder requires committed construction or repair pressure and optional-spending permission; a second upgrader requires sustained or overflowing strategic surplus. CPU constrained/critical modes reduce each to one and cap combined local, route, and remote hauler demand at three. Healthy CPU can exceed three haulers only when route-required carry capacity exceeds the projected capacity of three mature local bodies. Remote assignment continues reserving the final local-service hauler.
RCL5–RCL8 local hauler, builder, and upgrader tiers are large capital bodies gated by normal stable-or-surplus economy health, non-negative trend, reserve permission, workload/supply evidence, RCL capacity, and current affordability. Approved replacements may wait briefly for the target tier; emergency, starved, or zero-essential-role recovery immediately uses conservative fallbacks. Local harvesters retain their five-WORK throughput ceiling and remote haulers retain workload-specific bodies.
2026-07-27
Committed local construction makes the first builder essential. Builder demand may recover from zero to one without optional-worker spawn reserve and despite an existing increase cooldown when construction progress remains. This exception does not apply to a second builder or to upgraders; emergency and starved population caps remain intact.
Local route roads and currently unlocked extension capacity now use aggregate infrastructure work packages. The package is the approval boundary for one exact structure type, purpose, owning room, anchor/topology fingerprint, revision, and ordered coordinate set. Material changes supersede the approval and require a fresh operator decision. Completion, construction-site presence, and disappearance only update child progress and do not change the approved intent.
Road packages reuse the bounded route-road cache rather than pathfinding on package ticks. Each persistent eligible local route receives a stable package; overlapping tiles are assigned to the highest-priority deterministic owner and retain all supporting route IDs. Two new road sites may be placed per package evaluation, no more than six may remain outstanding, and global-site failures retry after 100 ticks. These values advance a route meaningfully while remaining below the much larger remote or room-wide construction backlog.
Extension packages use deterministic RCL-phase identities. They subtract completed structures, sites, legacy active plans, and prior package reservations before selecting children with the existing core scoring doctrine. Placement rechecks the live structure limit for every child. A later RCL uses a new phase identity and fresh approval rather than expanding an earlier approval.
Migration is additive. Legacy individual orders remain inspectable and execute
under their original exact approvals; their structures, sites, and active
reservations suppress package duplicates. Plan version 3 lazily initializes
workPackages without reinterpreting any old approval. Package records are
bounded by the route-intent cap plus the finite RCL phases, child scanning runs
inside infrastructure evaluation/revalidation cadence, and event history
remains bounded. This decision adds aggregate execution to established
doctrine; it does not introduce structure destruction, relocation, or a bunker
planner.
2026-08-09: Persistent logistics state uses bounded codecs and lifecycle compaction
Logistics route component samples and route events are persisted as versioned tuples, then decoded only at bounded evaluation, topology, and debug read boundaries. Component fields that match enclosing route context inherit owning room and validation tick; structure room derives from position; common reasons and lifecycle values use codes. Event summaries derive from retained structured route context, with a legacy-summary fallback when exact reconstruction is not possible. Canonical route IDs remain unchanged.
Local route-road intent path is the authoritative reusable geometry.
roadTiles is a delta containing only additional traffic-derived candidates;
consumers use the deduplicated union. This keeps cached path reuse and traffic
evidence without serializing path coordinates twice or introducing pathfinding
on read.
Rejected, cancelled, superseded, and invalidated work packages are terminal and
compact to identity/fingerprint/history tombstones. Completed packages remain
uncompacted because their exact children participate in missing-structure
reconciliation. Completed planned-structure routeSupport and remote approved
topology also remain intact because they continue to enforce route integration,
recovery, and immutable topology safety.
All migrations are room-local, schema-marked, idempotent passes. They run once through the existing logistics/infrastructure load cadence and add no broad steady-state discovery.
2026-07-19
Added route-scoped performance accounting as a compact feedback layer rather
than a new logistics execution owner. Existing local hauling, link logistics,
remote hauling, route adapters, infrastructure approval, and maintenance policy
retain their authority. src/logistics/performance.ts only accepts execution
outcomes, rolls bounded windows into route summaries, classifies health, and
projects already-computed evidence for debug, stats, and road scoring.
Performance uses the existing 25-tick logistics-network cadence, exponentially weighted rollups, a 75-tick minimum confidence gate, bounded anomaly history, and at most 24 weighted traffic tiles per route. Movement sampling is limited to creeps already executing a known persistent route. Stable route IDs and endpoint fingerprints invalidate stale evidence without creating a second route model.
Route jobs now expose assignment, collection, delivery, completion, abandonment, and last-progress timestamps. Executors update the matching room-owned job when one exists, while exact collected and delivered energy is attributed independently to the route performance window. This keeps telemetry useful even before route jobs become the universal assignment authority.
Traffic feedback can adjust priority only inside the existing road-intent, revision, approval, construction-site, and maintenance gates. High-value unroaded route tiles, repeated congestion, fatigue, backlog growth, and degraded health can improve ordering; stale, off-geometry, inactive, blocked, suspended, or policy-denied evidence cannot grant construction authority.
Custom path reuse remains disabled. Haulers use only Screeps' bounded built-in
moveTo reuse at their existing centralized movement boundary, with target and
required range represented by one stable key; this does not persist custom path
geometry. The bot records conservative eligibility
only after repeated traversal, throughput, and recalculation evidence, and
labels it eligible-telemetry-only. The current Screeps movement contract stays
unchanged until deterministic and Screeps Lab evidence demonstrates safe cache
invalidation and measurable CPU value.
2026-07-18
Connected logistics routes, infrastructure planning, remote-road planning, and maintenance through a small non-owning route-infrastructure support layer. Logistics still owns route state, demand, capacity, jobs, blockers, and fallbacks; infrastructure still owns proposals, approval, placement, and plan revalidation; MaintenanceManager still owns repair policy; remote operations still own activation and safety. The integration layer only translates compact intent plus current world facts into route support summaries and a route-road value lookup. It does not execute hauling, construction, repair, link transfers, remote policy, or terminal sends.
Infrastructure lifecycle is deliberately distinct from logistics route
lifecycle. Planned, pending-approval, approved, construction-site, completed,
missing, damaged, invalid, and unverified component states roll up to
fully-supported, partially-supported, degraded, or blocked route
infrastructure. Planned memory explains intent but never proves runtime support:
visible structures and construction sites are rechecked for exact type,
position, accessibility, and health. Invisible remote facts remain unverified.
A missing critical endpoint blocks the infrastructure-supported form; a missing
optional accelerator normally degrades it and preserves a usable conventional
fallback.
Road intent is derived only from persistent operational or degraded local and remote hauling routes whose policy permits work. Local geometry is cached under room infrastructure memory using stable endpoint and meaningful topology fingerprints, with at most one bounded path calculation per infrastructure evaluation. Remote routes reuse the already approved serialized remote-road path and keep validation cadence separate from path replanning. Existing road structures, road sites, active plans, and approved remote-road coordinates suppress duplicate proposals. A changed endpoint or geometry still follows the existing revision-specific approval lifecycle; route value never grants construction authority.
Maintenance creates one room-scoped position lookup from the persisted network and cached route roads. An operational route can promote its roads to the existing important class and add a capped score bonus, but never to critical. Construction ordering, emergency container work, reserve protection, and normal maintenance budget gates remain authoritative. Suspended, retired, blocked, policy-denied, and inactive remote routes are excluded so stale routes cannot hold permanent maintenance priority.
Compact route summaries and room-scoped aggregate telemetry are intentionally duplicated only at the contract boundary. Coordinate arrays remain in the infrastructure road caches rather than every route summary, component samples and blockers are bounded, and stats project already-calculated aggregates without route IDs or string reasons. Legacy logistics summaries without an infrastructure field normalize to a safe partially-supported/unverified state until the normal network evaluation refreshes them.
2026-07-15
Added a shared logistics-network representation layer without making it an execution owner. The layer defines compact typed nodes, routes, transport methods, lifecycle states, deterministic route IDs, room-owned route summaries, bounded route events, read-only debug inspection, and aggregate telemetry.
Adapters normalize facts from existing local hauling context, link-assisted
logistics, and remote-operation hauling into one model. They do not choose
hauler targets, assign jobs, transfer link energy, activate or suspend remote
operations, alter reserve policy, approve infrastructure, send terminal
resources, or optimize routes. EconomyManager, LinkManager,
RemoteOperationsManager, infrastructure planning, hauling workflows, and
terminal logistics remain the authorities for their current decisions.
The route memory deliberately stores only compact summaries under
Memory.rooms[roomName].logisticsNetwork. Nodes are derived from current room
state for inspection, while persisted routes retain enough state, blockers,
fallback references, demand, capacity, and transition events for operators to
understand the network across ticks. This prepares later route-driven transport
without introducing a global graph solver or a centralized logistics manager.
2026-07-15
Remote logistics now uses an explicit workload model shared by fleet sizing and remote hauler body selection. The model consumes the active home-owned remote operation, completed approved source-container handoff, and the approved remote road route when available. It estimates:
- one-way route distance
- road confidence
- round-trip cycle ticks
- source-capped production per tick
- required carry capacity per cycle with a bounded safety margin
- replacement lead time
- recommended remote logistics body
- desired hauler count
Fleet sizing and body selection remain separate policy decisions. Fleet demand
compares required carry capacity against effective assigned remote hauler
capacity, surplus unassigned haulers, and replacement timing. Body selection
chooses deterministic remote-road-* bodies for approved mostly roaded routes
and remote-balanced-* bodies for unroaded or uncertain routes. The ordinary
hauler role still executes remote hauling; no separate remoteHauler role was
introduced because assignment memory and role dispatch already distinguish the
remote workflow cleanly.
Missing or blocked route metrics use a conservative fallback route length and record a fallback reason rather than returning zero demand. Hostile suspension, home economy gates, exact container validation, and return-home behavior remain owned by the existing remote operation and hauling managers.
2026-07-15
Remote controller reservation is now a first-class subsystem of the
home-owned remote operation rather than a separate room evaluator.
RemoteReservationManager derives all demand from the primary active remote
operation, requires live target-room visibility, refuses foreign-owned and
foreign-reserved controllers, and gates all reservation work on the existing
home economy assessment.
The reservation policy is configured in config/remoteOperations.ts with a
target reservation, renewal threshold, safety buffer, travel estimate, and one
reserver cap. The dedicated remoteReserver role is intentionally tiny
(CLAIM + MOVE) and only travels to the assigned controller and calls
reserveController. If the operation pauses, visibility is lost, or the home
economy becomes unhealthy, demand drops naturally and the assignment clears or
returns home without changing harvesting, hauling, construction, or
infrastructure behavior.
Reservation telemetry is exported beside the existing remote metrics so operators can inspect remaining ticks, target ticks, renewal state, active reserver count, reserver activity, and CPU attribution without introducing a new dashboard hierarchy.
2026-07-15
Mature local harvesters are source-side capital investments. When an owned room has completed primary Storage with at least the configured healthy reserve ratio, the local harvester body policy approves the highest technically eligible harvester tier even if transient spawn energy, strained status, trend noise, or temporary reserve-spending permissions would otherwise down-tier the role.
This deliberately prefers occasional downstream inefficiency over long-lived source underproduction. Emergency mode, starved operation, zero-harvester recovery, rooms without owned Storage, and rooms below the healthy Storage reserve still use the existing recovery-safe smaller bodies. Remote harvesters and non-harvester roles do not inherit this lock.
2026-07-15
Remote source-container infrastructure now has a narrow lifecycle recovery path. When the home-owned infrastructure plan believes the approved remote source container is completed, the target room is visible, and the exact completed container is gone, the planner clears the stale live references, blocks the current plan for immediate reconsideration, marks the remote planning domain dirty, and lets the normal proposal/approval workflow create any replacement. Historical completed build orders remain in memory rather than being rewritten.
Dirty remote planning observation also tracks the visible container/site that satisfies each active remote infrastructure request, so creation or loss of the actual remote source container wakes the remote planning domain without adding a general full-room remote scan. The temporary remote construction builder remains scoped to the active approved assignment, but after construction is complete it may repair only that exact approved remote source container when it is damaged. No remote roads, reservation, generic remote repairs, maintenance manager, new role, or remote harvester repair behavior were added.
2026-07-14
Added the first remote hauling pilot without introducing a remoteHauler role.
Remote hauling authority stays with the active home-owned remote operation:
only an active operation with the same target room, source id, approved
completed source-container plan, and matching completed build order may
authorize hauling.
An ordinary hauler executes the pilot through compact creep.memory.remoteHauling
assignment state. The assignment stores identifiers and phase only; it does not
copy CIA dossiers or full operation memory. The hauler withdraws only from the
exact approved completed container, returns home with carried energy when the
assignment becomes invalid, and clears the assignment only after it is safely
home and empty.
Home logistics remains authoritative for delivery. Remote energy enters the same spawn, extension, tower buffer, reserve, controller buffer, tower top-off, and overflow policy as local hauler energy. Remote hauling may add at most one ordinary hauler to the population plan and may not consume the final essential local hauler. A dedicated remote-hauler role or specialized body is deferred until telemetry proves the need.
2026-07-13
Added a passive RemoteOperationsManager as the policy owner for the first
remote-harvesting foundation. The manager evaluates adjacent known rooms from
CIA dossiers, combines that advisory intelligence with a narrow home-room
economy readiness signal, persists compact room-owned assessments under
Memory.rooms[homeRoomName].remoteOperations, and exports read-only debug plus
numeric stats.
The CIA remains the owner of facts: observations, sources, ownership, reservations, hostiles, confidence, freshness, and strategic advisory scores. Remote operations do not rescan target rooms or store whole dossiers. The EconomyManager remains the owner of economic health; remote operations only consume the existing assessment through a small readiness helper. Infrastructure planning, spawn demand, roles, reservation, harvesting, hauling, combat, and construction are non-consumers in this milestone.
Hard blockers are deliberately conservative: hostile towers, foreign ownership,
foreign reservation, obsolete or insufficient intelligence, missing economy
assessment, home emergency mode, and home operating-reserve deficit prevent
eligibility. Scores are normalized to 0..100 and remain tunable through
config/remoteOperations.ts; reasons are retained in bounded arrays for
operator inspection rather than exported as stats strings.
This prepares the next remote-harvest pilot without creating a fake approval or activation system. Eligible means "worth considering"; it does not mean a remote operation is active or approved.
Expanded infrastructure autonomy from link-only planning to generic room-scoped structure planning while keeping the human approval gate mandatory. The manager now uses generic build-order lifecycle machinery, structure-limit accounting, and common tile validation, with structure-specific doctrine layered on top for core structures, containers, links, roads, extractor placement, industry structures, and critical ramparts.
Existing structures and construction sites are authoritative facts. The planner discovers missing legal infrastructure and does not relocate, demolish, or redesign completed layout just because a candidate would score better. A matching existing structure or site suppresses duplicate needs, and approved orders are revalidated against current room ownership, RCL, capacity, tile coexistence, anchors, revision, purpose, room, and position before any construction site is placed.
New build-order IDs include room identity, while legacy buildOrder0001 style
IDs remain inspectable through global debug lookup. This prepares the planner
for multiple owned rooms without assuming E48N13 or a single room-wide order
sequence. Remote planning and remote construction execution are intentionally
deferred to future remote operations work.
Defensive planning remains deliberately conservative. Ramparts may be proposed only for critical owned structures. Constructed walls are authorized and represented in debug state, but the bot does not infer a full wall line or bunker perimeter yet.
Infrastructure planning now maintains persistent infrastructure intelligence incrementally instead of rediscovering every room on a fixed 250-tick cadence. The manager records cheap room-observation signatures, marks affected planning domains dirty when meaningful facts change, and consumes a bounded number of dirty domains per tick. Mature blocked/rejected plans dirty only their own domain when eligible for reconsideration.
This mirrors the CIA boundary: intelligence gathers facts and publishes advisory recommendations, investment/approval decides what is allowed to proceed, and execution performs approved work. Infrastructure remains responsible for recommendations and validation, not investment policy or builder behavior.
RCL and energy capacity define body-tier eligibility, while economy and role pressure define body-tier approval. SpawnManager executes the approved selection and retains recovery-safe fallbacks.
The new body policy lives in spawnBodyPolicy.ts instead of adding more body
conditionals to SpawnManager. RoomManager builds one body selection plan per
tick from the spawn context, population plan, and latest economy assessment;
colony stats and spawning consume that same plan so telemetry cannot drift from
the body actually passed to spawnCreep.
Stable rooms may use normal operational tiers when reserves permit it, but premium RCL 5 bodies require surplus permissions, non-negative sustained trend, and role-specific pressure. Haulers require logistics pressure, upgraders require controller supply and controller-work permission, and builders require construction or important repair pressure. Emergency, starved, strained, and essential-replacement cases stay conservative so recovery harvesters and essential haulers are not blocked waiting for large bodies.
Added mature bodies:
- hauler
bulk-logistics: 12 CARRY, 6 MOVE, cost 900 - upgrader
surplus-controller: 6 WORK, 3 CARRY, 4 MOVE, cost 950 - builder
heavy-construction: 5 WORK, 5 CARRY, 5 MOVE, cost 1000
The existing harvester source-saturating tier remains the high harvester tier;
no additional harvester WORK parts were added because five WORK already reaches
normal source throughput.
2026-07-12
Export public colony state through a portable versioned Screeps Lab snapshot contract.
Context: Screeps Lab is a separate sibling repository that needs MMO-observed room state so it can later reconstruct private-server worlds, remap object IDs, restore player Memory, and mutate reconstructed sandboxes. The two repositories must remain independently owned and cannot share source modules, nested repos, submodules, package dependencies, or assumptions about each other's internal implementation.
Decision: this repository owns only the MMO-side exporter. The exporter captures one visible owned room as plain serializable data in schema version 1, includes raw player Memory, assigns snapshot-local object refs, preserves public MMO IDs as source metadata, publishes chunks through reserved RawMemory segments, and provides a read-only local downloader. Screeps Lab owns import, reconstruction, ID remapping, database writes, and future sandbox mutation.
Rationale: a neutral versioned artifact keeps the MMO bot focused on observable game state and gives Screeps Lab a stable integration boundary. Snapshot-local refs avoid treating public object IDs as portable identities, while the source ID index gives the importer enough metadata to later rewrite Memory references where safe.
Consequences: schema changes now require backward-conscious documentation.
Generated snapshots are artifacts and must not be committed. The MMO exporter
uses RawMemory segments 70-79, so future segment users must coordinate with
that reservation. The in-game checksum is deterministic but not cryptographic;
stronger artifact integrity can be added by local tooling later.
Rejected alternatives: direct database cloning from the MMO, copying this repository into Screeps Lab, importing Screeps Lab packages into the MMO bot, treating public object IDs as portable identities, and shaping the artifact around the current private-server storage schema.
Future compatibility expectation: optional additive fields may remain schema version 1, consumers should ignore unknown fields where possible, and changes to required fields or field meaning require deliberate versioning and coordination with Screeps Lab.
Added generalized hauler energy acquisition so dropped energy can participate in
normal logistics without turning roles/hauler.ts into a target-selection
module. The hauler role still owns only gathering/delivery state and asks the
workflow layer for an acquisition target. containerLogistics decides whether
that target is a withdrawable container or an energy drop, and acquireEnergy
dispatches to the existing focused withdraw or pickup actions.
Dropped energy is intentionally modeled as a logistics source, not role-specific
special behavior. Existing creep tasks provide target persistence and basic
claim avoidance: haulers continue valid withdraw or pickup assignments, and
new loose-energy pickup candidates already assigned to another active hauler are
excluded. Recurring source-container hauling remains higher priority than
trivial loose-energy cleanup; only nearby, significant, or decay-urgent drops
compete with ordinary container collection, while backed-up source containers
remain ahead of routine drops.
This first version does not add tombstones, ruins, links, terminals, minerals, remote-room salvage, multi-hauler pile splitting, or a separate reservation ledger. Those remain future logistics extensions after the generalized acquisition boundary proves useful.
Added link-assisted runtime logistics as an additive hauler capability rather than a room mode. Link eligibility is based on completed, currently usable source-container/source-link/storage-link topology, not RCL alone and not the mere existence of any link. Mixed operation is supported: a covered source can use link assistance while uncovered or blocked sources continue conventional source-container hauling.
Haulers may choose dynamic energy logistics jobs for legacy load-source-link
geometry and unload-receiver-link work. Urgent spawn, extension, and tower
operating delivery can preempt optional link service, and stale link assignments
clear when structures disappear, destinations fill, or the route is no longer
useful. Harvesters remain planted on source containers and harvest continuously;
for healthy adjacent source-link paths they also issue the source-link transfer.
Actual link-to-link transferEnergy() remains owned by LinkManager.
Haulers only load and unload links. Existing balanced hauler bodies remain in
place until telemetry shows enough persistent local-service pressure to justify
specialized bodies or a future split into transporter/logistics roles.
Added colony-authored infrastructure planning with human-approved build orders.
Configuration defines doctrine, authority, cadence, safety limits, candidate
summary bounds, and the explicit autonomous allowlist. Room memory owns the
actual plan under Memory.rooms[roomName].infrastructure; source code does not
store authoritative room-specific link coordinates.
Superseded by the 2026-07-13 general infrastructure expansion above: the first planner was link-only. It could identify source-side and storage-side link needs from visible topology, select deterministic legal candidates, persist the chosen plan, create a build order, explain the decision, and wait for console approval. The same approval model now applies to all authorized structure types. Build orders approve one exact planned-structure revision and coordinate. If a material detail changes, old approval is not reused; the order is superseded or invalidated and a new approval is required.
Execution always revalidates before site placement. The manager verifies room ownership, RCL legality, link limits, construction-site limits, allowlisted structure type, tile validity, matching existing sites/structures, anchor existence, and order freshness. Failure blocks or invalidates the order and reports why. The system does not autonomously destroy, remove, relocate, overwrite, reinterpret approval, or place non-link structures.
Builders remain ordinary consumers of construction sites. Link sites are added
to normal construction priority behind towers, extensions, and containers, so
approved link construction does not bypass critical core build priorities.
Completed-link transfer behavior remains owned by LinkManager; this patch
does not reduce hauler demand or implement new hauling behavior.
The infrastructure linkNetwork summary records planned/completed source and
receiver endpoints plus usable completed source-to-storage routes. This makes
the next logistics patch able to determine link-route readiness without
refactoring the planner.
The approval gate is a policy boundary. Later construction autonomy can loosen that policy after the same plan/build-order/revalidation lifecycle is proven safe.
Removed the mature harvester transfer cycle from the source-container workflow. Once a harvester reaches its assigned source container, it attempts to harvest its assigned source every tick and relies on Screeps overflow behavior to place excess energy into the container under the creep. The no-container bootstrap fallback still allows a full harvester to deliver directly to spawn or extensions until the room has completed source containers.
Telemetry continues to count harvest attempts, results, expected energy, actual estimated harvested energy, source-empty attempts, and full creep/container capacity blockage. Normal source-container harvesters should now remain in the harvest diagnostic state rather than alternating with the transfer state.
Added first-class harvesting telemetry to the existing stats pipeline rather
than creating a separate exporter or dashboard concern. Harvest action code
records compact per-tick harvester attempts, successes, movement, and
per-source harvested energy in room memory. The stats collector projects those
values into Memory.stats alongside calculated harvester capacity and average
active WORK parts.
The room-wide energy.gained.* metrics remain the existing economy contract.
Per-source harvest values are a deliberate source-id-keyed exception to the
usual low-cardinality guidance because source-level harvest diagnosis requires
stable source identity. Grafana, Graphite, StatsD, and exporter behavior remain
outside this repository.
Expanded harvester diagnostics on the same branch to explain cases where
theoretical capacity remains high but actual harvest drops. The telemetry keeps
the same room-scoped reset and stats projection model, with aggregate activity,
result buckets, per-source expected/missed harvest, and current-tick per-creep
numeric diagnostics. Assignment remains owned by SpawnManager; the harvester
role only records what it did with its assigned source.
2026-07-05
Started TypeScript rewrite.
One module per role.
Main loop is intentionally simple.
2026-07-06
Added a thin actions layer for common Screeps actions.
Roles keep state transitions and role-specific decisions.
Actions own one API operation, target fallback, movement, and status updates.
Added a workflows layer for reusable behavior composed from actions.
Workflows may combine multiple actions, while roles keep creep state transitions.
Spawn behavior is driven by a priority-ordered config.
The main loop still owns spawn execution and role dispatch for now.
Added a small structures/tower module as the first owned-structure behavior module.
The main loop finds owned towers in each visible room, while each tower's behavior stays modular and config-driven.
2026-07-07
Documentation under docs/ is part of the maintained project surface, not
optional notes.
Patches that change debugging, operations, console helpers, visuals, statuses,
intents, workflows, or developer-facing behavior should update the relevant
docs/ file in the same change.
For debug behavior, docs/DEBUG.md is the canonical reference.
2026-07-09
Added RoomManager as the owner of room-level state collection and per-room
tick orchestration.
The manager collects sources, owned spawns, creeps grouped by role,
construction sites, structures, containers, and controller economy data once per
tick. Spawn planning, dashboard output, population stats, tower execution, and
role dispatch now consume that room snapshot instead of rebuilding the same
room queries in main.ts.
This is intentionally a foundation step rather than a full SpawnManager or
RoleManager rewrite. Spawn priorities, harvester source assignment, role
behavior, and tower behavior are preserved while main.ts moves toward global
orchestration over owned rooms.
Extracted SpawnManager from RoomManager.
SpawnManager owns spawn planning, body selection, spawn execution, emergency fallback through configured affordable bodies, and harvester source assignment. RoomManager still controls per-room orchestration order and passes its room snapshot into SpawnManager.
Added persistent room intelligence under Memory.rooms[roomName].intelligence.
Room intelligence stores room facts needed by later scout and remote-room work: known source ids and positions, controller position, nearby container positions, road and important repair pressure, hostile sightings, and a compact status summary. This is intentionally observational; it does not yet change colony strategy.
Added a binary room energy status under room intelligence.
The first version treats a room as energy starved when total container storage is below 50% full. Builders and upgraders use that room-level signal to leave withdraw mode once they are at least 50% full, reducing crowding around scarce containers during heavy build demand. Haulers keep their existing behavior of delivering as soon as they have energy.
This is deliberately simple. Future iterations can replace the binary state with a more granular starvation score and per-target crowding logic.
2026-07-10
Added EconomyManager as a peer of SpawnManager, orchestrated by
RoomManager.
RoomManager owns the per-tick room execution order: collect room context,
update room intelligence, request an economy assessment, create the population
plan, then pass that plan to SpawnManager. Keeping this orchestration in
RoomManager makes the room tick readable without embedding economic policy in
the room loop itself.
EconomyManager owns economic interpretation: smoothed net energy trend,
stored reserves, source/container supply, construction backlog, repair
pressure, bounded builder/upgrader demand, hysteresis, and cooldown state. It
does not spawn creeps, choose bodies, or run role behavior.
SpawnManager remains responsible for spawn priorities, affordability, body
selection, harvester source assignment, source-assignment rebalancing, and spawn
execution. Harvester roles execute the assigned sourceId; they do not create a
competing assignment policy when the manager assignment is missing or stale. It
consumes a population plan so emergency harvesters and essential haulers keep
their survival-oriented priority while economy-sensitive builders and upgraders
can be tuned from room-level signals.
This separation avoids turning RoomManager into a policy module and avoids
making SpawnManager responsible for long-term room economics. The first
implementation is intentionally conservative and stores only compact trend,
assessment, desired-count, and cooldown state in room memory.
2026-07-11
Defined Memory.stats as this repository's explicit telemetry contract.
Internal Screeps Memory and exported telemetry are separate concerns. Room
memory, creep memory, manager state, intelligence, reasons, ids, positions, and
debug caches can remain internal even when they are useful for console
inspection. A value is available to downstream dashboards only when stats
collection deliberately projects it into Memory.stats.
This repository owns game state and internal Memory through the stats collection
code and the resulting Memory.stats object. Generic memory-to-StatsD export,
Graphite storage, and Grafana dashboard behavior are downstream observability
concerns and are not implementation responsibilities of this Screeps bot.
Completed the first storage transition without adding advanced reserve policy.
Completed owned storage is now the room's primary energy reserve through
room/energyReserve. Haulers still empty source containers and satisfy urgent
spawn, extension, and tower demand first, then deposit excess source energy into
storage before filling the controller-side container. Builders prefer storage as
the room-wide reserve, while upgraders continue to prefer the controller-side
buffer for path efficiency.
Source containers remain collection buffers, the controller container remains a local controller supply buffer, and workers retain source-container and harvest fallbacks. Explicit storage reserve targets, emergency economy behavior, overflow balancing, links, terminals, minerals, industry, and market automation remain roadmap-only work.
Added MaintenanceManager as a peer of EconomyManager and SpawnManager,
orchestrated by RoomManager.
Maintenance policy now belongs to the room tick instead of individual builders. The manager consumes the existing room snapshot and economy assessment, then classifies containers and roads into critical, important, normal, or disabled maintenance classes. It applies configurable start/target thresholds, budget eligibility, deterministic scoring, and assignment-aware target selection.
Builders still own their work state, build/repair/upgrade mechanics, and energy acquisition state transitions, but they no longer scan the room or decide which damaged structures matter. This keeps repair thresholds and infrastructure priority in one policy layer while preserving the existing role system.
Critical operational containers may preempt construction when they are in emergency condition. Important and normal maintenance stay budget-gated so routine road work does not starve construction, spawning recovery, or upgrading.
Maintenance telemetry is written as room stats and room memory summaries: backlog counts, backlog score, average container/road health, and maintenance energy spent tick/total. The cumulative energy total is separate from the general economy counter so Grafana can graph repair spend over time without resetting each tick.
Added explicit normal energy reserve policy.
EconomyManager now owns reserve assessment and spending permissions through a
persisted policy snapshot. The policy uses staged absolute RCL targets rather
than storage capacity percentages, so an RCL 4 room with new 300,000-capacity
Storage can be considered operational once it has a modest operating reserve
instead of waiting for storage to be mostly full.
room/economyPolicy is a shared helper rather than a manager. EconomyManager
uses it to calculate reserve thresholds, deficits, surplus, and optional-spend
permissions; hauler and container-logistics workflows use the latest persisted
assessment to enforce delivery and withdrawal eligibility. This keeps economic
strategy in the manager layer while letting logistics physically protect the
reserve.
Hauler delivery priority is now explicit: spawn/extensions, tower operating buffer, storage reserve, controller buffer when policy allows optional spend, tower top-off, then storage overflow. Builder and upgrader storage withdrawals also preserve the minimum operating reserve by checking the creep's free carry capacity before selecting Storage.
Added emergency economy mode as a temporary policy overlay.
Economy status still describes reserve health (starved, strained, stable,
or surplus), while economy mode describes the active operating rules
(normal or emergency). Keeping these separate lets a recovering room remain
in emergency mode until it passes a hysteresis exit threshold even after it is
no longer critically below the minimum reserve.
Emergency mode is entered only for storage-backed rooms when reserve energy falls below the minimum operating reserve. It exits when reserve energy recovers to the minimum operating reserve plus a configured margin. While active, EconomyManager tightens the same reserve policy that logistics already obeys: optional and surplus spending are disabled, controller buffer delivery is held, tower top-off is held, and primary storage withdrawals are blocked. Spawn and extension filling, tower operating energy, and storage recovery remain prioritized.
This preserves the layered boundary: EconomyManager owns detection, hysteresis, and policy permissions; logistics enforces those permissions; the hauler role continues to manage only gather/deliver state.
Added LinkManager as a structure-level room logistics module.
Links are classified from visible room positions every tick rather than by
stored ids. The initial deterministic priority is source, controller, then
storage; equal-priority ambiguity leaves a link unclassified so it cannot
silently serve conflicting roles. Classification and transfer thresholds live in
src/config/links.ts.
RoomManager keeps orchestration order: collect context, assess economy, run
link transfers, then continue maintenance, population planning, spawning,
dashboard output, towers, and creeps. EconomyManager still owns reserve
permissions, and LinkManager consumes canDeliverToControllerBuffer before
feeding controller links. This keeps controller-link support aligned with the
same policy that governs controller-container delivery.
The first routing behavior is deliberately small: source links feed a storage link, storage feeds a controller link when policy allows it, and direct source-to-controller routing is only a fallback when no storage link exists. Hauler demand discounts source-container energy only for sources with a usable source-to-storage link route, so links reduce long hauling pressure without removing haulers needed for spawn, extension, tower, storage, and fallback logistics.
Source links are forwarded by structure-level link routing. Harvesters keep the source container as their stand tile. For a completed source-link/downstream-link topology, the planted harvester now owns source-link loading. The container remains a recovery buffer, and a temporary six-WORK unboosted replacement is selected only while meaningful local endpoint backlog exists. Ordinary five-WORK and boosted UO source-saturating bodies remain the steady-state designs.
Added TerminalLogisticsManager as a read-only preparation layer for
inter-room logistics.
The first terminal milestone intentionally does not call terminal.send().
Instead, owned rooms persist terminal energy readiness, store usage, top stored
resources, and visible owned-room transaction-cost samples. This makes terminal
state visible in beta before resource movement policy exists, and gives future
room balancing a typed memory and stats contract to consume.
Terminal resource names and recommendations remain in room memory and debug
output. Memory.stats.rooms[roomName].terminal exports numeric readiness and
cost fields only, preserving the downstream telemetry contract.
Added strategic surplus management as the positive counterpart to reserve protection and emergency recovery.
EconomyManager now owns a persisted strategic surplus assessment with
inactive, building, sustained, and overflow states. This state is
separate from economy status and economy mode: status still describes reserve
health, mode still describes exceptional emergency rules, and strategic surplus
describes whether excess production should be consumed more aggressively.
The assessment uses smoothed positive trend, reserve surplus, persistence,
storage fill pressure, persistent source-container overflow pressure, spawn
reserve, and delivery capacity. building is a waiting state for candidate
surplus; sustained and overflow are active spending states. Exit hysteresis
and cooldowns avoid rapid toggling from noisy samples.
Spawn planning consumes the persisted state through desired counts rather than creating a new surplus spawn system. Controller upgrading remains the primary surplus sink, hauler demand rises for source overflow only when there is a valid destination, and MaintenanceManager uses the same assessment to allow more routine infrastructure upkeep without moving repair policy back into builder roles.
Advanced link routing, terminals, market behavior, minerals, factories, and multi-room resource balancing remain explicitly deferred to later RCL5-oriented milestones.
Investigated live Screeps API integration for local and cloud development.
The existing SCREEPS_TOKEN can authenticate both HTTP requests and WebSocket
subscriptions through the screeps-api package already used by this repository.
HTTP is appropriate for account metadata, shard metadata, current tick, memory
path reads, terrain, room object snapshots, and queueing console expressions.
WebSockets are the correct primitive for live console output, console command
results, CPU/memory updates, memory path subscriptions, and room state updates.
Codex should not call the raw Screeps API directly as the final architecture.
The preferred path is a small local Node service that wraps screeps-api with
narrow read-only and explicitly guarded command operations, followed by an MCP
server once the operation shapes are stable. This keeps token redaction, rate
limit handling, reconnects, command correlation, audit logging, and console
execution safeguards in one layer.
Remote console execution is possible through POST /api/user/console, but the
HTTP response only confirms that the expression was queued. The return value
arrives later on the user console WebSocket stream, so tooling must correlate
results carefully and treat arbitrary console expressions as live-game
operations.
See docs/LIVE_API.md for the full report and incremental implementation
roadmap.
Harvester body selection can use narrow per-body eligibility rules.
Body options remain simple ordered tiers in spawnConfig.ts, but an individual
option may now define a type-safe eligibility predicate over explicit body
selection context. That context combines the existing spawn context with the
current economy mode and status from EconomyManager, avoiding direct memory
reads from spawn config.
This supports the RCL 4 five-WORK source-saturating harvester only in normal
stable or surplus economy while keeping the four-WORK body as the constrained
production fallback. A broader BodyPlanner subsystem remains deferred until
more roles have repeated body-planning needs.
0.3.7.3: Console authorization owns colony bootstrap intent
Colonization execution is intentionally separate from expansion selection. The
operator authorizes an exact target/bootstrapper pair with debug.colonize(). A
narrow ColonyBootstrapManager stores durable state under the bootstrapper room
and automatically reevaluates temporary blockers. CIA facts remain advisory and
cannot create the operation.
Before handoff, acquisition and pioneer creeps retain the bootstrapper as
memory.homeRoom; builders carry an explicit pioneer assignment and reuse their
WORK/CARRY behavior. The only new capability role is the small CLAIM/MOVE
colonizer. First-spawn intent is stable and clearance is restricted to the
recorded blocking tile. After a completed spawn and ordinary target
RoomManager execution, parent demand stops and surviving pioneers are rehomed
as target builders.
This deliberately avoids a generalized Operations framework, autonomous
petitions, military planning, and inter-colony support policy. Those abstractions
remain deferred until repeated use cases justify them. Bootstrap evaluation is
bounded to active home-owned records each tick; the legal tile scan runs only
when an owned visible target lacks a stored first-spawn plan. Its cost appears
inside the existing per-room remoteOperations CPU profile section.
Planned
High-level sequencing lives in ROADMAP.md; this section captures the current
architectural direction.
RoleManager dispatches creep behavior.
RoomManager owns room-level decisions.
SpawnManager owns spawning logic.
The CIA owns persistent facts about visible rooms under
Memory.rooms[roomName].intelligence.
The CIA ingests visible-room observations from owned-room management and scouts, normalizes them into compact room dossiers, preserves bounded ownership history, keeps stale hostile records distinct from current hostile sightings, and exposes read-only query helpers.
The CIA never makes decisions. It provides intelligence. Expansion, defense, spawning, logistics, attack, reserve, and remote-harvest policy remain owned by consumers outside the CIA.
Strategic assessment is advisory CIA output stored on the dossier. It scores known rooms across economy, threat, logistics, expansion, remote harvest, and military value, then records an overall score, recommendation, confidence, and bounded CIA events. Threat is a danger score, and high threat penalizes overall strategic attractiveness.
Room energy status owns shared room starvation signals.
Scouts are dispatched globally from main.ts so they keep running after leaving
owned rooms. Owned-room economic creeps remain dispatched by RoomManager.
Utility modules own shared behavior.
Eventually each room should become mostly autonomous.
0.3.8: Defense policy coordinates existing room authorities
DefenseManager is a narrow room-scoped policy authority. It consumes the live
hostile objects already collected in RoomContext and capability facts owned by
CIA, then publishes one compact assessment with posture, adequacy, shared tower
target, defender demand, rampart readiness, and safe-mode advice.
It does not scan rooms independently or execute spawning, hauling, repairs, or
tower actions. SpawnManager, economy/logistics, maintenance/builders, and the
tower structure module retain those responsibilities. This avoids a military
super-manager while giving survival decisions one explainable source.
The peaceful path performs no pathfinding and retains no combat history. Richer military intelligence, force composition, tactical operations, and offensive behavior remain deferred to 0.5.
0.3.9.3: Boosting is temporary cross-colony provisioning
Boosted workforce is represented as compact operator intent plus temporary provider slots, not new creep roles. Builders are additive to automatic demand; harvesters transition exact source-service slots. E48N13 is selected through a capability list, owns spawn/boost preparation, and reuses the bounded reaction, Market, and ordinary-hauler contracts introduced by the preceding industry patches. The bounded reaction executor enables only the first required compounds: UO from U/O and LH from L/H. Boost preparation prefers an enabled local recipe when the full raw shortfall is already present, while an active Market directive retains authority until completion or explicit cancellation.
Before handoff, a provisioned creep retains E48N13 ownership and does not execute
its ordinary role. After boosting and deployment, homeRoom moves to the target
and temporary lifecycle state is removed. Target planning counts reserved
incoming capacity so it does not manufacture an ordinary duplicate. Harvester
reservations count only while their exact source remains covered, preserving
local emergency replacement authority after an unexpected death or delay.
UO harvester bodies use three WORK parts because doubled harvest power saturates
a normal source at that size. If emergency recovery fills a reserved source
before a delayed boosted worker arrives, handoff reconciles to the oldest
eligible ordinary source incumbent instead of creating a long-lived duplicate
beside the fresh fallback.
This deliberately avoids a permanent boosted role, general workforce broker, universal resource solver, autonomous ROI policy, generalized lab optimizer, and precise spawn-queue prediction. Preparation is serialized and cadence-bound until live evidence supports broader concurrency.
0.3.9.4: Surplus liquidation is a bounded policy over existing executors
surplusLiquidationManager owns only the decision and compact sequential plan.
It does not produce, haul, stage Terminal inventory, or call Game.market.deal;
the existing Factory, Lab, industry-logistics, Terminal, and Market managers
retain those authorities. Operator Factory/Lab/Market work and boost preparation
take precedence.
A raw mineral is eligible only when its native target is at least 95% full, its visible deposit has regenerated at least 1,000 units, normal economy optional spending is open, CPU emergency is absent, and a 10,000-unit strategic reserve plus exact active Factory/Lab/boost commitments remain protected. Each plan is limited to 1,000 raw units and at most two compatible resources.
Valuation consumes only current buy orders with room names and enough aggregate
volume to execute the whole bounded output. Factory quantities come from
COMMODITIES; Lab batching uses LAB_REACTION_AMOUNT. Raw, compressed, and
compound values are normalized to the exact raw units consumed. Compression or
chemistry must exceed the simpler executable baseline by the configured 10%
gross-credit premium. Energy is deliberately excluded from credit valuation and
remains governed by existing hard economy and Terminal-energy gates.
The policy retains only its current evaluation and active plan. Historical prices, rejected orders, counterparties, and decision history are not stored in Memory; Graphite/Grafana owns history. This explicitly excludes speculation, persistent orders, fair-value modeling, arbitrary recipe search, boost ROI, and true-profit claims.
0.4.4: External allocation is greedy, per-home, and multidimensional
External allocation is a narrow policy layer over existing operation-specific authorities. It ranks remote-source and highway-deposit objectives using bounded native economic evidence, then greedily admits only atomic minimum requests that fit the owning room's envelope. Spawn energy, workforce, hauling capacity, CPU allowance, infrastructure pressure, and reservation-room support stay as separate dimensions rather than becoming a fictitious universal currency.
Shared controller-reservation support is keyed by target room and charged only once when multiple source objectives share that room. Essential workforce recovery, the protected local-hauler floor, reserve authority, defense posture, and CPU admission can reduce the entire optional envelope to zero. Incumbent bias, a decisive-preemption margin, stable ID tie-breaking, and a 100-tick admission cooldown prevent marginal oscillation while allowing clearly better work to suspend a lower-value operation. Suspension retains compact state and existing creep execution continues to own safe cargo return.
Operation-specific authorities publish hard allocatability blockers before ranking. The allocator consumes that answer but does not reproduce the owning subsystem's rules. Incumbency, hysteresis, and cooldown can preserve only a still-allocatable operation; they cannot retain capacity for an objective that its runtime authority cannot admit. A hard-ineligible objective receives zero allocation in every budget dimension.
The allocator does not spawn creeps, plan paths, discover rooms, construct infrastructure, reserve controllers, or execute hauling. It consumes existing cached assessments and estimates on a 25-tick cadence. A colony-wide optimizer, knapsack solver, flow solver, and cross-room resource currency remain explicitly out of scope.
0.4.5: External portfolio rank translates evidence but owns no authority
Persistent remote energy and transient highway deposits now share a bounded
0..100 portfolio rank composed from explainable productive, strategic,
urgency, reliability, logistics, persistent-support, risk, continuity, Market,
and measured-performance dimensions. Native operation scores and values remain
visible for inspection but are not added to the portfolio result. The portfolio
rank itself is the candidate rank supplied to the 0.4.4 allocator, preventing
the old allocation score from being counted twice.
Remote valuation consumes existing source economics and compact logistics-route performance. Performance remains neutral until 250 evidence ticks and then has a clamped influence. Existing completed route infrastructure contributes at most six continuity points, so it can stabilize a healthy incumbent but cannot rescue a poor underlying return. Deposit valuation consumes the existing bounded opportunity assessment, stock and active Factory-demand signals, and cached executable Market evidence. Industry demand and Market value are inputs only: neither can authorize an operation, spawn a creep, or bypass a native blocker.
Completed deposit outcomes update one fixed resource-class EWMA summary per deposit constant. Samples and early-abandonment counts cap at 20, influence is clamped, and no per-operation or tick history is retained. Evaluation remains aligned with the external allocator's 25-tick cadence and performs no discovery, pathfinding, Market scan, logistics recomputation, or cross-home optimization.