Skip to content

knotkit/evolution

Runs deterministic population evolution with index-based parent selection and immutable permutation operators

import {
function evolution<T>(options: EvolutionOptions<T>): Evolution<T>

Create a deterministic population evolution backed by closure state.

Construction copies the initial array and evaluates every candidate exactly once. Each step() calls nextPopulation exactly once and evaluates each returned candidate exactly once. Equal scores retain the first best candidate encountered, including across generations. Snapshot arrays and wrapper records are frozen, but arbitrary candidate values are not cloned or deep-frozen; callers and policies must treat them as immutable. Randomness is consumed only by the caller's policy through the injected source. Callback exceptions pass through unchanged.

@throws ― {EvolutionInvalidInputError} With code EMPTY_POPULATION when the initial population is empty, INVALID_OBJECTIVE when the objective is unsupported, or INVALID_SCORE when evaluation returns a non-finite score.

evolution
,
function inversionMutation<T>(values: readonly T[], first: number, second: number): readonly T[]

Reverse the inclusive segment between two indices in a new array. Index order is unrestricted and equal indices are a fresh-array no-op. Runs in O(n) time and space and never mutates the input.

@throws ― {EvolutionInvalidInputError} With code INVALID_PERMUTATION when values is not an array or INVALID_INDEX when either index is not a safe integer inside it.

inversionMutation
} from 'knotkit/evolution'
import {
function splitmix32(seed: number): () => number

Creates a deterministic 32-bit pseudorandom number generator.

Each call advances a private state by 0x9e3779b9. This constant equals floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo 2^32. Because the increment is odd, it is coprime to 2^32. The resulting Weyl sequence visits every 32-bit state once before it repeats.

The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from the

https://github.com/skeeto/hash-prospector hash-prospector

search for low avalanche bias. Its XOR-shifts and multiplications by odd integers are invertible over 32-bit values. The mixer therefore preserves the full period while diffusing nearby states across the output bits.

Math.imul and the bitwise operators keep the mixing steps in 32-bit arithmetic. The final unsigned conversion produces an integer from 0 to 2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).

The SplitMix family was introduced by Steele, Lea, and Flood in

https://dl.acm.org/doi/10.1145/2660193.2660195 Fast Splittable Pseudorandom Number Generators

.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― seed - Initial seed, coerced to a signed 32-bit integer.

@returns ― A stateful function that returns the next value in the range [0, 1).

splitmix32
} from 'knotkit/prng'
const
const engine: Evolution<readonly number[]>
engine
=
evolution<readonly number[]>(options: EvolutionOptions<readonly number[]>): Evolution<readonly number[]>

Create a deterministic population evolution backed by closure state.

Construction copies the initial array and evaluates every candidate exactly once. Each step() calls nextPopulation exactly once and evaluates each returned candidate exactly once. Equal scores retain the first best candidate encountered, including across generations. Snapshot arrays and wrapper records are frozen, but arbitrary candidate values are not cloned or deep-frozen; callers and policies must treat them as immutable. Randomness is consumed only by the caller's policy through the injected source. Callback exceptions pass through unchanged.

@throws ― {EvolutionInvalidInputError} With code EMPTY_POPULATION when the initial population is empty, INVALID_OBJECTIVE when the objective is unsupported, or INVALID_SCORE when evaluation returns a non-finite score.

evolution
<readonly number[]>({
EvolutionOptions<readonly number[]>.initialPopulation: readonly (readonly number[])[]
initialPopulation
: [
[0, 1, 2, 3],
[0, 2, 1, 3],
[3, 1, 2, 0],
],
EvolutionOptions<readonly number[]>.evaluate: (candidate: readonly number[]) => number
evaluate
: (
candidate: readonly number[]
candidate
) =>
candidate: readonly number[]
candidate
.
ReadonlyArray<number>.reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: readonly number[]) => number, initialValue: number): number (+2 overloads)

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

@param ― callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.

@param ― initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

