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
@@ -48,9 +48,61 @@
48
48
  import type { LaneName, Ranked } from "./identity.js";
49
49
  import { byteLength } from "./identity.js";
50
50
  import type { SelfTunables } from "./tunables.js";
51
- import { addDays, isDay } from "../time.js";
52
- import { HANDOFF_RESERVE_MAX_BYTES, HANDOFF_RESERVE_MIN_BUDGET_MULTIPLE } from "../handoff/index.js";
53
- import { TODAY_ELSEWHERE_MAX_BYTES } from "../handoff/last-here.js";
51
+ import type { Kept, RescueCtx, Rescued } from "./briefing-room.js";
52
+ import {
53
+ foldParts,
54
+ withoutNearby,
55
+ arrivingHead,
56
+ arrivingNear,
57
+ elsewhereFormsOf,
58
+ keepArriving,
59
+ keepArrivingCount,
60
+ keepFirstOpen,
61
+ lendOf,
62
+ narrowerElsewhere,
63
+ pinnedLines,
64
+ shorterThan,
65
+ takeRoom,
66
+ tellLost,
67
+ } from "./briefing-room.js";
68
+ import type { PageBlock, PageRung } from "./briefing-page.js";
69
+ import { pageBlockBytes } from "./briefing-page.js";
70
+
71
+ // THE PARTS (2026-10-12, moves only): the room machinery (`briefing-room.ts`),
72
+ // the page's ladder (`briefing-page.ts`) and the delivery's own lines
73
+ // (`briefing-delivery.ts`). Their public names are this file's, as before.
74
+ export { ARRIVING_NEAR_DAYS, arrivingHead, arrivingNear, nearDue } from "./briefing-room.js";
75
+ export {
76
+ DELIVERY_SHARED_RESERVES,
77
+ PAGE_END_LINES,
78
+ PAGE_FLOOR_RESERVE_BYTES,
79
+ PAGE_FRAME_RESERVE_BYTES,
80
+ PAGE_HOST_BUDGET_BYTES,
81
+ PAGE_ROOM_BYTES,
82
+ PAGE_RUNGS,
83
+ deliveryReserveBound,
84
+ isPageFrameLine,
85
+ pageBlockBytes,
86
+ pageDateline,
87
+ pageEndLine,
88
+ pageRoomBytes,
89
+ pageTooLargeLine,
90
+ pageTopLine,
91
+ readPageTopLine,
92
+ } from "./briefing-page.js";
93
+ export type { PageBlock, PageRung } from "./briefing-page.js";
94
+ export {
95
+ PREFACE_RESERVE_BYTES,
96
+ WAKE_SYSTEM,
97
+ WAKE_WHOLE_SENTENCE,
98
+ applyPreface,
99
+ arrivingTense,
100
+ groupDigits,
101
+ prefaceLine,
102
+ readSentinel,
103
+ spliceBeforeSentinel,
104
+ } from "./briefing-delivery.js";
105
+ export type { PrefaceFacts, PrefacedBundle, SentinelReading } from "./briefing-delivery.js";
54
106
 
55
107
  /**
56
108
  * Composed order — behavioral-spec §1's, minus the two riders the Rulings drop
@@ -212,53 +264,149 @@ export const FRAMING = {
212
264
  identity: "Who I am:",
213
265
  craft: "How I work:",
214
266
  threads: "Still open:",
267
+ hints: "Might be relevant:",
268
+ horizon: "Coming up:",
269
+ } as const;
270
+
271
+ /**
272
+ * THE HEADINGS BEFORE THE PLAIN-WORDS RENAME (2026-10-12): a wake bundle
273
+ * stored under them is still delivered and read once after an upgrade, so
274
+ * every reader of a STORED bundle (`arrivingTense`, `collapsedLane`,
275
+ * `countedLanes`, the console's lane splitters) accepts both. Nothing
276
+ * composes them any more.
277
+ */
278
+ export const LEGACY_FRAMING = {
215
279
  hints: "Nearby, if it helps:",
216
280
  horizon: "Arriving:",
217
281
  } as const;
218
282
 
283
+ /** Every heading a lane has been printed under, the current one first. */
284
+ export function headingsOf(lane: LaneName): string[] {
285
+ const old = (LEGACY_FRAMING as Partial<Record<LaneName, string>>)[lane];
286
+ return old === undefined ? [laneHeading(lane)] : [laneHeading(lane), old];
287
+ }
288
+
219
289
  /**
220
290
  * THE WAKE SAYS WHAT IT LEFT OUT (2026-09-29, audit item 5). A lane that lost
221
291
  * elements — to its cap (`identity.ts#rankLanes`), to the identity share, or to
222
- * the budget trim — gets at most ONE short line saying how many more there are
223
- * and the ids `recall` can fetch whole (its `ids` argument). Furniture, like the
224
- * day-0 line: no `- ` bullet, not counted in `counts` or `elements`. It goes in
225
- * only while the composition still fits the budget; a line that does not fit is
226
- * dropped without a word, and the trim's own count stays in telemetry
227
- * (`self.briefing.trim`) as before.
292
+ * the budget trim — gets ONE short line saying how many more there are and the
293
+ * ids `recall` can fetch whole (its `ids` argument). Furniture, like the day-0
294
+ * line: no `- ` bullet, not counted in `counts` or `elements`.
295
+ *
296
+ * NOTHING IS DROPPED WITHOUT A WORD (2026-10-12, Mike's principle; the minimal
297
+ * version, chosen via RANDOM, lightly held). The line used to go in last, only
298
+ * while the composition still fit, and was otherwise "dropped without a word":
299
+ * a lane could vanish from the wake. Now each lane's line is RESERVED inside
300
+ * the budget before the trim loop gives room away — the loop composes WITH the
301
+ * line of every lane that has lost something so far, and pops until items and
302
+ * lines fit together — so a lane is always whole, shortened (some items and
303
+ * its count) or counted (its one collapsed line). A lane that lost nothing
304
+ * pays nothing, so a roomy wake is byte for byte what it was. A lane that
305
+ * lists an item keeps its own count under it; when not even the lanes' own
306
+ * lines fit beside the furniture, the lanes that list NOTHING fold into ONE
307
+ * line (`foldedLine`, `foldParts`), which takes room from what ranks below a
308
+ * dated line; only a wake with no such room left says nothing
309
+ * (`BriefingResult.untold`, red in doctor). The page is not stepped down for
310
+ * it: in its own room it outranks everything (`ROOM_ORDER`). "Nearby" is not
311
+ * reserved: the least of the lanes, its count takes only room nothing else
312
+ * wants, and is otherwise `quiet` (`tellLost`; COUNTERPARTS, 2026-10-12).
228
313
  *
229
314
  * How many ids one line names. `recall` takes up to ten at once; five keeps the
230
315
  * line near 120 bytes, and the count says when there are more than it names.
231
316
  */
232
317
  export const MORE_LINE_IDS = 5;
233
318
 
234
- /** What each lane's line calls the rest — the lane's heading, as a phrase. */
319
+ /** What each lane's line calls the rest — the lane's heading, as a phrase
320
+ * (2026-10-12: "coming up" and "might be relevant", as the headings say). */
235
321
  export const MORE_NOUN: Readonly<Record<LaneName, string>> = {
236
322
  identity: "about who I am",
237
323
  craft: "on how I work",
238
324
  threads: "still open",
325
+ hints: "might be relevant",
326
+ horizon: "coming up",
327
+ };
328
+
329
+ /** The phrases before the plain-words rename, read back (`countedLanes`) off
330
+ * a stored bundle as `LEGACY_FRAMING` is; nothing composes them any more. */
331
+ const LEGACY_MORE_NOUN: Readonly<Partial<Record<LaneName, string>>> = {
239
332
  hints: "nearby",
240
333
  horizon: "arriving",
241
334
  };
242
335
 
243
- /** The order lanes are offered room for their line: the reverse of the trim
244
- * order, so the lanes that are cut last are also told about first.
245
- *
246
- * NOT NEARBY (2026-10-01, random-f2's item 5): what the hints lane leaves
247
- * out is everything else warm in the store — "(331 more nearby; recall ids
248
- * …)" counted the store and named five ids nobody chose. Recall finds those
249
- * by asking. The other lanes' lines name a bounded list worth naming. */
250
- const MORE_ORDER: readonly LaneName[] = [
251
- "identity",
252
- "horizon",
253
- "threads",
254
- "craft",
255
- ];
256
-
257
336
  /** `(3 more still open; recall ids: mem_…, mem_…, mem_…)` */
258
337
  export function moreLine(lane: LaneName, ids: readonly string[]): string {
259
338
  return `(${String(ids.length)} more ${MORE_NOUN[lane]}; ${recallIds(ids)})`;
260
339
  }
261
340
 
