Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

All notable changes to Econ-Engine are documented here. The changelog records what changed in each update. Design rationale, experiments, observations, and lessons are documented separately in [Lab Notes](LAB_NOTES.md).

## [LIFE16-Routes-075] - (2026-10-30)

- Fixes a memory leak on long runs: the state kept every route ever walked, about 45,000 route segments a day, so the heap grew about 12 MB a day and a year's run ran out of memory, in Node and in the page's worker alike. Each step now frees the routes below the lowest one still being walked; route ids keep counting.
- Trajectories are unchanged, and so are the fingerprints.

## [LIFE17-Skills-074] - (2026-10-29)

- Life 17, skills and techniques. Each person holds experience, in seconds, for foraging, wood and each axe technique. At midnight unused experience fades by a fixed share a day, to half in ten years, and the day's work adds to it, anchored to the year so short calendars learn as fast per year. Skill follows the power law of practice: from a floor of 50% towards a ceiling of 150% that is never reached, half way after 16,000 hours of foraging, 5,000 of wood or 300 of craft.
Expand Down
10 changes: 10 additions & 0 deletions LAB_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@

Every meaningful model, architecture, experimental, or design update should receive a newest-first entry. Use at most one base update number per Git commit. Refinements completed before that commit keep the same base number with a decimal suffix—for example, `003` and `003.1` belong to the same commit family. Allocate the next base number only for a later commit. Preserve the context, observed problem or research question, rationale, important implementation decisions, trade-offs, findings, and unresolved questions. Distinguish verified observations from hypotheses. If the original rationale is unknown, say so rather than inferring intent from the finished code.

## [LIFE16-Routes-075] - (2026-10-30)

While measuring Life 17, a one-year run ran out of memory, and `main` grew at the same rate: running the canonical configuration day by day with `advanceValley` and collecting garbage every 25 days, the heap grew about 12 MB a day, to 2.4 GB by day 150. Node's default heap and the page's worker both fail before a year.

**Cause.** The module-level caches suspected first grow only slowly. Counted directly, the views remembered per person, nearest-frontier answers, place vicinities and ground lookups gained some tens of entries a day each. The earlier check that the state does not grow had compared JSON sizes of a few fields, and `state.routes` was not among them. A census of the state's arrays and maps between days 20 and 40 found it: 15,618 routes with 1.83 million segments at day 20 and 23,423 with 2.73 million at day 40. Every route ever planned stayed in the state, since a route's id is its index in that array.

**Fix.** A route is read only while its walk lasts. Within a step, the checker and replay also read routes of walks under way when the step began, and of walks started and ended in it. Each step therefore begins by deleting every route below the lowest one still walked; the lowest only rises, so the loop stops at the first slot already freed and costs nothing on most steps. Ids keep counting, so wake-up order, which breaks ties by route id, is unchanged, and so are all fingerprints. A day run in one step and the same day run minute by minute now free routes at different moments, so the test comparing them frees both before comparing.

**Result.** The same run after the fix: 421 MB at day 25, 453 MB at day 150, 508 MB at day 350. The slow remaining growth, about 0.3 MB a day, is the caches above and people's growing memories of banks and ways; it was not pursued.

## [LIFE17-Skills-074] - (2026-10-29)

