Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
107 commits
Select commit Hold shift + click to select a range
b49177e
fix(environment): keep read-only POSTs out of the write list
earakely-scale Oct 22, 2026
d5a1fa9
fix(environment): take an entity an unplanned write made when a read …
earakely-scale Oct 22, 2026
004b064
fix(environment): plan a create into the type its returned id is read…
earakely-scale Oct 22, 2026
d8f9c05
fix(environment): end a type's initial reads at the write its reads d…
earakely-scale Oct 22, 2026
64e472a
fix(environment): replay request lines that show entities in another …
earakely-scale Oct 22, 2026
28c3ae9
docs(environment): specify and record the state-target changes
earakely-scale Oct 22, 2026
48d7fae
fix(environment): keep a read-only POST a write when its evidence is …
earakely-scale Oct 22, 2026
5d48df7
fix(environment): answer a field selection only when the state shows …
earakely-scale Oct 22, 2026
ce2301d
fix(environment): hold adopted entities and linked creates to what th…
earakely-scale Oct 22, 2026
48106e1
Merge remote-tracking branch 'origin/main' into feat/environment-stat…
earakely-scale Oct 22, 2026
6656816
docs(environment): record the review fixes' measurements
earakely-scale Oct 22, 2026
22e27b1
fix(environment): release a discarded planning pass before planning a…
earakely-scale Oct 22, 2026
5702983
fix(environment): link no create whose id an earlier read showed, and…
earakely-scale Oct 22, 2026
0cf3b27
fix(environment): let the gate skip exactly the reads serving replays
earakely-scale Oct 22, 2026
096b1ca
Merge remote-tracking branch 'origin/main' into feat/environment-stat…
earakely-scale Oct 22, 2026
197b1a3
docs(environment): record the second review round's checks
earakely-scale Oct 22, 2026
5e2e84c
Merge remote-tracking branch 'origin/main' into st
earakely-scale Oct 23, 2026
0ed9e8c
fix(environment): read writes, links and creation cuts only from evid…
earakely-scale Oct 23, 2026
ed78be2
docs(environment): record the third review round's checks
earakely-scale Oct 23, 2026
c983edf
fix(environment): tie linked creates to their returned ids and order …
earakely-scale Oct 23, 2026
fa9f69c
docs(environment): record the fourth review round's checks
earakely-scale Oct 23, 2026
b8c164e
Merge commit '5d6b8a0ab' into st
earakely-scale Oct 23, 2026
f044816
Merge commit 3c5c887a2 into st
earakely-scale Oct 23, 2026
a6adf12
Merge commit '5f702dd6c^' into st
earakely-scale Oct 23, 2026
92f88a9
Merge commit 5f702dd6c into st
earakely-scale Oct 23, 2026
d04ba9d
Merge remote-tracking branch 'origin/main' into st
earakely-scale Oct 23, 2026
294fa3c
fix(environment): keep foreign keys, stale reads and double decoding …
earakely-scale Oct 23, 2026
ce9a153
docs(environment): record the fifth review round's checks
earakely-scale Oct 23, 2026
169842b
fix(environment): compare linked sources by position, decode path fie…
earakely-scale Oct 23, 2026
e3c5b23
docs(environment): record the sixth review round's checks
earakely-scale Oct 23, 2026
a3dbf79
Merge remote-tracking branch 'origin/main' into st
earakely-scale Oct 23, 2026
ca3eead
fix(environment): replay late and variant-only items, fill linked pat…
earakely-scale Oct 23, 2026
eb9344b
docs(environment): record the seventh review round's checks
earakely-scale Oct 23, 2026
94b8c55
fix(environment): blame a failed read on the writes whose fields it d…
earakely-scale Oct 23, 2026
fcf8d1a
fix(environment): explain unsent update changes and nested clocks by …
earakely-scale Oct 23, 2026
b1ca254
fix(environment): order collections by whole lines and sort only arra…
earakely-scale Oct 23, 2026
59439f5
Merge remote-tracking branch 'origin/main' into st
earakely-scale Oct 23, 2026
189152d
feat(environment): serve bulk writes at a collection and target item …
earakely-scale Oct 23, 2026
147ff45
fix(environment): decide late item lines against the lines left, char…
earakely-scale Oct 23, 2026
8876143
docs(environment): record the eighth review round's checks
earakely-scale Oct 23, 2026
6037875
fix(environment): set aside response members a path mints anew on eve…
earakely-scale Oct 23, 2026
342933e
fix(environment): count only reads finished before a linked create be…
earakely-scale Oct 23, 2026
0caf400
Merge #6385 head 342933ea into feat/environment-write-rules
earakely-scale Oct 23, 2026
cfa8310
fix(environment): count a list total nested in a paging object
earakely-scale Oct 23, 2026
65ba035
fix(environment): take a created entity's nested clocks from its read…
earakely-scale Oct 23, 2026
9d0dc27
fix(environment): import the compare tool definition as a type
earakely-scale Oct 23, 2026
c567281
docs(environment): describe the new write rules and trim repeated par…
earakely-scale Oct 23, 2026
7ef08a3
fix(environment): confirm no update whose clocks or fields the eviden…
earakely-scale Oct 23, 2026
434db04
fix(environment): show pinned query and body values in the served cat…
earakely-scale Oct 23, 2026
08c2532
docs(environment): specify and record the write-rule changes
earakely-scale Oct 23, 2026
456cfdf
Merge remote-tracking branch 'origin/main' into st
earakely-scale Oct 23, 2026
e08f003
fix(environment): keep served creates' items missing, check same-type…
earakely-scale Oct 23, 2026
e4c4940
docs(environment): record the ninth review round's checks
earakely-scale Oct 23, 2026
fd67f4f
Merge commit '0bbd635ab^' into wr2
earakely-scale Oct 23, 2026
d447349
Merge commit 0bbd635ab into wr2
earakely-scale Oct 23, 2026
391fe2c
Merge commit 'e4c494087' into wr2
earakely-scale Oct 23, 2026
1c8588a
Merge remote-tracking branch 'origin/main' into st
earakely-scale Oct 23, 2026
6ee9703
fix(environment): link creates past empty item reads, sweep repeated …
earakely-scale Oct 23, 2026
88ee22e
docs(environment): record the tenth review round's checks
earakely-scale Oct 23, 2026
72f0442
Merge commit '88ee22e2d' into wr2
earakely-scale Oct 23, 2026
d3828d5
fix(environment): take bulk ids literally, check each recorded call's…
earakely-scale Oct 23, 2026
364891b
docs(environment): record the review fixes' checks
earakely-scale Oct 23, 2026
2c0e7bd
Merge remote-tracking branch 'origin/main' into st
earakely-scale Oct 23, 2026
12e4df7
Merge remote-tracking branch 'origin/main' into wr2
earakely-scale Oct 24, 2026
5d612dc
Merge commit '2c0e7bdde' into wr2
earakely-scale Oct 24, 2026
c166a69
Merge remote-tracking branch 'origin/main' into st
earakely-scale Oct 24, 2026
4e622bb
Merge commit 'c166a694e6abd7e9c3c16ae4f938d0ef9f0d8fb6' into wr2
earakely-scale Oct 24, 2026
9614465
perf(environment): compare variant lines through shared entities and …
earakely-scale Oct 24, 2026
53b2966
docs(environment): record the eleventh review round's checks
earakely-scale Oct 24, 2026
715c578
Merge commit '53b2966c5' into wr2
earakely-scale Oct 24, 2026
f151988
Merge remote-tracking branch 'origin/main' into feat/environment-stat…
kaoru0822-kitauji Oct 24, 2026
b82e276
Merge remote-tracking branch 'origin/main' into feat/environment-writ…
kaoru0822-kitauji Oct 24, 2026
3dd85f2
perf(environment): list a type's collections only when the path's own…
earakely-scale Oct 24, 2026
f55c731
Merge remote-tracking branch 'origin/main' into st
earakely-scale Oct 24, 2026
6273d9b
Merge commit 'f55c73151' into wr2
earakely-scale Oct 24, 2026
dee4dd7
docs(environment): record the twelfth review round's checks and the s…
earakely-scale Oct 24, 2026
751af03
Merge commit 'dee4dd757a5a55f920f32c956f951ab4509c07f0' into wr2
earakely-scale Oct 24, 2026
f01215d
docs(environment): record the 50-capture sweep's wall, CPU and peak m…
earakely-scale Oct 24, 2026
3608c5a
Merge remote-tracking branch 'fork/feat/environment-state-targets' in…
earakely-scale Oct 24, 2026
5a6b4f1
Merge commit '3608c5aa2c2bd5aaa4c9786bdb9855996134e11b' into wr2
earakely-scale Oct 24, 2026
7584387
Merge remote-tracking branch 'fork/feat/environment-write-rules' into…
earakely-scale Oct 24, 2026
192db6c
chore: integrate latest main into environment write rules
gensokyo-dev Oct 24, 2026
3b66ee2
fix(environment): remove duplicate schema after main integration
gensokyo-dev Oct 24, 2026
f501e23
fix(environment): honor recorded bulk identity kinds
gensokyo-dev Oct 24, 2026
2c62bb9
fix(environment): retain scoped evidence and honor write defaults
gensokyo-dev Oct 24, 2026
352c027
test(environment): keep SDK regressions independently scoped
gensokyo-dev Oct 24, 2026
de4035a
docs(environment): record scoped write verification and measured costs
gensokyo-dev Oct 24, 2026
9942863
Merge remote-tracking branch 'origin/main' into integrate/6897-write-…
gensokyo-dev Oct 24, 2026
b3d706f
chore: merge main into environment write rules
morluto Oct 24, 2026
41aff3d
fix(environment): serve bulk writes whose response lists each entity …
earakely-scale Oct 24, 2026
a319ba1
docs(environment): measure the 50 captures at the scoped-envelope head
earakely-scale Oct 24, 2026
3fe3b0a
fix(environment): classify bulk responses and release verifier transf…
morluto Oct 24, 2026
f4bc513
fix(environment): classify and verify complete bulk responses
gensokyo-dev Oct 24, 2026
390541e
fix(javascript): retain capture context along covered mutation paths
morluto Oct 24, 2026
72ce7d6
merge: retain author bulk regressions with shared response verification
gensokyo-dev Oct 24, 2026
5ae634f
test(environment): verify bulk responses through the real MCP SDK
gensokyo-dev Oct 24, 2026
585d71c
test(environment): separate bulk response proof regressions
gensokyo-dev Oct 24, 2026
e73355e
chore: retain concurrent bulk response verification
morluto Oct 24, 2026
3e1b023
fix(environment): preserve request absence and generated value relati…
gensokyo-dev Oct 24, 2026
ac5f217
Merge commit 'e73355e1326aeaf4558d5a913596de627ae35bb2' into integrat…
gensokyo-dev Oct 24, 2026
034eed4
merge: sync main and keep its canonical JavaScript mutation analysis
gensokyo-dev Oct 24, 2026
75817ba
fix(environment): verify complete nested clocks on creates
gensokyo-dev Oct 24, 2026
5b91c99
fix(javascript): erase inline type imports before binding values
morluto Oct 24, 2026
ea64ca4
chore: sync main and retain canonical JavaScript binding fixes
morluto Oct 24, 2026
130121f
fix(environment): share complete generated value verification
gensokyo-dev Oct 24, 2026
7f01865
fix(verifiers): load the Windows source graph only when needed
gensokyo-dev Oct 24, 2026
7360127
fix(environment): validate write responses before stored clock restamps
gensokyo-dev Oct 24, 2026
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
Prev Previous commit
Next Next commit
fix(environment): order collections by whole lines and sort only arra…
…ys a read-back proves sorted