341
+ /**
342
+ * THE LANES THAT LIST NOTHING, FOLDED INTO ONE LINE (2026-10-12): what a wake
343
+ * prints when not even each such lane's own collapsed line fits beside the
344
+ * page and the furniture — each of them counted, with its own first ids, so
345
+ * every folded lane keeps a handle recall opens (`recall ids`). A lane that
346
+ * still lists an item keeps its own "N more" line under it and is never
347
+ * folded (decided by COUNTERPARTS, 2026-10-12, lightly held). Furniture,
348
+ * like the lines it stands for. It takes room as a dated line does, from the
349
+ * lanes below `arrivingFirst` in `ROOM_ORDER` (`render`'s trim loop).
350
+ */
351
+ export const FOLDED_WORDS = "More than this wake lists:";
352
+
353
+ /** Who the folded line names first: dated items, then what is open, then the rest. */
354
+ const FOLD_ORDER: readonly LaneName[] = ["horizon", "threads", "identity", "craft", "hints"];
355
+
356
+ /** How many ids each folded lane names — fewer than its own line's five. */
357
+ export const FOLD_LINE_IDS = 3;
358
+
359
+ /** `More than this wake lists: 7 coming up (recall ids: mem_…, mem_…, mem_…, and 4 more); 5 might be relevant (recall ids: …)` */
360
+ export function foldedLine(lost: Partial<Record<LaneName, readonly string[]>>): string | null {
361
+ const lanes = FOLD_ORDER.filter((l) => (lost[l]?.length ?? 0) > 0);
362
+ if (lanes.length === 0) return null;
363
+ const part = (l: LaneName): string => {
364
+ const ids = lost[l] ?? [];
365
+ const shown = ids.slice(0, FOLD_LINE_IDS);
366
+ return `${String(ids.length)} ${MORE_NOUN[l]} (recall ids: ${shown.join(", ")}${ids.length > shown.length ? `, and ${String(ids.length - shown.length)} more` : ""})`;
367
+ };
368
+ return `${FOLDED_WORDS} ${lanes.map(part).join("; ")}`;
369
+ }
370
+
371
+ /** True for the folded line (`foldedLine`), which belongs to no one lane. */
372
+ export function isFoldedLine(line: string): boolean {
373
+ return line.startsWith(`${FOLDED_WORDS} `);
374
+ }
375
+
376
+ /**
377
+ * WHAT A WAKE COUNTS, read back off its own lines (2026-10-12): each lane a
378
+ * "N more" line, a collapsed line or the folded line names, and N. Kept beside
379
+ * the three writers so their wording and this reader change together. Pure.
380
+ */
381
+ export function countedLanes(text: string): Partial<Record<LaneName, number>> {
382
+ const out: Partial<Record<LaneName, number>> = {};
383
+ const byNoun = new Map(LANE_ORDER.map((l) => [MORE_NOUN[l], l] as const));
384
+ for (const l of LANE_ORDER) {
385
+ const old = LEGACY_MORE_NOUN[l];
386
+ if (old !== undefined) byNoun.set(old, l);
387
+ }
388
+ for (const line of text.split("\n")) {
389
+ const collapsed = collapsedLane(line);
390
+ if (collapsed !== null) {
391
+ const heading = headingsOf(collapsed).find((h) => line.startsWith(`${h} `)) ?? laneHeading(collapsed);
392
+ out[collapsed] = Number(/^\D*(\d+) — /.exec(line.slice(heading.length))?.[1] ?? 0);
393
+ continue;
394
+ }
395
+ const more = /^\((\d+) more (.+?); recall ids/.exec(line);
396
+ const lane = more === null ? undefined : byNoun.get(more[2] ?? "");
397
+ if (more !== null && lane !== undefined) {
398
+ out[lane] = Number(more[1]);
399
+ continue;
400
+ }
401
+ if (!isFoldedLine(line)) continue;
402
+ for (const m of line.slice(FOLDED_WORDS.length + 1).matchAll(/(\d+) ([^;(]+?) \(recall ids: /g)) {
403
+ const l = byNoun.get(m[2] ?? "");
404
+ if (l !== undefined) out[l] = Number(m[1]);
405
+ }
406
+ }
407
+ return out;
408
+ }
409
+
262
410
  function recallIds(ids: readonly string[]): string {
263
411
  const shown = ids.slice(0, MORE_LINE_IDS);
264
412
  const which = ids.length > shown.length ? `recall ids (the first ${String(shown.length)})` : "recall ids";
@@ -286,9 +434,10 @@ export function collapsedLine(lane: LaneName, ids: readonly string[]): string {
286
434
  /** The lane a collapsed line (`collapsedLine`) speaks for, or null for any other line. */
287
435
  export function collapsedLane(line: string): LaneName | null {
288
436
  for (const lane of LANE_ORDER) {
289
- const heading = laneHeading(lane);
290
- if (!line.startsWith(`${heading} `)) continue;
291
- if (new RegExp(`^ \\d+ — ${COLLAPSED_WORDS}; recall ids`).test(line.slice(heading.length))) return lane;
437
+ for (const heading of headingsOf(lane)) {
438
+ if (!line.startsWith(`${heading} `)) continue;
439
+ if (new RegExp(`^ \\d+ — ${COLLAPSED_WORDS}; recall ids`).test(line.slice(heading.length))) return lane;
440
+ }
292
441
  }
293
442
  return null;
294
443
  }
@@ -338,67 +487,9 @@ export function collapsedLane(line: string): LaneName | null {
338
487
  * promised they may hand-edit (constitution 6) is a paste accident away.
339
488
  */
340
489
  export function identityCoreLine(name: string): string {
341
- return `This memory is for ${flatten(name)}. No identity has formed here yet — identity is earned at the boundary that ends a session, from what recurs across distinct days.`;
490
+ return `This memory is for ${flatten(name)}. We've only just met. Who I am takes shape as the same things come up across different days.`;
342
491
  }
343
492
 
344
- /**
345
- * THE PAGE, IN "WHO I AM" — furniture, like the day-0 line, and for the same
346
- * reason: it is not a ranked element, it carries no `- ` bullet, and `counts`
347
- * and the sentinel's `elements=` stay true of a bundle that holds it.
348
- *
349
- * The page prints FIRST and AS IS. Not re-wrapped, not re-ordered, not
350
- * summarised: a page reassembled here would be a page this module wrote, and
351
- * what the owner and the session are promised is the thing they wrote.
352
- * `FRAMING.context`'s "each line opens with the date it was learned" is a claim
353
- * about the element lines — the day-0 line has carried no date since it shipped
354
- * — and the page carries its own date on its own line instead.
355
- */
356
- export interface PageBlock {
357
- /**
358
- * The page as it will be injected, on the rung the room allowed
359
- * (`PageRung`, 2026-10-10): the whole page, the short version its writer
360
- * wrote with it, each section's heading and first sentence, its headings
361
- * alone, or the one line that says it did not fit (`pageTooLargeLine`).
362
- * Every rung is whole text — never part of a sentence (2026-10-09).
363
- */
364
- readonly text: string;
365
- /**
366
- * THE TOP LINE (2026-10-10, `pageTopLine`): what is below, the page's size,
367
- * the exact line it ends with, and both doors to the whole page — so a
368
- * reader whose copy was cut on the way (a host's preview) can tell. Null on
369
- * the one-line rung, which is its own top line.
370
- */
371
- readonly top: string | null;
372
- /** The page's own "last revised" line, or null when the page carries no date. */
373
- readonly dateline: string | null;
374
- /** THE END LINE (`pageEndLine`), after the dateline; null when `top` is. */
375
- readonly end: string | null;
376
- /** Which rung printed. */
377
- readonly rung: PageRung;
378
- /** True when the page did not print whole — any rung but `whole`. */
379
- readonly truncated: boolean;
380
- /** The page's own bytes, whole, whatever was rendered. */
381
- readonly wholeBytes: number;
382
- }
383
-
384
- /**
385
- * THE PAGE'S FALLBACK LADDER (2026-10-10), first to last; `Self#pageBlock`
386
- * takes the first that fits. Every rung is whole text, never a cut:
387
- *
388
- * - `whole` — the page, byte for byte;
389
- * - `short` — the short version the page's writer wrote WITH this
390
- * version of it (`SelfPage.short`, tied to the page's exact
391
- * text, so a page rewritten without one never shows a stale
392
- * one);
393
- * - `outline` — each `##` section's heading and its first whole sentence
394
- * (`page.ts#pageOutline`), mechanical;
395
- * - `headings` — the headings alone;
396
- * - `line` — one line naming the page's size and both doors
397
- * (`pageTooLargeLine`), its own top line.
398
- */
399
- export const PAGE_RUNGS = ["whole", "short", "outline", "headings", "line"] as const;
400
- export type PageRung = (typeof PAGE_RUNGS)[number];
401
-
402
493
  /**
403
494
  * What "Who I am" prints BESIDE the ranked elements. Both fields are decided by
404
495
  * `render` from the tunables and handed down, so `compose` stays a renderer with
@@ -413,27 +504,7 @@ export interface IdentityBlock {
413
504
 
414
505
  /** What "Who I am" says when no page has been written and the list is off. */
415
506
  export const PAGE_FORMING_LINE =
416
- "Still forming — no page has been written here yet. It is written at a boundary, from what recurs, and can be amended by hand.";
417
-
418
- /**
419
- * The page's own date, under the page. It states the DATE and — when the page
420
- * has gone stale — how long the silence was allowed to be, rather than "N days
421
- * ago": the bundle is composed at a boundary and then served unchanged until
422
- * the next one, so a delta computed here goes wrong while a date does not.
423
- */
424
- export function pageDateline(revisedOn: string, stale: boolean, staleDays: number): string | null {
425
- const on = revisedOn.trim();
426
- // A page with no readable date SAYS SO. Returning null printed the page with
427
- // no date and no staleness signal at all while every other surface called it
428
- // stale — the one state where the wake said less than it knew (adversarial
429
- // review m6). Only reachable on a hand-minted or hand-edited row.
430
- if (on === "" || !/^\d{4}-\d{2}-\d{2}$/.test(on) || !Number.isFinite(Date.parse(`${on}T00:00:00Z`))) {
431
- return "(Last revised — the page carries no readable date.)";
432
- }
433
- return stale
434
- ? `(Last revised ${on} — more than ${staleDays} days before this wake was composed.)`
435
- : `(Last revised ${on}.)`;
436
- }
507
+ "Still forming: I write this page after a few sessions, from what keeps coming up. It can be edited by hand.";
437
508
 
438
509
  /** Id → the verbatim statement AND its dates, at render time only. */
439
510
  export interface Resolved {
@@ -604,12 +675,28 @@ export interface BriefingResult extends Composed {
604
675
  readonly kept: Record<LaneName, string[]>;
605
676
  readonly trimmed: TrimEvent[];
606
677
  /**
607
- * The lanes that carry a "N more" line (`moreLine`), and N for each — what
608
- * the lane lost to its cap, the identity share or the trim, and that this
609
- * render had room to say. A lane that lost something with no room for the
610
- * line is absent here; its trim is still in `trimmed`.
678
+ * The lanes the wake COUNTS rather than lists in full, and N for each — what
679
+ * the lane lost to its cap, the identity share or the trim, said in its "N
680
+ * more" line (`moreLine`), its collapsed line, or the folded line (2026-10-12:
681
+ * reserved, so every lane that lost something is here).
611
682
  */
612
683
  readonly more: Partial<Record<LaneName, number>>;
684
+ /** True when the lanes that list nothing were folded into one line (`foldedLine`). */
685
+ readonly folded: boolean;
686
+ /**
687
+ * What the wake left out WITHOUT A WORD, per lane (2026-10-12): ids the lane
688
+ * lost that no line names. Empty unless not even the folded line fit — a
689
+ * floor over its budget, or a bug — and doctor's Wake line says so in red.
690
+ */
691
+ readonly untold: Partial<Record<LaneName, number>>;
692
+ /**
693
+ * NEARBY, LEFT UNCOUNTED BY RANK (2026-10-12, decided by COUNTERPARTS,
694
+ * lightly held): "Nearby" is the least of the lanes, so its count takes
695
+ * only room nothing else wants — its own line, else a place in the folded
696
+ * line — and when neither fits it is left out. A step-down, not a silent
697
+ * drop: recall finds those hints by asking. `{ hints: N }` or empty.
698
+ */
699
+ readonly quiet: Partial<Record<LaneName, number>>;
613
700
  /** True when the render crossed the pressure ratio — the tripwire that fires
614
701
  * when a budget is APPROACHED, not only when it blows (scar §2.4). */
615
702
  readonly pressure: boolean;
@@ -773,8 +860,6 @@ export function elementLine(item: Ranked, resolve: Resolve): string {
773
860
  return `- ${date}${standing}${statement}${r.standing?.suffix ?? ""}`;
774
861
  }
775
862
 
776
- type Kept = Record<LaneName, Ranked[]>;
777
-
778
863
  /** Every lane empty — the floor a composition cannot go below. */
779
864
  function emptyKept(): Kept {
780
865
  return { identity: [], craft: [], threads: [], hints: [], horizon: [] };
@@ -816,6 +901,9 @@ export function compose(
816
901
  yesterday?: string,
817
902
  /** The "Today, elsewhere" line (`BriefingRequest.elsewhere`), above "Nearby". */
818
903
  elsewhere?: string,
904
+ /** The lanes that list nothing, folded into one line (`foldedLine`), under
905
+ * "Who I am"; the caller then passes no `more` for them. */
906
+ fold?: string,
819
907
  ): Composed {
820
908
  const counts = emptyCounts();
821
909
  for (const lane of LANE_ORDER) counts[lane] = kept[lane].length;
@@ -862,6 +950,9 @@ export function compose(
862
950
  if (more.identity !== undefined) lines.push(more.identity);
863
951
  continue;
864
952
  }
953
+ // The folded line (2026-10-12): just under "Who I am", where a preview
954
+ // that keeps the head of the wake still carries it.
955
+ if (lane === "craft" && fold !== undefined && fold.length > 0) lines.push("", fold);
865
956
  const tail = more[lane];
866
957
  if (items.length === 0 && tail === undefined) continue;
867
958
  // Nothing listed: the tail is the lane's one collapsed line, heading
@@ -938,43 +1029,12 @@ function withheldForShare(
938
1029
  return kept.identity.splice(n);
939
1030
  }
940
1031
 
941
- /**
942
- * Give identity back the bytes nobody else could use. Elements return in rank
943
- * order and only while the whole composition still fits, so the result is the
944
- * same prefix of the identity lane a larger share would have produced.
945
- */
946
- function offerLeftover(
947
- kept: Kept,
948
- held: Ranked[],
949
- composed: Composed,
950
- req: BriefingRequest,
951
- resolve: Resolve,
952
- coreName: string | undefined,
953
- identity: IdentityBlock,
954
- yesterday?: string,
955
- elsewhere?: string,
956
- ): Composed {
957
- let current = composed;
958
- while (held.length > 0) {
959
- const next = held[0];
960
- if (next === undefined) break;
961
- kept.identity.push(next);
962
- const candidate = compose(kept, req.day, resolve, coreName, identity, {}, yesterday, elsewhere);
963
- if (candidate.bytes > req.budgetBytes) {
964
- kept.identity.pop();
965
- break;
966
- }
967
- held.shift();
968
- current = candidate;
969
- }
970
- return current;
971
- }
972
-
973
1032
  /**
974
1033
  * WHAT EACH LANE LOST, by id, in the lane's rank order: the budget trim's
975
1034
  * (popped from the end, so reversed back), then — identity only — what the
976
1035
  * share held back and the leftover did not return, then what the lane's cap
977
- * left out. Identity says nothing while the page replaces the list.
1036
+ * left out — but not Nearby's cap, which is the rest of the store
1037
+ * (`MORE_ORDER`'s note). Identity says nothing while the page replaces the list.
978
1038
  */
979
1039
  function lostByLane(
980
1040
  overflow: Partial<Record<LaneName, readonly string[]>> | undefined,
@@ -988,431 +1048,13 @@ function lostByLane(
988
1048
  const ids = [
989
1049
  ...trimmed.filter((e) => e.lane === lane).map((e) => e.id).reverse(),
990
1050
  ...(lane === "identity" ? held.map((r) => r.id) : []),
991
- ...(overflow?.[lane] ?? []),
1051
+ ...(lane === "hints" ? [] : (overflow?.[lane] ?? [])),
992
1052
  ];
993
1053
  if (ids.length > 0) out[lane] = ids;
994
1054
  }
995
1055
  return out;
996
1056
  }
997
1057
 
998
- /**
999
- * WHAT THE RENDER HAS COMPOSED SO FAR, rescue by rescue (2026-10-10): the trim
1000
- * loop's composition, then each lane that took room from the lanes below it
1001
- * (`takeRoom`). `lent` is what the composition runs past `budgetBytes` — lent
1002
- * by "Work here" first, then by the room held for "Last here" and the handoff
1003
- * pointer — and `pinned` the count lines already paid for, which
1004
- * `withMoreLines` keeps rather than re-tries.
1005
- */
1006
- interface Rescued {
1007
- readonly kept: Kept;
1008
- readonly trimmed: TrimEvent[];
1009
- readonly yesterday: string | undefined;
1010
- /** The "Today, elsewhere" line as it stands (`BriefingRequest.elsewhere`). */
1011
- readonly elsewhere: string | undefined;
1012
- readonly pinned: Partial<Record<LaneName, string[]>>;
1013
- readonly composed: Composed;
1014
- readonly lent: number;
1015
- }
1016
-
1017
- interface RescueCtx {
1018
- readonly req: BriefingRequest;
1019
- readonly resolve: Resolve;
1020
- readonly coreName: string | undefined;
1021
- readonly identity: IdentityBlock;
1022
- /** How many of Arriving's first lines no rescue below them may take
1023
- * (`arrivingHead`). */
1024
- readonly head: number;
1025
- /** The "Today, elsewhere" line's forms, widest first (`narrowerElsewhere`). */
1026
- readonly elsewhereForms: readonly string[];
1027
- }
1028
-
1029
- function copyKept(k: Kept): Kept {
1030
- return {
1031
- identity: [...k.identity],
1032
- craft: [...k.craft],
1033
- threads: [...k.threads],
1034
- hints: [...k.hints],
1035
- horizon: [...k.horizon],
1036
- };
1037
- }
1038
-
1039
- /** A non-negative whole number of bytes, or 0. */
1040
- function lendOf(n: number | undefined): number {
1041
- return Math.max(0, Math.floor(n ?? 0));
1042
- }
1043
-
1044
- /**
1045
- * The count lines a composition carries for its pinned lanes: "N more", or —
1046
- * a lane that lists nothing — its one collapsed line (`collapsedLine`).
1047
- */
1048
- function pinnedLines(pinned: Partial<Record<LaneName, readonly string[]>>, kept: Kept): Partial<Record<LaneName, string>> {
1049
- const out: Partial<Record<LaneName, string>> = {};
1050
- for (const lane of LANE_ORDER) {
1051
- const ids = pinned[lane];
1052
- if (ids === undefined || ids.length === 0) continue;
1053
- out[lane] = lane !== "identity" && kept[lane].length === 0 ? collapsedLine(lane, ids) : moreLine(lane, ids);
1054
- }
1055
- return out;
1056
- }
1057
-
1058
- /**
1059
- * How many of Arriving's first lines are its HEAD (2026-10-10): every plain
1060
- * reminder due the day the wake is read (`Ranked.due`, which `Self#build`
1061
- * puts first), or else its first line alone. No rescue ranked below
1062
- * `ROOM_ORDER`'s `arrivingFirst` takes them; "Still open"'s first item takes
1063
- * the lines after them, and last of all (`takeRoom`'s `arriving` step).
1064
- */
1065
- export function arrivingHead(horizon: readonly Pick<Ranked, "due">[]): number {
1066
- let n = 0;
1067
- while (horizon[n]?.due === true) n += 1;
1068
- return Math.min(horizon.length, Math.max(1, n));
1069
- }
1070
-
1071
- /** How many days ahead a dated item counts as NEAR at session start
1072
- * (`HorizonItem.near`; 2026-10-12, RANDOM's ruling, lightly held). */
1073
- export const ARRIVING_NEAR_DAYS = 3;
1074
-
1075
- /** Whether a dated item due `due` is NEAR on `at`: from that day through
1076
- * `ARRIVING_NEAR_DAYS` after it. A grace day's "was due" line, behind `at`,
1077
- * is not (RANDOM's ruling at the review of #445, 2026-10-12, lightly held). */
1078
- export function nearDue(due: string | undefined, at: string): boolean {
1079
- return due !== undefined && isDay(due) && isDay(at) && due >= at && due <= addDays(at, ARRIVING_NEAR_DAYS);
1080
- }
1081
-
1082
- /**
1083
- * How many of Arriving's first lines are NEAR (2026-10-12): the head, then
1084
- * every line after it marked `near` (`Ranked.near`, set at session start
1085
- * only, and sorted to follow the head). Zero when none is.
1086
- */
1087
- export function arrivingNear(horizon: readonly Pick<Ranked, "due" | "near">[]): number {
1088
- let n = 0;
1089
- while (horizon[n]?.due === true || horizon[n]?.near === true) n += 1;
1090
- return horizon.some((r) => r.near === true) ? n : 0;
1091
- }
1092
-
1093
- /**
1094
- * The "Today, elsewhere" line's forms the render may print, widest first:
1095
- * each within `TODAY_ELSEWHERE_MAX_BYTES` (2026-10-10), each narrower than
1096
- * the one before. Empty without a line.
1097
- */
1098
- function elsewhereFormsOf(line: string | undefined, shorter: readonly string[] | undefined): string[] {
1099
- if (line === undefined || line.length === 0) return [];
1100
- const out: string[] = [];
1101
- for (const form of [line, ...(shorter ?? [])]) {
1102
- const size = byteLength(flatten(form));
1103
- if (form.length === 0 || size > TODAY_ELSEWHERE_MAX_BYTES) continue;
1104
- const last = out[out.length - 1];
1105
- if (last !== undefined && size >= byteLength(flatten(last))) continue;
1106
- out.push(form);
1107
- }
1108
- return out;
1109
- }
1110
-
1111
- /** The "Today, elsewhere" line's next form after `line` in `forms`, or none. */
1112
- function narrowerElsewhere(line: string, forms: readonly string[]): string | undefined {
1113
- const at = forms.indexOf(line);
1114
- return at < 0 ? undefined : forms[at + 1];
1115
- }
1116
-
1117
- /** The Yesterday line's shorter forms, widest first, each narrower than `line`. */
1118
- function shorterThan(line: string | undefined, forms: readonly string[] | undefined): string[] {
1119
- if (line === undefined) return [];
1120
- const bytes = byteLength(line);
1121
- return (forms ?? []).filter((s) => s.length > 0 && byteLength(s) < bytes);
1122
- }
1123
-
1124
- /**
1125
- * TAKE ROOM FROM THE LANES BELOW `target`, lowest first, as `ROOM_ORDER` says
1126
- * (2026-10-10) — and only as much as it needs: the composition `want`, with
1127
- * its `pinned` count lines, is tried as it stands, then again after each
1128
- * step, and the first that fits is kept. The steps the render can take:
1129
- *
1130
- * - `work` — the room held for "Work here" (`lendBytes`);
1131
- * - `yesterday` — the Yesterday line, one title at a time given way to its
1132
- * id (`yesterdayShorter`);
1133
- * - `handoffs` — the room held for "Last here" and the handoff pointer
1134
- * (`handoffLendBytes`), which the delivery gives up in its own order;
1135
- * - `arriving` — Arriving's lines past its head (`arrivingHead`), from the
1136
- * end, each a `TrimEvent` so the lane's count can still say so;
1137
- * - `elsewhere` — the "Today, elsewhere" line, a narrower form at a time,
1138
- * then none (2026-10-10; between `handoffs` and `arriving` since the
1139
- * review of #380). The trim loop also asks here on the line's behalf
1140
- * (`target` `elsewhere`) before it steps the line down;
1141
- * - `handoffsKept` — the room held for the newest handoff's own block
1142
- * (`handoffKeepBytes`): reached only by `due`, the one lane above it
1143
- * that takes room here (review of #367; `arrivingNear` stops below it,
1144
- * review of #445).
1145
- *
1146
- * The lanes below them are the trim loop's and are gone before any rescue
1147
- * runs; `lastHere` is the delivery's, inside the room lent at `handoffs`; the
1148
- * page is chosen before the lanes (`Self#build`), and gives its borrowing
1149
- * back to `due` there. All or nothing: null when even the last step below
1150
- * `target` leaves no room — the render is then what it was.
1151
- */
1152
- function takeRoom(
1153
- target: RoomLane,
1154
- from: Rescued,
1155
- want: Kept,
1156
- pinned: Partial<Record<LaneName, readonly string[]>>,
1157
- trimmed: readonly TrimEvent[],
1158
- ctx: RescueCtx,
1159
- ): Rescued | null {
1160
- const { req } = ctx;
1161
- const work = lendOf(req.lendBytes);
1162
- const handoffs = lendOf(req.handoffLendBytes);
1163
- const kept = lendOf(req.handoffKeepBytes);
1164
- const k = copyKept(want);
1165
- const t = [...trimmed];
1166
- const pins: Partial<Record<LaneName, string[]>> = {};
1167
- for (const lane of LANE_ORDER) {
1168
- const ids = pinned[lane];
1169
- if (ids !== undefined && ids.length > 0) pins[lane] = [...ids];
1170
- }
1171
- let limit = req.budgetBytes + from.lent;
1172
- let y = from.yesterday;
1173
- let e = from.elsewhere;
1174
- const attempt = (): Rescued | null => {
1175
- const c = compose(k, req.day, ctx.resolve, ctx.coreName, ctx.identity, pinnedLines(pins, k), y, e);
1176
- return c.bytes <= limit
1177
- ? { kept: k, trimmed: t, yesterday: y, elsewhere: e, pinned: pins, composed: c, lent: Math.max(0, c.bytes - req.budgetBytes) }
1178
- : null;
1179
- };
1180
- let got = attempt();
1181
- for (const lane of ROOM_ORDER) {
1182
- if (got !== null || lane === target) break;
1183
- switch (lane) {
1184
- case "elsewhere":
1185
- // Its titles first, then the line (2026-10-10).
1186
- while (got === null && e !== undefined) {
1187
- e = narrowerElsewhere(e, ctx.elsewhereForms);
1188
- got = attempt();
1189
- }
1190
- break;
1191
- case "work":
1192
- if (req.budgetBytes + work > limit) {
1193
- limit = req.budgetBytes + work;
1194
- got = attempt();
1195
- }
1196
- break;
1197
- case "yesterday":
1198
- for (const form of shorterThan(y, req.yesterdayShorter)) {
1199
- y = form;
1200
- got = attempt();
1201
- if (got !== null) break;
1202
- }
1203
- break;
1204
- case "handoffs":
1205
- if (req.budgetBytes + work + handoffs > limit) {
1206
- limit = req.budgetBytes + work + handoffs;
1207
- got = attempt();
1208
- }
1209
- break;
1210
- case "arriving":
1211
- while (got === null && k.horizon.length > ctx.head) {
1212
- const dropped = k.horizon.pop();
1213
- if (dropped === undefined) break;
1214
- t.push({ lane: "horizon", id: dropped.id, strength: dropped.strength });
1215
- // A count already paid for names it too, first: it ranked first.
1216
- if (pins.horizon !== undefined) pins.horizon = [dropped.id, ...pins.horizon];
1217
- got = attempt();
1218
- }
1219
- break;
1220
- case "handoffsKept":
1221
- if (req.budgetBytes + work + handoffs + kept > limit) {
1222
- limit = req.budgetBytes + work + handoffs + kept;
1223
- got = attempt();
1224
- }
1225
- break;
1226
- default:
1227
- break;
1228
- }
1229
- }
1230
- return got;
1231
- }
1232
-
1233
- /**
1234
- * "ARRIVING:" LISTS ITS DATED ITEMS BEFORE THE FURNITURE BELOW IT KEEPS ITS
1235
- * ROOM (2026-10-10, `ROOM_ORDER`). The trim loop pops Arriving only after
1236
- * "Nearby", craft and "Still open" are gone, but the page, the Yesterday line
1237
- * and the room held for the delivery's lanes are nothing it can pop — so on
1238
- * the owner's lived day 19 his tax reminder collapsed to "Arriving: 1 — no
1239
- * room to list them" while yesterday's titles and four handoffs printed.
1240
- *
1241
- * Here the lane's first `upTo` lines are listed again — as many as fit, each
1242
- * time with the count of the rest (an item under a heading with no count
1243
- * reads as the only one arriving), or, when only the item fits, without it: a
1244
- * listed date outranks the count of the others. The room comes from the
1245
- * lanes below `target` (`takeRoom`). Called twice: for the lane's head at
1246
- * its own rank (`due` or `arrivingFirst`), and — after "Still open"'s first
1247
- * item — for the rest at `arriving`. Null when nothing was trimmed from it,
1248
- * or nothing more fits.
1249
- */
1250
- function keepArriving(
1251
- arrived: readonly Ranked[],
1252
- overflow: readonly string[],
1253
- upTo: number,
1254
- target: RoomLane,
1255
- from: Rescued,
1256
- ctx: RescueCtx,
1257
- ): Rescued | null {
1258
- const want = Math.min(upTo, arrived.length);
1259
- for (let n = want; n > from.kept.horizon.length; n--) {
1260
- const listed = arrived.slice(0, n);
1261
- const k: Kept = { ...copyKept(from.kept), horizon: [...listed] };
1262
- const t = from.trimmed.filter((e) => !(e.lane === "horizon" && listed.some((r) => r.id === e.id)));
1263
- // The rest, as `lostByLane` lists it: the trim's (popped from the end, so
1264
- // reversed back), then what the lane's cap left out.
1265
- const rest = [...t.filter((e) => e.lane === "horizon").map((e) => e.id).reverse(), ...overflow];
1266
- const others: Partial<Record<LaneName, string[]>> = { ...from.pinned };
1267
- delete others.horizon;
1268
- for (const counted of rest.length === 0 ? [false] : [true, false]) {
1269
- const got = takeRoom(target, from, k, counted ? { ...others, horizon: rest } : others, t, ctx);
1270
- if (got !== null) return got;
1271
- }
1272
- }
1273
- return null;
1274
- }
1275
-
1276
- /**
1277
- * "ARRIVING:" SAYS HOW MANY MORE, BY ID, BEFORE IT LISTS A LATER LINE IN FULL
1278
- * (review of #367, 2026-10-10). The lane's count names every dated item it
1279
- * did not list — the trim's and those past `prospective/`'s count
1280
- * (`BoundaryRequest.horizonMore`) — and those past the count leave no trim
1281
- * row for doctor to read, so a count left out is a dated item silently gone.
1282
- * Last of the rescues: when the lane lists something and has no count yet,
1283
- * the count takes room from the lanes below `arriving` — "Work here", the
1284
- * Yesterday line's titles, the handoffs' room — and, only when it names an
1285
- * item past that count (one no trim row records), from Arriving's lines past
1286
- * its head too, each named in the count it pays for. A count of the trim's
1287
- * alone leaves the listed lines as they are: a listed date outranks it, and
1288
- * doctor reads the trim. Null when the count is already in, there is nothing
1289
- * to count, or no room is found.
1290
- *
1291
- * AND WHEN THE LANE LISTS NOTHING (2026-10-12): its one collapsed line takes
1292
- * room the same way. The owner's 10-12 bundles carried seven dated items and
1293
- * not a word about them — the page, borrowing "Work here", had spent the
1294
- * room, and the line was offered only what was left.
1295
- */
1296
- function keepArrivingCount(overflow: readonly string[], from: Rescued, ctx: RescueCtx): Rescued | null {
1297
- if ((from.pinned.horizon?.length ?? 0) > 0) return null;
1298
- const rest = [...from.trimmed.filter((e) => e.lane === "horizon").map((e) => e.id).reverse(), ...overflow];
1299
- if (rest.length === 0) return null;
1300
- const pinned = { ...from.pinned, horizon: rest };
1301
- // Room as the composition stands: `withMoreLines` adds it then, as it adds every lane's.
1302
- const { req } = ctx;
1303
- 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) {
1304
- return null;
1305
- }
1306
- return takeRoom(overflow.length > 0 ? "openFirst" : "arriving", from, from.kept, pinned, from.trimmed, ctx);
1307
- }
1308
-
1309
- /**
1310
- * "STILL OPEN" KEEPS ITS FIRST ITEM, AND ITS COUNT (review of #350,
1311
- * 2026-10-09; its place in `ROOM_ORDER` since 2026-10-10).
1312
- *
1313
- * The owner's wake on 10-09 read "Still open:" over "(20 more still open; …)"
1314
- * and no item. The self page is furniture the trim cannot pop, the Yesterday
1315
- * line is too, and `TRIM_ORDER` takes "Still open" before "Arriving" — so
1316
- * beside a long page the lane gave up its last item while Arriving kept every
1317
- * line. The page is not what gives way: it is the self the wake is for
1318
- * (`Self#pageBlock`). What gives way is what `ROOM_ORDER` ranks below
1319
- * `openFirst`, lowest first (`takeRoom`): "Work here", the Yesterday line's
1320
- * titles, the room for "Last here" and the handoffs, and only then Arriving
1321
- * past its head — whose first line, and every plain reminder due the day the
1322
- * wake is read, rank above this.
1323
- *
1324
- * The target is the lane's first item AND its "N more" line: one item under a
1325
- * heading with no count reads as the only thing open. All or nothing: when
1326
- * even the last step leaves no room, the render is what it was, and a lane
1327
- * that lists nothing says so in one line (`collapsedLine`).
1328
- *
1329
- * AND THE COUNT BESIDE WHAT THE TRIM KEPT (review of #358, 2026-10-09): when
1330
- * the trim loop left the lane its items but no room for its "N more" line,
1331
- * the count is paid for out of "Work here" and out of nothing else
1332
- * (`openCount`, just above `work`): the items stay as the trim kept them (a
1333
- * smaller budget still keeps a subset). Not when the count already fits as
1334
- * the composition stands: `withMoreLines` adds it then, as it adds every
1335
- * lane's.
1336
- */
1337
- function keepFirstOpen(
1338
- arrived: readonly Ranked[],
1339
- overflow: readonly string[],
1340
- arrivedHorizon: number,
1341
- from: Rescued,
1342
- ctx: RescueCtx,
1343
- ): Rescued | null {
1344
- const first = arrived[0];
1345
- if (first === undefined) return null;
1346
- const kept = from.kept;
1347
- // Arriving's FIRST line outranks it: when not even that is listed, this
1348
- // budget has no room to rearrange.
1349
- if (kept.threads.length === 0 && arrivedHorizon > 0 && kept.horizon.length === 0) return null;
1350
- // What the lane lists: the items the trim kept, or — when it kept none —
1351
- // its first item.
1352
- const k: Kept = { ...copyKept(kept), threads: kept.threads.length > 0 ? [...kept.threads] : [first] };
1353
- const t = from.trimmed.filter((e) => !(e.lane === "threads" && k.threads.some((l) => l.id === e.id)));
1354
- // The rest of the lane, as `lostByLane` will list it: the trim's (popped
1355
- // from the end, so reversed back), then what the lane's cap left out.
1356
- const rest = [...t.filter((e) => e.lane === "threads").map((e) => e.id).reverse(), ...overflow];
1357
- const pinned: Partial<Record<LaneName, string[]>> = rest.length === 0 ? { ...from.pinned } : { ...from.pinned, threads: rest };
1358
- if (kept.threads.length > 0) {
1359
- // Items the trim kept: only their count is owed here, and only when it
1360
- // does not fit as the composition stands.
1361
- if (rest.length === 0) return null;
1362
- const { req } = ctx;
1363
- const asIs = compose(k, req.day, ctx.resolve, ctx.coreName, ctx.identity, pinnedLines(pinned, k), from.yesterday, from.elsewhere);
1364
- if (from.lent === 0 && asIs.bytes <= req.budgetBytes) return null;
1365
- return takeRoom("openCount", from, k, pinned, t, ctx);
1366
- }
1367
- return takeRoom("openFirst", from, k, pinned, t, ctx);
1368
- }
1369
-
1370
- /**
1371
- * Add each lane's "N more" line, in `MORE_ORDER`, only while the whole
1372
- * composition still fits the budget. A line that does not fit is left out and
1373
- * the next lane's is tried: they are one line each, and a shorter one may fit.
1374
- */
1375
- function withMoreLines(
1376
- composed: Composed,
1377
- ctx: {
1378
- kept: Kept;
1379
- lost: Partial<Record<LaneName, string[]>>;
1380
- req: BriefingRequest;
1381
- resolve: Resolve;
1382
- coreName: string | undefined;
1383
- identity: IdentityBlock;
1384
- yesterday?: string;
1385
- elsewhere?: string;
1386
- /** Lines already in `composed`, paid for before the others are offered
1387
- * room (a rescue's count, `takeRoom`): kept, never re-tried. */
1388
- pinned?: Partial<Record<LaneName, string[]>>;
1389
- },
1390
- ): { composed: Composed; more: Partial<Record<LaneName, number>> } {
1391
- let current = composed;
1392
- const lines: Partial<Record<LaneName, string>> = pinnedLines(ctx.pinned ?? {}, ctx.kept);
1393
- const more: Partial<Record<LaneName, number>> = {};
1394
- for (const lane of LANE_ORDER) {
1395
- const ids = ctx.pinned?.[lane];
1396
- if (ids === undefined || ids.length === 0) continue;
1397
- more[lane] = ids.length;
1398
- }
1399
- for (const lane of MORE_ORDER) {
1400
- const ids = ctx.lost[lane];
1401
- if (ids === undefined || ids.length === 0 || lines[lane] !== undefined) continue;
1402
- // A lane that kept nothing gets the one collapsed line instead: "N more"
1403
- // over no item is neither a list nor a count (2026-10-09).
1404
- lines[lane] = lane !== "identity" && ctx.kept[lane].length === 0 ? collapsedLine(lane, ids) : moreLine(lane, ids);
1405
- const candidate = compose(ctx.kept, ctx.req.day, ctx.resolve, ctx.coreName, ctx.identity, lines, ctx.yesterday, ctx.elsewhere);
1406
- if (candidate.bytes > ctx.req.budgetBytes) {
1407
- delete lines[lane];
1408
- continue;
1409
- }
1410
- current = candidate;
1411
- more[lane] = ids.length;
1412
- }
1413
- return { composed: current, more };
1414
- }
1415
-
1416
1058
  /**
1417
1059
  * Compose within the caller's budget, trimming in `TRIM_ORDER` until it fits.
1418
1060
  *
@@ -1528,19 +1170,35 @@ export function render(
1528
1170
  const outranksLine = (lane: LaneName): boolean =>
1529
1171
  ROOM_ORDER.indexOf(lone(lane) ? "openFirst" : TRIM_ROOM[lane]) > ROOM_ORDER.indexOf("elsewhere");
1530
1172
 
1173
+ // EACH LANE'S LINE IS RESERVED (2026-10-12): the loop composes with the
1174
+ // line of every lane that has lost something so far — to its cap, the
1175
+ // identity share or a pop — and pops until items and lines fit together.
1176
+ // When nothing is left to pop, the "Today, elsewhere" line steps down, and
1177
+ // then the lanes that list nothing fold into one line (`foldParts`) — and
1178
+ // they fold before the loop pops "Who I am", the lane the wake is for. A
1179
+ // floor that holds not even the folded line composes bare (`bare`): its
1180
+ // lanes go untold. "Nearby"'s count is not reserved: the least of the
1181
+ // lanes, it takes only room nothing else wants (`tellLost`; decided by
1182
+ // COUNTERPARTS, 2026-10-12, lightly held).
1183
+ let fold = false;
1184
+ let bare = false;
1185
+ const lostNow = (): Partial<Record<LaneName, string[]>> => withoutNearby(lostByLane(lanes.overflow, trimmed, held, suppressList));
1186
+ const linesFor = (lost: Partial<Record<LaneName, readonly string[]>>, k: Kept, folded: boolean): { more: Partial<Record<LaneName, string>>; fold?: string } =>
1187
+ folded ? foldParts(lost, k) : { more: pinnedLines(lost, k) };
1188
+
1531
1189
  for (;;) {
1532
- const c = compose(kept, req.day, resolve, coreName, identity, {}, yesterday, elsewhere);
1190
+ const lost = lostNow();
1191
+ const lines = bare ? { more: {} } : linesFor(lost, kept, fold);
1192
+ const c = compose(kept, req.day, resolve, coreName, identity, lines.more, yesterday, elsewhere, lines.fold);
1533
1193
  const fits = c.bytes <= base;
1534
1194
  let cut: TrimEvent | null = null;
1535
1195
  let stepped = false;
1536
1196
  if (!fits) {
1537
1197
  for (const lane of TRIM_ORDER) {
1538
1198
  if (elsewhere !== undefined && outranksLine(lane)) {
1539
- const from: Rescued = { kept, trimmed: [...trimmed], yesterday, elsewhere, pinned: {}, composed: c, lent: base - req.budgetBytes };
1540
- const rest = lone(lane)
1541
- ? [...trimmed.filter((e) => e.lane === "threads").map((e) => e.id).reverse(), ...(lanes.overflow?.threads ?? [])]
1542
- : [];
1543
- const got = takeRoom("elsewhere", from, kept, rest.length === 0 ? {} : { threads: rest }, trimmed, ctx);
1199
+ const from: Rescued = { kept, trimmed: [...trimmed], yesterday, elsewhere, pinned: lost, composed: c, lent: base - req.budgetBytes, fold };
1200
+ // "Still open"'s lone item keeps its count beside it: `lost` has it.
1201
+ const got = takeRoom("elsewhere", from, kept, lost, trimmed, ctx);
1544
1202
  if (got === null) {
1545
1203
  elsewhere = narrowerElsewhere(elsewhere, elsewhereForms);
1546
1204
  } else {
@@ -1548,17 +1206,57 @@ export function render(
1548
1206
  trimmed.splice(0, trimmed.length, ...got.trimmed);
1549
1207
  yesterday = got.yesterday;
1550
1208
  base = req.budgetBytes + got.lent;
1209
+ fold = got.fold;
1551
1210
  }
1552
1211
  stepped = true;
1553
1212
  break;
1554
1213
  }
1555
1214
  const items = kept[lane];
1556
1215
  if (items.length === 0) continue;
1216
+ if (lane === "identity" && !fold && Object.keys(lost).length > 0) {
1217
+ const folded = linesFor(lost, kept, true);
1218
+ if (compose(kept, req.day, resolve, coreName, identity, folded.more, yesterday, elsewhere, folded.fold).bytes <= base) {
1219
+ fold = true;
1220
+ stepped = true;
1221
+ break;
1222
+ }
1223
+ }
1557
1224
  const dropped = items.pop();
1558
1225
  if (dropped === undefined) continue;
1559
1226
  cut = { lane, id: dropped.id, strength: dropped.strength };
1560
1227
  break;
1561
1228
  }
1229
+ if (cut === null && !stepped) {
1230
+ // Nothing left to pop. The lanes' lines fold into one; then that
1231
+ // line takes room from what ranks below a dated line (`takeRoom` to
1232
+ // `arrivingFirst`: "Work here", the Yesterday line's titles, the
1233
+ // handoffs' room, "Today, elsewhere", Arriving past its head) — and
1234
+ // only when even that finds none do the lanes go untold (`bare`).
1235
+ const counting = Object.keys(lost).length > 0;
1236
+ if (counting && !fold) {
1237
+ fold = true;
1238
+ continue;
1239
+ }
1240
+ if (counting && !bare) {
1241
+ const from: Rescued = { kept, trimmed: [...trimmed], yesterday, elsewhere, pinned: lost, composed: c, lent: base - req.budgetBytes, fold: true };
1242
+ const got = takeRoom("arrivingFirst", from, kept, lost, trimmed, ctx, true);
1243
+ if (got === null) {
1244
+ bare = true;
1245
+ } else {
1246
+ for (const l of LANE_ORDER) kept[l] = got.kept[l];
1247
+ trimmed.splice(0, trimmed.length, ...got.trimmed);
1248
+ yesterday = got.yesterday;
1249
+ elsewhere = got.elsewhere;
1250
+ base = req.budgetBytes + got.lent;
1251
+ fold = got.fold;
1252
+ }
1253
+ continue;
1254
+ }
1255
+ if (elsewhere !== undefined) {
1256
+ elsewhere = narrowerElsewhere(elsewhere, elsewhereForms);
1257
+ continue;
1258
+ }
1259
+ }
1562
1260
  }
1563
1261
  if (stepped) continue;
1564
1262
  if (fits || cut === null) {
@@ -1568,13 +1266,14 @@ export function render(
1568
1266
  // count (review of #350), then the rest of "Arriving:", each taking room
1569
1267
  // only from the lanes below it: "Work here", the Yesterday line's
1570
1268
  // titles, the room for "Last here" and the handoffs — never the page. A
1571
- // rescue that finds no room leaves the render as it was.
1269
+ // rescue that finds no room leaves the render as it was. Each starts
1270
+ // from the lanes' reserved lines (`pinned`), and keeps them.
1572
1271
  const dueHead = lanes.horizon[0]?.due === true;
1573
1272
  const near = arrivingNear(lanes.horizon);
1574
1273
  // No later rescue takes a near line back to pay for a count of the rest.
1575
1274
  const nearCtx: RescueCtx = near > ctx.head ? { ...ctx, head: near } : ctx;
1576
1275
  const overflow = lanes.overflow;
1577
- let state: Rescued = { kept, trimmed: [...trimmed], yesterday, elsewhere, pinned: {}, composed: c, lent: base - req.budgetBytes };
1276
+ let state: Rescued = { kept, trimmed: [...trimmed], yesterday, elsewhere, pinned: lost, composed: c, lent: base - req.budgetBytes, fold: fold || bare };
1578
1277
  let first: Rescued | null = null;
1579
1278
  if (fits) {
1580
1279
  const steps: ((s: Rescued) => Rescued | null)[] = [
@@ -1600,21 +1299,34 @@ export function render(
1600
1299
  }
1601
1300
  const said = first === null ? yesterday : first.yesterday;
1602
1301
  const away = first === null ? elsewhere : first.elsewhere;
1302
+ // What it was composed to: the caller's budget, and what the delivery's
1303
+ // rooms lent (`takeRoom`) — so a reader comparing the bundle to its
1304
+ // ceiling sees one that fits, which it does: the delivery shows fewer
1305
+ // work lines, and then fewer handoffs, in what is left.
1306
+ const budgetBytes = req.budgetBytes + (first?.lent ?? base - req.budgetBytes);
1603
1307
  // The leftover clause. Only when NOTHING had to be trimmed: a lane that
1604
1308
  // lost an element wanted the room, and handing it to identity instead
1605
1309
  // would make the share decide the opposite of what it was set for. When
1606
1310
  // the other lanes are all present and the budget is still not spent, the
1607
- // held-back identity elements take it back, in rank order, whole. Not
1608
- // beside a kept first item: its count is already in, and the leftover
1609
- // composes without it.
1610
- const offered =
1611
- first !== null
1612
- ? first.composed
1613
- : trimmed.length === 0
1614
- ? offerLeftover(kept, held, c, req, resolve, coreName, identity, yesterday, elsewhere)
1615
- : c;
1616
- // THE "N MORE" LINES, last: they take only room nothing else wanted.
1617
- const told = withMoreLines(offered, {
1311
+ // held-back identity elements take it back, in rank order, whole — each
1312
+ // with the identity count of what is still held, so the count's room
1313
+ // stays reserved. Not beside a rescue: its counts are already in.
1314
+ if (fits && first === null && trimmed.length === 0) {
1315
+ while (held.length > 0) {
1316
+ const next = held[0];
1317
+ if (next === undefined) break;
1318
+ kept.identity.push(next);
1319
+ const l = linesFor(withoutNearby(lostByLane(lanes.overflow, trimmed, held.slice(1), suppressList)), kept, fold);
1320
+ if (compose(kept, req.day, resolve, coreName, identity, l.more, said, away, l.fold).bytes > req.budgetBytes) {
1321
+ kept.identity.pop();
1322
+ break;
1323
+ }
1324
+ held.shift();
1325
+ }
1326
+ }
1327
+ // THE LANES' LINES, last and checked: each lane that lost something is
1328
+ // counted, in its own line or the folded one (`tellLost`).
1329
+ const told = tellLost({
1618
1330
  kept,
1619
1331
  lost: lostByLane(lanes.overflow, trimmed, held, suppressList),
1620
1332
  req,
@@ -1623,15 +1335,16 @@ export function render(
1623
1335
  identity,
1624
1336
  ...(said === undefined ? {} : { yesterday: said }),
1625
1337
  ...(away === undefined ? {} : { elsewhere: away }),
1338
+ limit: budgetBytes,
1626
1339
  ...(first === null ? {} : { pinned: first.pinned }),
1627
1340
  });
1628
1341
  // AN ARRIVING ID THE COUNT COULD NOT NAME LEAVES A TRIM ROW (review of
1629
1342
  // #367, 2026-10-10). One past the lane's cap — `prospective/`'s count
1630
1343
  // (`BoundaryRequest.horizonMore`) or the lane's own — was never a line
1631
1344
  // the trim popped, so when the lane's count did not fit either it was in
1632
- // no line and no row, and doctor read the wake as green. Now it is
1633
- // recorded as a popped line is (no rank of its own: strength 0), and
1634
- // doctor's Wake line counts it.
1345
+ // no line and no row. Now it is recorded as a popped line is (no rank of
1346
+ // its own: strength 0). Since 2026-10-12 the count is reserved, so this
1347
+ // is only a floor over its budget, and `untold` says so too.
1635
1348
  if (told.more.horizon === undefined) {
1636
1349
  const recorded = new Set(trimmed.filter((e) => e.lane === "horizon").map((e) => e.id));
1637
1350
  for (const id of lanes.overflow?.horizon ?? []) {
@@ -1639,11 +1352,6 @@ export function render(
1639
1352
  }
1640
1353
  }
1641
1354
  const composed = told.composed;
1642
- // What it was composed to: the caller's budget, and what the delivery's
1643
- // rooms lent (`takeRoom`) — so a reader comparing the bundle to its
1644
- // ceiling sees one that fits, which it does: the delivery shows fewer
1645
- // work lines, and then fewer handoffs, in what is left.
1646
- const budgetBytes = req.budgetBytes + (first?.lent ?? base - req.budgetBytes);
1647
1355
  return {
1648
1356
  ...composed,
1649
1357
  budgetBytes,
@@ -1657,6 +1365,9 @@ export function render(
1657
1365
  },
1658
1366
  trimmed,
1659
1367
  more: told.more,
1368
+ folded: told.folded,
1369
+ untold: told.untold,
1370
+ quiet: told.quiet,
1660
1371
  pressure: composed.bytes >= budgetBytes * t.BUDGET_PRESSURE,
1661
1372
  overBudget: !fits,
1662
1373
  ...(away === undefined ? {} : { elsewhere: away }),
@@ -1673,567 +1384,4 @@ export function render(
1673
1384
  }
1674
1385
  trimmed.push(cut);
1675
1386
  }
1676
- }
1677
-
1678
- // ── reading a rendered bundle back ──────────────────────────────────────────
1679
-
1680
- export interface SentinelReading {
1681
- readonly present: boolean;
1682
- readonly line: string | null;
1683
- readonly statedBytes: number | null;
1684
- readonly statedElements: number | null;
1685
- readonly actualBytes: number;
1686
- /** The sentinel is the last line AND its stated total matches the real one. */
1687
- readonly intact: boolean;
1688
- }
1689
-
1690
- const SENTINEL_RE = /^<!-- counterparts:wake\/end .*elements=(\d+) bytes=(\d+) -->$/;
1691
-
1692
- /**
1693
- * The consumer's half of the guarantee: verify arrival from the last line alone.
1694
- * A bundle whose sentinel is missing was truncated in transit; one whose stated
1695
- * bytes disagree with its real bytes was edited or clipped. Both are errors, and
1696
- * neither is silence.
1697
- */
1698
- export function readSentinel(text: string): SentinelReading {
1699
- const actualBytes = byteLength(text);
1700
- const lines = text.split("\n");
1701
- const line = lines[lines.length - 1] ?? "";
1702
- const m = SENTINEL_RE.exec(line);
1703
- if (m === null) {
1704
- return {
1705
- present: false,
1706
- line: null,
1707
- statedBytes: null,
1708
- statedElements: null,
1709
- actualBytes,
1710
- intact: false,
1711
- };
1712
- }
1713
- const statedElements = Number(m[1]);
1714
- const statedBytes = Number(m[2]);
1715
- return {
1716
- present: true,
1717
- line,
1718
- statedBytes,
1719
- statedElements,
1720
- actualBytes,
1721
- intact: statedBytes === actualBytes,
1722
- };
1723
- }
1724
-
1725
-
1726
- // ── the delivery preface (composed at INJECTION, never at sleep) ─────────────
1727
-
1728
- /**
1729
- * THE ONE LINE THE BODY CANNOT WRITE FOR ITSELF.
1730
- *
1731
- * The bundle is composed at a boundary and then served, unchanged, to every
1732
- * session until the next one. On 2026-09-03 the memory system under this host
1733
- * was switched from v1 to Counterparts mid-day; the stored wake still carried a
1734
- * v1-era finding ("bansai's surprise pipeline has never fired") as a current
1735
- * fact, nothing in the body said which system was speaking or how old the
1736
- * render was, and the model repeated it as current until the owner corrected
1737
- * it. Only the HTML comment named the system, and comments are furniture.
1738
- *
1739
- * So one line, composed where and when the bundle is DELIVERED — which system,
1740
- * which lived day, today's date, how big the store is — and it says out loud
1741
- * that the body below was composed at the last boundary. Constitution 16: if
1742
- * the owner (or the waking session) cannot see it, it isn't trustworthy.
1743
- *
1744
- * It is deliberately not per-session: nothing in it varies between two sessions
1745
- * on the same day in the same store, so the delivery check the next hook makes
1746
- * (§2.3) compares a sentinel that is stable for as long as the bundle is.
1747
- */
1748
- export const WAKE_SYSTEM = "Counterparts";
1749
-
1750
- /**
1751
- * THE WHOLE WAKE'S OWN WAY BACK (2026-10-10), the preface's last sentence.
1752
- *
1753
- * Measured on Claude Code 2.1.296 (host numbers: `adapters/config.ts`
1754
- * `HOST_OUTPUT_CHARS`, `HOST_PREVIEW_CHARS`): a hook field over the host's cap
1755
- * is saved to a file, and the model is shown a "too large, saved to <path>"
1756
- * note and about the first 2,000 characters — and nothing tells it to read
1757
- * the file, which holds all of it. So the wake says so itself, where any
1758
- * preview carries it: in the preface, the line after the opening comment. It
1759
- * names the end (`counterparts:wake/end`, the sentinel every wake closes on)
1760
- * and the door (the file the host made). No other door reads a session's
1761
- * composed wake today (self INTERFACE-GAPS §13). The self page's own top line
1762
- * (`pageTopLine`) is the second layer, for a cut inside the wake.
1763
- */
1764
- export const WAKE_WHOLE_SENTENCE =
1765
- "If a note says this was too large and saved to a file, read that file: it holds all of this, down to the counterparts:wake/end line.";
1766
-
1767
- /**
1768
- * The room the composed budget leaves for the preface, in bytes. It is the
1769
- * preface's OWN cap, asserted by a test at the widest plausible day, date and
1770
- * store size — one number, not a lane cap that can drift from what it bounds.
1771
- * Structural, not tunable: the renderer must reserve exactly what delivery adds.
1772
- *
1773
- * Raised 128 → 160 on 2026-09-14 with U4's second number: the widest line is now
1774
- * 126 bytes (a six-digit day and a billion rows on both counts), and a cap two
1775
- * bytes above its own worst case is a cap that fails the first time the line
1776
- * gains a word.
1777
- *
1778
- * Raised again on 2026-10-10 by exactly the whole-wake sentence
1779
- * (`WAKE_WHOLE_SENTENCE`) and its space, which the line now ends with: 160 +
1780
- * 133 = 293. The page's room is derived through this number
1781
- * (`deliveryReserveBound`), so the sentence is paid for there too.
1782
- */
1783
- export const PREFACE_RESERVE_BYTES =
1784
- // Measured with an encoder of its own: `identity.ts#byteLength` may not be
1785
- // initialised yet when an import cycle evaluates this module first.
1786
- 160 + new TextEncoder().encode(` ${WAKE_WHOLE_SENTENCE}`).length;
1787
-
1788
- /**
1789
- * THE ROOM THE WAKE'S OWN FURNITURE TAKES AROUND THE PAGE, in bytes — the
1790
- * number `Self.build` subtracts from the caller's ceiling before it asks
1791
- * whether the page fits. Structural, not tunable, and measured rather than guessed: a test
1792
- * composes the widest plausible furniture (a six-digit day and six-digit lane
1793
- * counts in both comment lines, the stale dateline at a six-digit threshold)
1794
- * and asserts it fits under this.
1795
- *
1796
- * It exists because of the adversarial review of PR #138. The page's cap was
1797
- * clamped to the WHOLE budget, so a long page filled the budget exactly and the
1798
- * header, `FRAMING.context`, the heading, the dateline and the sentinel pushed
1799
- * the composition past it — and nothing could trim it back, because the identity
1800
- * lane is empty by then and the page is furniture the trim loop cannot pop. An
1801
- * 8,657-byte page published `overBudget: true` at host budgets of 400, 900,
1802
- * 2,000 and 6,000. That is scar §2.18's guarantee paying for a block of prose,
1803
- * and it is the same measurement that kept the still-forming line out of the
1804
- * default switch (NOTES §12a) — applied to the page this time.
1805
- *
1806
- * Widest measured furniture: 444 bytes. 512 is that plus room for a line to
1807
- * gain a word.
1808
- */
1809
- export const PAGE_FLOOR_RESERVE_BYTES = 512;
1810
-
1811
- /**
1812
- * HOW MANY OF THE DELIVERY'S RESERVES ARE HELD UNDER THE SHARE RULE
1813
- * (`handoff/#reserveBytes`), beside the preface: the handoff pointer with its
1814
- * "Last here" line, and "Work here" with the "Last said here" line beside it
1815
- * (2026-10-11, one term; `counterpart.ts#wakeReserveBytes` and
1816
- * `#workReserveBytes`). Each is at most an eighth of the ceiling and never past
1817
- * `HANDOFF_RESERVE_MAX_BYTES`. A third reserve there is a third here, or the
1818
- * page's limit below promises room the wake does not have — a test holds the
1819
- * root to `deliveryReserveBound`.
1820
- */
1821
- export const DELIVERY_SHARED_RESERVES = 2;
1822
-
1823
- /**
1824
- * THE MOST THE DELIVERY CAN HOLD BACK FROM A HOST CEILING, in bytes
1825
- * (2026-10-09): the preface's reserve and `DELIVERY_SHARED_RESERVES` terms at
1826
- * the share rule's widest. What the root subtracts on a given day is usually
1827
- * less; this is the bound the page's limit is sized under. Pure.
1828
- */
1829
- export function deliveryReserveBound(budgetBytes: number): number {
1830
- const share = Math.max(
1831
- 0,
1832
- Math.min(HANDOFF_RESERVE_MAX_BYTES, Math.floor(budgetBytes / HANDOFF_RESERVE_MIN_BUDGET_MULTIPLE)),
1833
- );
1834
- return PREFACE_RESERVE_BYTES + DELIVERY_SHARED_RESERVES * share;
1835
- }
1836
-
1837
- /**
1838
- * THE END LINE OF EACH RUNG (2026-10-10). Fixed words, so the top line's
1839
- * quote of it costs a known number of bytes and a reader can match it
1840
- * exactly. Printed after the page's dateline. The one-line rung has none: it
1841
- * is its own top line.
1842
- */
1843
- export const PAGE_END_LINES: Readonly<Record<Exclude<PageRung, "line">, string>> = {
1844
- whole: "(End of my page.)",
1845
- short: "(End of the short version.)",
1846
- outline: "(End of the outline.)",
1847
- headings: "(End of the headings.)",
1848
- };
1849
-
1850
- /** The end line a rung prints, or null for the one-line rung. */
1851
- export function pageEndLine(rung: PageRung): string | null {
1852
- return rung === "line" ? null : PAGE_END_LINES[rung];
1853
- }
1854
-
1855
- /** Both doors to the whole page, in the words every rung uses. */
1856
- const PAGE_DOORS = "the self_page tool or 'counterparts self-page'";
1857
-
1858
- /**
1859
- * THE TOP LINE OF EACH RUNG (2026-10-10): what follows, the page's size, the
1860
- * exact line it ends with, and — if that line is missing — that it was cut
1861
- * on the way, and both doors to the whole page. It is what protects against
1862
- * the cuts this package does not make: a host's preview keeps the head of
1863
- * what it was handed, so the top line survives the cut it describes.
1864
- * `wholeBytes` is the page's own size, whatever the rung shows. Plain words,
1865
- * for whoever reads the wake. Null on the one-line rung.
1866
- */
1867
- export function pageTopLine(rung: PageRung, wholeBytes: number): string | null {
1868
- const n = groupDigits(wholeBytes);
1869
- const end = pageEndLine(rung);
1870
- if (end === null) return null;
1871
- const ends = `It ends with "${end}" — if you don't see that line, it was cut off`;
1872
- switch (rung) {
1873
- case "whole":
1874
- return `(My page, ${n} bytes. ${ends}: read it whole with ${PAGE_DOORS}.)`;
1875
- case "short":
1876
- return `(The short version of my ${n}-byte page, too long for this wake. ${ends}. Read the whole page with ${PAGE_DOORS}.)`;
1877
- case "outline":
1878
- return `(My page is ${n} bytes, too long for this wake: here is each section's heading and first sentence. ${ends}. Read the whole page with ${PAGE_DOORS}.)`;
1879
- case "headings":
1880
- return `(My page is ${n} bytes, too long for this wake: here are its section headings. ${ends}. Read the whole page with ${PAGE_DOORS}.)`;
1881
- case "line":
1882
- return null;
1883
- }
1884
- }
1885
-
1886
- /** Each rung's top line (and the last rung's one line), as a reader finds it again. */
1887
- const PAGE_TOP_READERS: readonly (readonly [PageRung, RegExp])[] = [
1888
- ["whole", /^\(My page, ([\d,]+) bytes\. It ends with "/],
1889
- ["short", /^\(The short version of my ([\d,]+)-byte page, too long for this wake\./],
1890
- ["outline", /^\(My page is ([\d,]+) bytes, too long for this wake: here is each section's heading and first sentence\./],
1891
- ["headings", /^\(My page is ([\d,]+) bytes, too long for this wake: here are its section headings\./],
1892
- ["line", /^\(My page is (\d+) bytes — no room for it (?:whole )?in this wake\./],
1893
- ];
1894
-
1895
- /**
1896
- * WHICH RUNG A WAKE PRINTED THE PAGE ON, read back off its own words
1897
- * (2026-10-10) — for a reader of a published bundle that has no render row
1898
- * (the dashboard's wake costs). The first top line found, and the page's
1899
- * size it states; null when the wake carries none (no page, or a bundle
1900
- * published before the ladder). Kept beside `pageTopLine` so the wording and
1901
- * its reader change together; a test round-trips every rung. Pure.
1902
- */
1903
- export function readPageTopLine(text: string): { rung: PageRung; wholeBytes: number } | null {
1904
- for (const line of text.split("\n")) {
1905
- for (const [rung, re] of PAGE_TOP_READERS) {
1906
- const m = re.exec(line);
1907
- if (m !== null) return { rung, wholeBytes: Number((m[1] ?? "0").replace(/,/g, "")) };
1908
- }
1909
- }
1910
- return null;
1911
- }
1912
-
1913
- /**
1914
- * A LINE OF THE WAKE'S OWN FRAME AROUND THE PAGE (review of #363): a rung's
1915
- * top line or end line, or the one line, standing whole on a line of its own.
1916
- * A session that copies its page out of the wake and back through a writer
1917
- * would otherwise store them, and every wake after would print a stale size
1918
- * and an end line in the middle of the page — after which a cut would look
1919
- * whole. Left out where the page is written and where it is rendered, like
1920
- * its datelines (`Self#ownWords`). A sentence that only mentions one is not
1921
- * one. Pure.
1922
- */
1923
- export function isPageFrameLine(line: string): boolean {
1924
- const t = line.trim();
1925
- if (!t.startsWith("(") || !t.endsWith(")")) return false;
1926
- if ((Object.values(PAGE_END_LINES) as readonly string[]).includes(t)) return true;
1927
- return PAGE_TOP_READERS.some(([, re]) => re.test(t));
1928
- }
1929
-
1930
- /**
1931
- * THE ROOM A PAGE BLOCK TAKES in "Who I am", in bytes: its top line, its text
1932
- * and its end line, with the newlines that join them. The dateline is not
1933
- * counted here — it is furniture, inside `PAGE_FLOOR_RESERVE_BYTES`. Pure.
1934
- */
1935
- export function pageBlockBytes(block: Pick<PageBlock, "top" | "text" | "end">): number {
1936
- return (
1937
- byteLength(block.text) +
1938
- (block.top === null ? 0 : byteLength(block.top) + 1) +
1939
- (block.end === null ? 0 : byteLength(block.end) + 1)
1940
- );
1941
- }
1942
-
1943
- /**
1944
- * THE MOST THE TOP AND END LINES TAKE beside the page itself, in bytes
1945
- * (2026-10-10) — on the two rungs a writer writes for, `whole` and `short`,
1946
- * at a size wider than the write ceiling lets the top line state (999,999
1947
- * bytes against 16,384). Structural, not tunable, and measured: the widest is
1948
- * the short version's, 261, and a test holds both under this. It is paid for
1949
- * in the page's room (`pageRoomBytes`), so the room the writer is told is the
1950
- * room the page itself has, top and end lines already counted. (The two
1951
- * mechanical rungs' frames are wider — no writer aims at them, and the wake
1952
- * measures every rung exactly.)
1953
- */
1954
- export const PAGE_FRAME_RESERVE_BYTES = 264;
1955
-
1956
- /**
1957
- * THE PAGE THE WAKE PRINTS WHOLE at a host ceiling, whatever the delivery
1958
- * reserves that day, in bytes (2026-10-09): the ceiling, less the most the
1959
- * delivery can hold back (`deliveryReserveBound`), less the furniture the wake
1960
- * wraps the page in (`PAGE_FLOOR_RESERVE_BYTES`), less its top and end lines
1961
- * (`PAGE_FRAME_RESERVE_BYTES`, 2026-10-10). `Self#pageBlock` prints a page
1962
- * whole whenever it fits the room the composition actually has, which is
1963
- * never less than this. A short version within it prints whole the same way.
1964
- * Grows with the ceiling. Pure.
1965
- */
1966
- export function pageRoomBytes(hostBudgetBytes: number): number {
1967
- return hostBudgetBytes - deliveryReserveBound(hostBudgetBytes) - PAGE_FLOOR_RESERVE_BYTES - PAGE_FRAME_RESERVE_BYTES;
1968
- }
1969
-
1970
- /**
1971
- * THE HOST CEILING THE PAGE'S LIMIT IS SIZED AGAINST, in bytes — the one
1972
- * `install` writes when nobody names one (`adapters/cli/commands.ts`'s
1973
- * `DEFAULT_BUDGET_BYTES` is this constant), and the one every host reads
1974
- * today: Claude Code's hooks and Claude Desktop's `wake` tool deliver the same
1975
- * bundle, composed at the configuration's `injectionBudgetBytes`.
1976
- *
1977
- * NOT a ceiling anything composes against: scar §2.18 holds, and a host that
1978
- * reported none still composes no wake. It sizes one write limit, below.
1979
- */
1980
- export const PAGE_HOST_BUDGET_BYTES = 9_000;
1981
-
1982
- /**
1983
- * THE SELF PAGE'S ROOM, in bytes (2026-10-09; a target, not a limit, since
1984
- * 2026-10-10): `pageRoomBytes` at `PAGE_HOST_BUDGET_BYTES`. One number for
1985
- * both ends, derived rather than chosen, so what the writer is told and what
1986
- * the wake guarantees cannot drift apart: a page within it prints whole, byte
1987
- * for byte, top and end lines included, at that ceiling or a larger one,
1988
- * under the widest reserves the delivery can take.
1989
- *
1990
- * The writer is told it as a TARGET ("aim under N bytes"), and a page past it
1991
- * is kept whole — refused only past the write ceiling (`PAGE_MAX_BYTES`,
1992
- * 16,384). Past the room the wake steps down the ladder (`PageRung`) on a day
1993
- * it cannot hold the page, so the writer is asked for a short version within
1994
- * this same number, written with the page.
1995
- *
1996
- * Why one number: #350's second reviewer measured the old pair apart — the
1997
- * wake's cap was `min(6,144, budget − 512)`, which under the widest reserves at
1998
- * 9,000 is 6,078, while the writer accepted up to 16,384 — so a page between
1999
- * them was cut. #358 then refused every page past the room, and the page's
2000
- * history showed the stopgap losing by a few hundred bytes each time (7,012,
2001
- * 6,767, then 6,085, each trimmed by hand).
2002
- */
2003
- export const PAGE_ROOM_BYTES = pageRoomBytes(PAGE_HOST_BUDGET_BYTES);
2004
-
2005
- /**
2006
- * THE LAST RUNG (2026-10-09): the one short line a wake with no room for any
2007
- * other prints instead of the page — never a fragment of it. It names the
2008
- * page's size and both doors, so it is its own top line.
2009
- */
2010
- export function pageTooLargeLine(bytes: number): string {
2011
- return `(My page is ${bytes} bytes — no room for it whole in this wake. Read it with the self_page tool, or 'counterparts self-page'.)`;
2012
- }
2013
-
2014
- export interface PrefaceFacts {
2015
- /** Which memory system composed and is delivering this. */
2016
- readonly system: string;
2017
- /** The lived day (scar E8) — days lived, never calendar days. */
2018
- readonly day: number;
2019
- /** Today's calendar date as the HOST reports it. Absent ⇒ no date is stated. */
2020
- readonly date?: string;
2021
- /** Live memories in the store AT DELIVERY, not at the render:
2022
- * `countMemories({ type: "memory", archived: false })`. */
2023
- readonly memories: number;
2024
- /**
2025
- * TRUE when the body was ASSEMBLED at session start (2026-10-10,
2026
- * `Self#assemble`) rather than read as the last boundary composed it: the
2027
- * line then says so — fewer bytes than the words it replaces, so the
2028
- * reserve holds.
2029
- */
2030
- readonly assembled?: boolean;
2031
- /**
2032
- * EVERY live row at delivery — memories, journal episodes, beliefs and
2033
- * entities: `countMemories({ archived: false })` (IMPROVEMENTS U4).
2034
- *
2035
- * The header said "14,002 memories" while recall said "considered 41 of 14,701
2036
- * live rows" in the same session, and nothing on either surface said why the
2037
- * two differed by ~700. Both numbers were right and neither was labelled: the
2038
- * header counts `type: "memory"` rows, recall's `storeSize` is
2039
- * `list({ archived: false }).length`, the same WHERE minus the type clause, so
2040
- * the gap is exactly the live episodes and schema rows (superseded rows are
2041
- * `archived = 1` and are outside both). Stating both, in recall's own words —
2042
- * "live rows" — is what makes the model's two readings one vocabulary.
2043
- *
2044
- * Required, not optional: a line that sometimes carries the second number and
2045
- * sometimes does not is a line whose absence a reader has to interpret.
2046
- */
2047
- readonly liveRows: number;
2048
- }
2049
-
2050
- /** Thousands, hand-rolled: `toLocaleString` varies with the runtime's ICU. */
2051
- export function groupDigits(n: number): string {
2052
- const s = String(Math.trunc(Math.abs(n)));
2053
- let out = "";
2054
- for (let i = 0; i < s.length; i++) {
2055
- if (i > 0 && (s.length - i) % 3 === 0) out += ",";
2056
- out += s[i];
2057
- }
2058
- return n < 0 ? `-${out}` : out;
2059
- }
2060
-
2061
- /** One line, under `PREFACE_RESERVE_BYTES`, stating what the body cannot — and
2062
- * saying WHICH population each of its two counts is (U4) — then how to read
2063
- * all of it when a host cut it (`WAKE_WHOLE_SENTENCE`, 2026-10-10). */
2064
- export function prefaceLine(f: PrefaceFacts): string {
2065
- const when = f.date === undefined ? `day ${f.day}` : `day ${f.day} (${f.date})`;
2066
- return (
2067
- `${f.system} memory, ${when}, ${groupDigits(f.memories)} memories of ` +
2068
- `${groupDigits(f.liveRows)} live rows — ${f.assembled === true ? "assembled at session start" : "composed at the last boundary"}. ${WAKE_WHOLE_SENTENCE}`
2069
- );
2070
- }
2071
-
2072
- /**
2073
- * THE TENSE ONLY THE DELIVERY KNOWS (2026-10-09).
2074
- *
2075
- * The owner's wake on 10-09 carried "Arriving: - … (due 2026-10-08) · …". By
2076
- * design: a one-off stays in the horizon lane for its grace days, and the wake
2077
- * is composed at a boundary — the evening one, the day before — and read the
2078
- * next morning. The DATE was true; the lane's heading made it read as still to
2079
- * come. A render can put a date it is already past into the past tense
2080
- * (`Resolved.duePast`), but on the evening of the 8th the 8th is today, and only
2081
- * the delivery knows the morning is the 9th.
2082
- *
2083
- * So, where the preface is composed and with the same date (`WakeDelivery
2084
- * .date`, the person's day): an Arriving line whose due date is before today
2085
- * reads `(was due 2026-10-05)`, and `(was due yesterday, 2026-10-08)` the day
2086
- * after. Only the date prefix of a `- ` line in the Arriving lane is touched —
2087
- * never a statement, never another lane — and only as far as `room` allows:
2088
- * "was " on every such line first, then "yesterday, " while room remains, so a
2089
- * line that would not fit keeps the date it was composed with, which is still
2090
- * true. The caller passes what the preface reserve has left
2091
- * (`PREFACE_RESERVE_BYTES`), so the delivered bundle stays inside it.
2092
- */
2093
- export function arrivingTense(text: string, today: string, room: number): string {
2094
- if (!isDay(today) || room <= 0) return text;
2095
- const lines = text.split("\n");
2096
- // The LAST such heading: the lane is last, and a page above it is printed as
2097
- // written, so a line of the page that happens to read "Arriving:" is not it.
2098
- const start = lines.lastIndexOf(FRAMING.horizon);
2099
- if (start < 0) return text;
2100
- const prior = addDays(today, -1);
2101
- const shape = /^(- (?:(?:by )?\d{4}-\d{2}-\d{2} \()?)(was )?due (\d{4}-\d{2}-\d{2})(?=[,)]| · )/;
2102
- const was = `${DUE_PAST_WORD} `;
2103
- const words = { was: byteLength(was) - byteLength(`${DUE_WORD} `), yesterday: byteLength("yesterday, ") };
2104
- const past: { i: number; head: string; already: boolean; date: string; rest: string; was: boolean; yesterday: boolean }[] = [];
2105
- for (let i = start + 1; i < lines.length && lines[i] !== ""; i++) {
2106
- const line = lines[i] ?? "";
2107
- const m = shape.exec(line);
2108
- const date = m?.[3];
2109
- if (m === null || date === undefined || date >= today) continue;
2110
- const already = m[2] !== undefined;
2111
- past.push({ i, head: m[1] ?? "- ", already, date, rest: line.slice(m[0].length), was: already, yesterday: false });
2112
- }
2113
- let left = room;
2114
- for (const p of past) {
2115
- if (p.was || left < words.was) continue;
2116
- p.was = true;
2117
- left -= words.was;
2118
- }
2119
- for (const p of past) {
2120
- if (!p.was || p.date !== prior || left < words.yesterday) continue;
2121
- p.yesterday = true;
2122
- left -= words.yesterday;
2123
- }
2124
- for (const p of past) {
2125
- if (!p.was || (p.already && !p.yesterday)) continue;
2126
- lines[p.i] = `${p.head}${was}${p.yesterday ? "yesterday, " : ""}${p.date}${p.rest}`;
2127
- }
2128
- return lines.join("\n");
2129
- }
2130
-
2131
- export interface PrefacedBundle {
2132
- readonly text: string;
2133
- readonly bytes: number;
2134
- /** The sentinel of the DELIVERED text — what the next hook must see. */
2135
- readonly sentinel: string | null;
2136
- /** False when the bundle was not a well-formed render and was left alone. */
2137
- readonly applied: boolean;
2138
- }
2139
-
2140
- const BYTES_FIELD = /bytes=\d+/;
2141
- const OPEN_RE = /^<!-- counterparts:wake .*elements=(\d+) bytes=(\d+) -->$/;
2142
-
2143
- /**
2144
- * Splice the preface INSIDE the wake block, above the composed body, and re-solve
2145
- * the byte fixed point so the opening comment and the tail sentinel both state
2146
- * the delivered total. The alternative — adding bytes and leaving the two lines
2147
- * describing something smaller — would hand every reader a sentinel that fails
2148
- * the check it exists to pass (§1 G2).
2149
- *
2150
- * A bundle that is not a well-formed render (bootstrap line, clipped, edited) is
2151
- * returned UNTOUCHED: rewriting the byte count of a damaged bundle would erase
2152
- * the damage, which is the one thing the sentinel is for.
2153
- */
2154
- export function applyPreface(text: string, preface: string): PrefacedBundle {
2155
- const lines = text.split("\n");
2156
- const open = lines[0] ?? "";
2157
- const tail = lines[lines.length - 1] ?? "";
2158
- if (lines.length < 2 || !OPEN_RE.test(open) || !SENTINEL_RE.test(tail)) {
2159
- return {
2160
- text,
2161
- bytes: byteLength(text),
2162
- sentinel: SENTINEL_RE.test(tail) ? tail : null,
2163
- applied: false,
2164
- };
2165
- }
2166
- const build = (stated: string): string[] => [
2167
- open.replace(BYTES_FIELD, `bytes=${stated}`),
2168
- preface,
2169
- ...lines.slice(1, -1),
2170
- tail.replace(BYTES_FIELD, `bytes=${stated}`),
2171
- ];
2172
- const skeleton = byteLength(build("").join("\n"));
2173
- const composed = build(String(fixedPointTotal(skeleton, 2)));
2174
- const out = composed.join("\n");
2175
- return {
2176
- text: out,
2177
- bytes: byteLength(out),
2178
- sentinel: composed[composed.length - 1] ?? null,
2179
- applied: true,
2180
- };
2181
- }
2182
-
2183
- /**
2184
- * Splice a block in at the FOOT of the wake block, above the tail sentinel, and
2185
- * re-solve the byte fixed point so both comment lines state the delivered total
2186
- * — `applyPreface`'s mechanism, pointed at the other end of the bundle.
2187
- *
2188
- * It exists for the per-directory handoff pointer (E1), which is a delivery-time
2189
- * fact for exactly the reason the preface is: ONE bundle is published per store
2190
- * at a boundary and read by sessions in every directory, so which directory this
2191
- * session opened in cannot be known when the body is composed. The pointer is
2192
- * FURNITURE — no `- ` bullet, no lane — so `counts` and the sentinel's
2193
- * `elements=` stay true of a bundle that carries it, exactly as they stay true
2194
- * of one carrying the page or the day-0 line.
2195
- *
2196
- * At the foot rather than the head because a handoff is the last thing that
2197
- * happened here and the first thing to pick up, and because the preface's own
2198
- * place above the body is a claim about the WHOLE bundle that a second line
2199
- * there would blunt.
2200
- *
2201
- * A bundle that is not a well-formed render is returned UNTOUCHED, for
2202
- * `applyPreface`'s reason: rewriting the byte count of a damaged bundle erases
2203
- * the damage the sentinel exists to show.
2204
- */
2205
- export function spliceBeforeSentinel(text: string, block: string): PrefacedBundle {
2206
- const lines = text.split("\n");
2207
- const open = lines[0] ?? "";
2208
- const tail = lines[lines.length - 1] ?? "";
2209
- if (lines.length < 2 || !OPEN_RE.test(open) || !SENTINEL_RE.test(tail) || block.length === 0) {
2210
- return {
2211
- text,
2212
- bytes: byteLength(text),
2213
- sentinel: SENTINEL_RE.test(tail) ? tail : null,
2214
- applied: false,
2215
- };
2216
- }
2217
- const body = lines.slice(1, -1);
2218
- // `compose` already pushes a blank line before the sentinel, so the separator
2219
- // is added only when this bundle does not have one — a doubled blank line is
2220
- // not wrong, but it costs bytes the reserve measured for one.
2221
- const gap = body[body.length - 1] === "" ? [] : [""];
2222
- const build = (stated: string): string[] => [
2223
- open.replace(BYTES_FIELD, `bytes=${stated}`),
2224
- ...body,
2225
- ...gap,
2226
- block,
2227
- "",
2228
- tail.replace(BYTES_FIELD, `bytes=${stated}`),
2229
- ];
2230
- const skeleton = byteLength(build("").join("\n"));
2231
- const composed = build(String(fixedPointTotal(skeleton, 2)));
2232
- const out = composed.join("\n");
2233
- return {
2234
- text: out,
2235
- bytes: byteLength(out),
2236
- sentinel: composed[composed.length - 1] ?? null,
2237
- applied: true,
2238
- };
2239
- }
1387
+ }