The owner added step 17 to the roadmap ahead of conflict and approved its specification: skill built from experience over a working life by the power law of practice, talents as how fast one learns, and three axe techniques priced by the logs an axe will cut. A first build learnt techniques by watching or by trial after a competent axe; in a year nobody learnt one. The owner then replaced learning: every attempt can fail and still teaches, people think of techniques themselves (more often the open) or see one in an axe they buy, watching is dropped, and people practise in free time (longer the conscientious). The revised specification was approved and built.
Expand Down
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ The 3D world draws each firm and Government across its plot: `buildingScale` str
- **Ways.** `ways.ts` keeps each person's remembered ways: immutable corridors of triangles between two ends (the hearth, a place, a known bank point), at most `waysRemembered` (64), the least recently used forgotten first. A walk to such an end takes a way that holds the walker's triangle, whole or joined part-way, in either direction; the route is pulled straight along the way's corridor at the walker's current load. A way is planned again once a day has passed and the person has seen new ground since, or at once if it crosses ground no longer known. Walk events record whether the walk used a way, joined one or planned a new one. An idle person with nothing to explore takes one leisure walk a day along the way from home used longest ago (`leisureMinute`), goes home when away, and otherwise rests.
- **Ties.** `ties.ts` keeps each person's ties: an immutable record per person known, at most `tiesRemembered` (150), the least familiar forgotten first. A tie holds familiarity (minutes spent standing within talking distance, counted once at the end of a task in both ties), credit (minutes of work given less received) and grievance (minutes, from refusals), each fading by `tieFadePerMillion` a day with its own remainder. After an exchange, a person who needs food or wood asks the people met, closest tie first and each at most once a day; the one asked gives up to what they can spare and the asker lacks when their goodwill covers what the asker already owes, and otherwise refuses. Gifts move food lots or wood and are recorded as `gift` events; refusals as `refusal` events; time together as `together` events.
- **Skills and techniques.** `skills.ts` holds each person's experience in integer seconds for foraging, wood and each axe technique. At midnight `skillDay` fades it by a fixed share a day (half in ten years) and adds the day's work times `daysPerYear`-anchored talent, then sets skill as `floor + (ceiling − floor)·E/(E + half)`, from 50% towards 150%. Talents are drawn once by `drawTalents` and founders start with years of experience. A person holds two bitsets: `ideas`, the techniques they may try, and `known`, those they have made one of that worked. Founders have the idea of what they know. After every stint of axe work, `inventAfter` draws from the invent stream for each technique whose prerequisite is known, at a chance per hour of work raised by openness; buying an axe gives the idea of its technique. Proficiency is defined for every idea and carries a share of the person's other technique experience. `axes.ts` begins an axe with an attempt drawn from the attempt stream (`attemptOf`): it works with a chance rising with proficiency above the floor, or breaks at a drawn second, losing its stone and returning its wood; the first success by an idea makes it known. Needed axes use the known technique with least work per working log, counting a stone fetch when the person holds no spare. Under priority 9, `practiceChoice` in `forager.ts` spends a daily budget raised by conscientiousness on practice axes, untried ideas first, fetching a stone within exploring range; only practice tries an idea. A practice axe that works when its maker already holds an axe and a spare is taken apart (`dismantled`), its stone and wood back in hand. `leisureWalk` allows one walk in `leisureWalkDays` days. `skillViolations`, the checker's replay of attempt and invention draws, and its midnight replay hold experience, ideas, techniques and practice to these rules.
- **Tasks and lazy bodies.** `tasks.ts` builds a `TaskRecord` (kind, start and end minute, place, route, reason, starting body and load). `body.ts` gives energy and water at any minute of a task in closed form (`energyAt`, `waterAt`), and `positionAt` gives the position along its route. Nobody is advanced minute by minute. Food, wood, fire, huts, axes, trade and skills (`food.ts`, `work.ts`, `fire.ts`, `huts.ts`, `axes.ts`, `trade.ts`, `practice.ts`, `social.ts`) apply their rules when a task settles or two people meet.
- **Tasks and lazy bodies.** `tasks.ts` builds a `TaskRecord` (kind, start and end minute, place, route, reason, starting body and load). `body.ts` gives energy and water at any minute of a task in closed form (`energyAt`, `waterAt`), and `positionAt` gives the position along its route. A route is stored in `state.routes` under its id while a walk can read it; each step first frees every route below the lowest still walked (`releaseRoutes`), and ids keep counting. Nobody is advanced minute by minute. Food, wood, fire, huts, axes, trade and skills (`food.ts`, `work.ts`, `fire.ts`, `huts.ts`, `axes.ts`, `trade.ts`, `practice.ts`, `social.ts`) apply their rules when a task settles or two people meet.
- **Checker.** `invariants.ts` checks each interval against the preceding immutable state. `replay.ts` keeps separate stock, fish, body, tool, hut and water ledgers, replays recorded transfers and regrowth, and compares them with the returned state. `replayTies` replays time together, gifts, refusals and the midnight fade, and checks each gift against the giving rule. Geography is checked once.