A collection's initial order comes from the first list line that shows every entity its
type's sightings do and applies no order. A view renders a string-array field sorted
only after a counted read-back shows the written values in an order that neither the
written order nor existing-values-first explains, and never once a read showed it
unsorted. Sort and direction parameters share one vocabulary and are never learned as
inert, and a create placed by disagreeing sorts or a random id falls back to last.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
earakely-scale and claude committed Oct 23, 2026
commit b1ca2547f8c3037c75bd7446df4718cf6550f922
9 changes: 6 additions & 3 deletions docs/specs/agent-environments/list-queries/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ the line recorded, from the collection's initial entities, explains it:
nothing else matched); an empty term matches everything, and a term that matched no field leaves the parameter inert
until another line's term does;
- `sort` by the field the value names, with `-` or an `asc`/`desc` suffix, and `direction` for a separate `asc`/`desc`
parameter: numbers by value, text ignoring case, null last ascending, ties (case-only differences included) in state
(or `ascending`/`descending`) parameter: numbers by value, text ignoring case, null last ascending, ties (case-only differences included) in state
order; an empty selection needs no sort;
- `limit`, `offset` and `page` (counted from 1 or 0 only when the line distinguishes them) for paging; zero or a negative limit
lists every match;
Expand All @@ -39,8 +39,11 @@ Query totals retain their numeric or canonical decimal-string type. Unknown or d
`state.source` distinguishes a computed response from recording replay; `replay.exact_match` describes only the
retained source envelope and can be false for a correctly computed new query.