reduce
((
total: number
total
,
value: number
value
,
index: number
index
) =>
total: number
total
+
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.abs(x: number): number

Returns the absolute value of a number (the value without regard to whether it is positive or negative). For example, the absolute value of -5 is the same as the absolute value of 5.

@param ― x A numeric expression for which the absolute value is needed.

abs
(
value: number
value
-
index: number
index
), 0),
EvolutionOptions<readonly number[]>.objective: Objective
objective
: 'minimize',
EvolutionOptions<readonly number[]>.random: RandomSource
random
:
function splitmix32(seed: number): () => number

Creates a deterministic 32-bit pseudorandom number generator.

Each call advances a private state by 0x9e3779b9. This constant equals floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo 2^32. Because the increment is odd, it is coprime to 2^32. The resulting Weyl sequence visits every 32-bit state once before it repeats.

The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from the

https://github.com/skeeto/hash-prospector hash-prospector

search for low avalanche bias. Its XOR-shifts and multiplications by odd integers are invertible over 32-bit values. The mixer therefore preserves the full period while diffusing nearby states across the output bits.

Math.imul and the bitwise operators keep the mixing steps in 32-bit arithmetic. The final unsigned conversion produces an integer from 0 to 2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).

The SplitMix family was introduced by Steele, Lea, and Flood in

https://dl.acm.org/doi/10.1145/2660193.2660195 Fast Splittable Pseudorandom Number Generators

.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― seed - Initial seed, coerced to a signed 32-bit integer.

@returns ― A stateful function that returns the next value in the range [0, 1).

splitmix32
(42),
EvolutionOptions<readonly number[]>.nextPopulation: (context: EvolutionContext<readonly number[]>) => readonly (readonly number[])[]
nextPopulation
: ({
snapshot: EvolutionSnapshot<readonly number[]>
snapshot
}) =>
snapshot: EvolutionSnapshot<readonly number[]>
snapshot
.
EvolutionSnapshot<readonly number[]>.population: readonly EvaluatedCandidate<readonly number[]>[]
population
.
ReadonlyArray<EvaluatedCandidate<readonly number[]>>.map<readonly number[]>(callbackfn: (value: EvaluatedCandidate<readonly number[]>, index: number, array: readonly EvaluatedCandidate<readonly number[]>[]) => readonly number[], thisArg?: any): (readonly number[])[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
(({
value: readonly number[]
value
}) =>
inversionMutation<number>(values: readonly number[], first: number, second: number): readonly number[]

Reverse the inclusive segment between two indices in a new array. Index order is unrestricted and equal indices are a fresh-array no-op. Runs in O(n) time and space and never mutates the input.

@throws ― {EvolutionInvalidInputError} With code INVALID_PERMUTATION when values is not an array or INVALID_INDEX when either index is not a safe integer inside it.

inversionMutation
(
value: readonly number[]
value
, 1, 2)),
})
const engine: Evolution<readonly number[]>
engine
.
Evolution<readonly number[]>.run(generations: number): EvolutionSnapshot<readonly number[]>

Execute exactly generations steps without retaining intermediate snapshots.

@throws ― {EvolutionInvalidInputError} With code INVALID_GENERATION_COUNT when the count is not a non-negative safe integer, EMPTY_POPULATION when a policy returns no candidates, or INVALID_SCORE when evaluation returns a non-finite score.

run
(20)
const engine: Evolution<readonly number[]>
engine
.
Evolution<readonly number[]>.snapshot(): EvolutionSnapshot<readonly number[]>

Return the frozen current snapshot without evaluating, advancing, or consuming randomness.

