counterparts 0.3.19 → 0.3.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/README.md +12 -4
  3. package/docs/module-map.md +6 -0
  4. package/package.json +1 -1
  5. package/src/adapters/claude-code/CONTRACT.md +14 -13
  6. package/src/adapters/claude-code/NOTES.md +29 -0
  7. package/src/adapters/claude-code/bin/hook.ts +12 -4
  8. package/src/adapters/claude-code/bin/runner.ts +41 -20
  9. package/src/adapters/claude-code/doctor.ts +123 -30
  10. package/src/adapters/claude-code/hooks.ts +70 -86
  11. package/src/adapters/claude-code/index.ts +0 -3
  12. package/src/adapters/cli/NOTES.md +8 -0
  13. package/src/adapters/cli/commands-delete.ts +273 -0
  14. package/src/adapters/cli/commands-install.ts +29 -10
  15. package/src/adapters/cli/commands-note.ts +1 -1
  16. package/src/adapters/cli/commands-readings.ts +4 -2
  17. package/src/adapters/cli/commands-scope.ts +25 -4
  18. package/src/adapters/cli/commands-self.ts +4 -1
  19. package/src/adapters/cli/commands-start-fresh.ts +1 -1
  20. package/src/adapters/cli/commands.ts +22 -3
  21. package/src/adapters/cli/help.ts +7 -7
  22. package/src/adapters/cli/install.ts +4 -2
  23. package/src/adapters/cli/mechanisms.ts +2 -2
  24. package/src/adapters/cli/removal.ts +1 -1
  25. package/src/adapters/config.ts +112 -30
  26. package/src/adapters/dashboard/CONTRACT.md +14 -0
  27. package/src/adapters/dashboard/NOTES.md +15 -0
  28. package/src/adapters/dashboard/activity.ts +1 -1
  29. package/src/adapters/dashboard/bin/dashboard.ts +3 -3
  30. package/src/adapters/dashboard/browse.ts +1 -1
  31. package/src/adapters/dashboard/identity.ts +1 -1
  32. package/src/adapters/dashboard/registries.ts +14 -14
  33. package/src/adapters/dashboard/resolve.ts +1 -1
  34. package/src/adapters/dashboard/status.ts +5 -2
  35. package/src/adapters/dashboard/web/actions.ts +21 -2
  36. package/src/adapters/dashboard/web/app.html +1 -1
  37. package/src/adapters/dashboard/web/flow.ts +1 -1
  38. package/src/adapters/dashboard/web/mechanisms/consolidation/index.js +2 -2
  39. package/src/adapters/dashboard/web/mechanisms/consolidation/panel.js +1 -1
  40. package/src/adapters/dashboard/web/mechanisms/decay/index.js +1 -1
  41. package/src/adapters/dashboard/web/mechanisms/reconsolidation/index.js +2 -2
  42. package/src/adapters/dashboard/web/mechanisms/retrieval/panel.js +3 -3
  43. package/src/adapters/dashboard/web/mechanisms/salience/panel.js +2 -2
  44. package/src/adapters/dashboard/web/narrate.ts +11 -11
  45. package/src/adapters/dashboard/web/pages/flow/sections/heatmap.js +1 -1
  46. package/src/adapters/dashboard/web/pages/health/sections/checks.js +3 -2
  47. package/src/adapters/dashboard/web/pages/health/sections/cycle.js +5 -5
  48. package/src/adapters/dashboard/web/pages/health/sections/mechanisms.js +1 -1
  49. package/src/adapters/dashboard/web/pages/health/sections/wake.js +2 -2
  50. package/src/adapters/dashboard/web/pages/memories/sections/tools.js +73 -3
  51. package/src/adapters/dashboard/web/pages/self/sections/dreams.js +2 -2
  52. package/src/adapters/dashboard/web/pages/self/sections/journal.js +5 -5
  53. package/src/adapters/dashboard/web/pages/self/sections/page.js +13 -13
  54. package/src/adapters/dashboard/web/pages/self/sections/settling.js +1 -1
  55. package/src/adapters/dashboard/web/pages/self/sections/wake.js +7 -7
  56. package/src/adapters/dashboard/web/server.ts +9 -1
  57. package/src/adapters/dashboard/web/shared/event-modal.js +1 -1
  58. package/src/adapters/dashboard/web/shared/memory-card-words.js +1 -1
  59. package/src/adapters/dashboard/web/shared/memory-modal.js +5 -5
  60. package/src/adapters/dashboard/web/views/activity.ts +1 -1
  61. package/src/adapters/dashboard/web/views/dreams.ts +1 -1
  62. package/src/adapters/dashboard/web/views/health.ts +1 -1
  63. package/src/adapters/dashboard/web/views/mechanisms.ts +6 -6
  64. package/src/adapters/dashboard/web/views/mind.ts +21 -9
  65. package/src/adapters/dashboard/web/views/overview.ts +3 -3
  66. package/src/adapters/expansions.ts +14 -1
  67. package/src/adapters/fired.ts +1 -1
  68. package/src/adapters/lifecycle.ts +25 -4
  69. package/src/adapters/log/index.ts +21 -0
  70. package/src/adapters/mcp/CONTRACT.md +1 -1
  71. package/src/adapters/mcp/server-self-tools.ts +25 -1
  72. package/src/adapters/mcp/server-words.ts +3 -2
  73. package/src/adapters/mcp/server.ts +45 -9
  74. package/src/adapters/mcp/tools.ts +4 -3
  75. package/src/adapters/plugin.ts +44 -8
  76. package/src/adapters/sessions.ts +5 -2
  77. package/src/adapters/snapshots.ts +90 -1
  78. package/src/adapters/store-id.ts +58 -0
  79. package/src/core/counterpart-boundary.ts +9 -0
  80. package/src/core/counterpart.ts +19 -6
  81. package/src/core/dream/CONTRACT.md +8 -0
  82. package/src/core/dream/index.ts +15 -2
  83. package/src/core/handoff/last-here.ts +24 -12
  84. package/src/core/onboarding.ts +231 -62
  85. package/src/core/prospective/CONTRACT.md +4 -1
  86. package/src/core/prospective/index.ts +23 -5
  87. package/src/core/recall/CONTRACT.md +3 -1
  88. package/src/core/recall/INTERFACE-GAPS.md +1 -1
  89. package/src/core/recall/NOTES.md +14 -0
  90. package/src/core/recall/session.ts +40 -1
  91. package/src/core/reconsolidation.ts +1 -1
  92. package/src/core/remember/CONTRACT.md +14 -8
  93. package/src/core/remember/owes.ts +68 -28
  94. package/src/core/remember/owner-strike-seam.ts +6 -3
  95. package/src/core/remember/spans.ts +3 -2
  96. package/src/core/remember/tunables.ts +18 -5
  97. package/src/core/remember/write-up-seam.ts +2 -1
  98. package/src/core/self/CONTRACT.md +25 -9
  99. package/src/core/self/NOTES.md +6 -0
  100. package/src/core/self/briefing-delivery.ts +349 -0
  101. package/src/core/self/briefing-page.ts +315 -0
  102. package/src/core/self/briefing-room.ts +563 -0
  103. package/src/core/self/briefing.ts +304 -1156
  104. package/src/core/self/index.ts +28 -6
  105. package/src/core/store/NOTES.md +6 -5
  106. package/src/core/store/index.ts +39 -0
  107. package/src/core/store/paths.ts +9 -2
  108. package/src/adapters/claude-code/primacy.ts +0 -162