Parameter names decide which roles are tried (`sort` for `orderBy`, `search` for `q`), and any parameter may be a
filter or inert. No two parameters of one call take the same `sort`, `direction` or paging role: the answer would
Parameter names decide which roles are tried (`sort` for `orderBy`, `search` for `q`), and any other parameter may be a
filter or inert. A name asking for an order in any common spelling (`_sort`, `sort[]`, `sort[0][field]`, `sorters[...]`,
`sort-column`, `sortKey`, `orderBy`) is only a `sort`; a direction name (`_order`, `sortDirection`, `dir`) given a direction
is only a `direction`, and given anything else is an ordinary parameter; `reverse` is never inert unless false. The same
vocabulary decides which lines set a collection's initial order (see the state view). No two parameters of one call take the same `sort`, `direction` or paging role: the answer would
depend on which applied last, and serving supplies a call's values in name order rather than as recorded, so such a
combination explains no line and such a call replays its recording. A line with more than 12 query parameters is left
unexplained, which bounds the search; names such as `__proto__` are kept as the query's own members. The lines' roles
Expand Down
6 changes: 4 additions & 2 deletions docs/specs/agent-environments/state-coverage/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,10 @@ tool, view kind, provider, network activity or write effect.
value. Objects at the root or in one member keep precedence. `at` and
`replaceAt` read and replace exactly these forms besides the root and one
member, so the gate and renderers run unchanged.
- An entity's state order is its earliest sighting on the timeline and it cites
its records in timeline order, whichever plan observed it first.
- An entity's state order is its place on the first whole line its collection's
application order lists, else its earliest sighting on the timeline (see
the state view); it cites its records in timeline order, whichever plan
observed it first.
- Each tool description reads `METHOD template; <returns>; recorded statuses
…; replays retained records […]; evidence ev_…` after the untrusted-catalog
warning. `<returns>` describes one level deep the first cited `2xx` record
Expand Down
17 changes: 17 additions & 0 deletions docs/specs/agent-environments/state-view/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,23 @@ later increments.
under the view's separator, with its own fraction digits padded with zeros to
the view's width and none dropped; an epoch spelling is computed from the
instant.
- An item or list view names in `sorted_arrays` the fields it lists as string
arrays in code-point order whatever order they were written in (tags kept as
a set). Only the write gate learns it. A field is a candidate when every
initial entity shows it as a sorted string array or null, one with two
distinct strings, and no read the gate counts has listed it unsorted with two
distinct strings. It is learned from a counted read that fails with the
stored order and passes with the field sorted, and only when that read lists
a written array in an order that is neither the written one nor values the
initial state held first, then the new ones as written (an application
ordering by tag id or creation shows that order too). The stored value keeps
the written order, so a write's own answer echoes it; every view of the type
for which the field is still a candidate sorts it as well.
- A collection's initial order is the order of the first line that lists every
entity any initial read shows in it and names no sort, direction (`sort[]`,
`_sort`, `sort-column`, `sortKey`, `orderBy` and like spellings) or random
parameter (`random`, `rand`, `shuffle`, `seed`); a collection without such a
line keeps its entities' earliest sightings.
- A list has `all` membership only when no item-total envelope member (`total`,
`count` and their compounds, not page counts) differs from the number of
entities it lists and no `has_more`, `next` or next-page token is set.
Expand Down
14 changes: 13 additions & 1 deletion docs/specs/agent-environments/state-writes/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,13 @@ and the state is left unchanged.
collection's order: sorted by the identity field or a clock field (ascending
or descending), `first` or `last`. The rule is the first candidate consistent
with both the initial `all`-membership recordings and the position a later
recorded list shows. With no evidence, the rule is `last`.
recorded list shows. With no evidence, the rule is `last`. A sort by a
random identity (version 4 UUIDs, or generated ids every creation clock lists
in another order) is a candidate only after `last`: the recorded order by it is
a coincidence until a list shows a create placed by it; time-ordered ids
(ObjectId, ULID, TSID, version 7 UUIDs) keep it. When the sorts the recorded
order admits would place the created entity differently, none is claimed
before `last` until a later list settles it.