snapshot
().
EvolutionSnapshot<readonly number[]>.best: EvaluatedCandidate<readonly number[]>
best
// { value, score }
evolution.ts
import { type
interface EvolutionContext<T>

The current immutable snapshot and caller-owned random source supplied to a population policy.

EvolutionContext
,
function inversionMutation<T>(values: readonly T[], first: number, second: number): readonly T[]

Reverse the inclusive segment between two indices in a new array. Index order is unrestricted and equal indices are a fresh-array no-op. Runs in O(n) time and space and never mutates the input.

@throws ― {EvolutionInvalidInputError} With code INVALID_PERMUTATION when values is not an array or INVALID_INDEX when either index is not a safe integer inside it.

inversionMutation
,
function rankSelection(random: RandomSource, scores: readonly number[], selectionSize: number, objective: Objective): readonly number[]

Select source indices with replacement from exponential competition-rank weights.

Each result consumes one weighted-choice draw. Scores are validated and ranked once, remain unmodified, and the returned indices refer to the original score order.

@throws ― {EvolutionInvalidInputError} With code EMPTY_POPULATION for no scores, INVALID_SCORE for a non-finite score, INVALID_SELECTION_SIZE for a negative or unsafe selection size, or INVALID_OBJECTIVE for an unsupported objective.

@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

rankSelection
} from 'knotkit/evolution'
const
const nextPopulation: ({ snapshot, random }: EvolutionContext<readonly number[]>) => (readonly number[])[]
nextPopulation
= ({
snapshot: EvolutionSnapshot<readonly number[]>
snapshot
,
random: RandomSource
random
}:
interface EvolutionContext<T>

The current immutable snapshot and caller-owned random source supplied to a population policy.

EvolutionContext
<readonly number[]>) => {
const
const scores: number[]
scores
=
snapshot: EvolutionSnapshot<readonly number[]>
snapshot
.
EvolutionSnapshot<readonly number[]>.population: readonly EvaluatedCandidate<readonly number[]>[]
population
.
ReadonlyArray<EvaluatedCandidate<readonly number[]>>.map<number>(callbackfn: (value: EvaluatedCandidate<readonly number[]>, index: number, array: readonly EvaluatedCandidate<readonly number[]>[]) => number, thisArg?: any): number[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
(({
score: number
score
}) =>
score: number
score
)
const
const selected: readonly number[]
selected
=
function rankSelection(random: RandomSource, scores: readonly number[], selectionSize: number, objective: Objective): readonly number[]

Select source indices with replacement from exponential competition-rank weights.

Each result consumes one weighted-choice draw. Scores are validated and ranked once, remain unmodified, and the returned indices refer to the original score order.

@throws ― {EvolutionInvalidInputError} With code EMPTY_POPULATION for no scores, INVALID_SCORE for a non-finite score, INVALID_SELECTION_SIZE for a negative or unsafe selection size, or INVALID_OBJECTIVE for an unsupported objective.

@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

rankSelection
(
random: RandomSource
random
,
const scores: number[]
scores
,
const scores: number[]
scores
.
Array<number>.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

length
, 'minimize')
return
const selected: readonly number[]
selected
.
ReadonlyArray<number>.map<readonly number[]>(callbackfn: (value: number, index: number, array: readonly number[]) => readonly number[], thisArg?: any): (readonly number[])[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
index: number
index
) =>
inversionMutation<number>(values: readonly number[], first: number, second: number): readonly number[]

Reverse the inclusive segment between two indices in a new array. Index order is unrestricted and equal indices are a fresh-array no-op. Runs in O(n) time and space and never mutates the input.

@throws ― {EvolutionInvalidInputError} With code INVALID_PERMUTATION when values is not an array or INVALID_INDEX when either index is not a safe integer inside it.

inversionMutation
(
snapshot: EvolutionSnapshot<readonly number[]>
snapshot
.
EvolutionSnapshot<readonly number[]>.population: readonly EvaluatedCandidate<readonly number[]>[]
population
[
index: number
index
].
EvaluatedCandidate<readonly number[]>.value: readonly number[]
value
, 1, 2))
}
  • find a good route or schedule where improving one position at a time gets stuck
  • keep the best candidate seen across generations while a whole population changes
  • select parents in proportion to rank, then recombine two orderings into one child ordering
  • run an optimizer deterministically from a seed so a recorded run replays exactly
  • decide when to stop from a stagnation count instead of a fixed generation budget
  • mutate or cross a permutation without touching the array the caller handed in
{"v":1,"box":[44.9462,94.1597,854.9333,437.3555],"x":{"s":"linear","lim":[-1.35,31.35],"inv":false,"g":0,"t":"Generation","tk":[[0,"0"],[10,"10"],[20,"20"],[30,"30"]]},"y":{"s":"linear","lim":[-0.45,10.45],"inv":false,"g":0,"tk":[[0,"0"],[2,"2"],[4,"4"],[6,"6"],[10,"10"]]},"ti":"Best so far holds 0 from generation 8, though 19 of 22 later generations do worse","a":[{"k":"line","c":"#1d5fa6","s":"x","d":[0,10,1,6,2,4,3,2,4,2,5,2,6,2,7,2,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0],"p":[78.39,108.33,103.16,234.27,127.93,297.24,152.7,360.22,177.47,360.22,202.24,360.22,227.01,360.22,251.78,360.22,276.55,423.19,301.32,423.19,326.09,423.19,350.86,423.19,375.63,423.19,400.4,423.19,425.17,423.19,449.94,423.19,474.71,423.19,499.48,423.19,524.25,423.19,549.02,423.19,573.79,423.19,598.56,423.19,623.33,423.19,648.1,423.19,672.87,423.19,697.64,423.19,722.41,423.19,747.18,423.19,771.95,423.19,796.72,423.19,821.49,423.19],"ds":"post"},{"k":"scatter","c":"#c4501b","s":"xy","d":[0,10,1,6,2,4,3,2,4,4,5,4,6,6,7,2,8,0,9,2,10,0,11,2,12,4,13,6,14,4,15,6,16,4,17,2,18,4,19,2,20,0,21,2,22,0,23,2,24,4,25,6,26,4,27,6,28,4,29,2,30,4],"p":[78.39,108.33,103.16,234.27,127.93,297.24,152.7,360.22,177.47,297.24,202.24,297.24,227.01,234.27,251.78,360.22,276.55,423.19,301.32,360.22,326.09,423.19,350.86,360.22,375.63,297.24,400.4,234.27,425.17,297.24,449.94,234.27,474.71,297.24,499.48,360.22,524.25,297.24,549.02,360.22,573.79,423.19,598.56,360.22,623.33,423.19,648.1,360.22,672.87,297.24,697.64,234.27,722.41,297.24,747.18,234.27,771.95,297.24,796.72,360.22,821.49,297.24],"r":4.96},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"}],"lg":[]} 0 10 20 30 Generation 0 2 4 6 10 Total displacement from sorted order (positions) Best so far Best in generation Best so far holds 0 from generation 8, though 19 of 22 later generations do worse
{"v":1,"box":[44.9462,150.6246,406.9333,437.3555],"x":{"s":"linear","lim":[-1.35,31.35],"inv":false,"g":0,"t":"Generation","tk":[[0,"0"],[10,"10"],[20,"20"],[30,"30"]]},"y":{"s":"linear","lim":[-0.45,10.45],"inv":false,"g":0,"tk":[[0,"0"],[2,"2"],[4,"4"],[6,"6"],[10,"10"]]},"ti":"Best so far holds 0 from generation 8,\nthough 19 of 22 later generations do\nworse","a":[{"k":"line","c":"#1d5fa6","s":"x","d":[0,10,1,6,2,4,3,2,4,2,5,2,6,2,7,2,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0],"p":[59.89,162.46,70.96,267.68,82.03,320.3,93.1,372.91,104.17,372.91,115.24,372.91,126.31,372.91,137.38,372.91,148.45,425.52,159.52,425.52,170.59,425.52,181.66,425.52,192.73,425.52,203.8,425.52,214.87,425.52,225.94,425.52,237.01,425.52,248.08,425.52,259.15,425.52,270.22,425.52,281.29,425.52,292.36,425.52,303.43,425.52,314.5,425.52,325.57,425.52,336.64,425.52,347.71,425.52,358.78,425.52,369.85,425.52,380.92,425.52,391.99,425.52],"ds":"post"},{"k":"scatter","c":"#c4501b","s":"xy","d":[0,10,1,6,2,4,3,2,4,4,5,4,6,6,7,2,8,0,9,2,10,0,11,2,12,4,13,6,14,4,15,6,16,4,17,2,18,4,19,2,20,0,21,2,22,0,23,2,24,4,25,6,26,4,27,6,28,4,29,2,30,4],"p":[59.89,162.46,70.96,267.68,82.03,320.3,93.1,372.91,104.17,320.3,115.24,320.3,126.31,267.68,137.38,372.91,148.45,425.52,159.52,372.91,170.59,425.52,181.66,372.91,192.73,320.3,203.8,267.68,214.87,320.3,225.94,267.68,237.01,320.3,248.08,372.91,259.15,320.3,270.22,372.91,281.29,425.52,292.36,372.91,303.43,425.52,314.5,372.91,325.57,320.3,336.64,267.68,347.71,320.3,358.78,267.68,369.85,320.3,380.92,372.91,391.99,320.3],"r":4.96},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"}],"lg":[]} 0 10 20 30 Generation 0 2 4 6 10 Total displacement from sorted order (positions) Best so far Best in generation Best so far holds 0 from generation 8, though 19 of 22 later generations do worse
  • Evolve 12 permutations of 8 items for 30 generations, using seeds 17 and 42.
  • Best displacement went from 10 to 0. Best order: [0, 1, 2, 3, 4, 5, 6, 7].
  • The population score can rise while the engine retains the best candidate it has seen.

Hover or focus a chart for exact values. Drawn by demo.ts against knotkit/evolution.

ExportReturnsDoes
evolutionEvolution<T>Generation-at-a-time engine: construction evaluates the initial population once, each `step` calls the caller's policy and evaluates its output once, and no intermediate generation is retained.
tournamentSelectionreadonly number[]`selectionSize` winners, each from a tournament of distinct indices sampled by Floyd's algorithm; the same winner may repeat across tournaments and ties keep the first sampled index. O(k(n + t log t)) with tournament size t.
exponentialRankWeightsreadonly number[]`Math.exp(-rank)` per score after one ranking pass from best to worst, equal scores sharing a competition rank; O(n log n).
exponentialRankLogWeightsreadonly number[]`-rank` from that same ranking pass, finite for every entry so it feeds `weightedSampleFromLogWeights` without an exponentiation that underflows; O(n log n).
rankSelectionreadonly number[]`exponentialRankWeights` consumed once per output through `weightedChoice`, selecting with replacement; O(n log n + k n).
orderCrossoverreadonly T[]One child that keeps the inclusive cut segment of the first parent and fills the remaining positions in the second parent's cyclic order; O(n) expected, allocating a `Set` and a donor cycle.
swapMutationreadonly T[]Swap two positions in a copy; either index order is accepted and equal indices are a valid no-op. O(n).
inversionMutationreadonly T[]Reverse the inclusive segment between two positions in a copy; either index order is accepted. O(n).
rotateLeftMutationreadonly T[]Rotate the inclusive segment one position left in a copy; requires `first <= second`. O(n).
rotateRightMutationreadonly T[]Rotate the inclusive segment one position right in a copy; requires `first <= second`. O(n).

Cost per member. Open a row for every operation.

evolution 3 members
MemberCost
snapshotO(1)
stepO(n) plus evaluator and policy work
runO(generations) steps
InputTypeGet one from
randomness, drawn only by the caller's policy through the context and never allocated by the engineRandomSourceknotkit/prng
fitness, which decides every score and therefore every selection outcome(candidate: T) => numberthe caller
the next-generation policy, which owns selection, crossover, and mutation(context: EvolutionContext<T>) => readonly T[]the caller
objective direction, which decides what a score better than another meansObjectiveknotkit/evolution

Every error this module throws is EvolutionInvalidInputError, with a code from a closed, exported list. Branch on the code; the message is for people.

EvolutionInvalidInputError
EMPTY_POPULATION INVALID_SCORE INVALID_SELECTION_SIZE INVALID_TOURNAMENT_SIZE INVALID_OBJECTIVE INVALID_PERMUTATION INVALID_INDEX INVALID_CUT DUPLICATE_ELEMENT UNEQUAL_PARENT_DOMAIN
Other
INVALID_GENERATION_COUNT
If you need to…Use instead
a seeded random source, or control over the draw sequenceknotkit/prng
draw a sample, a pair, or a weighted selection outside a populationknotkit/sampling
a stopping rule, a checkpoint schedule, or a per-generation tracecaller code around bounded `run` calls; the engine retains only the current generation
optimize real-valued parameters where a gradient existsa derivative-based optimizer, since the shipped operators act on permutations
order the population by scoreArray.prototype.sort over `snapshot().population`

Measured by the suite in packages/evolution/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.

Prompt · knotkit/evolution
Use knotkit/evolution for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/evolution'.

Exports:
- `evolution` → `Evolution<T>`: Generation-at-a-time engine: construction evaluates the initial population once, each `step` calls the caller's policy and evaluates its output once, and no intermediate generation is retained.
- `tournamentSelection` → `readonly number[]`: `selectionSize` winners, each from a tournament of distinct indices sampled by Floyd's algorithm; the same winner may repeat across tournaments and ties keep the first sampled index. O(k(n + t log t)) with tournament size t.
- `exponentialRankWeights` → `readonly number[]`: `Math.exp(-rank)` per score after one ranking pass from best to worst, equal scores sharing a competition rank; O(n log n).
- `exponentialRankLogWeights` → `readonly number[]`: `-rank` from that same ranking pass, finite for every entry so it feeds `weightedSampleFromLogWeights` without an exponentiation that underflows; O(n log n).
- `rankSelection` → `readonly number[]`: `exponentialRankWeights` consumed once per output through `weightedChoice`, selecting with replacement; O(n log n + k n).
- `orderCrossover` → `readonly T[]`: One child that keeps the inclusive cut segment of the first parent and fills the remaining positions in the second parent's cyclic order; O(n) expected, allocating a `Set` and a donor cycle.
- `swapMutation` → `readonly T[]`: Swap two positions in a copy; either index order is accepted and equal indices are a valid no-op. O(n).
- `inversionMutation` → `readonly T[]`: Reverse the inclusive segment between two positions in a copy; either index order is accepted. O(n).
- `rotateLeftMutation` → `readonly T[]`: Rotate the inclusive segment one position left in a copy; requires `first <= second`. O(n).
- `rotateRightMutation` → `readonly T[]`: Rotate the inclusive segment one position right in a copy; requires `first <= second`. O(n).

Inputs and their sources:
- randomness, drawn only by the caller's policy through the context and never allocated by the engine: `RandomSource` from `knotkit/prng`
- fitness, which decides every score and therefore every selection outcome: `(candidate: T) => number` from `the caller`
- the next-generation policy, which owns selection, crossover, and mutation: `(context: EvolutionContext<T>) => readonly T[]` from `the caller`
- objective direction, which decides what a score better than another means: `Objective` from `knotkit/evolution`

Use something else when:
- a seeded random source, or control over the draw sequence → knotkit/prng
- draw a sample, a pair, or a weighted selection outside a population → knotkit/sampling
- a stopping rule, a checkpoint schedule, or a per-generation trace → caller code around bounded `run` calls; the engine retains only the current generation
- optimize real-valued parameters where a gradient exists → a derivative-based optimizer, since the shipped operators act on permutations
- order the population by score → Array.prototype.sort over `snapshot().population`

Errors are EvolutionInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/evolution.md
Types: node_modules/knotkit/evolution/ and https://knotkit.jkomyno.dev/reference/knotkit/evolution/