@@ -0,0 +1,349 @@
1
+ /**
2
+ * THE DELIVERY'S OWN LINES — the sentinel read back, the preface, the tense
3
+ * only the delivery knows, and the splices that keep both byte counts true —
4
+ * moved out of `briefing.ts` on 2026-10-12 (moves only). Imported by
5
+ * `briefing.ts`, which re-exports its public names, and by `briefing-page.ts`
6
+ * for the preface's reserve (`split-parts.test.ts`).
7
+ */
8
+ import { byteLength } from "./identity.js";
9
+ import { addDays, isDay } from "../time.js";
10
+ import { DUE_PAST_WORD, DUE_WORD, FRAMING, LEGACY_FRAMING, fixedPointTotal } from "./briefing.js";
11
+
12
+
13
+ // ── reading a rendered bundle back ──────────────────────────────────────────
14
+
15
+ export interface SentinelReading {
16
+ readonly present: boolean;
17
+ readonly line: string | null;
18
+ readonly statedBytes: number | null;
19
+ readonly statedElements: number | null;
20
+ readonly actualBytes: number;
21
+ /** The sentinel is the last line AND its stated total matches the real one. */
22
+ readonly intact: boolean;
23
+ }
24
+
25
+ const SENTINEL_RE = /^<!-- counterparts:wake\/end .*elements=(\d+) bytes=(\d+) -->$/;
26
+
27
+ /**
28
+ * The consumer's half of the guarantee: verify arrival from the last line alone.
29
+ * A bundle whose sentinel is missing was truncated in transit; one whose stated
30
+ * bytes disagree with its real bytes was edited or clipped. Both are errors, and
31
+ * neither is silence.
32
+ */
33
+ export function readSentinel(text: string): SentinelReading {
34
+ const actualBytes = byteLength(text);
35
+ const lines = text.split("\n");
36
+ const line = lines[lines.length - 1] ?? "";
37
+ const m = SENTINEL_RE.exec(line);
38
+ if (m === null) {
39
+ return {
40
+ present: false,
41
+ line: null,
42
+ statedBytes: null,
43
+ statedElements: null,
44
+ actualBytes,
45
+ intact: false,
46
+ };
47
+ }
48
+ const statedElements = Number(m[1]);
49
+ const statedBytes = Number(m[2]);
50
+ return {
51
+ present: true,
52
+ line,
53
+ statedBytes,
54
+ statedElements,
55
+ actualBytes,
56
+ intact: statedBytes === actualBytes,
57
+ };
58
+ }
59
+
60
+
61
+ // ── the delivery preface (composed at INJECTION, never at sleep) ─────────────
62
+
63
+ /**
64
+ * THE ONE LINE THE BODY CANNOT WRITE FOR ITSELF.
65
+ *
66
+ * The bundle is composed at a boundary and then served, unchanged, to every
67
+ * session until the next one. On 2026-09-03 the memory system under this host
68
+ * was switched from v1 to Counterparts mid-day; the stored wake still carried a
69
+ * v1-era finding ("bansai's surprise pipeline has never fired") as a current
70
+ * fact, nothing in the body said which system was speaking or how old the
71
+ * render was, and the model repeated it as current until the owner corrected
72
+ * it. Only the HTML comment named the system, and comments are furniture.
73
+ *
74
+ * So one line, composed where and when the bundle is DELIVERED — which system,
75
+ * which lived day, today's date, how big the store is — and it says out loud
76
+ * that the body below was composed at the last boundary. Constitution 16: if
77
+ * the owner (or the waking session) cannot see it, it isn't trustworthy.
78
+ *
79
+ * It is deliberately not per-session: nothing in it varies between two sessions
80
+ * on the same day in the same store, so the delivery check the next hook makes
81
+ * (§2.3) compares a sentinel that is stable for as long as the bundle is.
82
+ */
83
+ export const WAKE_SYSTEM = "Counterparts";
84
+
85
+ /**
86
+ * THE WHOLE WAKE'S OWN WAY BACK (2026-10-10), the preface's last sentence.
87
+ *
88
+ * Measured on Claude Code 2.1.296 (host numbers: `adapters/config.ts`
89
+ * `HOST_OUTPUT_CHARS`, `HOST_PREVIEW_CHARS`): a hook field over the host's cap
90
+ * is saved to a file, and the model is shown a "too large, saved to <path>"
91
+ * note and about the first 2,000 characters — and nothing tells it to read
92
+ * the file, which holds all of it. So the wake says so itself, where any
93
+ * preview carries it: in the preface, the line after the opening comment. It
94
+ * names the end (`counterparts:wake/end`, the sentinel every wake closes on)
95
+ * and the door (the file the host made). No other door reads a session's
96
+ * composed wake today (self INTERFACE-GAPS §13). The self page's own top line
97
+ * (`pageTopLine`) is the second layer, for a cut inside the wake.
98
+ */
99
+ export const WAKE_WHOLE_SENTENCE =
100
+ "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.";
101
+
102
+ /**
103
+ * The room the composed budget leaves for the preface, in bytes. It is the
104
+ * preface's OWN cap, asserted by a test at the widest plausible day, date and
105
+ * store size — one number, not a lane cap that can drift from what it bounds.
106
+ * Structural, not tunable: the renderer must reserve exactly what delivery adds.
107
+ *
108
+ * Raised 128 → 160 on 2026-09-14 with U4's second number: the widest line is now
109
+ * 126 bytes (a six-digit day and a billion rows on both counts), and a cap two
110
+ * bytes above its own worst case is a cap that fails the first time the line
111
+ * gains a word.
112
+ *
113
+ * Raised again on 2026-10-10 by exactly the whole-wake sentence
114
+ * (`WAKE_WHOLE_SENTENCE`) and its space, which the line now ends with: 160 +
115
+ * 133 = 293. The page's room is derived through this number
116
+ * (`deliveryReserveBound`), so the sentence is paid for there too.
117
+ */
118
+ export const PREFACE_RESERVE_BYTES =
119
+ // Measured with an encoder of its own: `identity.ts#byteLength` may not be
120
+ // initialised yet when an import cycle evaluates this module first.
121
+ 160 + new TextEncoder().encode(` ${WAKE_WHOLE_SENTENCE}`).length;
122
+
123
+ export interface PrefaceFacts {
124
+ /** Which memory system composed and is delivering this. */
125
+ readonly system: string;
126
+ /** The lived day (scar E8) — days lived, never calendar days. */
127
+ readonly day: number;
128
+ /** Today's calendar date as the HOST reports it. Absent ⇒ no date is stated. */
129
+ readonly date?: string;
130
+ /** Live memories in the store AT DELIVERY, not at the render:
131
+ * `countMemories({ type: "memory", archived: false })`. */
132
+ readonly memories: number;
133
+ /**
134
+ * TRUE when the body was ASSEMBLED at session start (2026-10-10,
135
+ * `Self#assemble`) rather than read as the last boundary composed it: the
136
+ * line then says so — fewer bytes than the words it replaces, so the
137
+ * reserve holds.
138
+ */
139
+ readonly assembled?: boolean;
140
+ /**
141
+ * EVERY live row at delivery — memories, journal episodes, beliefs and
142
+ * entities: `countMemories({ archived: false })` (IMPROVEMENTS U4).
143
+ *
144
+ * The header said "14,002 memories" while recall said "considered 41 of 14,701
145
+ * live rows" in the same session, and nothing on either surface said why the
146
+ * two differed by ~700. Both numbers were right and neither was labelled: the
147
+ * header counts `type: "memory"` rows, recall's `storeSize` is
148
+ * `list({ archived: false }).length`, the same WHERE minus the type clause, so
149
+ * the gap is exactly the live episodes and schema rows (superseded rows are
150
+ * `archived = 1` and are outside both). Stating both, in recall's own words —
151
+ * "live rows" — is what makes the model's two readings one vocabulary.
152
+ *
153
+ * Required, not optional: a line that sometimes carries the second number and
154
+ * sometimes does not is a line whose absence a reader has to interpret.
155
+ */
156
+ readonly liveRows: number;
157
+ }
158
+
159
+ /** Thousands, hand-rolled: `toLocaleString` varies with the runtime's ICU. */
160
+ export function groupDigits(n: number): string {
161
+ const s = String(Math.trunc(Math.abs(n)));
162
+ let out = "";
163
+ for (let i = 0; i < s.length; i++) {
164
+ if (i > 0 && (s.length - i) % 3 === 0) out += ",";
165
+ out += s[i];
166
+ }
167
+ return n < 0 ? `-${out}` : out;
168
+ }
169
+
170
+ /** One line, under `PREFACE_RESERVE_BYTES`, stating what the body cannot — and
171
+ * saying WHICH population each of its two counts is (U4) — then how to read
172
+ * all of it when a host cut it (`WAKE_WHOLE_SENTENCE`, 2026-10-10). */
173
+ export function prefaceLine(f: PrefaceFacts): string {
174
+ const when = f.date === undefined ? `day ${f.day}` : `day ${f.day} (${f.date})`;
175
+ return (
176
+ `${f.system} memory, ${when}, ${groupDigits(f.memories)} memories of ` +
177
+ `${groupDigits(f.liveRows)} live rows — ${f.assembled === true ? "assembled at session start" : "composed at the last boundary"}. ${WAKE_WHOLE_SENTENCE}`
178
+ );
179
+ }
180
+
181
+ /**
182
+ * THE TENSE ONLY THE DELIVERY KNOWS (2026-10-09).
183
+ *
184
+ * The owner's wake on 10-09 carried "Arriving: - … (due 2026-10-08) · …". By
185
+ * design: a one-off stays in the horizon lane for its grace days, and the wake
186
+ * is composed at a boundary — the evening one, the day before — and read the
187
+ * next morning. The DATE was true; the lane's heading made it read as still to
188
+ * come. A render can put a date it is already past into the past tense
189
+ * (`Resolved.duePast`), but on the evening of the 8th the 8th is today, and only
190
+ * the delivery knows the morning is the 9th.
191
+ *
192
+ * So, where the preface is composed and with the same date (`WakeDelivery
193
+ * .date`, the person's day): an Arriving line whose due date is before today
194
+ * reads `(was due 2026-10-05)`, and `(was due yesterday, 2026-10-08)` the day
195
+ * after. Only the date prefix of a `- ` line in the Arriving lane is touched —
196
+ * never a statement, never another lane — and only as far as `room` allows:
197
+ * "was " on every such line first, then "yesterday, " while room remains, so a
198
+ * line that would not fit keeps the date it was composed with, which is still
199
+ * true. The caller passes what the preface reserve has left
200
+ * (`PREFACE_RESERVE_BYTES`), so the delivered bundle stays inside it.
201
+ */
202
+ export function arrivingTense(text: string, today: string, room: number): string {
203
+ if (!isDay(today) || room <= 0) return text;
204
+ const lines = text.split("\n");
205
+ // The LAST such heading: the lane is last, and a page above it is printed as
206
+ // written, so a line of the page that happens to read "Arriving:" is not it.
207
+ // A bundle stored before the plain-words rename still says "Arriving:".
208
+ const start = Math.max(lines.lastIndexOf(FRAMING.horizon), lines.lastIndexOf(LEGACY_FRAMING.horizon));
209
+ if (start < 0) return text;
210
+ const prior = addDays(today, -1);
211
+ const shape = /^(- (?:(?:by )?\d{4}-\d{2}-\d{2} \()?)(was )?due (\d{4}-\d{2}-\d{2})(?=[,)]| · )/;
212
+ const was = `${DUE_PAST_WORD} `;
213
+ const words = { was: byteLength(was) - byteLength(`${DUE_WORD} `), yesterday: byteLength("yesterday, ") };
214
+ const past: { i: number; head: string; already: boolean; date: string; rest: string; was: boolean; yesterday: boolean }[] = [];
215
+ for (let i = start + 1; i < lines.length && lines[i] !== ""; i++) {
216
+ const line = lines[i] ?? "";
217
+ const m = shape.exec(line);
218
+ const date = m?.[3];
219
+ if (m === null || date === undefined || date >= today) continue;
220
+ const already = m[2] !== undefined;
221
+ past.push({ i, head: m[1] ?? "- ", already, date, rest: line.slice(m[0].length), was: already, yesterday: false });
222
+ }
223
+ let left = room;
224
+ for (const p of past) {
225
+ if (p.was || left < words.was) continue;
226
+ p.was = true;
227
+ left -= words.was;
228
+ }
229
+ for (const p of past) {
230
+ if (!p.was || p.date !== prior || left < words.yesterday) continue;
231
+ p.yesterday = true;
232
+ left -= words.yesterday;
233
+ }
234
+ for (const p of past) {
235
+ if (!p.was || (p.already && !p.yesterday)) continue;
236
+ lines[p.i] = `${p.head}${was}${p.yesterday ? "yesterday, " : ""}${p.date}${p.rest}`;
237
+ }
238
+ return lines.join("\n");
239
+ }
240
+
241
+ export interface PrefacedBundle {
242
+ readonly text: string;
243
+ readonly bytes: number;
244
+ /** The sentinel of the DELIVERED text — what the next hook must see. */
245
+ readonly sentinel: string | null;
246
+ /** False when the bundle was not a well-formed render and was left alone. */
247
+ readonly applied: boolean;
248
+ }
249
+
250
+ const BYTES_FIELD = /bytes=\d+/;
251
+ const OPEN_RE = /^<!-- counterparts:wake .*elements=(\d+) bytes=(\d+) -->$/;
252
+
253
+ /**
254
+ * Splice the preface INSIDE the wake block, above the composed body, and re-solve
255
+ * the byte fixed point so the opening comment and the tail sentinel both state
256
+ * the delivered total. The alternative — adding bytes and leaving the two lines
257
+ * describing something smaller — would hand every reader a sentinel that fails
258
+ * the check it exists to pass (§1 G2).
259
+ *
260
+ * A bundle that is not a well-formed render (bootstrap line, clipped, edited) is
261
+ * returned UNTOUCHED: rewriting the byte count of a damaged bundle would erase
262
+ * the damage, which is the one thing the sentinel is for.
263
+ */
264
+ export function applyPreface(text: string, preface: string): PrefacedBundle {
265
+ const lines = text.split("\n");
266
+ const open = lines[0] ?? "";
267
+ const tail = lines[lines.length - 1] ?? "";
268
+ if (lines.length < 2 || !OPEN_RE.test(open) || !SENTINEL_RE.test(tail)) {
269
+ return {
270
+ text,
271
+ bytes: byteLength(text),
272
+ sentinel: SENTINEL_RE.test(tail) ? tail : null,
273
+ applied: false,
274
+ };
275
+ }
276
+ const build = (stated: string): string[] => [
277
+ open.replace(BYTES_FIELD, `bytes=${stated}`),
278
+ preface,
279
+ ...lines.slice(1, -1),
280
+ tail.replace(BYTES_FIELD, `bytes=${stated}`),
281
+ ];
282
+ const skeleton = byteLength(build("").join("\n"));
283
+ const composed = build(String(fixedPointTotal(skeleton, 2)));
284
+ const out = composed.join("\n");
285
+ return {
286
+ text: out,
287
+ bytes: byteLength(out),
288
+ sentinel: composed[composed.length - 1] ?? null,
289
+ applied: true,
290
+ };
291
+ }
292
+
293
+ /**
294
+ * Splice a block in at the FOOT of the wake block, above the tail sentinel, and
295
+ * re-solve the byte fixed point so both comment lines state the delivered total
296
+ * — `applyPreface`'s mechanism, pointed at the other end of the bundle.
297
+ *
298
+ * It exists for the per-directory handoff pointer (E1), which is a delivery-time
299
+ * fact for exactly the reason the preface is: ONE bundle is published per store
300
+ * at a boundary and read by sessions in every directory, so which directory this
301
+ * session opened in cannot be known when the body is composed. The pointer is
302
+ * FURNITURE — no `- ` bullet, no lane — so `counts` and the sentinel's
303
+ * `elements=` stay true of a bundle that carries it, exactly as they stay true
304
+ * of one carrying the page or the day-0 line.
305
+ *
306
+ * At the foot rather than the head because a handoff is the last thing that
307
+ * happened here and the first thing to pick up, and because the preface's own
308
+ * place above the body is a claim about the WHOLE bundle that a second line
309
+ * there would blunt.
310
+ *
311
+ * A bundle that is not a well-formed render is returned UNTOUCHED, for
312
+ * `applyPreface`'s reason: rewriting the byte count of a damaged bundle erases
313
+ * the damage the sentinel exists to show.
314
+ */
315
+ export function spliceBeforeSentinel(text: string, block: string): PrefacedBundle {
316
+ const lines = text.split("\n");
317
+ const open = lines[0] ?? "";
318
+ const tail = lines[lines.length - 1] ?? "";
319
+ if (lines.length < 2 || !OPEN_RE.test(open) || !SENTINEL_RE.test(tail) || block.length === 0) {
320
+ return {
321
+ text,
322
+ bytes: byteLength(text),
323
+ sentinel: SENTINEL_RE.test(tail) ? tail : null,
324
+ applied: false,
325
+ };
326
+ }
327
+ const body = lines.slice(1, -1);
328
+ // `compose` already pushes a blank line before the sentinel, so the separator
329
+ // is added only when this bundle does not have one — a doubled blank line is
330
+ // not wrong, but it costs bytes the reserve measured for one.
331
+ const gap = body[body.length - 1] === "" ? [] : [""];
332
+ const build = (stated: string): string[] => [
333
+ open.replace(BYTES_FIELD, `bytes=${stated}`),
334
+ ...body,
335
+ ...gap,
336
+ block,
337
+ "",
338
+ tail.replace(BYTES_FIELD, `bytes=${stated}`),
339
+ ];
340
+ const skeleton = byteLength(build("").join("\n"));
341
+ const composed = build(String(fixedPointTotal(skeleton, 2)));
342
+ const out = composed.join("\n");
343
+ return {
344
+ text: out,
345
+ bytes: byteLength(out),
346
+ sentinel: composed[composed.length - 1] ?? null,
347
+ applied: true,
348
+ };
349
+ }
@@ -0,0 +1,315 @@
1
+ /**
2
+ * THE SELF PAGE IN THE WAKE — its block, its ladder of whole rungs, the
3
+ * lines around it and the room it is sized to, moved out of `briefing.ts` on
4
+ * 2026-10-12 (moves only). Imported by `briefing.ts` alone, which re-exports
5
+ * its public names (`split-parts.test.ts`).
6
+ */
7
+ import { byteLength } from "./identity.js";
8
+ import { HANDOFF_RESERVE_MAX_BYTES, HANDOFF_RESERVE_MIN_BUDGET_MULTIPLE } from "../handoff/index.js";
9
+ import { PREFACE_RESERVE_BYTES, groupDigits } from "./briefing-delivery.js";
10
+
11
+
12
+
13
+ /**
14
+ * THE PAGE, IN "WHO I AM" — furniture, like the day-0 line, and for the same
15
+ * reason: it is not a ranked element, it carries no `- ` bullet, and `counts`
16
+ * and the sentinel's `elements=` stay true of a bundle that holds it.
17
+ *
18
+ * The page prints FIRST and AS IS. Not re-wrapped, not re-ordered, not
19
+ * summarised: a page reassembled here would be a page this module wrote, and
20
+ * what the owner and the session are promised is the thing they wrote.
21
+ * `FRAMING.context`'s "each line opens with the date it was learned" is a claim
22
+ * about the element lines — the day-0 line has carried no date since it shipped
23
+ * — and the page carries its own date on its own line instead.
24
+ */
25
+ export interface PageBlock {
26
+ /**
27
+ * The page as it will be injected, on the rung the room allowed
28
+ * (`PageRung`, 2026-10-10): the whole page, the short version its writer
29
+ * wrote with it, each section's heading and first sentence, its headings
30
+ * alone, or the one line that says it did not fit (`pageTooLargeLine`).
31
+ * Every rung is whole text — never part of a sentence (2026-10-09).
32
+ */
33
+ readonly text: string;
34
+ /**
35
+ * THE TOP LINE (2026-10-10, `pageTopLine`): what is below, the page's size,
36
+ * the exact line it ends with, and both doors to the whole page — so a
37
+ * reader whose copy was cut on the way (a host's preview) can tell. Null on
38
+ * the one-line rung, which is its own top line.
39
+ */
40
+ readonly top: string | null;
41
+ /** The page's own "last revised" line, or null when the page carries no date. */
42
+ readonly dateline: string | null;
43
+ /** THE END LINE (`pageEndLine`), after the dateline; null when `top` is. */
44
+ readonly end: string | null;
45
+ /** Which rung printed. */
46
+ readonly rung: PageRung;
47
+ /** True when the page did not print whole — any rung but `whole`. */
48
+ readonly truncated: boolean;
49
+ /** The page's own bytes, whole, whatever was rendered. */
50
+ readonly wholeBytes: number;
51
+ }
52
+
53
+ /**
54
+ * THE PAGE'S FALLBACK LADDER (2026-10-10), first to last; `Self#pageBlock`
55
+ * takes the first that fits. Every rung is whole text, never a cut:
56
+ *
57
+ * - `whole` — the page, byte for byte;
58
+ * - `short` — the short version the page's writer wrote WITH this
59
+ * version of it (`SelfPage.short`, tied to the page's exact
60
+ * text, so a page rewritten without one never shows a stale
61
+ * one);
62
+ * - `outline` — each `##` section's heading and its first whole sentence
63
+ * (`page.ts#pageOutline`), mechanical;
64
+ * - `headings` — the headings alone;
65
+ * - `line` — one line naming the page's size and both doors
66
+ * (`pageTooLargeLine`), its own top line.
67
+ */
68
+ export const PAGE_RUNGS = ["whole", "short", "outline", "headings", "line"] as const;
69
+ export type PageRung = (typeof PAGE_RUNGS)[number];
70
+
71
+ /**
72
+ * The page's own date, under the page. It states the DATE and — when the page
73
+ * has gone stale — how long the silence was allowed to be, rather than "N days
74
+ * ago": the bundle is composed at a boundary and then served unchanged until
75
+ * the next one, so a delta computed here goes wrong while a date does not.
76
+ */
77
+ export function pageDateline(revisedOn: string, stale: boolean, staleDays: number): string | null {
78
+ const on = revisedOn.trim();
79
+ // A page with no readable date SAYS SO. Returning null printed the page with
80
+ // no date and no staleness signal at all while every other surface called it
81
+ // stale — the one state where the wake said less than it knew (adversarial
82
+ // review m6). Only reachable on a hand-minted or hand-edited row.
83
+ if (on === "" || !/^\d{4}-\d{2}-\d{2}$/.test(on) || !Number.isFinite(Date.parse(`${on}T00:00:00Z`))) {
84
+ return "(Last revised — the page carries no readable date.)";
85
+ }
86
+ return stale
87
+ ? `(Last revised ${on} — more than ${staleDays} days before this wake was composed.)`
88
+ : `(Last revised ${on}.)`;
89
+ }
90
+
91
+ /**
92
+ * THE ROOM THE WAKE'S OWN FURNITURE TAKES AROUND THE PAGE, in bytes — the
93
+ * number `Self.build` subtracts from the caller's ceiling before it asks
94
+ * whether the page fits. Structural, not tunable, and measured rather than guessed: a test
95
+ * composes the widest plausible furniture (a six-digit day and six-digit lane
96
+ * counts in both comment lines, the stale dateline at a six-digit threshold)
97
+ * and asserts it fits under this.
98
+ *
99
+ * It exists because of the adversarial review of PR #138. The page's cap was
100
+ * clamped to the WHOLE budget, so a long page filled the budget exactly and the
101
+ * header, `FRAMING.context`, the heading, the dateline and the sentinel pushed
102
+ * the composition past it — and nothing could trim it back, because the identity
103
+ * lane is empty by then and the page is furniture the trim loop cannot pop. An
104
+ * 8,657-byte page published `overBudget: true` at host budgets of 400, 900,
105
+ * 2,000 and 6,000. That is scar §2.18's guarantee paying for a block of prose,
106
+ * and it is the same measurement that kept the still-forming line out of the
107
+ * default switch (NOTES §12a) — applied to the page this time.
108
+ *
109
+ * Widest measured furniture: 444 bytes. 512 is that plus room for a line to
110
+ * gain a word.
111
+ */
112
+ export const PAGE_FLOOR_RESERVE_BYTES = 512;
113
+
114
+ /**
115
+ * HOW MANY OF THE DELIVERY'S RESERVES ARE HELD UNDER THE SHARE RULE
116
+ * (`handoff/#reserveBytes`), beside the preface: the handoff pointer with its
117
+ * "Last here" line, and "Work here" with the "Last said here" line beside it
118
+ * (2026-10-11, one term; `counterpart.ts#wakeReserveBytes` and
119
+ * `#workReserveBytes`). Each is at most an eighth of the ceiling and never past
120
+ * `HANDOFF_RESERVE_MAX_BYTES`. A third reserve there is a third here, or the
121
+ * page's limit below promises room the wake does not have — a test holds the
122
+ * root to `deliveryReserveBound`.
123
+ */
124
+ export const DELIVERY_SHARED_RESERVES = 2;
125
+
126
+ /**
127
+ * THE MOST THE DELIVERY CAN HOLD BACK FROM A HOST CEILING, in bytes
128
+ * (2026-10-09): the preface's reserve and `DELIVERY_SHARED_RESERVES` terms at
129
+ * the share rule's widest. What the root subtracts on a given day is usually
130
+ * less; this is the bound the page's limit is sized under. Pure.
131
+ */
132
+ export function deliveryReserveBound(budgetBytes: number): number {
133
+ const share = Math.max(
134
+ 0,
135
+ Math.min(HANDOFF_RESERVE_MAX_BYTES, Math.floor(budgetBytes / HANDOFF_RESERVE_MIN_BUDGET_MULTIPLE)),
136
+ );
137
+ return PREFACE_RESERVE_BYTES + DELIVERY_SHARED_RESERVES * share;
138
+ }
139
+
140
+ /**
141
+ * THE END LINE OF EACH RUNG (2026-10-10). Fixed words, so the top line's
142
+ * quote of it costs a known number of bytes and a reader can match it
143
+ * exactly. Printed after the page's dateline. The one-line rung has none: it
144
+ * is its own top line.
145
+ */
146
+ export const PAGE_END_LINES: Readonly<Record<Exclude<PageRung, "line">, string>> = {
147
+ whole: "(End of my page.)",
148
+ short: "(End of the short version.)",
149
+ outline: "(End of the outline.)",
150
+ headings: "(End of the headings.)",
151
+ };
152
+
153
+ /** The end line a rung prints, or null for the one-line rung. */
154
+ export function pageEndLine(rung: PageRung): string | null {
155
+ return rung === "line" ? null : PAGE_END_LINES[rung];
156
+ }
157
+
158
+ /** Both doors to the whole page, in the words every rung uses. */
159
+ const PAGE_DOORS = "the self_page tool or 'counterparts self-page'";
160
+
161
+ /**
162
+ * THE TOP LINE OF EACH RUNG (2026-10-10): what follows, the page's size, the
163
+ * exact line it ends with, and — if that line is missing — that it was cut
164
+ * on the way, and both doors to the whole page. It is what protects against
165
+ * the cuts this package does not make: a host's preview keeps the head of
166
+ * what it was handed, so the top line survives the cut it describes.
167
+ * `wholeBytes` is the page's own size, whatever the rung shows. Plain words,
168
+ * for whoever reads the wake. Null on the one-line rung.
169
+ */
170
+ export function pageTopLine(rung: PageRung, wholeBytes: number): string | null {
171
+ const n = groupDigits(wholeBytes);
172
+ const end = pageEndLine(rung);
173
+ if (end === null) return null;
174
+ const ends = `It ends with "${end}" — if you don't see that line, it was cut off`;
175
+ switch (rung) {
176
+ case "whole":
177
+ return `(My page, ${n} bytes. ${ends}: read it whole with ${PAGE_DOORS}.)`;
178
+ case "short":
179
+ return `(The short version of my ${n}-byte page, too long for this wake. ${ends}. Read the whole page with ${PAGE_DOORS}.)`;
180
+ case "outline":
181
+ 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}.)`;
182
+ case "headings":
183
+ return `(My page is ${n} bytes, too long for this wake: here are its section headings. ${ends}. Read the whole page with ${PAGE_DOORS}.)`;
184
+ case "line":
185
+ return null;
186
+ }
187
+ }
188
+
189
+ /** Each rung's top line (and the last rung's one line), as a reader finds it again. */
190
+ const PAGE_TOP_READERS: readonly (readonly [PageRung, RegExp])[] = [
191
+ ["whole", /^\(My page, ([\d,]+) bytes\. It ends with "/],
192
+ ["short", /^\(The short version of my ([\d,]+)-byte page, too long for this wake\./],
193
+ ["outline", /^\(My page is ([\d,]+) bytes, too long for this wake: here is each section's heading and first sentence\./],
194
+ ["headings", /^\(My page is ([\d,]+) bytes, too long for this wake: here are its section headings\./],
195
+ ["line", /^\(My page is (\d+) bytes — no room for it (?:whole )?in this wake\./],
196
+ ];
197
+
198
+ /**
199
+ * WHICH RUNG A WAKE PRINTED THE PAGE ON, read back off its own words
200
+ * (2026-10-10) — for a reader of a published bundle that has no render row
201
+ * (the dashboard's wake costs). The first top line found, and the page's
202
+ * size it states; null when the wake carries none (no page, or a bundle
203
+ * published before the ladder). Kept beside `pageTopLine` so the wording and
204
+ * its reader change together; a test round-trips every rung. Pure.
205
+ */
206
+ export function readPageTopLine(text: string): { rung: PageRung; wholeBytes: number } | null {
207
+ for (const line of text.split("\n")) {
208
+ for (const [rung, re] of PAGE_TOP_READERS) {
209
+ const m = re.exec(line);
210
+ if (m !== null) return { rung, wholeBytes: Number((m[1] ?? "0").replace(/,/g, "")) };
211
+ }
212
+ }
213
+ return null;
214
+ }
215
+
216
+ /**
217
+ * A LINE OF THE WAKE'S OWN FRAME AROUND THE PAGE (review of #363): a rung's
218
+ * top line or end line, or the one line, standing whole on a line of its own.
219
+ * A session that copies its page out of the wake and back through a writer
220
+ * would otherwise store them, and every wake after would print a stale size
221
+ * and an end line in the middle of the page — after which a cut would look
222
+ * whole. Left out where the page is written and where it is rendered, like
223
+ * its datelines (`Self#ownWords`). A sentence that only mentions one is not
224
+ * one. Pure.
225
+ */
226
+ export function isPageFrameLine(line: string): boolean {
227
+ const t = line.trim();
228
+ if (!t.startsWith("(") || !t.endsWith(")")) return false;
229
+ if ((Object.values(PAGE_END_LINES) as readonly string[]).includes(t)) return true;
230
+ return PAGE_TOP_READERS.some(([, re]) => re.test(t));
231
+ }
232
+
233
+ /**
234
+ * THE ROOM A PAGE BLOCK TAKES in "Who I am", in bytes: its top line, its text
235
+ * and its end line, with the newlines that join them. The dateline is not
236
+ * counted here — it is furniture, inside `PAGE_FLOOR_RESERVE_BYTES`. Pure.
237
+ */
238
+ export function pageBlockBytes(block: Pick<PageBlock, "top" | "text" | "end">): number {
239
+ return (
240
+ byteLength(block.text) +
241
+ (block.top === null ? 0 : byteLength(block.top) + 1) +
242
+ (block.end === null ? 0 : byteLength(block.end) + 1)
243
+ );
244
+ }
245
+
246
+ /**
247
+ * THE MOST THE TOP AND END LINES TAKE beside the page itself, in bytes
248
+ * (2026-10-10) — on the two rungs a writer writes for, `whole` and `short`,
249
+ * at a size wider than the write ceiling lets the top line state (999,999
250
+ * bytes against 16,384). Structural, not tunable, and measured: the widest is
251
+ * the short version's, 261, and a test holds both under this. It is paid for
252
+ * in the page's room (`pageRoomBytes`), so the room the writer is told is the
253
+ * room the page itself has, top and end lines already counted. (The two
254
+ * mechanical rungs' frames are wider — no writer aims at them, and the wake
255
+ * measures every rung exactly.)
256
+ */
257
+ export const PAGE_FRAME_RESERVE_BYTES = 264;
258
+
259
+ /**
260
+ * THE PAGE THE WAKE PRINTS WHOLE at a host ceiling, whatever the delivery
261
+ * reserves that day, in bytes (2026-10-09): the ceiling, less the most the
262
+ * delivery can hold back (`deliveryReserveBound`), less the furniture the wake
263
+ * wraps the page in (`PAGE_FLOOR_RESERVE_BYTES`), less its top and end lines
264
+ * (`PAGE_FRAME_RESERVE_BYTES`, 2026-10-10). `Self#pageBlock` prints a page
265
+ * whole whenever it fits the room the composition actually has, which is
266
+ * never less than this. A short version within it prints whole the same way.
267
+ * Grows with the ceiling. Pure.
268
+ */
269
+ export function pageRoomBytes(hostBudgetBytes: number): number {
270
+ return hostBudgetBytes - deliveryReserveBound(hostBudgetBytes) - PAGE_FLOOR_RESERVE_BYTES - PAGE_FRAME_RESERVE_BYTES;
271
+ }
272
+
273
+ /**
274
+ * THE HOST CEILING THE PAGE'S LIMIT IS SIZED AGAINST, in bytes — the one
275
+ * `install` writes when nobody names one (`adapters/cli/commands.ts`'s
276
+ * `DEFAULT_BUDGET_BYTES` is this constant), and the one every host reads
277
+ * today: Claude Code's hooks and Claude Desktop's `wake` tool deliver the same
278
+ * bundle, composed at the configuration's `injectionBudgetBytes`.
279
+ *
280
+ * NOT a ceiling anything composes against: scar §2.18 holds, and a host that
281
+ * reported none still composes no wake. It sizes one write limit, below.
282
+ */
283
+ export const PAGE_HOST_BUDGET_BYTES = 9_000;
284
+
285
+ /**
286
+ * THE SELF PAGE'S ROOM, in bytes (2026-10-09; a target, not a limit, since
287
+ * 2026-10-10): `pageRoomBytes` at `PAGE_HOST_BUDGET_BYTES`. One number for
288
+ * both ends, derived rather than chosen, so what the writer is told and what
289
+ * the wake guarantees cannot drift apart: a page within it prints whole, byte
290
+ * for byte, top and end lines included, at that ceiling or a larger one,
291
+ * under the widest reserves the delivery can take.
292
+ *
293
+ * The writer is told it as a TARGET ("aim under N bytes"), and a page past it
294
+ * is kept whole — refused only past the write ceiling (`PAGE_MAX_BYTES`,
295
+ * 16,384). Past the room the wake steps down the ladder (`PageRung`) on a day
296
+ * it cannot hold the page, so the writer is asked for a short version within
297
+ * this same number, written with the page.
298
+ *
299
+ * Why one number: #350's second reviewer measured the old pair apart — the
300
+ * wake's cap was `min(6,144, budget − 512)`, which under the widest reserves at
301
+ * 9,000 is 6,078, while the writer accepted up to 16,384 — so a page between
302
+ * them was cut. #358 then refused every page past the room, and the page's
303
+ * history showed the stopgap losing by a few hundred bytes each time (7,012,
304
+ * 6,767, then 6,085, each trimmed by hand).
305
+ */
306
+ export const PAGE_ROOM_BYTES = pageRoomBytes(PAGE_HOST_BUDGET_BYTES);
307
+
308
+ /**
309
+ * THE LAST RUNG (2026-10-09): the one short line a wake with no room for any
310
+ * other prints instead of the page — never a fragment of it. It names the
311
+ * page's size and both doors, so it is its own top line.
312
+ */
313
+ export function pageTooLargeLine(bytes: number): string {
314
+ 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'.)`;
315
+ }