## The gate

Expand Down Expand Up @@ -456,6 +462,12 @@ refuses to answer with.
- After a failed item check, the copy takes the read's recorded values (or
drops the entity on a recorded absence). A list whose check failed is not
checked again.
- A failed item or list read the gate counts passes when the view lists some
string-array fields sorted and its order rules out the written one and the
order the values were first held in (see `sorted_arrays` in the state view);
the type's views keep the fewest such fields the read needs, and the read
checks the writes it exercises. A counted read listing such a field unsorted
rules it out for its view.
- A list that fails only for where one create placed its entity passes when
another of that create's insert candidates reproduces it, which then
becomes the plan's rule, unless an earlier list check relied on the rule
Expand Down
32 changes: 32 additions & 0 deletions src/application/environment/environmentStateWriteAnswer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2065,3 +2065,35 @@ describe("path fields of creates read under another path", () => {
}
});
});

describe("array fields a view lists sorted", () => {
it("answers the update with the written order and later reads with it sorted", () => {
const tagged = (entry: Book, tags: string[]): Book => ({ ...entry, tags });
const books = servedFrom([
[
"GET",
"/api/books",
[tagged(FIRST_BOOK, ["alpha", "beta"]), tagged(SECOND_BOOK, ["gamma"])],
],
["GET", "/api/books/1", tagged(FIRST_BOOK, ["alpha", "beta"])],
["GET", "/api/books/2", tagged(SECOND_BOOK, ["gamma"])],
[
"PATCH",
"/api/books/2",
tagged(SECOND_BOOK, ["zeta", "delta"]),
200,
{ tags: ["zeta", "delta"] },
],
["GET", "/api/books/2", tagged(SECOND_BOOK, ["delta", "zeta"])],
]);
expect(
books.answer("patch_books_by_id", {
id: "1",
body: { tags: ["omega", "beta"] },
}).body,
).toMatchObject({ tags: ["omega", "beta"] });
expect(books.answer("get_books_by_id", { id: "1" }).body).toMatchObject({
tags: ["beta", "omega"],
});
});
});
5 changes: 5 additions & 0 deletions src/domain/analysisView/EnvironmentStateExtraction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import {
type ObservedEntity,
type StateObservation,
} from "./environmentStateMerge.js";
import { orderByWholeLines } from "./environmentStateInitialOrder.js";
import { rewriteCuts, type RewriteSpan } from "./environmentStateRewrites.js";
import {
checkItemPlan,
Expand Down Expand Up @@ -209,6 +210,10 @@ export class EnvironmentStateExtraction {
this.#planList(candidate);
for (const plan of this.#plans) this.#observePlan(plan);
this.#dropVariants();
orderByWholeLines(
this.#entities.values(),
(ordinal) => this.#byOrdinal.get(ordinal)?.query,
);
this.#classifyChanges();
this.#merge();
return candidates;
Expand Down
31 changes: 29 additions & 2 deletions src/domain/analysisView/EnvironmentStateWriteSimulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { linkedTarget } from "./environmentStateWriteLinks.js";
import { updatedEntity } from "./environmentStateWriteApply.js";
import { projectedRead } from "./environmentStateWriteObserve.js";
import { OmittedFields } from "./environmentStateWriteOmitted.js";
import { SortedArrays } from "./environmentStateWriteSorted.js";
import {
checkDocumentRead,
checkItemRead,
Expand Down Expand Up @@ -100,6 +101,8 @@ export class EnvironmentStateWriteSimulation {
readonly #effects = new WriteEffects();
/** Fields reads show the application leaves out, which serving then does not require. */
readonly omitted = new OmittedFields((bytes) => this.#input.io.retain(bytes));
/** Array fields reads showed a view lists sorted. */
readonly #sorted: SortedArrays;
readonly #lastCheck = new Map<string, number>();
/** When the latest modelled write to each target since its last check ended. */
readonly #touchedSince: PendingTargets = new Map();
Expand Down Expand Up @@ -150,6 +153,11 @@ export class EnvironmentStateWriteSimulation {
for (const ordinal of tool.record_ordinals)
this.#toolOf.set(ordinal, tool);
this.#checkedLines = checkedLines(input);
this.#sorted = new SortedArrays(input.views.values(), input.entities, {
state: this.#state,
io: input.io,
idField: (type) => this.#types.get(type)?.id_field,
});
this.#taint = new WriteTaint(
[...this.#types.keys()],
new Map(
Expand Down Expand Up @@ -231,7 +239,7 @@ export class EnvironmentStateWriteSimulation {
const view = this.#input.views.get(
this.#toolOf.get(ordinal)?.name ?? "",
);
return view === undefined ? undefined : this.omitted.view(view);
return view === undefined ? undefined : this.#viewOf(view);
},
idField: (type) => this.#types.get(type)!.id_field,
observed: (ordinal) =>
Expand Down Expand Up @@ -424,10 +432,20 @@ export class EnvironmentStateWriteSimulation {
return servedLine(this.#checkedLines.get(view.tool), record);
}

/** The view as the gate currently knows it: without the fields reads showed omitted, with the arrays they showed sorted. */
#viewOf(view: StateView): StateView {
return this.#sorted.view(this.omitted.view(view));
}

/** The views as reads showed them. */
views(views: readonly StateView[]): StateView[] {
return this.#sorted.views(this.omitted.views(views));
}

#read(record: StateRecordFacts, index: number, tool: StateToolFacts): void {
const original = this.#input.views.get(tool.name);
if (original === undefined) return;
const view = this.omitted.view(original);
let view = this.#viewOf(original);
if (projectedRead(view, record, this.#input.io)) return;
const borrowers = this.#observations.get(record.ordinal);
if (!borrowers && this.#resynced(view, record, index)) return;
Expand All @@ -441,6 +459,15 @@ export class EnvironmentStateWriteSimulation {
runningAt(this.#touchedSince, key, record.start),
);
if (blocked(keys)) return;
// A read the gate counts can show the view lists a written array sorted, or rule that out.
outcome = this.#sorted.retry(
view,
{ record, outcome },
(candidate) => this.#check(candidate, record),
blocked,
);
view = this.#viewOf(original);
keys = [...outcome.targets, ...outcome.unheld];
let exercised = exercisedBy(this.#touched, keys, borrowers);
if (borrowers !== undefined) {
this.omitted.keep(view, outcome);
Expand Down
86 changes: 86 additions & 0 deletions src/domain/analysisView/environmentStateInitialOrder.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { describe, expect, it } from "vitest";

import { orderByWholeLines } from "./environmentStateInitialOrder.js";
import type {
ObservedEntity,
StateObservation,
} from "./environmentStateMerge.js";

/** One sighting: a list line's entry at `index`, or an item read when `item`. */
const sighting = (
ordinal: number,
index: number,
item = false,
): StateObservation => ({
position: ordinal,
index,
ordinal,
tool: item ? "get_books_by_id" : "get_books",
item,
object: {},
});

const entity = (id: string, ...observations: StateObservation[]) => ({
type: "/api/books",
collection: "/api/books",
id,
order: [observations[0]!.position, observations[0]!.index] as const,
observations,
});

/** The entities' ids in initial order once the whole lines rank them, given each line's query. */
const ordered = (
entities: ObservedEntity[],
queries: Readonly<Record<number, string>>,
): string[] => {
orderByWholeLines(entities, (ordinal) => queries[ordinal]);
return entities
.toSorted(
(left, right) =>
left.order[0] - right.order[0] || left.order[1] - right.order[1],
)
.map((candidate) => candidate.id);
};

describe("initial order from whole lines", () => {
it("takes the first whole line that applies no sort, random or seed parameter", () => {
const queries = {
0: "random=true",
1: "sort[]=name",
2: "sort-column=name",
3: "sortKey=name",
4: "orderDirection=desc",
5: "seed=7",
6: "page=1",
};
const lines = Object.keys(queries).map(Number);
// Every line lists both; the earlier ones apply an order of their own.
const at = (first: string) =>
lines.map((ordinal) =>
sighting(ordinal, (ordinal === 6) === (first === "b") ? 0 : 1),
);
expect(
ordered([entity("a", ...at("a")), entity("b", ...at("b"))], queries),
).toEqual(["b", "a"]);
});

it("does not take a line that lists part of the collection, or an item read", () => {
const entities = [
entity("a", sighting(0, 0, true), sighting(2, 1)),
entity("b", sighting(1, 0), sighting(2, 2)),
entity("c", sighting(2, 0)),
];
expect(ordered(entities, { 1: "name=b" })).toEqual(["c", "a", "b"]);
});

it("keeps the earliest sightings of a collection no whole default line lists", () => {
const entities = [
entity("a", sighting(1, 0), sighting(2, 1)),
entity("b", sighting(0, 0, true), sighting(2, 0)),
];
expect(ordered(entities, { 1: "status=open", 2: "sort=name" })).toEqual([
"b",
"a",
]);
});
});
58 changes: 58 additions & 0 deletions src/domain/analysisView/environmentStateInitialOrder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { ObservedEntity } from "./environmentStateMerge.js";
import { appliesOrder } from "./environmentStateOrderParameters.js";

/** Query parameters that ask for a random order. */
const RANDOM = new Set(["random", "rand", "shuffle", "seed"]);

/** Whether a recorded query leaves the order to the application: no sort, direction or random parameter. */
const defaultOrder = (query: string | null | undefined): boolean =>
[...new URLSearchParams(query ?? "").keys()].every(
(name) => !appliesOrder(name) && !RANDOM.has(name.toLowerCase()),
);

/**
* Order each collection's entities as the earliest whole list line in the application's own order
* shows them: a line that lists every entity any initial read shows in the collection and applies no
* sort, direction or random parameter. A collection without such a line keeps its earliest sightings.
*/
export const orderByWholeLines = (
entities: Iterable<ObservedEntity>,
queryOf: (ordinal: number) => string | null | undefined,
): void => {
const collections = new Map<string, ObservedEntity[]>();
for (const entity of entities) {
const key = `${entity.type}\u0000${entity.collection}`;
const members = collections.get(key);
if (members === undefined) collections.set(key, [entity]);
else members.push(entity);
}
for (const members of collections.values()) {
const lines = new Map<number, { position: number; listed: number }>();
for (const entity of members)
for (const observation of entity.observations) {
if (observation.item) continue;
const line = lines.get(observation.ordinal);
if (line === undefined)
lines.set(observation.ordinal, {
position: observation.position,
listed: 1,
});
else line.listed += 1;
}
let first: [number, number] | undefined;
for (const [ordinal, line] of lines)
if (
line.listed === members.length &&
(first === undefined || line.position < first[1]) &&
defaultOrder(queryOf(ordinal))
)
first = [ordinal, line.position];
if (first === undefined) continue;
for (const entity of members) {
const sighting = entity.observations.find(
(observation) => !observation.item && observation.ordinal === first[0],
)!;
entity.order = [sighting.position, sighting.index];
}
}
};
27 changes: 27 additions & 0 deletions src/domain/analysisView/environmentStateListQuery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,3 +374,30 @@ describe("queries the state can always answer", () => {
});
});
});

describe("parameters that ask for an order", () => {
it("reads a sort field in any spelling as a sort, never as a parameter without effect", () => {
expect(explainLine(line("?_sort=id&_order=DESC", [4, 3, 2, 1]))).toEqual({
_sort: { role: "sort" },
_order: { role: "direction" },
});
expect(
explainLine(line("?sortKey=id&sortDirection=descending", [4, 3, 2, 1])),
).toEqual({
sortKey: { role: "sort" },
sortDirection: { role: "direction" },
});
// A sort value naming no field leaves the line unexplained rather than without effect.
expect(explainLine(line("?_sort=newest", [1, 2, 3, 4]))).toBeUndefined();
});

it("reads a direction name given no direction as an ordinary parameter", () => {
expect(explainLine(line("?direction=shared-by", [1, 2, 3, 4]))).toEqual({
direction: { role: "inert", values: ["shared-by"] },
});
expect(explainLine(line("?reverse=false", [1, 2, 3, 4]))).toEqual({
reverse: { role: "inert", values: ["false"] },
});
expect(explainLine(line("?reverse=true", [1, 2, 3, 4]))).toBeUndefined();
});
});
Loading