counterparts 0.1.0

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 (195) hide show
  1. package/CONSTITUTION.md +68 -0
  2. package/LICENSE +21 -0
  3. package/README.md +348 -0
  4. package/docs/ELI5.md +84 -0
  5. package/docs/QUICKSTART.md +1258 -0
  6. package/docs/module-map.md +81 -0
  7. package/package.json +63 -0
  8. package/src/adapters/claude-code/CONTRACT.md +606 -0
  9. package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
  10. package/src/adapters/claude-code/NOTES.md +1055 -0
  11. package/src/adapters/claude-code/bin/hook.ts +820 -0
  12. package/src/adapters/claude-code/bin/runner.ts +522 -0
  13. package/src/adapters/claude-code/config.ts +778 -0
  14. package/src/adapters/claude-code/credentials.ts +199 -0
  15. package/src/adapters/claude-code/doctor.ts +2557 -0
  16. package/src/adapters/claude-code/embed-client.ts +617 -0
  17. package/src/adapters/claude-code/hooks.ts +2240 -0
  18. package/src/adapters/claude-code/index.ts +224 -0
  19. package/src/adapters/claude-code/interpret-client.ts +395 -0
  20. package/src/adapters/claude-code/page-writer.ts +462 -0
  21. package/src/adapters/claude-code/primacy.ts +162 -0
  22. package/src/adapters/claude-code/spawn.ts +241 -0
  23. package/src/adapters/claude-code/standdown.ts +536 -0
  24. package/src/adapters/claude-code/transcript.ts +661 -0
  25. package/src/adapters/claude-code/vectors.ts +415 -0
  26. package/src/adapters/cli/CONTRACT.md +255 -0
  27. package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
  28. package/src/adapters/cli/NOTES.md +936 -0
  29. package/src/adapters/cli/bin/counterparts.ts +74 -0
  30. package/src/adapters/cli/commands.ts +6095 -0
  31. package/src/adapters/cli/export.ts +766 -0
  32. package/src/adapters/cli/index.ts +103 -0
  33. package/src/adapters/cli/install.ts +670 -0
  34. package/src/adapters/cli/removal.ts +1186 -0
  35. package/src/adapters/cli/repair-dates.ts +659 -0
  36. package/src/adapters/cli/self-page.ts +229 -0
  37. package/src/adapters/cli/snapshot.ts +279 -0
  38. package/src/adapters/cli/start-fresh.ts +1228 -0
  39. package/src/adapters/config-path.ts +342 -0
  40. package/src/adapters/dashboard/CONTRACT.md +67 -0
  41. package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
  42. package/src/adapters/dashboard/NOTES.md +474 -0
  43. package/src/adapters/dashboard/activity.ts +121 -0
  44. package/src/adapters/dashboard/ansi.ts +82 -0
  45. package/src/adapters/dashboard/bin/dashboard.ts +479 -0
  46. package/src/adapters/dashboard/browse.ts +298 -0
  47. package/src/adapters/dashboard/identity.ts +182 -0
  48. package/src/adapters/dashboard/index.ts +183 -0
  49. package/src/adapters/dashboard/layout.ts +149 -0
  50. package/src/adapters/dashboard/registries.ts +291 -0
  51. package/src/adapters/dashboard/resolve.ts +206 -0
  52. package/src/adapters/dashboard/source.ts +48 -0
  53. package/src/adapters/dashboard/status.ts +327 -0
  54. package/src/adapters/dashboard/stories.ts +194 -0
  55. package/src/adapters/dashboard/web/app.html +1731 -0
  56. package/src/adapters/dashboard/web/brain.html +463 -0
  57. package/src/adapters/dashboard/web/fired.ts +31 -0
  58. package/src/adapters/dashboard/web/flow.ts +457 -0
  59. package/src/adapters/dashboard/web/narrate.ts +1042 -0
  60. package/src/adapters/dashboard/web/reveal.ts +135 -0
  61. package/src/adapters/dashboard/web/server.ts +287 -0
  62. package/src/adapters/dashboard/web/views.ts +1744 -0
  63. package/src/adapters/expansions.ts +569 -0
  64. package/src/adapters/fired.ts +1580 -0
  65. package/src/adapters/mcp/CONTRACT.md +240 -0
  66. package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
  67. package/src/adapters/mcp/NOTES.md +205 -0
  68. package/src/adapters/mcp/bin/serve.ts +349 -0
  69. package/src/adapters/mcp/deliberate.ts +619 -0
  70. package/src/adapters/mcp/index.ts +101 -0
  71. package/src/adapters/mcp/protocol.ts +170 -0
  72. package/src/adapters/mcp/server.ts +1740 -0
  73. package/src/adapters/mcp/stdio.ts +56 -0
  74. package/src/adapters/mcp/tools.ts +779 -0
  75. package/src/adapters/scopes.ts +657 -0
  76. package/src/adapters/sessions.ts +402 -0
  77. package/src/adapters/snapshots.ts +1069 -0
  78. package/src/adapters/stance-env.ts +137 -0
  79. package/src/core/associate/CONTRACT.md +118 -0
  80. package/src/core/associate/INTERFACE-GAPS.md +173 -0
  81. package/src/core/associate/NOTES.md +194 -0
  82. package/src/core/associate/buffer.ts +66 -0
  83. package/src/core/associate/edges.ts +188 -0
  84. package/src/core/associate/index.ts +570 -0
  85. package/src/core/associate/pending.ts +383 -0
  86. package/src/core/associate/spread.ts +149 -0
  87. package/src/core/associate/tunables.ts +123 -0
  88. package/src/core/bridge.ts +272 -0
  89. package/src/core/briefing.ts +67 -0
  90. package/src/core/counterpart.ts +3855 -0
  91. package/src/core/encode/CONTRACT.md +151 -0
  92. package/src/core/encode/INTERFACE-GAPS.md +135 -0
  93. package/src/core/encode/NOTES.md +146 -0
  94. package/src/core/encode/aliases.ts +71 -0
  95. package/src/core/encode/battery.ts +284 -0
  96. package/src/core/encode/chunk.ts +265 -0
  97. package/src/core/encode/emotion.ts +119 -0
  98. package/src/core/encode/floor.ts +76 -0
  99. package/src/core/encode/index.ts +100 -0
  100. package/src/core/encode/precision.ts +162 -0
  101. package/src/core/encode/preselect.ts +269 -0
  102. package/src/core/encode/salience.ts +108 -0
  103. package/src/core/encode/secrets.ts +265 -0
  104. package/src/core/encode/tunables.ts +99 -0
  105. package/src/core/encode/types.ts +286 -0
  106. package/src/core/encode/words.ts +75 -0
  107. package/src/core/handoff/CONTRACT.md +199 -0
  108. package/src/core/handoff/INTERFACE-GAPS.md +166 -0
  109. package/src/core/handoff/NOTES.md +206 -0
  110. package/src/core/handoff/index.ts +957 -0
  111. package/src/core/mint.ts +279 -0
  112. package/src/core/observer.ts +28 -0
  113. package/src/core/physics/CONTRACT.md +341 -0
  114. package/src/core/physics/NOTES.md +155 -0
  115. package/src/core/physics/clock.ts +51 -0
  116. package/src/core/physics/index.ts +1054 -0
  117. package/src/core/prospective/CONTRACT.md +137 -0
  118. package/src/core/prospective/INTERFACE-GAPS.md +112 -0
  119. package/src/core/prospective/NOTES.md +160 -0
  120. package/src/core/prospective/derive.ts +188 -0
  121. package/src/core/prospective/index.ts +1030 -0
  122. package/src/core/prospective/tunables.ts +72 -0
  123. package/src/core/prospective/windows.ts +187 -0
  124. package/src/core/recall/CONTRACT.md +326 -0
  125. package/src/core/recall/INTERFACE-GAPS.md +163 -0
  126. package/src/core/recall/NOTES.md +472 -0
  127. package/src/core/recall/activate.ts +521 -0
  128. package/src/core/recall/cues.ts +275 -0
  129. package/src/core/recall/gate.ts +441 -0
  130. package/src/core/recall/index.ts +692 -0
  131. package/src/core/recall/probe.ts +239 -0
  132. package/src/core/recall/reference.ts +201 -0
  133. package/src/core/recall/render.ts +285 -0
  134. package/src/core/recall/session.ts +403 -0
  135. package/src/core/recall/tunables.ts +329 -0
  136. package/src/core/remember/CONTRACT.md +293 -0
  137. package/src/core/remember/INTERFACE-GAPS.md +189 -0
  138. package/src/core/remember/NOTES.md +373 -0
  139. package/src/core/remember/fallback.ts +452 -0
  140. package/src/core/remember/index.ts +103 -0
  141. package/src/core/remember/owner-strike-seam.ts +479 -0
  142. package/src/core/remember/proposals.ts +609 -0
  143. package/src/core/remember/spans.ts +1310 -0
  144. package/src/core/remember/tunables.ts +111 -0
  145. package/src/core/remember/updates.ts +198 -0
  146. package/src/core/retrieval.ts +96 -0
  147. package/src/core/revision.ts +441 -0
  148. package/src/core/schemas/CONTRACT.md +190 -0
  149. package/src/core/schemas/INTERFACE-GAPS.md +172 -0
  150. package/src/core/schemas/NOTES.md +260 -0
  151. package/src/core/schemas/aliases.ts +160 -0
  152. package/src/core/schemas/index.ts +1459 -0
  153. package/src/core/schemas/tunables.ts +44 -0
  154. package/src/core/schemas/types.ts +387 -0
  155. package/src/core/self/CONTRACT.md +459 -0
  156. package/src/core/self/INTERFACE-GAPS.md +284 -0
  157. package/src/core/self/NOTES.md +1057 -0
  158. package/src/core/self/briefing.ts +980 -0
  159. package/src/core/self/episodes.ts +483 -0
  160. package/src/core/self/freeze.ts +103 -0
  161. package/src/core/self/identity.ts +604 -0
  162. package/src/core/self/index.ts +2130 -0
  163. package/src/core/self/journal-file.ts +760 -0
  164. package/src/core/self/page.ts +404 -0
  165. package/src/core/self/tunables.ts +244 -0
  166. package/src/core/self/writer.ts +714 -0
  167. package/src/core/sleep/CONTRACT.md +298 -0
  168. package/src/core/sleep/INTERFACE-GAPS.md +262 -0
  169. package/src/core/sleep/NOTES.md +770 -0
  170. package/src/core/sleep/briefing.ts +86 -0
  171. package/src/core/sleep/consolidate.ts +241 -0
  172. package/src/core/sleep/cycle.ts +598 -0
  173. package/src/core/sleep/decay.ts +237 -0
  174. package/src/core/sleep/dedup.ts +373 -0
  175. package/src/core/sleep/index.ts +112 -0
  176. package/src/core/sleep/log.ts +116 -0
  177. package/src/core/sleep/markers.ts +164 -0
  178. package/src/core/sleep/prune.ts +170 -0
  179. package/src/core/sleep/strength-cache.ts +176 -0
  180. package/src/core/sleep/tunables.ts +135 -0
  181. package/src/core/sleep/types.ts +542 -0
  182. package/src/core/store/CONTRACT.md +446 -0
  183. package/src/core/store/NOTES.md +1068 -0
  184. package/src/core/store/cache.ts +709 -0
  185. package/src/core/store/db.ts +275 -0
  186. package/src/core/store/errors.ts +134 -0
  187. package/src/core/store/index.ts +2450 -0
  188. package/src/core/store/operational.ts +610 -0
  189. package/src/core/store/owner-op-seam.ts +428 -0
  190. package/src/core/store/paths.ts +494 -0
  191. package/src/core/store/prose.ts +165 -0
  192. package/src/core/store/render.ts +87 -0
  193. package/src/core/store/walk-seam.ts +78 -0
  194. package/src/core/types.ts +68 -0
  195. package/tools/install-loop/run.sh +1063 -0
