counterparts 0.3.19 → 0.3.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/README.md +12 -4
  3. package/docs/module-map.md +6 -0
  4. package/package.json +1 -1
  5. package/src/adapters/claude-code/CONTRACT.md +14 -13
  6. package/src/adapters/claude-code/NOTES.md +29 -0
  7. package/src/adapters/claude-code/bin/hook.ts +12 -4
  8. package/src/adapters/claude-code/bin/runner.ts +41 -20
  9. package/src/adapters/claude-code/doctor.ts +123 -30
  10. package/src/adapters/claude-code/hooks.ts +70 -86
  11. package/src/adapters/claude-code/index.ts +0 -3
  12. package/src/adapters/cli/NOTES.md +8 -0
  13. package/src/adapters/cli/commands-delete.ts +273 -0
  14. package/src/adapters/cli/commands-install.ts +29 -10
  15. package/src/adapters/cli/commands-note.ts +1 -1
  16. package/src/adapters/cli/commands-readings.ts +4 -2
  17. package/src/adapters/cli/commands-scope.ts +25 -4
  18. package/src/adapters/cli/commands-self.ts +4 -1
  19. package/src/adapters/cli/commands-start-fresh.ts +1 -1
  20. package/src/adapters/cli/commands.ts +22 -3
  21. package/src/adapters/cli/help.ts +7 -7
  22. package/src/adapters/cli/install.ts +4 -2
  23. package/src/adapters/cli/mechanisms.ts +2 -2
  24. package/src/adapters/cli/removal.ts +1 -1
  25. package/src/adapters/config.ts +112 -30
  26. package/src/adapters/dashboard/CONTRACT.md +14 -0
  27. package/src/adapters/dashboard/NOTES.md +15 -0
  28. package/src/adapters/dashboard/activity.ts +1 -1
  29. package/src/adapters/dashboard/bin/dashboard.ts +3 -3
  30. package/src/adapters/dashboard/browse.ts +1 -1
  31. package/src/adapters/dashboard/identity.ts +1 -1
  32. package/src/adapters/dashboard/registries.ts +14 -14
  33. package/src/adapters/dashboard/resolve.ts +1 -1
  34. package/src/adapters/dashboard/status.ts +5 -2
  35. package/src/adapters/dashboard/web/actions.ts +21 -2
  36. package/src/adapters/dashboard/web/app.html +1 -1
  37. package/src/adapters/dashboard/web/flow.ts +1 -1
  38. package/src/adapters/dashboard/web/mechanisms/consolidation/index.js +2 -2
  39. package/src/adapters/dashboard/web/mechanisms/consolidation/panel.js +1 -1
  40. package/src/adapters/dashboard/web/mechanisms/decay/index.js +1 -1
  41. package/src/adapters/dashboard/web/mechanisms/reconsolidation/index.js +2 -2
  42. package/src/adapters/dashboard/web/mechanisms/retrieval/panel.js +3 -3
  43. package/src/adapters/dashboard/web/mechanisms/salience/panel.js +2 -2
  44. package/src/adapters/dashboard/web/narrate.ts +11 -11
  45. package/src/adapters/dashboard/web/pages/flow/sections/heatmap.js +1 -1
  46. package/src/adapters/dashboard/web/pages/health/sections/checks.js +3 -2
  47. package/src/adapters/dashboard/web/pages/health/sections/cycle.js +5 -5
  48. package/src/adapters/dashboard/web/pages/health/sections/mechanisms.js +1 -1
  49. package/src/adapters/dashboard/web/pages/health/sections/wake.js +2 -2
  50. package/src/adapters/dashboard/web/pages/memories/sections/tools.js +73 -3
  51. package/src/adapters/dashboard/web/pages/self/sections/dreams.js +2 -2
  52. package/src/adapters/dashboard/web/pages/self/sections/journal.js +5 -5
  53. package/src/adapters/dashboard/web/pages/self/sections/page.js +13 -13
  54. package/src/adapters/dashboard/web/pages/self/sections/settling.js +1 -1
  55. package/src/adapters/dashboard/web/pages/self/sections/wake.js +7 -7
  56. package/src/adapters/dashboard/web/server.ts +9 -1
  57. package/src/adapters/dashboard/web/shared/event-modal.js +1 -1
  58. package/src/adapters/dashboard/web/shared/memory-card-words.js +1 -1
  59. package/src/adapters/dashboard/web/shared/memory-modal.js +5 -5
  60. package/src/adapters/dashboard/web/views/activity.ts +1 -1
  61. package/src/adapters/dashboard/web/views/dreams.ts +1 -1
  62. package/src/adapters/dashboard/web/views/health.ts +1 -1
  63. package/src/adapters/dashboard/web/views/mechanisms.ts +6 -6
  64. package/src/adapters/dashboard/web/views/mind.ts +21 -9
  65. package/src/adapters/dashboard/web/views/overview.ts +3 -3
  66. package/src/adapters/expansions.ts +14 -1
  67. package/src/adapters/fired.ts +1 -1
  68. package/src/adapters/lifecycle.ts +25 -4
  69. package/src/adapters/log/index.ts +21 -0
  70. package/src/adapters/mcp/CONTRACT.md +1 -1
  71. package/src/adapters/mcp/server-self-tools.ts +25 -1
  72. package/src/adapters/mcp/server-words.ts +3 -2
  73. package/src/adapters/mcp/server.ts +45 -9
  74. package/src/adapters/mcp/tools.ts +4 -3
  75. package/src/adapters/plugin.ts +44 -8
  76. package/src/adapters/sessions.ts +5 -2
  77. package/src/adapters/snapshots.ts +90 -1
  78. package/src/adapters/store-id.ts +58 -0
  79. package/src/core/counterpart-boundary.ts +9 -0
  80. package/src/core/counterpart.ts +19 -6
  81. package/src/core/dream/CONTRACT.md +8 -0
  82. package/src/core/dream/index.ts +15 -2
  83. package/src/core/handoff/last-here.ts +24 -12
  84. package/src/core/onboarding.ts +231 -62
  85. package/src/core/prospective/CONTRACT.md +4 -1
  86. package/src/core/prospective/index.ts +23 -5
  87. package/src/core/recall/CONTRACT.md +3 -1
  88. package/src/core/recall/INTERFACE-GAPS.md +1 -1
  89. package/src/core/recall/NOTES.md +14 -0
  90. package/src/core/recall/session.ts +40 -1
  91. package/src/core/reconsolidation.ts +1 -1
  92. package/src/core/remember/CONTRACT.md +14 -8
  93. package/src/core/remember/owes.ts +68 -28
  94. package/src/core/remember/owner-strike-seam.ts +6 -3
  95. package/src/core/remember/spans.ts +3 -2
  96. package/src/core/remember/tunables.ts +18 -5
  97. package/src/core/remember/write-up-seam.ts +2 -1
  98. package/src/core/self/CONTRACT.md +25 -9
  99. package/src/core/self/NOTES.md +6 -0
  100. package/src/core/self/briefing-delivery.ts +349 -0
  101. package/src/core/self/briefing-page.ts +315 -0
  102. package/src/core/self/briefing-room.ts +563 -0
  103. package/src/core/self/briefing.ts +304 -1156
  104. package/src/core/self/index.ts +28 -6
  105. package/src/core/store/NOTES.md +6 -5
  106. package/src/core/store/index.ts +39 -0
  107. package/src/core/store/paths.ts +9 -2
  108. package/src/adapters/claude-code/primacy.ts +0 -162