`ruleFixtures.ts` is imported only by tests: surveyed ground and small explicit lakes isolate rules without changing production starts.
Expand Down
17 changes: 16 additions & 1 deletion src/valley/engine.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { addTestLake } from './ruleFixtures'
import { describe, expect, it } from 'vitest'
import { advanceValley, createValley, stepValley, cloneValley } from './engine'
import { advanceValley, createValley, stepValley, cloneValley, releaseRoutes } from './engine'
import { FLAT_LAND } from './config'
import { WakeQueue } from './clock'

Expand All @@ -27,6 +27,9 @@ describe('wake-up engine', () => {
for (let minute = 1; minute <= 1_440; minute += 1) single = stepValley(single, minute)
batch.lastInterval = []
single.lastInterval = []
// Single steps free finished routes sooner; both hold the same ones once freed up to the same lowest walk.
releaseRoutes(batch)
releaseRoutes(single)
expect(batch).toEqual(single)
expect(state).toEqual(before)
})
Expand Down Expand Up @@ -64,6 +67,9 @@ describe('wake-up engine', () => {
for (let minute = 1; minute <= 1_440; minute += 1) single = stepValley(single, minute)
batch.lastInterval = []
single.lastInterval = []
// Single steps free finished routes sooner; both hold the same ones once freed up to the same lowest walk.
releaseRoutes(batch)
releaseRoutes(single)
expect(batch).toEqual(single)
expect(state).toEqual(before)
})
Expand All @@ -76,6 +82,15 @@ describe('wake-up engine', () => {
expect(owned).toEqual(stepped)
}
})
it('frees the routes below the lowest still walked and keeps counting ids', () => {
// Routes are freed as a step begins, so the step with no minutes frees those of the walks ended before it.
const state = advanceValley(advanceValley(createValley(FLAT_LAND), 2_880), 2_880)
const walked = state.foragers.flatMap((p) => (p.task?.kind === 'walk' ? [p.task.routeId] : []))
const lowest = Math.min(state.routes.length, ...walked)
expect(lowest).toBeGreaterThan(0)
for (let id = 0; id < state.routes.length; id += 1) expect(id in state.routes).toBe(id >= lowest)
for (const id of walked) expect(state.routes[id]).toBeDefined()
})
})

describe('food, water and wood tasks', () => {
Expand Down
12 changes: 12 additions & 0 deletions src/valley/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,17 @@ export function stepValley(previous: ValleyState, toMinute = previous.minute + 1
throw new Error('Target minute must be a safe integer at or after the current minute')
return advanceValley(cloneValley(previous), toMinute, stop)
}
/**
* Frees the routes no walk can read again. A route is read only while its walk lasts, and by the step's checks and
* replay for walks under way when the step began, so every route below the lowest one still walked is dropped. Ids
* keep counting, so nothing else changes; without this a year's routes outgrow the heap.
*/
export function releaseRoutes(state: ValleyState) {
let lowest = state.routes.length
for (const person of state.foragers) if (person.task?.kind === 'walk') lowest = Math.min(lowest, person.task.routeId)
// Routes below an earlier lowest were freed then, and the lowest only rises, so this stops at the last one freed.
for (let id = lowest - 1; id >= 0 && state.routes[id] !== undefined; id -= 1) delete state.routes[id]
}
/**
* Runs `state` itself on to `toMinute`, exactly as `stepValley` runs a copy of it, and returns it. Only for a caller
* that owns the state and never reads it again as it was, such as the engine's worker: the copy each step makes, and
Expand All @@ -529,6 +540,7 @@ export function advanceValley(state: ValleyState, toMinute = state.minute + 1, s
throw new Error('Target minute must be a safe integer at or after the current minute')
const start = state.minute
state.lastInterval = []
releaseRoutes(state)
if (toMinute === start) return state
while (state.queue.peek() && state.queue.peek()!.minute <= toMinute) {
if (stop && state.queue.peek()!.minute > state.minute && state.minute > start && stop()) {
Expand Down
Loading