@@ -0,0 +1,980 @@
1
+ /**
2
+ * THE WAKE BRIEFING — composed here, with no model in the room.
3
+ *
4
+ * Rulings (module-map, 2026-08-25): *the wake briefing renders WITHOUT a model at
5
+ * launch.* v0's briefing was in fact model-compressed, so the precedent cuts the
6
+ * other way and Amendment 15 decides instead — the simplest brain-faithful rule
7
+ * that could work is rank-and-take, and machinery is earned only after it fails.
8
+ * There is no client, no fetch, no URL and no prompt in this file, and the test
9
+ * suite enumerates that.
10
+ *
11
+ * What the composition guarantees, and why each one exists:
12
+ *
13
+ * - **The budget governs the composed total**, not any lane. v1 byte-capped its
14
+ * index lane at 8,192 and left the bundle unbounded; every session for eleven
15
+ * days received about 3 of 16 elements and nothing said so (scar §2.3).
16
+ * - **The budget is the CALLER'S.** It arrives on the request because the
17
+ * injection ceiling is a host capability, not a memory property (scar §2.18).
18
+ * There is no default in this module to fall back to.
19
+ * - **The trim order is declared and tested** (`TRIM_ORDER`), and trimming eats
20
+ * from the END of a lane, whose ordering is itself policy: *truncation must
21
+ * never be iteration luck* (§1 G3–G4).
22
+ * - **The identity SHARE decides how the total is split when lanes compete.**
23
+ * The budget still governs the composed total (§5 G2); the share is not a
24
+ * lane budget but a rule about who wins the contested bytes, and it exists
25
+ * because trimming identity LAST means a store of long identity elements
26
+ * silently takes everything: measured 2026-09-04, the delivered wake was 8
27
+ * identity elements at ~1.1 KB each and four empty lanes. Whole elements
28
+ * only, never a truncated one; and when the other lanes cannot fill the
29
+ * remainder, identity takes the leftover back — a ceiling, not a cap.
30
+ * - **Truncation is never mid-statement.** A statement is admitted whole or not
31
+ * at all — there is no `clip()` here on purpose. A half-sentence about who
32
+ * someone is, is not a smaller identity; it is a corrupted one.
33
+ * - **The header AND the tail sentinel each state the bundle's own true counts
34
+ * and bytes**, so a truncated injection is detectable from a truncation
35
+ * preview alone — from either end (§1 G2). Because both lines state a number
36
+ * that composing them changes, composition solves for the fixed point.
37
+ * - **Ids resolve to text HERE**, at render time, through `Resolve` — never
38
+ * baked into the decision record or the telemetry, so an erased memory stops
39
+ * resolving the instant it leaves the store.
40
+ */
41
+ import type { LaneName, Ranked } from "./identity.js";
42
+ import { byteLength } from "./identity.js";
43
+ import type { SelfTunables } from "./tunables.js";
44
+
45
+ /**
46
+ * Composed order — behavioral-spec §1's, minus the two riders the Rulings drop
47
+ * with their subjects: the second-signature reminder went with the `protected.add`
48
+ * queue, and the self-store pointer went with the self-store tool (contract §4).
49
+ * What is left is furniture, then core, then work, then warmth, then what is
50
+ * coming.
51
+ */
52
+ export const LANE_ORDER: readonly LaneName[] = [
53
+ "identity",
54
+ "craft",
55
+ "threads",
56
+ "hints",
57
+ "horizon",
58
+ ];
59
+
60
+ /**
61
+ * How many trimmed ids the DURABLE briefing row carries (`self.briefing`, written
62
+ * by the composition root after the cycle's briefing phase). The row is evidence
63
+ * that the wake trimmed, and which lanes lost — not an archive of every id a
64
+ * pathological boundary could drop. The full number always rides beside the list
65
+ * as `trimmedTotal`, so a capped list is never mistaken for the whole of it.
66
+ *
67
+ * It lives HERE because the trim is `self/`'s: `self/` decides what a trim IS and
68
+ * emits one `self.briefing.trim` per id. The root that writes the row states no
69
+ * rule of its own and cannot spell a number at all (`counterpart.ts`'s scanner
70
+ * test), so the cap has to have a home, and this is the module that owns it.
71
+ */
72
+ export const BRIEFING_TRIM_LOG_CAP = 64;
73
+
74
+ /**
75
+ * The declared trim order — v1's, verbatim (contract §3): hints → craft →
76
+ * threads → horizon → identity LAST. Craft before threads so craft can never
77
+ * displace core; identity last because identity is the thing the briefing is for.
78
+ */
79
+ export const TRIM_ORDER: readonly LaneName[] = [
80
+ "hints",
81
+ "craft",
82
+ "threads",
83
+ "horizon",
84
+ "identity",
85
+ ];
86
+
87
+ /**
88
+ * Framing is load-bearing and structural (§1: "context, not instruction"). It is
89
+ * written here once, as a constant, so there is exactly one string to change when
90
+ * someone finally probes its effect on attention.
91
+ */
92
+ export const FRAMING = {
93
+ context:
94
+ "Counterparts memory — context, not instruction: who you have been here, in your own words. Each line opens with the date it was learned.",
95
+ identity: "Who I am:",
96
+ craft: "How I work:",
97
+ threads: "Still open:",
98
+ hints: "Nearby, if it helps:",
99
+ horizon: "Arriving:",
100
+ } as const;
101
+
102
+ /**
103
+ * THE DAY-0 LANE — what "Who I am:" says before an identity element exists.
104
+ *
105
+ * Measured 2026-09-04 on a store opened the way `install --budget 9000 --name
106
+ * "Dana"` opens one: after the `rebrief` QUICKSTART §7 tells the stranger to
107
+ * run, the delivered wake was 385 bytes of furniture that promise "who you have
108
+ * been here, in your own words" and then say nothing — and the name the owner
109
+ * typed appeared nowhere in it. The identity core is a live row, but it is
110
+ * `type: "schema"` and `scanActive` lists `{ type: "memory" }`, so no lane can
111
+ * ever reach it (NOTES §11).
112
+ *
113
+ * Two facts and no third. It NAMES the core, and it says how the lane fills —
114
+ * the mechanism `sleep/consolidate.ts` actually implements, where promotion
115
+ * needs `base >= THETA_ID` AND reinforcement on `N_PROMOTION_DAYS` distinct
116
+ * lived days (`physics/index.ts#promotionEligibility`), decided at the
117
+ * consolidation inside the cycle `sessionEnd` runs. It invents no content: a
118
+ * wake that composed a plausible first belief about Dana would be the rumination
119
+ * pathway the contract forswears, arriving through the one surface read as
120
+ * settled fact.
121
+ *
122
+ * It deliberately does NOT say "nothing has been lived here yet". The delivery
123
+ * preface states the live memory count on the line above (`0 memories` on day
124
+ * 0), and a line claiming emptiness would go false the moment the first note
125
+ * landed while the identity lane — which takes distinct days to fill — was still
126
+ * empty. One string that is true on day 0 and on day 30; the preface carries the
127
+ * count, this line carries the WHO.
128
+ *
129
+ * No `- ` bullet: that prefix is reserved for a resolved statement, and
130
+ * `FRAMING.context` promises every such line opens with the date it was learned,
131
+ * which this line has none of. It is furniture, so `counts.identity` stays 0 and
132
+ * the header and sentinel still read `elements=0`.
133
+ *
134
+ * **The name is FLATTENED, like every other string that reaches the bundle.**
135
+ * `flatten` is what makes "a statement is a line here" true (see its own note),
136
+ * and the name is the only user-supplied string this module renders — so it is
137
+ * held to the same rule, at the one place the line is built. Adversarial review
138
+ * of PR #71: a name carrying newlines injected lines into the delivered wake,
139
+ * including a forged `- <date> <claim>` bullet that reads as a resolved
140
+ * statement and that the dashboard's lane splitter then filed under a heading
141
+ * the store had no rows for. Not a privilege boundary — the name is the owner's
142
+ * own, and the sentinel still verified — but the "furniture, not an element"
143
+ * property is exactly what a second line defeats, and a prose file the owner is
144
+ * promised they may hand-edit (constitution 6) is a paste accident away.
145
+ */
146
+ export function identityCoreLine(name: string): string {
147
+ 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.`;
148
+ }
149
+
150
+ /**
151
+ * THE PAGE, IN "WHO I AM" — furniture, like the day-0 line, and for the same
152
+ * reason: it is not a ranked element, it carries no `- ` bullet, and `counts`
153
+ * and the sentinel's `elements=` stay true of a bundle that holds it.
154
+ *
155
+ * The page prints FIRST and AS IS. Not re-wrapped, not re-ordered, not
156
+ * summarised: a page reassembled here would be a page this module wrote, and
157
+ * what the owner and the session are promised is the thing they wrote.
158
+ * `FRAMING.context`'s "each line opens with the date it was learned" is a claim
159
+ * about the element lines — the day-0 line has carried no date since it shipped
160
+ * — and the page carries its own date on its own line instead.
161
+ */
162
+ export interface PageBlock {
163
+ /** The page as it will be injected: already cut to the cap, marker included. */
164
+ readonly text: string;
165
+ /** The page's own "last revised" line, or null when the page carries no date. */
166
+ readonly dateline: string | null;
167
+ /** True when the cap cut it — `text` already carries the marker that says so. */
168
+ readonly truncated: boolean;
169
+ /** The page's own bytes, whole, whatever was rendered. */
170
+ readonly wholeBytes: number;
171
+ }
172
+
173
+ /**
174
+ * What "Who I am" prints BESIDE the ranked elements. Both fields are decided by
175
+ * `render` from the tunables and handed down, so `compose` stays a renderer with
176
+ * no policy of its own.
177
+ */
178
+ export interface IdentityBlock {
179
+ /** The written page, when one exists. It replaces the list (spec §15 item 4). */
180
+ readonly page: PageBlock | null;
181
+ /** Printed when there is NO page and the list has been switched off. */
182
+ readonly forming: string | null;
183
+ }
184
+
185
+ /** What "Who I am" says when no page has been written and the list is off. */
186
+ export const PAGE_FORMING_LINE =
187
+ "Still forming — no page has been written here yet. It is written at a boundary, from what recurs, and can be amended by hand.";
188
+
189
+ /**
190
+ * The page's own date, under the page. It states the DATE and — when the page
191
+ * has gone stale — how long the silence was allowed to be, rather than "N days
192
+ * ago": the bundle is composed at a boundary and then served unchanged until
193
+ * the next one, so a delta computed here goes wrong while a date does not.
194
+ */
195
+ export function pageDateline(revisedOn: string, stale: boolean, staleDays: number): string | null {
196
+ const on = revisedOn.trim();
197
+ // A page with no readable date SAYS SO. Returning null printed the page with
198
+ // no date and no staleness signal at all while every other surface called it
199
+ // stale — the one state where the wake said less than it knew (adversarial
200
+ // review m6). Only reachable on a hand-minted or hand-edited row.
201
+ if (on === "" || !/^\d{4}-\d{2}-\d{2}$/.test(on) || !Number.isFinite(Date.parse(`${on}T00:00:00Z`))) {
202
+ return "(Last revised — the page carries no readable date.)";
203
+ }
204
+ return stale
205
+ ? `(Last revised ${on} — more than ${staleDays} days before this wake was composed.)`
206
+ : `(Last revised ${on}.)`;
207
+ }
208
+
209
+ /** Id → the verbatim statement AND its dates, at render time only. */
210
+ export interface Resolved {
211
+ readonly statement: string;
212
+ /**
213
+ * The encode date (`ProseDoc.learnedOn`), at whatever precision it was stated.
214
+ * Absent or blank means undated — the store writes `learned_on = ''` on a
215
+ * chased row — and an undated element renders with no prefix rather than an
216
+ * empty one.
217
+ */
218
+ readonly learnedOn?: string;
219
+ /** The content date (`ProseDoc.happenedOn`), rendered only when it DIFFERS. */
220
+ readonly happenedOn?: string;
221
+ /**
222
+ * True when the encode date is only an UPPER BOUND — the element was known BY
223
+ * then, not learned then. Set for migrated elements, whose `learned_on` is
224
+ * v1's date when v1 carried one and the IMPORT date when it did not, with
225
+ * nothing in the row to tell the two apart. See `datePrefix`.
226
+ */
227
+ readonly boundedDate?: boolean;
228
+ }
229
+
230
+ export type Resolve = (id: string) => Resolved;
231
+
232
+ export interface BriefingRequest {
233
+ /** The host's reported injection ceiling, in bytes. REQUIRED — scar §2.18. */
234
+ readonly budgetBytes: number;
235
+ /** The lived day (scar E8), stated in the header so a stale bundle is legible. */
236
+ readonly day: number;
237
+ /**
238
+ * The identity core's name, when the caller found one AND the identity lane is
239
+ * empty — the day-0 lane (`identityCoreLine`, NOTES §11). Absent means render
240
+ * nothing, which is what a store with no core has always rendered. The lookup
241
+ * is the caller's because it reads prose, and `self/` invents no name.
242
+ */
243
+ readonly coreName?: string;
244
+ /**
245
+ * THE WRITTEN SELF PAGE, already cut to its cap and dated by the caller
246
+ * (`Self.build` → `page.ts#renderPage`). Present means "Who I am" prints this
247
+ * and NOT the rotating list; absent means the list renders as it always has,
248
+ * or — when `PAGE_EMPTY_SHOWS_LIST` is off — the still-forming line does.
249
+ *
250
+ * It arrives ready because the cap is a byte decision that needs the caller's
251
+ * budget and the page's own prose, and this module composes rather than reads.
252
+ */
253
+ readonly page?: PageBlock;
254
+ /**
255
+ * TRUE when the store HAS a page, whatever this render could fit of it. A
256
+ * ceiling with no room for the wake's own furniture carries no page block at
257
+ * all, and without this the renderer could not tell that from a store that has
258
+ * never been written to — so with `PAGE_EMPTY_SHOWS_LIST` off it printed "no
259
+ * page has been written here yet" over a store holding one (adversarial review
260
+ * MINOR-D). Absent means the caller did not say, which reads as "no page".
261
+ */
262
+ readonly pageExists?: boolean;
263
+ }
264
+
265
+ export interface TrimEvent {
266
+ readonly lane: LaneName;
267
+ readonly id: string;
268
+ readonly strength: number;
269
+ }
270
+
271
+ export interface Composed {
272
+ readonly text: string;
273
+ readonly bytes: number;
274
+ readonly header: string;
275
+ readonly sentinel: string;
276
+ readonly counts: Record<LaneName, number>;
277
+ readonly elements: number;
278
+ }
279
+
280
+ export interface BriefingResult extends Composed {
281
+ readonly budgetBytes: number;
282
+ readonly day: number;
283
+ /** Ids kept, per lane, in rendered order. */
284
+ readonly kept: Record<LaneName, string[]>;
285
+ readonly trimmed: TrimEvent[];
286
+ /** True when the render crossed the pressure ratio — the tripwire that fires
287
+ * when a budget is APPROACHED, not only when it blows (scar §2.4). */
288
+ readonly pressure: boolean;
289
+ /** True when even the floor (furniture + sentinel, zero statements) does not
290
+ * fit the caller's budget. The floor still publishes: an under-floor budget is
291
+ * a host misconfiguration, and the wake never fails the session (§1 G7). */
292
+ readonly overBudget: boolean;
293
+ /** The page as it RENDERED — null when no page was handed to this render. The
294
+ * bytes are the injected ones (the marker included), so a cut page's cost and
295
+ * its true size are both readable. */
296
+ readonly page: { readonly bytes: number; readonly truncated: boolean; readonly wholeBytes: number } | null;
297
+ }
298
+
299
+
300
+ function headerLine(day: number, elements: number, bytes: string): string {
301
+ return `<!-- counterparts:wake day=${day} elements=${elements} bytes=${bytes} -->`;
302
+ }
303
+
304
+ function sentinelLine(
305
+ day: number,
306
+ counts: Record<LaneName, number>,
307
+ elements: number,
308
+ bytes: string,
309
+ ): string {
310
+ const lanes = LANE_ORDER.map((l) => `${l}=${counts[l]}`).join(" ");
311
+ return `<!-- counterparts:wake/end day=${day} ${lanes} elements=${elements} bytes=${bytes} -->`;
312
+ }
313
+
314
+ function laneHeading(lane: LaneName): string {
315
+ switch (lane) {
316
+ case "identity":
317
+ return FRAMING.identity;
318
+ case "craft":
319
+ return FRAMING.craft;
320
+ case "threads":
321
+ return FRAMING.threads;
322
+ case "hints":
323
+ return FRAMING.hints;
324
+ case "horizon":
325
+ return FRAMING.horizon;
326
+ }
327
+ }
328
+
329
+ /**
330
+ * One statement per line, VERBATIM. Whitespace is flattened (a statement is a
331
+ * line here) but never cut: what is rendered is exactly what `Resolve` returned,
332
+ * or the statement is not rendered at all.
333
+ */
334
+ export function flatten(text: string): string {
335
+ return text.replace(/\s+/g, " ").trim();
336
+ }
337
+
338
+ /**
339
+ * THE DATE, IN FRONT OF THE CLAIM.
340
+ *
341
+ * Measured 2026-09-04: the wake rendered every element with no date of any kind,
342
+ * and a migrated element learned 2026-07-26 ("the credential fix sits
343
+ * uncommitted pending review") was read as a current fact and repeated to the
344
+ * owner as one. The delivery preface dates the WAKE; nothing dated the ELEMENTS,
345
+ * and a reader with no age cannot discount one.
346
+ *
347
+ * LEADING, not trailing, for three reasons: the age is read before the claim
348
+ * rather than after it has landed; the element's own text still ENDS the line,
349
+ * so "a statement is admitted whole" stays checkable by its own final
350
+ * punctuation and nothing that follows can be mistaken for part of it; and it is
351
+ * the cheaper of the two forms — 14 bytes at day precision (`YYYY-MM-DD` plus
352
+ * ` · `), against 21 for a trailing `(learned YYYY-MM-DD)`, on every element in
353
+ * every lane. The word "learned" is stated ONCE, in `FRAMING.context`, instead
354
+ * of once per element.
355
+ *
356
+ * The element text itself is never touched: the annotation lives outside it, so
357
+ * a belief still renders verbatim for contradiction detection.
358
+ *
359
+ * A differing content date is named inline and neutrally — `(of 2026-06-01)` —
360
+ * because the horizon lane's dates are in the FUTURE (an arriving occasion), and
361
+ * "happened" would be a lie about half of them.
362
+ *
363
+ * **`by` — the upper bound, and why a MIGRATED element gets one.** Run live on
364
+ * 2026-09-05, the first dated wake read `2026-09-03 ·` on all eleven elements,
365
+ * including a July incident and a mid-August finding: the importer writes the
366
+ * IMPORT date as `learned_on` for every row v1 carried no date for, and nothing
367
+ * in the row distinguishes those from the ones that kept v1's own. A wrong date
368
+ * is worse than no date — it is a claim, made confidently, in the one line the
369
+ * reader uses to discount everything else — so a migrated element states what is
370
+ * actually known: `by 2026-09-03 ·`, three bytes for a date that is true
371
+ * whichever of the two it is.
372
+ *
373
+ * A migrated element carrying a CONTENT date is the exception and renders
374
+ * plainly, as everything else does: `happened_on` is evidence about the thing
375
+ * itself, it survived the import unaltered, and hedging real evidence would make
376
+ * `by` mean nothing. *Named cost: a migrated row that did keep v1's own date and
377
+ * has no content date is hedged too — "by 2026-07-26" instead of "2026-07-26".
378
+ * Weaker, never wrong, and the alternative needs a per-row discriminator the
379
+ * import did not record.*
380
+ */
381
+ export const DATE_SEP = " · ";
382
+ export const DATE_BOUND = "by ";
383
+
384
+ export function datePrefix(r: Resolved): string {
385
+ const learned = (r.learnedOn ?? "").trim();
386
+ if (learned === "") return "";
387
+ const happened = (r.happenedOn ?? "").trim();
388
+ if (happened !== "" && happened !== learned) return `${learned} (of ${happened})${DATE_SEP}`;
389
+ const bound = r.boundedDate === true ? DATE_BOUND : "";
390
+ return `${bound}${learned}${DATE_SEP}`;
391
+ }
392
+
393
+ /**
394
+ * ONE rendered line for one element — the single place the shape is decided, so
395
+ * the byte accounting (`elementBytes`, and through it the identity share) can
396
+ * never disagree with what `compose` actually writes.
397
+ */
398
+ export function elementLine(item: Ranked, resolve: Resolve): string {
399
+ const r = resolve(item.id);
400
+ return `- ${datePrefix(r)}${flatten(r.statement)}`;
401
+ }
402
+
403
+ type Kept = Record<LaneName, Ranked[]>;
404
+
405
+ function emptyCounts(): Record<LaneName, number> {
406
+ return { identity: 0, craft: 0, threads: 0, hints: 0, horizon: 0 };
407
+ }
408
+
409
+ /**
410
+ * Solve the byte fixed point EXACTLY rather than iterating and hoping.
411
+ *
412
+ * The header and the sentinel each state the composed total, so the total
413
+ * depends on how many DIGITS the total has. With `skeleton` = the composed bytes
414
+ * excluding the two numbers, the true total for a digit width `w` is
415
+ * `skeleton + occurrences * w`; the fixed point is the first `w` whose own digit
416
+ * count matches. v1's approach — iterate a few times and take what you get —
417
+ * silently ships a sentinel that is wrong by one or two bytes exactly when the
418
+ * total crosses a power of ten, which is the moment anyone reads it.
419
+ */
420
+ export function fixedPointTotal(skeletonBytes: number, occurrences: number): number {
421
+ for (let w = 1; w <= 12; w++) {
422
+ const total = skeletonBytes + occurrences * w;
423
+ if (String(total).length === w) return total;
424
+ }
425
+ // Unreachable for any total under 10^12; loud rather than silently wrong.
426
+ throw new Error(`self: byte fixed point did not converge (skeleton=${skeletonBytes})`);
427
+ }
428
+
429
+ export function compose(
430
+ kept: Kept,
431
+ day: number,
432
+ resolve: Resolve,
433
+ coreName?: string,
434
+ identity?: IdentityBlock,
435
+ ): Composed {
436
+ const counts = emptyCounts();
437
+ for (const lane of LANE_ORDER) counts[lane] = kept[lane].length;
438
+ const elements = LANE_ORDER.reduce((n, lane) => n + counts[lane], 0);
439
+ // The day-0 lane: a heading and one line of furniture, never an element. The
440
+ // counts and `elements` above are untouched, so `elements=0` in the header and
441
+ // `identity=0` in the sentinel stay true of a bundle that carries it. The same
442
+ // is true of the page and the still-forming line below.
443
+ const page = identity?.page ?? null;
444
+ const forming = identity?.forming ?? null;
445
+ const dayZero =
446
+ page === null && kept.identity.length === 0 && coreName !== undefined && coreName.length > 0
447
+ ? coreName
448
+ : null;
449
+
450
+ const build = (bytes: string): string => {
451
+ const lines: string[] = [headerLine(day, elements, bytes), FRAMING.context];
452
+ for (const lane of LANE_ORDER) {
453
+ const items = kept[lane];
454
+ if (lane === "identity") {
455
+ const furniture = page !== null || forming !== null || dayZero !== null;
456
+ if (items.length === 0 && !furniture) continue;
457
+ lines.push("", laneHeading(lane));
458
+ // THE PAGE FIRST, and then nothing else that speaks for the same thing:
459
+ // `render` empties the lane when a page exists, so the loop below is a
460
+ // no-op there. A direct caller that hands both is rendered both rather
461
+ // than silently cut, because `counts.identity` would otherwise state a
462
+ // number the bundle does not carry.
463
+ if (page !== null) {
464
+ lines.push(page.text);
465
+ if (page.dateline !== null) lines.push(page.dateline);
466
+ } else {
467
+ if (forming !== null) lines.push(forming);
468
+ if (dayZero !== null) lines.push(identityCoreLine(dayZero));
469
+ }
470
+ for (const item of items) lines.push(elementLine(item, resolve));
471
+ continue;
472
+ }
473
+ if (items.length === 0) continue;
474
+ lines.push("", laneHeading(lane));
475
+ for (const item of items) lines.push(elementLine(item, resolve));
476
+ }
477
+ lines.push("", sentinelLine(day, counts, elements, bytes));
478
+ return lines.join("\n");
479
+ };
480
+
481
+ const skeleton = byteLength(build(""));
482
+ const total = fixedPointTotal(skeleton, 2);
483
+ const stated = String(total);
484
+ const text = build(stated);
485
+ return {
486
+ text,
487
+ bytes: byteLength(text),
488
+ header: headerLine(day, elements, stated),
489
+ sentinel: sentinelLine(day, counts, elements, stated),
490
+ counts,
491
+ elements,
492
+ };
493
+ }
494
+
495
+ /** What one element costs the composition: its own rendered line, exactly —
496
+ * the DATE included, so the share bounds what is actually written. */
497
+ function elementBytes(item: Ranked, resolve: Resolve): number {
498
+ return byteLength(`${elementLine(item, resolve)}\n`);
499
+ }
500
+
501
+ /** The identity lane's ceiling in bytes while other lanes are competing for it. */
502
+ export function identityShareBytes(budgetBytes: number, t: SelfTunables): number {
503
+ return Math.floor(budgetBytes * t.IDENTITY_SHARE);
504
+ }
505
+
506
+ /**
507
+ * Cut the identity lane down to its share, BY WHOLE ELEMENTS, and return what
508
+ * was held back (in rank order) so the leftover pass can offer it the room.
509
+ *
510
+ * Two rules keep this from becoming a lane budget:
511
+ *
512
+ * - **No other lane has content ⇒ no share at all.** A store that is nothing
513
+ * but identity is not a store competing with itself, and half a budget of
514
+ * white space is not a smaller wake, it is a worse one.
515
+ * - **The first element always survives the cut.** An element is admitted
516
+ * whole or not at all, so a single element longer than the share would
517
+ * otherwise empty the lane the briefing exists for. The BUDGET may still
518
+ * take it later, in `TRIM_ORDER` position, which is where that decision
519
+ * belongs.
520
+ */
521
+ function withheldForShare(
522
+ kept: Kept,
523
+ budgetBytes: number,
524
+ resolve: Resolve,
525
+ t: SelfTunables,
526
+ ): Ranked[] {
527
+ const competing = LANE_ORDER.some((l) => l !== "identity" && kept[l].length > 0);
528
+ if (!competing || kept.identity.length === 0) return [];
529
+ const share = identityShareBytes(budgetBytes, t);
530
+ let used = 0;
531
+ let n = 0;
532
+ for (const item of kept.identity) {
533
+ const cost = elementBytes(item, resolve);
534
+ if (n > 0 && used + cost > share) break;
535
+ used += cost;
536
+ n += 1;
537
+ }
538
+ return kept.identity.splice(n);
539
+ }
540
+
541
+ /**
542
+ * Give identity back the bytes nobody else could use. Elements return in rank
543
+ * order and only while the whole composition still fits, so the result is the
544
+ * same prefix of the identity lane a larger share would have produced.
545
+ */
546
+ function offerLeftover(
547
+ kept: Kept,
548
+ held: Ranked[],
549
+ composed: Composed,
550
+ req: BriefingRequest,
551
+ resolve: Resolve,
552
+ coreName: string | undefined,
553
+ identity: IdentityBlock,
554
+ ): Composed {
555
+ let current = composed;
556
+ while (held.length > 0) {
557
+ const next = held[0];
558
+ if (next === undefined) break;
559
+ kept.identity.push(next);
560
+ const candidate = compose(kept, req.day, resolve, coreName, identity);
561
+ if (candidate.bytes > req.budgetBytes) {
562
+ kept.identity.pop();
563
+ break;
564
+ }
565
+ held.shift();
566
+ current = candidate;
567
+ }
568
+ return current;
569
+ }
570
+
571
+ /**
572
+ * Compose within the caller's budget, trimming in `TRIM_ORDER` until it fits.
573
+ *
574
+ * Trimming pops the LAST item of the lane — the lane's own ordering decides who
575
+ * that is (identity: weakest; threads: the newest non-relational one) — and never
576
+ * skips down the lane looking for something that would fit, because a
577
+ * skip-and-refill is exactly the iteration luck §1 G4 forbids.
578
+ *
579
+ * If the floor itself does not fit, the floor is returned anyway with
580
+ * `overBudget: true`. That is a deliberate divergence from `recall/`, which goes
581
+ * quiet: a quiet turn is a turn with nothing to say, but a wake with nothing to
582
+ * say is amnesia, and v1 shipped exactly that failure disguised as a fresh
583
+ * install (scar §2.3). A misconfigured ceiling gets a tripwire, not a lobotomy.
584
+ */
585
+ export function render(
586
+ lanes: Kept,
587
+ req: BriefingRequest,
588
+ resolve: Resolve,
589
+ t: SelfTunables,
590
+ ): BriefingResult {
591
+ const kept: Kept = {
592
+ identity: [...lanes.identity],
593
+ craft: [...lanes.craft],
594
+ threads: [...lanes.threads],
595
+ hints: [...lanes.hints],
596
+ horizon: [...lanes.horizon],
597
+ };
598
+ const trimmed: TrimEvent[] = [];
599
+ // THE DAY-0 GUARD, DECIDED ONCE, HERE — on the lane as it ARRIVED.
600
+ //
601
+ // Adversarial review of PR #71: gating the lookup on the ranked lane and the
602
+ // render on the post-trim copy is two predicates, and the trim loop pops from
603
+ // `kept.identity` last but it does pop. A day-30 store with two real identity
604
+ // beliefs and a 400-byte ceiling trimmed both and then asserted "No identity
605
+ // has formed here yet" — identity amnesia printed over a store that has
606
+ // identity, which is this module's own worst failure (scar §2.3). Unreachable
607
+ // through `Self`, which never sets `coreName` on a non-empty lane; reachable
608
+ // by any caller of this exported function, and the CONTRACT's "guarded by the
609
+ // empty lane" has to be true at the seam that renders, not only at the seam
610
+ // that looks the name up. A store that HAS identity says nothing about not
611
+ // having it, whatever the budget did to the lane.
612
+ const coreName = lanes.identity.length === 0 ? req.coreName : undefined;
613
+ // THE PAGE REPLACES THE LIST (spec §15 item 4), and it replaces it HERE — by
614
+ // emptying the lane before the share, the trim order or the counts see it —
615
+ // so `counts.identity` and the sentinel's `elements=` state what the bundle
616
+ // actually carries. The lane's elements are not "trimmed": nothing was
617
+ // dropped for want of room, so no `TrimEvent` is written for them, and the
618
+ // rotation memory (`RENDERED_PREFIX`) simply stops advancing while a page is
619
+ // what renders.
620
+ //
621
+ // THE STILL-FORMING LINE, which is about the PAGE and never about identity,
622
+ // and which prints on ONE value of the switch: the list has been turned off
623
+ // and no page has been written, so the line stands in the list's place.
624
+ //
625
+ // **It deliberately does NOT print under the default, on a lane that happens
626
+ // to be empty**, and the reason is measured rather than tidy. It is FURNITURE
627
+ // — untrimmable, like the day-0 line — so printing it whenever the lane is
628
+ // empty adds ~127 bytes to the floor of every such wake. A host reporting a
629
+ // 400-byte ceiling then composes 539 and publishes `overBudget`, which is the
630
+ // host-budget guarantee (§1, scar §2.18) paying for a sentence. On a
631
+ // brand-new store the day-0 line already says the same thing in the words
632
+ // this module chose for it — "No identity has formed here yet — identity is
633
+ // earned at the boundary…" — so the honesty the plan asks for on a first wake
634
+ // is already there, and the switch's other value is one word away for an
635
+ // owner who wants the sentence verbatim. See NOTES §12.
636
+ const page = req.page ?? null;
637
+ const exists = page !== null || req.pageExists === true;
638
+ const suppressList = page !== null || !t.PAGE_EMPTY_SHOWS_LIST;
639
+ if (suppressList) kept.identity.length = 0;
640
+ const identity: IdentityBlock = {
641
+ page,
642
+ // A page this ceiling could not carry is still a page, so the line that says
643
+ // none has been written stays off it (MINOR-D).
644
+ forming: !exists && !t.PAGE_EMPTY_SHOWS_LIST ? PAGE_FORMING_LINE : null,
645
+ };
646
+ // THE SHARE, applied BEFORE the trim order rather than inside it: identity
647
+ // trims last by policy, so by the time the trim loop could bound identity
648
+ // every other lane is already gone. Held-back elements are not trimmed —
649
+ // nothing is dropped here, and `held` is offered the leftover below.
650
+ const held = withheldForShare(kept, req.budgetBytes, resolve, t);
651
+
652
+ for (;;) {
653
+ const c = compose(kept, req.day, resolve, coreName, identity);
654
+ const fits = c.bytes <= req.budgetBytes;
655
+ let cut: TrimEvent | null = null;
656
+ if (!fits) {
657
+ for (const lane of TRIM_ORDER) {
658
+ const items = kept[lane];
659
+ if (items.length === 0) continue;
660
+ const dropped = items.pop();
661
+ if (dropped === undefined) continue;
662
+ cut = { lane, id: dropped.id, strength: dropped.strength };
663
+ break;
664
+ }
665
+ }
666
+ if (fits || cut === null) {
667
+ // The leftover clause. Only when NOTHING had to be trimmed: a lane that
668
+ // lost an element wanted the room, and handing it to identity instead
669
+ // would make the share decide the opposite of what it was set for. When
670
+ // the other lanes are all present and the budget is still not spent, the
671
+ // held-back identity elements take it back, in rank order, whole.
672
+ const composed =
673
+ trimmed.length === 0 ? offerLeftover(kept, held, c, req, resolve, coreName, identity) : c;
674
+ return {
675
+ ...composed,
676
+ budgetBytes: req.budgetBytes,
677
+ day: req.day,
678
+ kept: {
679
+ identity: kept.identity.map((r) => r.id),
680
+ craft: kept.craft.map((r) => r.id),
681
+ threads: kept.threads.map((r) => r.id),
682
+ hints: kept.hints.map((r) => r.id),
683
+ horizon: kept.horizon.map((r) => r.id),
684
+ },
685
+ trimmed,
686
+ pressure: composed.bytes >= req.budgetBytes * t.BUDGET_PRESSURE,
687
+ overBudget: !fits,
688
+ page:
689
+ identity.page === null
690
+ ? null
691
+ : {
692
+ bytes: byteLength(identity.page.text),
693
+ truncated: identity.page.truncated,
694
+ wholeBytes: identity.page.wholeBytes,
695
+ },
696
+ };
697
+ }
698
+ trimmed.push(cut);
699
+ }
700
+ }
701
+
702
+ // ── reading a rendered bundle back ──────────────────────────────────────────
703
+
704
+ export interface SentinelReading {
705
+ readonly present: boolean;
706
+ readonly line: string | null;
707
+ readonly statedBytes: number | null;
708
+ readonly statedElements: number | null;
709
+ readonly actualBytes: number;
710
+ /** The sentinel is the last line AND its stated total matches the real one. */
711
+ readonly intact: boolean;
712
+ }
713
+
714
+ const SENTINEL_RE = /^<!-- counterparts:wake\/end .*elements=(\d+) bytes=(\d+) -->$/;
715
+
716
+ /**
717
+ * The consumer's half of the guarantee: verify arrival from the last line alone.
718
+ * A bundle whose sentinel is missing was truncated in transit; one whose stated
719
+ * bytes disagree with its real bytes was edited or clipped. Both are errors, and
720
+ * neither is silence.
721
+ */
722
+ export function readSentinel(text: string): SentinelReading {
723
+ const actualBytes = byteLength(text);
724
+ const lines = text.split("\n");
725
+ const line = lines[lines.length - 1] ?? "";
726
+ const m = SENTINEL_RE.exec(line);
727
+ if (m === null) {
728
+ return {
729
+ present: false,
730
+ line: null,
731
+ statedBytes: null,
732
+ statedElements: null,
733
+ actualBytes,
734
+ intact: false,
735
+ };
736
+ }
737
+ const statedElements = Number(m[1]);
738
+ const statedBytes = Number(m[2]);
739
+ return {
740
+ present: true,
741
+ line,
742
+ statedBytes,
743
+ statedElements,
744
+ actualBytes,
745
+ intact: statedBytes === actualBytes,
746
+ };
747
+ }
748
+
749
+
750
+ // ── the delivery preface (composed at INJECTION, never at sleep) ─────────────
751
+
752
+ /**
753
+ * THE ONE LINE THE BODY CANNOT WRITE FOR ITSELF.
754
+ *
755
+ * The bundle is composed at a boundary and then served, unchanged, to every
756
+ * session until the next one. On 2026-09-03 the memory system under this host
757
+ * was switched from v1 to Counterparts mid-day; the stored wake still carried a
758
+ * v1-era finding ("bansai's surprise pipeline has never fired") as a current
759
+ * fact, nothing in the body said which system was speaking or how old the
760
+ * render was, and the model repeated it as current until the owner corrected
761
+ * it. Only the HTML comment named the system, and comments are furniture.
762
+ *
763
+ * So one line, composed where and when the bundle is DELIVERED — which system,
764
+ * which lived day, today's date, how big the store is — and it says out loud
765
+ * that the body below was composed at the last boundary. Constitution 16: if
766
+ * the owner (or the waking session) cannot see it, it isn't trustworthy.
767
+ *
768
+ * It is deliberately not per-session: nothing in it varies between two sessions
769
+ * on the same day in the same store, so the delivery check the next hook makes
770
+ * (§2.3) compares a sentinel that is stable for as long as the bundle is.
771
+ */
772
+ export const WAKE_SYSTEM = "Counterparts";
773
+
774
+ /**
775
+ * The room the composed budget leaves for the preface, in bytes. It is the
776
+ * preface's OWN cap, asserted by a test at the widest plausible day, date and
777
+ * store size — one number, not a lane cap that can drift from what it bounds.
778
+ * Structural, not tunable: the renderer must reserve exactly what delivery adds.
779
+ *
780
+ * Raised 128 → 160 on 2026-09-14 with U4's second number: the widest line is now
781
+ * 126 bytes (a six-digit day and a billion rows on both counts), and a cap two
782
+ * bytes above its own worst case is a cap that fails the first time the line
783
+ * gains a word.
784
+ */
785
+ export const PREFACE_RESERVE_BYTES = 160;
786
+
787
+ /**
788
+ * THE ROOM THE WAKE'S OWN FURNITURE TAKES AROUND THE PAGE, in bytes — the
789
+ * number `Self.build` subtracts from the caller's ceiling before it caps the
790
+ * page. Structural, not tunable, and measured rather than guessed: a test
791
+ * composes the widest plausible furniture (a six-digit day and six-digit lane
792
+ * counts in both comment lines, the stale dateline at a six-digit threshold)
793
+ * and asserts it fits under this.
794
+ *
795
+ * It exists because of the adversarial review of PR #138. The page's cap was
796
+ * clamped to the WHOLE budget, so a long page filled the budget exactly and the
797
+ * header, `FRAMING.context`, the heading, the dateline and the sentinel pushed
798
+ * the composition past it — and nothing could trim it back, because the identity
799
+ * lane is empty by then and the page is furniture the trim loop cannot pop. An
800
+ * 8,657-byte page published `overBudget: true` at host budgets of 400, 900,
801
+ * 2,000 and 6,000. That is scar §2.18's guarantee paying for a block of prose,
802
+ * and it is the same measurement that kept the still-forming line out of the
803
+ * default switch (NOTES §12a) — applied to the page this time.
804
+ *
805
+ * Widest measured furniture: 444 bytes. 512 is that plus room for a line to
806
+ * gain a word.
807
+ */
808
+ export const PAGE_FLOOR_RESERVE_BYTES = 512;
809
+
810
+ /**
811
+ * The smallest room worth rendering a PAGE into. Below it the wake says the
812
+ * page exists and does not fit, in one short line, rather than handing the
813
+ * reader a sentence and a marker — a fragment of a self is not a smaller self.
814
+ */
815
+ export const PAGE_MIN_RENDER_BYTES = 240;
816
+
817
+ /** The one short line a wake with no room for the page prints instead of it. */
818
+ export function pageTooLargeLine(bytes: number): string {
819
+ return `(My page is ${bytes} bytes — no room for it in this wake. Read it with 'counterparts self-page'.)`;
820
+ }
821
+
822
+ export interface PrefaceFacts {
823
+ /** Which memory system composed and is delivering this. */
824
+ readonly system: string;
825
+ /** The lived day (scar E8) — days lived, never calendar days. */
826
+ readonly day: number;
827
+ /** Today's calendar date as the HOST reports it. Absent ⇒ no date is stated. */
828
+ readonly date?: string;
829
+ /** Live memories in the store AT DELIVERY, not at the render:
830
+ * `countMemories({ type: "memory", archived: false })`. */
831
+ readonly memories: number;
832
+ /**
833
+ * EVERY live row at delivery — memories, journal episodes, beliefs and
834
+ * entities: `countMemories({ archived: false })` (IMPROVEMENTS U4).
835
+ *
836
+ * The header said "14,002 memories" while recall said "considered 41 of 14,701
837
+ * live rows" in the same session, and nothing on either surface said why the
838
+ * two differed by ~700. Both numbers were right and neither was labelled: the
839
+ * header counts `type: "memory"` rows, recall's `storeSize` is
840
+ * `list({ archived: false }).length`, the same WHERE minus the type clause, so
841
+ * the gap is exactly the live episodes and schema rows (superseded rows are
842
+ * `archived = 1` and are outside both). Stating both, in recall's own words —
843
+ * "live rows" — is what makes the model's two readings one vocabulary.
844
+ *
845
+ * Required, not optional: a line that sometimes carries the second number and
846
+ * sometimes does not is a line whose absence a reader has to interpret.
847
+ */
848
+ readonly liveRows: number;
849
+ }
850
+
851
+ /** Thousands, hand-rolled: `toLocaleString` varies with the runtime's ICU. */
852
+ export function groupDigits(n: number): string {
853
+ const s = String(Math.trunc(Math.abs(n)));
854
+ let out = "";
855
+ for (let i = 0; i < s.length; i++) {
856
+ if (i > 0 && (s.length - i) % 3 === 0) out += ",";
857
+ out += s[i];
858
+ }
859
+ return n < 0 ? `-${out}` : out;
860
+ }
861
+
862
+ /** One line, under `PREFACE_RESERVE_BYTES`, stating what the body cannot — and
863
+ * saying WHICH population each of its two counts is (U4). */
864
+ export function prefaceLine(f: PrefaceFacts): string {
865
+ const when = f.date === undefined ? `day ${f.day}` : `day ${f.day} (${f.date})`;
866
+ return (
867
+ `${f.system} memory, ${when}, ${groupDigits(f.memories)} memories of ` +
868
+ `${groupDigits(f.liveRows)} live rows — composed at the last boundary.`
869
+ );
870
+ }
871
+
872
+ export interface PrefacedBundle {
873
+ readonly text: string;
874
+ readonly bytes: number;
875
+ /** The sentinel of the DELIVERED text — what the next hook must see. */
876
+ readonly sentinel: string | null;
877
+ /** False when the bundle was not a well-formed render and was left alone. */
878
+ readonly applied: boolean;
879
+ }
880
+
881
+ const BYTES_FIELD = /bytes=\d+/;
882
+ const OPEN_RE = /^<!-- counterparts:wake .*elements=(\d+) bytes=(\d+) -->$/;
883
+
884
+ /**
885
+ * Splice the preface INSIDE the wake block, above the composed body, and re-solve
886
+ * the byte fixed point so the opening comment and the tail sentinel both state
887
+ * the delivered total. The alternative — adding bytes and leaving the two lines
888
+ * describing something smaller — would hand every reader a sentinel that fails
889
+ * the check it exists to pass (§1 G2).
890
+ *
891
+ * A bundle that is not a well-formed render (bootstrap line, clipped, edited) is
892
+ * returned UNTOUCHED: rewriting the byte count of a damaged bundle would erase
893
+ * the damage, which is the one thing the sentinel is for.
894
+ */
895
+ export function applyPreface(text: string, preface: string): PrefacedBundle {
896
+ const lines = text.split("\n");
897
+ const open = lines[0] ?? "";
898
+ const tail = lines[lines.length - 1] ?? "";
899
+ if (lines.length < 2 || !OPEN_RE.test(open) || !SENTINEL_RE.test(tail)) {
900
+ return {
901
+ text,
902
+ bytes: byteLength(text),
903
+ sentinel: SENTINEL_RE.test(tail) ? tail : null,
904
+ applied: false,
905
+ };
906
+ }
907
+ const build = (stated: string): string[] => [
908
+ open.replace(BYTES_FIELD, `bytes=${stated}`),
909
+ preface,
910
+ ...lines.slice(1, -1),
911
+ tail.replace(BYTES_FIELD, `bytes=${stated}`),
912
+ ];
913
+ const skeleton = byteLength(build("").join("\n"));
914
+ const composed = build(String(fixedPointTotal(skeleton, 2)));
915
+ const out = composed.join("\n");
916
+ return {
917
+ text: out,
918
+ bytes: byteLength(out),
919
+ sentinel: composed[composed.length - 1] ?? null,
920
+ applied: true,
921
+ };
922
+ }
923
+
924
+ /**
925
+ * Splice a block in at the FOOT of the wake block, above the tail sentinel, and
926
+ * re-solve the byte fixed point so both comment lines state the delivered total
927
+ * — `applyPreface`'s mechanism, pointed at the other end of the bundle.
928
+ *
929
+ * It exists for the per-directory handoff pointer (E1), which is a delivery-time
930
+ * fact for exactly the reason the preface is: ONE bundle is published per store
931
+ * at a boundary and read by sessions in every directory, so which directory this
932
+ * session opened in cannot be known when the body is composed. The pointer is
933
+ * FURNITURE — no `- ` bullet, no lane — so `counts` and the sentinel's
934
+ * `elements=` stay true of a bundle that carries it, exactly as they stay true
935
+ * of one carrying the page or the day-0 line.
936
+ *
937
+ * At the foot rather than the head because a handoff is the last thing that
938
+ * happened here and the first thing to pick up, and because the preface's own
939
+ * place above the body is a claim about the WHOLE bundle that a second line
940
+ * there would blunt.
941
+ *
942
+ * A bundle that is not a well-formed render is returned UNTOUCHED, for
943
+ * `applyPreface`'s reason: rewriting the byte count of a damaged bundle erases
944
+ * the damage the sentinel exists to show.
945
+ */
946
+ export function spliceBeforeSentinel(text: string, block: string): PrefacedBundle {
947
+ const lines = text.split("\n");
948
+ const open = lines[0] ?? "";
949
+ const tail = lines[lines.length - 1] ?? "";
950
+ if (lines.length < 2 || !OPEN_RE.test(open) || !SENTINEL_RE.test(tail) || block.length === 0) {
951
+ return {
952
+ text,
953
+ bytes: byteLength(text),
954
+ sentinel: SENTINEL_RE.test(tail) ? tail : null,
955
+ applied: false,
956
+ };
957
+ }
958
+ const body = lines.slice(1, -1);
959
+ // `compose` already pushes a blank line before the sentinel, so the separator
960
+ // is added only when this bundle does not have one — a doubled blank line is
961
+ // not wrong, but it costs bytes the reserve measured for one.
962
+ const gap = body[body.length - 1] === "" ? [] : [""];
963
+ const build = (stated: string): string[] => [
964
+ open.replace(BYTES_FIELD, `bytes=${stated}`),
965
+ ...body,
966
+ ...gap,
967
+ block,
968
+ "",
969
+ tail.replace(BYTES_FIELD, `bytes=${stated}`),
970
+ ];
971
+ const skeleton = byteLength(build("").join("\n"));
972
+ const composed = build(String(fixedPointTotal(skeleton, 2)));
973
+ const out = composed.join("\n");
974
+ return {
975
+ text: out,
976
+ bytes: byteLength(out),
977
+ sentinel: composed[composed.length - 1] ?? null,
978
+ applied: true,
979
+ };
980
+ }