@@ -0,0 +1,563 @@
1
+ /**
2
+ * THE WAKE'S ROOM — who gives way to whom when the composition is short of
3
+ * it, moved out of `briefing.ts` on 2026-10-12 (moves only; the rules are
4
+ * `briefing.ts#ROOM_ORDER`'s). `render` calls these after its trim loop:
5
+ * `takeRoom` and the rescues it serves, and `tellLost`, which says every lane
6
+ * that lost something. Imported by `briefing.ts` alone (`split-parts.test.ts`).
7
+ */
8
+ import type { LaneName, Ranked } from "./identity.js";
9
+ import { byteLength } from "./identity.js";
10
+ import { addDays, isDay } from "../time.js";
11
+ import { TODAY_ELSEWHERE_MAX_BYTES } from "../handoff/last-here.js";
12
+ import { LANE_ORDER, ROOM_ORDER, collapsedLine, compose, flatten, foldedLine, moreLine } from "./briefing.js";
13
+ import type { BriefingRequest, Composed, IdentityBlock, Resolve, RoomLane, TrimEvent } from "./briefing.js";
14
+
15
+
16
+ /** The order lanes are offered room for their line when it was not reserved
17
+ * (the last resort, `tellLost`): the reverse of the trim order, so the
18
+ * lanes that are cut last are also told about first.
19
+ *
20
+ * NEARBY'S CAP IS NOT COUNTED (2026-10-01, random-f2's item 5): what the
21
+ * hints lane's CAP leaves out is everything else warm in the store — "(331
22
+ * more nearby; recall ids …)" counted the store and named five ids nobody
23
+ * chose. Recall finds those by asking. What the BUDGET popped from the lane
24
+ * is counted (2026-10-12): at most `HINTS_MAX` hints this wake chose, each
25
+ * worth its id (`lostByLane`). */
26
+ const MORE_ORDER: readonly LaneName[] = [
27
+ "identity",
28
+ "horizon",
29
+ "threads",
30
+ "craft",
31
+ "hints",
32
+ ];
33
+
34
+ export type Kept = Record<LaneName, Ranked[]>;
35
+
36
+ /**
37
+ * WHAT THE RENDER HAS COMPOSED SO FAR, rescue by rescue (2026-10-10): the trim
38
+ * loop's composition, then each lane that took room from the lanes below it
39
+ * (`takeRoom`). `lent` is what the composition runs past `budgetBytes` — lent
40
+ * by "Work here" first, then by the room held for "Last here" and the handoff
41
+ * pointer — and `pinned` the count lines already paid for, which
42
+ * the render keeps (`tellLost`).
43
+ */
44
+ export interface Rescued {
45
+ readonly kept: Kept;
46
+ readonly trimmed: TrimEvent[];
47
+ readonly yesterday: string | undefined;
48
+ /** The "Today, elsewhere" line as it stands (`BriefingRequest.elsewhere`). */
49
+ readonly elsewhere: string | undefined;
50
+ readonly pinned: Partial<Record<LaneName, string[]>>;
51
+ readonly composed: Composed;
52
+ readonly lent: number;
53
+ /** True when the lanes of `pinned` that list nothing are said in the one
54
+ * folded line (`foldParts`): the trim loop found no room for each lane's own. A rescue may unfold it,
55
+ * never fold it. */
56
+ readonly fold: boolean;
57
+ }
58
+
59
+ export interface RescueCtx {
60
+ readonly req: BriefingRequest;
61
+ readonly resolve: Resolve;
62
+ readonly coreName: string | undefined;
63
+ readonly identity: IdentityBlock;
64
+ /** How many of Arriving's first lines no rescue below them may take
65
+ * (`arrivingHead`). */
66
+ readonly head: number;
67
+ /** The "Today, elsewhere" line's forms, widest first (`narrowerElsewhere`). */
68
+ readonly elsewhereForms: readonly string[];
69
+ }
70
+
71
+ export function copyKept(k: Kept): Kept {
72
+ return {
73
+ identity: [...k.identity],
74
+ craft: [...k.craft],
75
+ threads: [...k.threads],
76
+ hints: [...k.hints],
77
+ horizon: [...k.horizon],
78
+ };
79
+ }
80
+
81
+ /** A non-negative whole number of bytes, or 0. */
82
+ export function lendOf(n: number | undefined): number {
83
+ return Math.max(0, Math.floor(n ?? 0));
84
+ }
85
+
86
+ /**
87
+ * The count lines a composition carries for its pinned lanes: "N more", or —
88
+ * a lane that lists nothing — its one collapsed line (`collapsedLine`).
89
+ */
90
+ export function pinnedLines(pinned: Partial<Record<LaneName, readonly string[]>>, kept: Kept): Partial<Record<LaneName, string>> {
91
+ const out: Partial<Record<LaneName, string>> = {};
92
+ for (const lane of LANE_ORDER) {
93
+ const ids = pinned[lane];
94
+ if (ids === undefined || ids.length === 0) continue;
95
+ out[lane] = lane !== "identity" && kept[lane].length === 0 ? collapsedLine(lane, ids) : moreLine(lane, ids);
96
+ }
97
+ return out;
98
+ }
99
+
100
+ /**
101
+ * THE SAME COUNTS, FOLDED (2026-10-12, decided by COUNTERPARTS, lightly
102
+ * held): a lane that still lists an item keeps its own "N more" line under
103
+ * it ("Who I am" always does); only the lanes that list nothing go into the
104
+ * one folded line (`foldedLine`). No fold when no lane lists nothing.
105
+ */
106
+ export function foldParts(pinned: Partial<Record<LaneName, readonly string[]>>, kept: Kept): { more: Partial<Record<LaneName, string>>; fold?: string } {
107
+ const listing: Partial<Record<LaneName, readonly string[]>> = {};
108
+ const empty: Partial<Record<LaneName, readonly string[]>> = {};
109
+ for (const lane of LANE_ORDER) {
110
+ const ids = pinned[lane];
111
+ if (ids === undefined || ids.length === 0) continue;
112
+ if (lane !== "identity" && kept[lane].length === 0) empty[lane] = ids;
113
+ else listing[lane] = ids;
114
+ }
115
+ const fold = foldedLine(empty);
116
+ return fold === null ? { more: pinnedLines(listing, kept) } : { more: pinnedLines(listing, kept), fold };
117
+ }
118
+
119
+ /**
120
+ * How many of Arriving's first lines are its HEAD (2026-10-10): every plain
121
+ * reminder due the day the wake is read (`Ranked.due`, which `Self#build`
122
+ * puts first), or else its first line alone. No rescue ranked below
123
+ * `ROOM_ORDER`'s `arrivingFirst` takes them; "Still open"'s first item takes
124
+ * the lines after them, and last of all (`takeRoom`'s `arriving` step).
125
+ */
126
+ export function arrivingHead(horizon: readonly Pick<Ranked, "due">[]): number {
127
+ let n = 0;
128
+ while (horizon[n]?.due === true) n += 1;
129
+ return Math.min(horizon.length, Math.max(1, n));
130
+ }
131
+
132
+ /** How many days ahead a dated item counts as NEAR at session start
133
+ * (`HorizonItem.near`; 2026-10-12, RANDOM's ruling, lightly held). */
134
+ export const ARRIVING_NEAR_DAYS = 3;
135
+
136
+ /** Whether a dated item due `due` is NEAR on `at`: from that day through
137
+ * `ARRIVING_NEAR_DAYS` after it. A grace day's "was due" line, behind `at`,
138
+ * is not (RANDOM's ruling at the review of #445, 2026-10-12, lightly held). */
139
+ export function nearDue(due: string | undefined, at: string): boolean {
140
+ return due !== undefined && isDay(due) && isDay(at) && due >= at && due <= addDays(at, ARRIVING_NEAR_DAYS);
141
+ }
142
+
143
+ /**
144
+ * How many of Arriving's first lines are NEAR (2026-10-12): the head, then
145
+ * every line after it marked `near` (`Ranked.near`, set at session start
146
+ * only, and sorted to follow the head). Zero when none is.
147
+ */
148
+ export function arrivingNear(horizon: readonly Pick<Ranked, "due" | "near">[]): number {
149
+ let n = 0;
150
+ while (horizon[n]?.due === true || horizon[n]?.near === true) n += 1;
151
+ return horizon.some((r) => r.near === true) ? n : 0;
152
+ }
153
+
154
+ /**
155
+ * The "Today, elsewhere" line's forms the render may print, widest first:
156
+ * each within `TODAY_ELSEWHERE_MAX_BYTES` (2026-10-10), each narrower than
157
+ * the one before. Empty without a line.
158
+ */
159
+ export function elsewhereFormsOf(line: string | undefined, shorter: readonly string[] | undefined): string[] {
160
+ if (line === undefined || line.length === 0) return [];
161
+ const out: string[] = [];
162
+ for (const form of [line, ...(shorter ?? [])]) {
163
+ const size = byteLength(flatten(form));
164
+ if (form.length === 0 || size > TODAY_ELSEWHERE_MAX_BYTES) continue;
165
+ const last = out[out.length - 1];
166
+ if (last !== undefined && size >= byteLength(flatten(last))) continue;
167
+ out.push(form);
168
+ }
169
+ return out;
170
+ }
171
+
172
+ /** The "Today, elsewhere" line's next form after `line` in `forms`, or none. */
173
+ export function narrowerElsewhere(line: string, forms: readonly string[]): string | undefined {
174
+ const at = forms.indexOf(line);
175
+ return at < 0 ? undefined : forms[at + 1];
176
+ }
177
+
178
+ /** The Yesterday line's shorter forms, widest first, each narrower than `line`. */
179
+ export function shorterThan(line: string | undefined, forms: readonly string[] | undefined): string[] {
180
+ if (line === undefined) return [];
181
+ const bytes = byteLength(line);
182
+ return (forms ?? []).filter((s) => s.length > 0 && byteLength(s) < bytes);
183
+ }
184
+
185
+ /**
186
+ * TAKE ROOM FROM THE LANES BELOW `target`, lowest first, as `ROOM_ORDER` says
187
+ * (2026-10-10) — and only as much as it needs: the composition `want`, with
188
+ * its `pinned` count lines, is tried as it stands, then again after each
189
+ * step, and the first that fits is kept. The steps the render can take:
190
+ *
191
+ * - `work` — the room held for "Work here" (`lendBytes`);
192
+ * - `yesterday` — the Yesterday line, one title at a time given way to its
193
+ * id (`yesterdayShorter`);
194
+ * - `handoffs` — the room held for "Last here" and the handoff pointer
195
+ * (`handoffLendBytes`), which the delivery gives up in its own order;
196
+ * - `arriving` — Arriving's lines past its head (`arrivingHead`), from the
197
+ * end, each a `TrimEvent` so the lane's count can still say so;
198
+ * - `elsewhere` — the "Today, elsewhere" line, a narrower form at a time,
199
+ * then none (2026-10-10; between `handoffs` and `arriving` since the
200
+ * review of #380). The trim loop also asks here on the line's behalf
201
+ * (`target` `elsewhere`) before it steps the line down;
202
+ * - `handoffsKept` — the room held for the newest handoff's own block
203
+ * (`handoffKeepBytes`): reached only by `due`, the one lane above it
204
+ * that takes room here (review of #367; `arrivingNear` stops below it,
205
+ * review of #445).
206
+ *
207
+ * The lanes below them are the trim loop's and are gone before any rescue
208
+ * runs; `lastHere` is the delivery's, inside the room lent at `handoffs`; the
209
+ * page is chosen before the lanes (`Self#build`), and gives its borrowing
210
+ * back to `due` there. All or nothing: null when even the last step below
211
+ * `target` leaves no room — the render is then what it was.
212
+ */
213
+ export function takeRoom(
214
+ target: RoomLane,
215
+ from: Rescued,
216
+ want: Kept,
217
+ pinned: Partial<Record<LaneName, readonly string[]>>,
218
+ trimmed: readonly TrimEvent[],
219
+ ctx: RescueCtx,
220
+ /** Folded (`from.fold`): try the one folded line before each lane's own —
221
+ * the trim loop's own call, so the lanes' count borrows as little as it
222
+ * can (2026-10-12). */
223
+ foldFirst = false,
224
+ ): Rescued | null {
225
+ const { req } = ctx;
226
+ const work = lendOf(req.lendBytes);
227
+ const handoffs = lendOf(req.handoffLendBytes);
228
+ const kept = lendOf(req.handoffKeepBytes);
229
+ const k = copyKept(want);
230
+ const t = [...trimmed];
231
+ const pins: Partial<Record<LaneName, string[]>> = {};
232
+ for (const lane of LANE_ORDER) {
233
+ const ids = pinned[lane];
234
+ if (ids !== undefined && ids.length > 0) pins[lane] = [...ids];
235
+ }
236
+ let limit = req.budgetBytes + from.lent;
237
+ let y = from.yesterday;
238
+ let e = from.elsewhere;
239
+ const attempt = (): Rescued | null => {
240
+ // Folded already (2026-10-12): each lane's own line when there is room,
241
+ // else the one line — never a lane left without a word. `foldFirst`:
242
+ // the one line first.
243
+ const each = (): Composed => compose(k, req.day, ctx.resolve, ctx.coreName, ctx.identity, pinnedLines(pins, k), y, e);
244
+ const parts = from.fold ? foldParts(pins, k) : null;
245
+ const one = (): Composed | null =>
246
+ parts?.fold === undefined ? null : compose(k, req.day, ctx.resolve, ctx.coreName, ctx.identity, parts.more, y, e, parts.fold);
247
+ let fold = false;
248
+ let c: Composed;
249
+ const first = foldFirst ? one() : null;
250
+ if (first !== null && first.bytes <= limit) {
251
+ c = first;
252
+ fold = true;
253
+ } else {
254
+ c = each();
255
+ const second = c.bytes > limit && !foldFirst ? one() : null;
256
+ if (second !== null) {
257
+ c = second;
258
+ fold = true;
259
+ }
260
+ }
261
+ return c.bytes <= limit
262
+ ? { kept: k, trimmed: t, yesterday: y, elsewhere: e, pinned: pins, composed: c, lent: Math.max(0, c.bytes - req.budgetBytes), fold }
263
+ : null;
264
+ };
265
+ let got = attempt();
266
+ for (const lane of ROOM_ORDER) {
267
+ if (got !== null || lane === target) break;
268
+ switch (lane) {
269
+ case "elsewhere":
270
+ // Its titles first, then the line (2026-10-10).
271
+ while (got === null && e !== undefined) {
272
+ e = narrowerElsewhere(e, ctx.elsewhereForms);
273
+ got = attempt();
274
+ }
275
+ break;
276
+ case "work":
277
+ if (req.budgetBytes + work > limit) {
278
+ limit = req.budgetBytes + work;
279
+ got = attempt();
280
+ }
281
+ break;
282
+ case "yesterday":
283
+ for (const form of shorterThan(y, req.yesterdayShorter)) {
284
+ y = form;
285
+ got = attempt();
286
+ if (got !== null) break;
287
+ }
288
+ break;
289
+ case "handoffs":
290
+ if (req.budgetBytes + work + handoffs > limit) {
291
+ limit = req.budgetBytes + work + handoffs;
292
+ got = attempt();
293
+ }
294
+ break;
295
+ case "arriving":
296
+ while (got === null && k.horizon.length > ctx.head) {
297
+ const dropped = k.horizon.pop();
298
+ if (dropped === undefined) break;
299
+ t.push({ lane: "horizon", id: dropped.id, strength: dropped.strength });
300
+ // The lane's count names it, first: it ranked first. Always
301
+ // (2026-10-12): a line popped here is never popped without a word.
302
+ pins.horizon = [dropped.id, ...(pins.horizon ?? [])];
303
+ got = attempt();
304
+ }
305
+ break;
306
+ case "handoffsKept":
307
+ if (req.budgetBytes + work + handoffs + kept > limit) {
308
+ limit = req.budgetBytes + work + handoffs + kept;
309
+ got = attempt();
310
+ }
311
+ break;
312
+ default:
313
+ break;
314
+ }
315
+ }
316
+ return got;
317
+ }
318
+
319
+ /**
320
+ * "ARRIVING:" LISTS ITS DATED ITEMS BEFORE THE FURNITURE BELOW IT KEEPS ITS
321
+ * ROOM (2026-10-10, `ROOM_ORDER`). The trim loop pops Arriving only after
322
+ * "Nearby", craft and "Still open" are gone, but the page, the Yesterday line
323
+ * and the room held for the delivery's lanes are nothing it can pop — so on
324
+ * the owner's lived day 19 his tax reminder collapsed to "Arriving: 1 — no
325
+ * room to list them" while yesterday's titles and four handoffs printed.
326
+ *
327
+ * Here the lane's first `upTo` lines are listed again — as many as fit, each
328
+ * time with the count of the rest (an item under a heading with no count
329
+ * reads as the only one arriving). Without the count only for a plain
330
+ * reminder due the day the wake is read (`target` `due`): it is said in full
331
+ * whatever else happens (#442), and the render's last step folds the count
332
+ * it could not carry into one line (2026-10-12; before that, any listed date
333
+ * outranked the count of the others, and the rest went unsaid). The room comes from the
334
+ * lanes below `target` (`takeRoom`). Called twice: for the lane's head at
335
+ * its own rank (`due` or `arrivingFirst`), and — after "Still open"'s first
336
+ * item — for the rest at `arriving`. Null when nothing was trimmed from it,
337
+ * or nothing more fits.
338
+ */
339
+ export function keepArriving(
340
+ arrived: readonly Ranked[],
341
+ overflow: readonly string[],
342
+ upTo: number,
343
+ target: RoomLane,
344
+ from: Rescued,
345
+ ctx: RescueCtx,
346
+ ): Rescued | null {
347
+ const want = Math.min(upTo, arrived.length);
348
+ for (let n = want; n > from.kept.horizon.length; n--) {
349
+ const listed = arrived.slice(0, n);
350
+ const k: Kept = { ...copyKept(from.kept), horizon: [...listed] };
351
+ const t = from.trimmed.filter((e) => !(e.lane === "horizon" && listed.some((r) => r.id === e.id)));
352
+ // The rest, as `lostByLane` lists it: the trim's (popped from the end, so
353
+ // reversed back), then what the lane's cap left out.
354
+ const rest = [...t.filter((e) => e.lane === "horizon").map((e) => e.id).reverse(), ...overflow];
355
+ const others: Partial<Record<LaneName, string[]>> = { ...from.pinned };
356
+ delete others.horizon;
357
+ for (const counted of rest.length === 0 ? [false] : target === "due" ? [true, false] : [true]) {
358
+ const got = takeRoom(target, from, k, counted ? { ...others, horizon: rest } : others, t, ctx);
359
+ if (got !== null) return got;
360
+ }
361
+ }
362
+ return null;
363
+ }
364
+
365
+ /**
366
+ * "ARRIVING:" SAYS HOW MANY MORE, BY ID, BEFORE IT LISTS A LATER LINE IN FULL
367
+ * (review of #367, 2026-10-10). The lane's count names every dated item it
368
+ * did not list — the trim's and those past `prospective/`'s count
369
+ * (`BoundaryRequest.horizonMore`) — and those past the count leave no trim
370
+ * row for doctor to read, so a count left out is a dated item silently gone.
371
+ * Last of the rescues: when the lane lists something and has no count yet,
372
+ * the count takes room from the lanes below `arriving` — "Work here", the
373
+ * Yesterday line's titles, the handoffs' room — and, only when it names an
374
+ * item past that count (one no trim row records), from Arriving's lines past
375
+ * its head too, each named in the count it pays for. A count of the trim's
376
+ * alone leaves the listed lines as they are: a listed date outranks it, and
377
+ * doctor reads the trim. Null when the count is already in, there is nothing
378
+ * to count, or no room is found.
379
+ *
380
+ * AND WHEN THE LANE LISTS NOTHING (2026-10-12): its one collapsed line takes
381
+ * room the same way. The owner's 10-12 bundles carried seven dated items and
382
+ * not a word about them — the page, borrowing "Work here", had spent the
383
+ * room, and the line was offered only what was left.
384
+ */
385
+ export function keepArrivingCount(overflow: readonly string[], from: Rescued, ctx: RescueCtx): Rescued | null {
386
+ if ((from.pinned.horizon?.length ?? 0) > 0) return null;
387
+ const rest = [...from.trimmed.filter((e) => e.lane === "horizon").map((e) => e.id).reverse(), ...overflow];
388
+ if (rest.length === 0) return null;
389
+ const pinned = { ...from.pinned, horizon: rest };
390
+ // Room as the composition stands: `tellLost` says it then, as it says every lane's.
391
+ const { req } = ctx;
392
+ if (from.lent === 0 && compose(from.kept, req.day, ctx.resolve, ctx.coreName, ctx.identity, pinnedLines(pinned, from.kept), from.yesterday, from.elsewhere).bytes <= req.budgetBytes) {
393
+ return null;
394
+ }
395
+ return takeRoom(overflow.length > 0 ? "openFirst" : "arriving", from, from.kept, pinned, from.trimmed, ctx);
396
+ }
397
+
398
+ /**
399
+ * "STILL OPEN" KEEPS ITS FIRST ITEM, AND ITS COUNT (review of #350,
400
+ * 2026-10-09; its place in `ROOM_ORDER` since 2026-10-10).
401
+ *
402
+ * The owner's wake on 10-09 read "Still open:" over "(20 more still open; …)"
403
+ * and no item. The self page is furniture the trim cannot pop, the Yesterday
404
+ * line is too, and `TRIM_ORDER` takes "Still open" before "Arriving" — so
405
+ * beside a long page the lane gave up its last item while Arriving kept every
406
+ * line. The page is not what gives way: it is the self the wake is for
407
+ * (`Self#pageBlock`). What gives way is what `ROOM_ORDER` ranks below
408
+ * `openFirst`, lowest first (`takeRoom`): "Work here", the Yesterday line's
409
+ * titles, the room for "Last here" and the handoffs, and only then Arriving
410
+ * past its head — whose first line, and every plain reminder due the day the
411
+ * wake is read, rank above this.
412
+ *
413
+ * The target is the lane's first item AND its "N more" line: one item under a
414
+ * heading with no count reads as the only thing open. All or nothing: when
415
+ * even the last step leaves no room, the render is what it was, and a lane
416
+ * that lists nothing says so in one line (`collapsedLine`).
417
+ *
418
+ * AND THE COUNT BESIDE WHAT THE TRIM KEPT (review of #358, 2026-10-09): when
419
+ * the trim loop left the lane its items but no room for its "N more" line,
420
+ * the count is paid for out of "Work here" and out of nothing else
421
+ * (`openCount`, just above `work`): the items stay as the trim kept them (a
422
+ * smaller budget still keeps a subset). Not when the count already fits as
423
+ * the composition stands: `tellLost` says it then, as it says every
424
+ * lane's.
425
+ */
426
+ export function keepFirstOpen(
427
+ arrived: readonly Ranked[],
428
+ overflow: readonly string[],
429
+ arrivedHorizon: number,
430
+ from: Rescued,
431
+ ctx: RescueCtx,
432
+ ): Rescued | null {
433
+ const first = arrived[0];
434
+ if (first === undefined) return null;
435
+ const kept = from.kept;
436
+ // Arriving's FIRST line outranks it: when not even that is listed, this
437
+ // budget has no room to rearrange.
438
+ if (kept.threads.length === 0 && arrivedHorizon > 0 && kept.horizon.length === 0) return null;
439
+ // What the lane lists: the items the trim kept, or — when it kept none —
440
+ // its first item.
441
+ const k: Kept = { ...copyKept(kept), threads: kept.threads.length > 0 ? [...kept.threads] : [first] };
442
+ const t = from.trimmed.filter((e) => !(e.lane === "threads" && k.threads.some((l) => l.id === e.id)));
443
+ // The rest of the lane, as `lostByLane` will list it: the trim's (popped
444
+ // from the end, so reversed back), then what the lane's cap left out.
445
+ const rest = [...t.filter((e) => e.lane === "threads").map((e) => e.id).reverse(), ...overflow];
446
+ const pinned: Partial<Record<LaneName, string[]>> = { ...from.pinned, threads: rest };
447
+ if (rest.length === 0) delete pinned.threads;
448
+ if (kept.threads.length > 0) {
449
+ // Items the trim kept: only their count is owed here, and only when it
450
+ // does not fit as the composition stands.
451
+ if (rest.length === 0) return null;
452
+ const { req } = ctx;
453
+ const asIs = compose(k, req.day, ctx.resolve, ctx.coreName, ctx.identity, pinnedLines(pinned, k), from.yesterday, from.elsewhere);
454
+ if (from.lent === 0 && asIs.bytes <= req.budgetBytes) return null;
455
+ return takeRoom("openCount", from, k, pinned, t, ctx);
456
+ }
457
+ return takeRoom("openFirst", from, k, pinned, t, ctx);
458
+ }
459
+
460
+ /**
461
+ * THE LANES' LINES, SAID LAST AND CHECKED (2026-10-12): every lane that lost
462
+ * something, counted under `limit`, the first of these that fits:
463
+ *
464
+ * 1. each lane's own line ("N more", or the collapsed line of a lane that
465
+ * lists nothing);
466
+ * 2. the same, with the lanes that list nothing folded into one line
467
+ * (`foldParts`) — "Nearby" among them when it lists nothing;
468
+ * 3. and 4. those two again without "Nearby": the least of the lanes, its
469
+ * count takes only room nothing else wants (decided by COUNTERPARTS,
470
+ * 2026-10-12, lightly held). Left out, it is `quiet` — a step-down;
471
+ * 5. and 6. the counts the last rescue composed with (`pinned`), which
472
+ * fit: only a due-day plain reminder listed past its lane's count
473
+ * (#442) leaves a lane out of them, and that lane is `untold`;
474
+ * 7. the last resort — a floor over its budget, or a bug — each lane's own
475
+ * line in `MORE_ORDER` while it still fits, and what is left `untold`,
476
+ * which the caller records and doctor reads in red.
477
+ *
478
+ * Every lane but "Nearby" had its room reserved: the trim loop and every
479
+ * rescue composed with its line.
480
+ */
481
+ export function tellLost(ctx: {
482
+ kept: Kept;
483
+ lost: Partial<Record<LaneName, string[]>>;
484
+ req: BriefingRequest;
485
+ resolve: Resolve;
486
+ coreName: string | undefined;
487
+ identity: IdentityBlock;
488
+ yesterday?: string;
489
+ elsewhere?: string;
490
+ limit: number;
491
+ /** The counts the last rescue composed with, when one ran. */
492
+ pinned?: Partial<Record<LaneName, readonly string[]>>;
493
+ }): {
494
+ composed: Composed;
495
+ more: Partial<Record<LaneName, number>>;
496
+ folded: boolean;
497
+ untold: Partial<Record<LaneName, number>>;
498
+ quiet: Partial<Record<LaneName, number>>;
499
+ } {
500
+ const at = (more: Partial<Record<LaneName, string>>, fold?: string): Composed =>
501
+ compose(ctx.kept, ctx.req.day, ctx.resolve, ctx.coreName, ctx.identity, more, ctx.yesterday, ctx.elsewhere, fold);
502
+ const countsOf = (lost: Partial<Record<LaneName, readonly string[]>>): Partial<Record<LaneName, number>> => {
503
+ const out: Partial<Record<LaneName, number>> = {};
504
+ for (const lane of LANE_ORDER) {
505
+ const n = lost[lane]?.length ?? 0;
506
+ if (n > 0) out[lane] = n;
507
+ }
508
+ return out;
509
+ };
510
+ const counts = countsOf(ctx.lost);
511
+ const reserved = withoutNearby(ctx.lost);
512
+ const hints = ctx.lost.hints?.length ?? 0;
513
+ const quiet: Partial<Record<LaneName, number>> = hints > 0 ? { hints } : {};
514
+ const tries: { lost: Partial<Record<LaneName, readonly string[]>>; fold: boolean }[] = [
515
+ { lost: ctx.lost, fold: false },
516
+ { lost: ctx.lost, fold: true },
517
+ ...(hints > 0 ? [{ lost: reserved, fold: false }, { lost: reserved, fold: true }] : []),
518
+ ...(ctx.pinned === undefined ? [] : [{ lost: ctx.pinned, fold: false }, { lost: ctx.pinned, fold: true }]),
519
+ ];
520
+ for (const t of tries) {
521
+ const parts = t.fold ? foldParts(t.lost, ctx.kept) : { more: pinnedLines(t.lost, ctx.kept) };
522
+ if (t.fold && parts.fold === undefined) continue;
523
+ const c = at(parts.more, parts.fold);
524
+ if (Object.keys(counts).length === 0 || c.bytes <= ctx.limit) {
525
+ const said = countsOf(t.lost);
526
+ const untold: Partial<Record<LaneName, number>> = {};
527
+ for (const lane of LANE_ORDER) {
528
+ const n = counts[lane];
529
+ if (n !== undefined && said[lane] === undefined && lane !== "hints") untold[lane] = n;
530
+ }
531
+ return { composed: c, more: said, folded: parts.fold !== undefined, untold, quiet: said.hints === undefined ? quiet : {} };
532
+ }
533
+ }
534
+ // The last resort: what fits, lane by lane; the rest is untold ("Nearby": quiet).
535
+ let current = at({});
536
+ const lines: Partial<Record<LaneName, string>> = {};
537
+ const more: Partial<Record<LaneName, number>> = {};
538
+ for (const lane of MORE_ORDER) {
539
+ const ids = ctx.lost[lane];
540
+ if (ids === undefined || ids.length === 0) continue;
541
+ lines[lane] = lane !== "identity" && ctx.kept[lane].length === 0 ? collapsedLine(lane, ids) : moreLine(lane, ids);
542
+ const candidate = at(lines);
543
+ if (candidate.bytes > ctx.limit) {
544
+ delete lines[lane];
545
+ continue;
546
+ }
547
+ current = candidate;
548
+ more[lane] = ids.length;
549
+ }
550
+ const untold: Partial<Record<LaneName, number>> = {};
551
+ for (const lane of LANE_ORDER) {
552
+ const n = counts[lane];
553
+ if (n !== undefined && more[lane] === undefined && lane !== "hints") untold[lane] = n;
554
+ }
555
+ return { composed: current, more, folded: false, untold, quiet: more.hints === undefined ? quiet : {} };
556
+ }
557
+
558
+ /** The lanes whose count is reserved: every lane but "Nearby" (2026-10-12). */
559
+ export function withoutNearby<T>(lost: Partial<Record<LaneName, T>>): Partial<Record<LaneName, T>> {
560
+ const out = { ...lost };
561
+ delete out.hints;
562
+ return out;
563
+ }