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,957 @@
1
+ /**
2
+ * THE HANDOFF — where the work in THIS directory stands, for the next session
3
+ * that opens here.
4
+ *
5
+ * It is not a memory, and that is the whole of its design. A memory is an
6
+ * interpretation of what was learned; a handoff is working context — "what I was
7
+ * doing here" — which is true for a fortnight and then is not true at all. v1
8
+ * had the same lane under the name `task-state`, expiring; the spec's §6.4 is
9
+ * where it comes back, and the owner's words for why (§15 item 6) are that today
10
+ * he types "prep a handoff so we can pick up from here in a new session" and
11
+ * wants that to happen on its own.
12
+ *
13
+ * **Never a memory** — every clause below is a mechanism, not a promise:
14
+ *
15
+ * - **Not recalled.** `recall/activate.ts` skips the row in the scan, the way
16
+ * it skips the self page, and `creditReferences` refuses it a use even when
17
+ * a session expands it by id. Nothing here ever accrues `uses` or
18
+ * `reinforced_days`, so `physics#promotionEligibility` — which needs
19
+ * reinforcement on N distinct lived days — can never be satisfied and the
20
+ * row can never cross into the identity band.
21
+ * - **Not consolidated, never identity, never in "Who I am".** `scanActive`
22
+ * lists `{ type: "memory" }` and this is a schema row, so no briefing lane
23
+ * can reach it. The pointer the wake prints is FURNITURE, like the page and
24
+ * the day-0 line: the lane counts and the sentinel's `elements=` are
25
+ * untouched by it.
26
+ * - **Exempt from dedup**, free, by `sleep/types.ts#isSchemaRow`: a schema row
27
+ * is not a duplicate candidate.
28
+ * - **Invisible to `schemas/`**: `toMetaRecord` returns null for any role but
29
+ * entity, belief and current-state, so the index build skips it.
30
+ * - **It is let go by the ordinary means.** The row is NOT `protected` — the
31
+ * one thing the self page is and this is not. It is born in the episodic
32
+ * band with nothing on any salience dimension, so it decays like anything
33
+ * else and `physics#pruneVerdict` archives it once it is under the floor and
34
+ * has dwelt `D_FLOOR_DAYS`. Nothing new forgets it; the existing forgetting
35
+ * does.
36
+ *
37
+ * **One live pointer per directory.** A newer handoff for the same scope is an
38
+ * ordinary `store.revise` of the SAME row, so the one it replaces becomes an
39
+ * ordinary version and the row keeps its whole chain — the self page's
40
+ * precedent (`self/page.ts`, "ONE ROW FOR THE LIFE OF THE PAGE"), chosen over an
41
+ * archived row because a superseded row is one more thing `revise`'s readers
42
+ * have to find and because `pruneSupersededVersions` already bounds versions at
43
+ * the ordinary retention. Two sessions ending at once: last writer wins, and the
44
+ * loser is kept as the version underneath it.
45
+ *
46
+ * **It expires in LIVED days** (`store.livedDay()`), not calendar days, because
47
+ * a fortnight of holidays is not a fortnight of work. An expired handoff stops
48
+ * being shown and stops being written over: the row is simply left to the prune.
49
+ */
50
+ import type { ProseDoc, Store } from "../store/index.js";
51
+
52
+ /** The `meta.role` that makes a schema row a handoff. One per scope. */
53
+ export const HANDOFF_ROLE = "handoff";
54
+
55
+ /**
56
+ * The `kind` the row carries. A handoff is about a DIRECTORY — a place of work —
57
+ * and `kind` is the row's subject everywhere else in the store (the self page is
58
+ * `kind: "self"`). It also keeps the recall scan's exemption cheap: the prose
59
+ * read is gated on `type === "schema" && kind === "place"`, so only schema rows
60
+ * about places pay for it.
61
+ */
62
+ export const HANDOFF_KIND = "place";
63
+
64
+ /** The durable row every accepted handoff leaves. Read by `fired`. */
65
+ export const HANDOFF_WRITTEN_EVENT = "handoff.written";
66
+
67
+ /** The durable row every pointer shown at a wake leaves. Read by `fired`. */
68
+ export const HANDOFF_SHOWN_EVENT = "handoff.shown";
69
+
70
+ /**
71
+ * The durable row every REFUSED handoff leaves, beside the accepted ones rather
72
+ * than instead of them — owner ruling 2's corollary (2026-09-18): a cap reports
73
+ * what it refused where the owner will see it.
74
+ */
75
+ export const HANDOFF_REFUSED_EVENT = "handoff.refused";
76
+
77
+ /**
78
+ * The durable row a RETIRED pointer leaves. A session that finished the work
79
+ * says so by sending the field empty, and "there is nothing to pick up here
80
+ * any more" is a fact about this directory worth one row.
81
+ */
82
+ export const HANDOFF_CLEARED_EVENT = "handoff.cleared";
83
+
84
+ /**
85
+ * THE WRITE CAP. Refused past it, never cut: what gets cut at write time is the
86
+ * only copy (the page's rule, `self/index.ts#revisePage`). A handoff is a
87
+ * paragraph or two about where a directory stands — 2 KB is a generous ceiling
88
+ * for that and a small one against the 16 KB the page may have.
89
+ */
90
+ export const HANDOFF_MAX_BYTES = 2048;
91
+
92
+ /** The excerpt's cap in the pointer line. The body is never shown whole at a
93
+ * wake; the id is the door to the whole of it. */
94
+ export const HANDOFF_EXCERPT_BYTES = 160;
95
+
96
+ /**
97
+ * THE CEILING ON THE RESERVE, in bytes — the widest block this module can
98
+ * produce, measured by a test at a full-width excerpt, a real id and a six-digit
99
+ * lived day. It is a CEILING and not the reserve: see `reserveBytes`.
100
+ */
101
+ export const HANDOFF_RESERVE_MAX_BYTES = 448;
102
+
103
+ /**
104
+ * Slack on top of the block that actually exists, so a reserve taken at one
105
+ * boundary still covers the block delivered at the next wake. Only two things
106
+ * move between them — the days-left number gains or loses a digit, and a
107
+ * cleared-then-rewritten pointer changes length — and the second is bounded by
108
+ * the reserve's own ceiling.
109
+ */
110
+ export const HANDOFF_RESERVE_MARGIN_BYTES = 48;
111
+
112
+ /**
113
+ * THE SHARE RULE — the reserve is taken only when the budget is at least this
114
+ * many times the reserve.
115
+ *
116
+ * The adversarial review measured what the flat 448-byte reserve cost
117
+ * (MAJOR-1): at a 1,200-byte ceiling a session in a directory with NO handoff
118
+ * lost 4 of its 6 identity elements, at 2,000 it lost 4 of 13, at 3,000 five of
119
+ * 23 — because the reserve is store-wide and the bundle is one. At the budget
120
+ * the parallel run uses (9,000) the lane caps bind first and the cost is zero.
121
+ *
122
+ * A pointer is a fortnight of working context. It is not worth a third of a
123
+ * small wake's memories, and on a ceiling that tight the honest answer is to
124
+ * carry no pointer at all — which is what returning 0 does: nothing is
125
+ * reserved, nothing is trimmed, and the splice at delivery simply finds no room
126
+ * and drops the pointer whole. Eight is chosen so that the reserve can never
127
+ * cost more than an eighth of the bundle, which at the measured block size
128
+ * turns the reserve on from about 2,400 bytes up.
129
+ *
130
+ * One comparison, not a second budgeter: nothing here decides what to trim.
131
+ */
132
+ export const HANDOFF_RESERVE_MIN_BUDGET_MULTIPLE = 8;
133
+
134
+ /**
135
+ * THE ROOM THE POINTER TAKES IN THE WAKE — what `Counterpart` subtracts from the
136
+ * compose budget at a boundary, beside `PREFACE_RESERVE_BYTES`.
137
+ *
138
+ * Three properties, in the order they matter:
139
+ *
140
+ * 1. **No live handoff anywhere ⇒ zero.** That is what makes a store with no
141
+ * handoff compose the wake it composed before this module existed, byte
142
+ * for byte.
143
+ * 2. **Sized to the block that EXISTS**, not to the widest one that could. The
144
+ * review measured 295 bytes of ceiling left unused at budget 2,000 — five
145
+ * memories spent to buy two lines and a third of a kilobyte of nothing.
146
+ * The boundary already knows which handoffs are live and what their
147
+ * pointers say, so it can ask.
148
+ * 3. **Off entirely below the share rule**, because the reserve is store-wide
149
+ * and the bundle is one: a directory that will never be shown a pointer
150
+ * pays for it otherwise, and on a small ceiling it pays in memories.
151
+ *
152
+ * Pure. The caller passes the live blocks' byte lengths and its ceiling.
153
+ */
154
+ export function reserveBytes(blockBytes: readonly number[], budgetBytes: number): number {
155
+ const widest = blockBytes.reduce((n, b) => Math.max(n, b), 0);
156
+ if (widest <= 0) return 0;
157
+ const want = Math.min(widest + HANDOFF_RESERVE_MARGIN_BYTES, HANDOFF_RESERVE_MAX_BYTES);
158
+ return want * HANDOFF_RESERVE_MIN_BUDGET_MULTIPLE <= budgetBytes ? want : 0;
159
+ }
160
+
161
+ /**
162
+ * How long a pointer shows, in LIVED days since it was written. About a
163
+ * fortnight of use (spec §15 item 6). After it the pointer stops showing; the
164
+ * row is then let go by the ordinary prune, which is the only forgetting this
165
+ * module has.
166
+ */
167
+ export const HANDOFF_LIFE_DAYS = 14;
168
+
169
+ /** Prose meta the row keeps beside its body. */
170
+ export const HANDOFF_META_SCOPE = "scope";
171
+ export const HANDOFF_META_WRITTEN_ON = "writtenOn";
172
+ export const HANDOFF_META_WRITTEN_DAY = "writtenDay";
173
+ export const HANDOFF_META_SESSION = "session";
174
+
175
+ /**
176
+ * The wake's own structural markers, refused in a handoff body for the reason
177
+ * `revisePage` refuses them: the excerpt is spliced INSIDE the wake block, so a
178
+ * body carrying an end-of-wake comment would put a false end in front of real
179
+ * lanes for the model reading it. The constant's owner is
180
+ * `self/index.ts#WAKE_MARKER`; it is spelled here rather than imported because
181
+ * `handoff/` depends on `store/` and nothing else.
182
+ */
183
+ export const WAKE_MARKER = "<!-- counterparts:wake";
184
+
185
+ export type HandoffRefusal =
186
+ | "observer"
187
+ | "no-scope"
188
+ | "empty"
189
+ | "empty-after-gate"
190
+ | "not-text"
191
+ | "nothing-to-clear"
192
+ | "no-room"
193
+ | "store-refused"
194
+ | "too-large"
195
+ | "forged-markers"
196
+ | "gate-refused";
197
+
198
+ export interface HandoffWrite {
199
+ readonly written: boolean;
200
+ /** `created`, `revised` or `cleared` when written; the refusal otherwise. */
201
+ readonly reason: HandoffRefusal | "created" | "revised" | "cleared";
202
+ readonly id: string | null;
203
+ readonly version: number | null;
204
+ readonly bytes: number;
205
+ /** The gate that turned it away, when one did. */
206
+ readonly gate: { readonly gate: string; readonly reason: string } | null;
207
+ /** Set when the battery took something out on the way in (a credential). */
208
+ readonly redacted: { readonly gate: string; readonly bytesBefore: number } | null;
209
+ /** Lived days this pointer will show for, counting the day it was written. */
210
+ readonly showsForDays: number | null;
211
+ }
212
+
213
+ export interface Handoff {
214
+ readonly id: string;
215
+ readonly scope: string;
216
+ /** The handoff, verbatim. Never truncated here — see `excerpt`. */
217
+ readonly body: string;
218
+ readonly bytes: number;
219
+ /** The calendar date it was written, `YYYY-MM-DD`; "" when unrecorded. */
220
+ readonly writtenOn: string;
221
+ /** The lived day it was written; null when unrecorded. */
222
+ readonly writtenDay: number | null;
223
+ readonly session: string | null;
224
+ /** `revision` on the row: 0 for one written once and never replaced. */
225
+ readonly version: number;
226
+ }
227
+
228
+ /** The gate every entrance passes (SEAMS H). Shaped like `bridge.EpisodeGate`,
229
+ * restated as a parameter so this module imports no gate of its own. */
230
+ export type HandoffGate = (input: {
231
+ text: string;
232
+ handles: readonly string[];
233
+ sessionId: string;
234
+ }) => { ok: true; text?: string } | { ok: false; gate: string; reason: string };
235
+
236
+ function byteLengthOf(s: string): number {
237
+ return new TextEncoder().encode(s).length;
238
+ }
239
+
240
+ /**
241
+ * A statement is a line here, as it is in the wake (`briefing.ts#flatten`) —
242
+ * AND nothing in it can steer a terminal or a reader.
243
+ *
244
+ * `\s+` is `\n \r \t` and friends. It is not NUL, not ESC, and not U+202E:
245
+ * measured by the adversarial review (MINOR-4), a right-to-left override in a
246
+ * handoff reversed the display of everything after it in the delivered wake for
247
+ * any reader that honours bidi, and an ANSI escape landed in a prompt that is
248
+ * sometimes rendered in a terminal. Line injection was already blocked — the CR
249
+ * case folds here and only one line is ever excerpted — and this closes the
250
+ * rest of the class in the same place, so there is one function to check.
251
+ *
252
+ * `\p{Cc}` is the C0/C1 controls, `\p{Cf}` the format characters (the bidi
253
+ * overrides and embeddings, the zero-width joiner, the byte-order mark). They
254
+ * are DROPPED rather than replaced: a handoff is prose about work, and a
255
+ * visible substitute for an invisible character is noise in a two-line pointer.
256
+ */
257
+ export function flatten(text: string): string {
258
+ // A control that IS whitespace becomes a space — `\n` must not join two words
259
+ // into one — and everything else in the two classes is dropped. Then the
260
+ // ordinary collapse, so a dropped character cannot leave a double space.
261
+ return text
262
+ .replace(/[\p{Cc}\p{Cf}]/gu, (c) => (/\s/u.test(c) ? " " : ""))
263
+ .replace(/\s+/g, " ")
264
+ .trim();
265
+ }
266
+
267
+ // ── finding it ──────────────────────────────────────────────────────────────
268
+
269
+ /**
270
+ * Is this document a handoff? Read STRUCTURALLY by `recall/` for the reason
271
+ * `isSelfPage` is: a shape check that fails reads as "not a handoff", which is
272
+ * the direction that only ever costs a candidate slot.
273
+ */
274
+ export function isHandoffDoc(doc: ProseDoc): boolean {
275
+ return doc.type === "schema" && doc.meta["role"] === HANDOFF_ROLE;
276
+ }
277
+
278
+ /** `isHandoffDoc` by id, for callers holding rows rather than documents. */
279
+ export function isHandoffRow(store: Store, id: string): boolean {
280
+ const row = store.row(id);
281
+ if (row === undefined || row.type !== "schema" || row.kind !== HANDOFF_KIND) return false;
282
+ try {
283
+ return isHandoffDoc(store.readProse(id));
284
+ } catch {
285
+ return false;
286
+ }
287
+ }
288
+
289
+ /** One live handoff row, read far enough to rank it. */
290
+ interface LiveRow {
291
+ readonly id: string;
292
+ readonly scope: string;
293
+ readonly writtenDay: number | null;
294
+ }
295
+
296
+ /**
297
+ * Every live handoff row in the store, whatever its scope, with the two fields
298
+ * every caller here ranks by. One walk, one prose read per row.
299
+ */
300
+ export function liveHandoffRows(store: Store): LiveRow[] {
301
+ const out: LiveRow[] = [];
302
+ for (const id of store.list({ type: "schema", kind: HANDOFF_KIND, archived: false })) {
303
+ try {
304
+ const meta = store.readProse(id).meta;
305
+ if (meta["role"] !== HANDOFF_ROLE) continue;
306
+ const scope = meta[HANDOFF_META_SCOPE];
307
+ const day = meta[HANDOFF_META_WRITTEN_DAY];
308
+ out.push({
309
+ id,
310
+ scope: typeof scope === "string" ? scope : "",
311
+ writtenDay: typeof day === "number" ? day : null,
312
+ });
313
+ } catch {
314
+ continue;
315
+ }
316
+ }
317
+ return out;
318
+ }
319
+
320
+ /** Ids only, for the callers that do not rank. */
321
+ export function handoffRows(store: Store): string[] {
322
+ return liveHandoffRows(store).map((r) => r.id);
323
+ }
324
+
325
+ /**
326
+ * THE NEWEST live row per scope. Two rows for one directory should be
327
+ * impossible — `write` mints only when `findHandoffRow` returns null — but
328
+ * `findHandoffRow` → `put` is not one transaction, and the deployment is one
329
+ * process per hook and one server per session, so a cross-process race is
330
+ * narrow rather than closed (adversarial review MINOR-8). When it happens the
331
+ * loser used to be picked by `list()`'s id ordering, silently, and went on
332
+ * holding the reserve open while being invisible to every read.
333
+ *
334
+ * Newest `writtenDay` wins, id as the tiebreak so the answer is stable. The
335
+ * losers are named so `write` can retire them.
336
+ */
337
+ export function newestPerScope(rows: readonly LiveRow[]): Map<string, LiveRow> {
338
+ const best = new Map<string, LiveRow>();
339
+ for (const r of rows) {
340
+ if (r.scope.length === 0) continue;
341
+ const held = best.get(r.scope);
342
+ if (
343
+ held === undefined ||
344
+ (r.writtenDay ?? -1) > (held.writtenDay ?? -1) ||
345
+ ((r.writtenDay ?? -1) === (held.writtenDay ?? -1) && r.id > held.id)
346
+ ) {
347
+ best.set(r.scope, r);
348
+ }
349
+ }
350
+ return best;
351
+ }
352
+
353
+ /**
354
+ * THIS DIRECTORY'S row, live or expired, or null — the newest one when a race
355
+ * has left more than one.
356
+ *
357
+ * Box 2 has no meta query (`schemas/INTERFACE-GAPS §2`), so the scope match is a
358
+ * body read, exactly as `findSelfPage` reads for the role.
359
+ */
360
+ export function findHandoffRow(store: Store, scope: string): string | null {
361
+ const want = scope.trim();
362
+ if (want.length === 0) return null;
363
+ return newestPerScope(liveHandoffRows(store)).get(want)?.id ?? null;
364
+ }
365
+
366
+ /** The OTHER live rows for this scope — a race's losers, which `write` retires. */
367
+ export function duplicateHandoffRows(store: Store, scope: string): string[] {
368
+ const want = scope.trim();
369
+ if (want.length === 0) return [];
370
+ const rows = liveHandoffRows(store).filter((r) => r.scope === want);
371
+ const winner = newestPerScope(rows).get(want)?.id ?? null;
372
+ return rows.filter((r) => r.id !== winner).map((r) => r.id);
373
+ }
374
+
375
+ /** The handoff as a value, or null. A row whose prose will not read is absent
376
+ * to every reader here, never a throw (`self/` §5 G7's rule, borrowed). */
377
+ export function readHandoff(store: Store, scope: string): Handoff | null {
378
+ const id = findHandoffRow(store, scope);
379
+ return id === null ? null : handoffOf(store, { id, scope, writtenDay: null });
380
+ }
381
+
382
+ /** The same read, for a caller that has already walked and holds the row. */
383
+ function handoffOf(store: Store, live: LiveRow): Handoff | null {
384
+ const id = live.id;
385
+ let doc: ProseDoc;
386
+ try {
387
+ doc = store.readProse(id);
388
+ } catch {
389
+ return null;
390
+ }
391
+ const scope = live.scope;
392
+ const row = store.row(id);
393
+ const writtenDay = doc.meta[HANDOFF_META_WRITTEN_DAY];
394
+ const writtenOn = doc.meta[HANDOFF_META_WRITTEN_ON];
395
+ const session = doc.meta[HANDOFF_META_SESSION];
396
+ return {
397
+ id,
398
+ scope,
399
+ body: doc.body,
400
+ bytes: byteLengthOf(doc.body),
401
+ writtenOn: typeof writtenOn === "string" ? writtenOn : "",
402
+ writtenDay: typeof writtenDay === "number" ? writtenDay : null,
403
+ session: typeof session === "string" && session.length > 0 ? session : null,
404
+ version: row?.revision ?? 0,
405
+ };
406
+ }
407
+
408
+ /**
409
+ * Has this one run out? A handoff with no recorded lived day has: an undated
410
+ * pointer cannot be aged, and showing one forever is the failure the expiry
411
+ * exists to prevent.
412
+ */
413
+ export function expired(h: Handoff, day: number, lifeDays = HANDOFF_LIFE_DAYS): boolean {
414
+ if (h.writtenDay === null) return true;
415
+ return daysLeft(h.writtenDay, day, lifeDays) <= 0;
416
+ }
417
+
418
+ /**
419
+ * LIVED DAYS THIS POINTER HAS LEFT, counting the day it was written as the
420
+ * first of them. Zero or less means it has run out.
421
+ *
422
+ * The first draft was `day - writtenDay > lifeDays`, which showed the pointer on
423
+ * days 0…14 — fifteen days, while every word around it said fourteen — and made
424
+ * `pointerDoor` print "It stops showing after 0 more days of use." on the last
425
+ * one, which reads as a bug to anyone who sees it (adversarial review NIT 1 and
426
+ * 2). One function, so the constant, the prose and the sentence cannot disagree.
427
+ */
428
+ export function daysLeft(writtenDay: number, day: number, lifeDays = HANDOFF_LIFE_DAYS): number {
429
+ return lifeDays - (day - writtenDay);
430
+ }
431
+
432
+ // ── what the wake prints ────────────────────────────────────────────────────
433
+
434
+ /** The marker a cut excerpt ends with. Three bytes, and the cut reserves them. */
435
+ export const ELLIPSIS = "\u2026";
436
+
437
+ /**
438
+ * A heading line \u2014 Markdown ATX or a Setext underline \u2014 or a blank one. Not
439
+ * what the pointer is for; see `excerpt`.
440
+ */
441
+ function isHeading(line: string): boolean {
442
+ const t = line.trim();
443
+ return t.length === 0 || /^#{1,6}\s/.test(t) || /^[=-]{3,}$/.test(t);
444
+ }
445
+
446
+ /** The first line of a handoff, flattened and cut to fit, with an ellipsis when
447
+ * it was cut. Cuts at a word where one is near the end, never mid-word when a
448
+ * space is within the last fifth of the room. */
449
+ export function excerpt(body: string, capBytes = HANDOFF_EXCERPT_BYTES): string {
450
+ const lines = body.split("\n");
451
+ // The first line with SUBSTANCE on it: not blank, and not the title the
452
+ // writer put above the substance. A model asked for a handoff writes a titled
453
+ // note about as often as a bare paragraph, and `"# Handoff\n\nThe empty-input
454
+ // case still fails…"` produced a pointer that said nothing at all
455
+ // (adversarial review MINOR-6).
456
+ const line = lines.find((l) => !isHeading(l)) ?? lines.find((l) => l.trim().length > 0) ?? body;
457
+ const first = flatten(line);
458
+ if (byteLengthOf(first) <= capBytes) return first;
459
+ // The ellipsis is THREE bytes, not one: `…` is U+2026. Reserving a character
460
+ // rather than its bytes is how a cap that says 160 renders 161 — measured,
461
+ // not reasoned about.
462
+ const room = Math.max(0, capBytes - byteLengthOf(ELLIPSIS));
463
+ const bytes = new TextEncoder().encode(first);
464
+ const prefix = new TextDecoder("utf-8", { fatal: false }).decode(bytes.slice(0, room));
465
+ const clean = prefix.replace(/�+$/u, "");
466
+ const space = clean.lastIndexOf(" ");
467
+ const kept = space > clean.length * 0.8 ? clean.slice(0, space) : clean;
468
+ return `${kept.trimEnd()}${ELLIPSIS}`;
469
+ }
470
+
471
+ /** The pointer's first line: the date and the first line of what was written. */
472
+ export function pointerLine(h: Handoff, capBytes = HANDOFF_EXCERPT_BYTES): string {
473
+ const when = /^\d{4}-\d{2}-\d{2}$/.test(h.writtenOn.trim()) ? h.writtenOn.trim() : "an unrecorded date";
474
+ return `Where I left off in this directory (${when}): ${excerpt(h.body, capBytes)}`;
475
+ }
476
+
477
+ /** The pointer's second line: the door to the whole of it, and its life. */
478
+ export function pointerDoor(h: Handoff, day: number, lifeDays = HANDOFF_LIFE_DAYS): string {
479
+ const left = h.writtenDay === null ? lifeDays : daysLeft(h.writtenDay, day, lifeDays);
480
+ // Never "0 more days": `pointerBlock` returns null once `daysLeft` reaches 0,
481
+ // so the smallest number this line can print is 1 — the last day it shows.
482
+ const days = left === 1 ? "one more day" : `${Math.max(1, left)} more days`;
483
+ return `(The whole of it is ${h.id} — expand it with the counterparts recall tool. It stops showing after ${days} of use.)`;
484
+ }
485
+
486
+ /**
487
+ * THE BLOCK the wake splices in, or null when this one has run out.
488
+ *
489
+ * Two lines and no heading: the pointer is FURNITURE, and furniture that opens
490
+ * its own section costs a blank line and a heading for two lines of content.
491
+ * Both lines are flattened, so a handoff body can never inject a line into the
492
+ * bundle — the scar `identityCoreLine` carries (a name with newlines in it
493
+ * forged a resolved statement into the wake).
494
+ */
495
+ export function pointerBlock(h: Handoff, day: number, lifeDays = HANDOFF_LIFE_DAYS): string | null {
496
+ if (expired(h, day, lifeDays)) return null;
497
+ return [flatten(pointerLine(h)), flatten(pointerDoor(h, day, lifeDays))].join("\n");
498
+ }
499
+
500
+ // ── the module ──────────────────────────────────────────────────────────────
501
+
502
+ export interface HandoffsOptions {
503
+ readonly store: Store;
504
+ readonly gate: HandoffGate;
505
+ readonly observer?: boolean;
506
+ readonly onEvent?: (e: {
507
+ at: number;
508
+ name: string;
509
+ ref?: string;
510
+ data?: Record<string, string | number | boolean | null>;
511
+ }) => void;
512
+ readonly now?: () => number;
513
+ }
514
+
515
+ export interface WriteInput {
516
+ readonly body: string;
517
+ /** The canonical directory this handoff is about. Required and non-empty. */
518
+ readonly scope: string;
519
+ readonly session?: string | null;
520
+ readonly day?: number;
521
+ }
522
+
523
+ export class Handoffs {
524
+ private readonly store: Store;
525
+ private readonly gate: HandoffGate;
526
+ private readonly observer: boolean;
527
+ private readonly onEvent: HandoffsOptions["onEvent"];
528
+ private readonly nowFn: () => number;
529
+
530
+ constructor(opts: HandoffsOptions) {
531
+ this.store = opts.store;
532
+ this.gate = opts.gate;
533
+ this.observer = opts.observer === true;
534
+ this.onEvent = opts.onEvent;
535
+ this.nowFn = opts.now ?? Date.now;
536
+ }
537
+
538
+ private emit(
539
+ name: string,
540
+ ref?: string,
541
+ data?: Record<string, string | number | boolean | null>,
542
+ ): void {
543
+ this.onEvent?.({
544
+ at: this.nowFn(),
545
+ name,
546
+ ...(ref === undefined ? {} : { ref }),
547
+ ...(data === undefined ? {} : { data }),
548
+ });
549
+ }
550
+
551
+ /** This directory's live, unexpired handoff, or null. */
552
+ read(scope: string, day?: number): Handoff | null {
553
+ const h = readHandoff(this.store, scope);
554
+ if (h === null) return null;
555
+ return expired(h, day ?? this.store.livedDay()) ? null : h;
556
+ }
557
+
558
+ /** This directory's row whatever its age — the door `write` revises. */
559
+ readAny(scope: string): Handoff | null {
560
+ return readHandoff(this.store, scope);
561
+ }
562
+
563
+ /**
564
+ * DOES ANY DIRECTORY HOLD A LIVE POINTER? Kept because it reads as the
565
+ * question it is, and because the doctor and the tests ask it.
566
+ */
567
+ anyLive(day?: number): boolean {
568
+ return this.liveBlockBytes(day).length > 0;
569
+ }
570
+
571
+ /**
572
+ * THE BYTE LENGTHS OF EVERY LIVE POINTER BLOCK, one per DIRECTORY — what the
573
+ * boundary hands `reserveBytes`.
574
+ *
575
+ * Per directory and not per row: a race's loser is invisible to every read,
576
+ * and before `newestPerScope` it went on holding the reserve open until it
577
+ * expired (adversarial review MINOR-8). The walk is bounded by the number of
578
+ * directories the owner has worked in, and it never throws — a store that
579
+ * will not answer reserves nothing, which composes the wake master composes.
580
+ */
581
+ liveBlockBytes(day?: number): number[] {
582
+ const d = day ?? this.store.livedDay();
583
+ const out: number[] = [];
584
+ // ONE walk, not one per directory. The first draft called `readHandoff`
585
+ // per scope, and each of those walks the store again — D+1 walks for D
586
+ // directories, at every boundary, for a number that is the same shape as
587
+ // the one already in hand.
588
+ for (const [, row] of newestPerScope(liveHandoffRows(this.store))) {
589
+ if (row.writtenDay === null || daysLeft(row.writtenDay, d) <= 0) continue;
590
+ const h = handoffOf(this.store, row);
591
+ if (h === null) continue;
592
+ const block = pointerBlock(h, d);
593
+ if (block !== null) out.push(byteLengthOf(block));
594
+ }
595
+ return out;
596
+ }
597
+
598
+ /**
599
+ * THE ONE SEAM THAT WRITES A HANDOFF. Refusals are named and durable, as the
600
+ * page's are: there is no silent no-op on this path.
601
+ */
602
+ write(input: WriteInput): HandoffWrite {
603
+ const day = input.day ?? this.store.livedDay();
604
+ const draft = input.body.replace(/\r\n/g, "\n").trim();
605
+ let bytes = byteLengthOf(draft);
606
+ const scope = input.scope.trim();
607
+ const session = input.session ?? null;
608
+ const none = { id: null, version: null, gate: null, redacted: null, showsForDays: null } as const;
609
+ const refuse = (
610
+ reason: HandoffRefusal,
611
+ detail: Record<string, string | number | boolean> = {},
612
+ extra: Partial<HandoffWrite> = {},
613
+ ): HandoffWrite => this.refuse(reason, { day, session, bytes, ...detail }, { ...none, ...extra });
614
+
615
+ if (this.observer) {
616
+ // The stand-down writes nothing at all, the durable row included: an
617
+ // instrument that logged its own refusal would be changing the store it is
618
+ // reading (observer-mode G3).
619
+ this.emit("handoff.observer.standdown", undefined, { site: "write" });
620
+ return { ...none, written: false, reason: "observer", bytes };
621
+ }
622
+ // NO SCOPE, NO POINTER — and the rule lives HERE rather than at the MCP
623
+ // door, which is what makes the refusal durable (adversarial review
624
+ // MAJOR-2a: the adapter's own short-circuit wrote a ring event and no row,
625
+ // so guarantee 3 was false on the only live entrance).
626
+ //
627
+ // Two shapes of "no place to be about": a host that named no directory at
628
+ // all, and one whose only answer was the STORE'S OWN directory — which is
629
+ // `resolveScope`'s last resort, "a bad answer… kept only because a server
630
+ // with no scope at all cannot deposit". A pointer filed there is about
631
+ // nowhere and every session in every project would be handed it.
632
+ if (scope.length === 0 || sameDirectory(scope, this.store.dir)) {
633
+ return refuse("no-scope", {});
634
+ }
635
+ // AN EMPTY BODY IS A CLEAR, not a refusal, and the caller decides which it
636
+ // meant by what it passed: `write("")` is unreachable from the live door,
637
+ // which routes a present-but-blank field to `clear()`. A direct caller that
638
+ // reaches here with nothing still gets the named, durable refusal.
639
+ if (draft.length === 0) return refuse("empty", {});
640
+ if (bytes > HANDOFF_MAX_BYTES) {
641
+ return refuse("too-large", { bytes, limit: HANDOFF_MAX_BYTES });
642
+ }
643
+ if (draft.includes(WAKE_MARKER)) return refuse("forged-markers", { bytes });
644
+ // THE BATTERY, on the handoff as on the page and the journal (SEAMS H). A
645
+ // handoff is written in a hurry at the end of a session and is exactly the
646
+ // kind of prose a token gets pasted into.
647
+ const verdict = this.gate({ text: draft, handles: [], sessionId: `handoff:${session ?? ""}` });
648
+ if (!verdict.ok) {
649
+ return refuse(
650
+ "gate-refused",
651
+ { bytes, gate: verdict.gate, gateReason: verdict.reason },
652
+ { gate: { gate: verdict.gate, reason: verdict.reason } },
653
+ );
654
+ }
655
+ // THE GATE'S TEXT, and never the draft as a fallback. The first draft read
656
+ // `verdict.text.length > 0 ? verdict.text : draft`, so a gate that ever
657
+ // accepted a body that redacted down to NOTHING would have stored the
658
+ // ORIGINAL, unredacted words — a trapdoor pointing the wrong way
659
+ // (adversarial review MINOR-7). Unreachable today, because
660
+ // `empty-after-redaction` refuses that case first; a latent hole in a
661
+ // redaction path is worth one line whether or not anything can reach it.
662
+ const text = verdict.text ?? draft;
663
+ if (text.length === 0) return refuse("empty-after-gate", {});
664
+ const redacted = text === draft ? null : { gate: "secrets", bytesBefore: bytes };
665
+ bytes = byteLengthOf(text);
666
+
667
+ const meta: Record<string, unknown> = {
668
+ role: HANDOFF_ROLE,
669
+ [HANDOFF_META_SCOPE]: scope,
670
+ [HANDOFF_META_WRITTEN_ON]: this.store.today(),
671
+ [HANDOFF_META_WRITTEN_DAY]: day,
672
+ [HANDOFF_META_SESSION]: session,
673
+ };
674
+ const existing = findHandoffRow(this.store, scope);
675
+ let id: string;
676
+ let version: number;
677
+ // THE STORE'S OWN REFUSALS ARE NAMED TOO. `put` and `revise` refuse inputs
678
+ // of their own — a body that is whitespace or NUL only, a lone surrogate
679
+ // (F5, the floor) — and an uncaught throw here would leave the caller a
680
+ // thrown error and the owner no row, which is MAJOR-2's shape on a
681
+ // different input. The store's verdict is the truth and is reported as
682
+ // such rather than second-guessed: nothing here pre-strips a body to get
683
+ // past a refusal that exists for a reason.
684
+ try {
685
+ if (existing === null) {
686
+ id = this.store.put({
687
+ type: "schema",
688
+ kind: HANDOFF_KIND,
689
+ title: handoffTitle(scope),
690
+ body: text,
691
+ meta,
692
+ learnedOn: this.store.today(),
693
+ // NOT protected, on purpose: this is the one standing row in the
694
+ // store that is meant to be let go, and `protected` is what would
695
+ // stop the prune from ever doing it.
696
+ });
697
+ version = 0;
698
+ } else {
699
+ id = existing;
700
+ version = this.store.revise(id, {
701
+ body: text,
702
+ title: handoffTitle(scope),
703
+ meta,
704
+ reason: "handoff",
705
+ });
706
+ }
707
+ } catch (err) {
708
+ const code = (err as { code?: string }).code;
709
+ return refuse("store-refused", { bytes, code: typeof code === "string" ? code : "UNKNOWN" });
710
+ }
711
+ // THE DWELL CLOCK, RESET. `store.revise` writes the body and a version row
712
+ // and touches no physics column, so a row born on day 1 and rewritten on day
713
+ // 200 still reads `lastUsedDay = 1` — dwell 199, strength under the floor,
714
+ // and `pruneVerdict` archives a pointer that was written this morning.
715
+ // Moving the clock to the write is what makes "a live pointer is never
716
+ // pruned out from under the wake" true rather than hoped for.
717
+ this.store.updatePhysics(id, { lastUsedDay: day });
718
+ // A RACE'S LOSERS ARE RETIRED HERE, where a write for this scope is already
719
+ // happening. `findHandoffRow` now picks the newest, so a duplicate is
720
+ // already invisible to every read; archiving it is what stops it holding
721
+ // the reserve open until it expires (adversarial review MINOR-8).
722
+ for (const stale of duplicateHandoffRows(this.store, scope)) {
723
+ if (stale === id) continue;
724
+ try {
725
+ this.store.archive(stale, "handoff-duplicate");
726
+ this.emit("handoff.duplicate.retired", stale, {});
727
+ } catch {
728
+ /* a duplicate that will not archive is still not the one that is read */
729
+ }
730
+ }
731
+ this.store.appendEvent({
732
+ name: HANDOFF_WRITTEN_EVENT,
733
+ day,
734
+ ref: id,
735
+ payload: {
736
+ // THE SCOPE AS A LENGTH, never the path: telemetry is ids, counts,
737
+ // bytes, reasons and flags, and a directory path is neither (store §5
738
+ // G10). Which directory it was is on the row, where the owner reads it.
739
+ session,
740
+ bytes,
741
+ version,
742
+ created: existing === null,
743
+ ...(redacted === null ? {} : { redacted: true, redactedBy: redacted.gate }),
744
+ lifeDays: HANDOFF_LIFE_DAYS,
745
+ },
746
+ });
747
+ this.emit(HANDOFF_WRITTEN_EVENT, id, {
748
+ bytes,
749
+ version,
750
+ created: existing === null,
751
+ });
752
+ return {
753
+ written: true,
754
+ reason: existing === null ? "created" : "revised",
755
+ id,
756
+ version,
757
+ bytes,
758
+ gate: null,
759
+ redacted,
760
+ showsForDays: HANDOFF_LIFE_DAYS,
761
+ };
762
+ }
763
+
764
+ /**
765
+ * THE POINTER FOR THIS WAKE, or null. Pure — it writes nothing, so a caller
766
+ * that finds no room can drop it without having claimed it was shown.
767
+ */
768
+ pointer(scope: string, day?: number): { block: string; handoff: Handoff } | null {
769
+ const d = day ?? this.store.livedDay();
770
+ const h = this.read(scope, d);
771
+ if (h === null) return null;
772
+ const block = pointerBlock(h, d);
773
+ return block === null ? null : { block, handoff: h };
774
+ }
775
+
776
+ /**
777
+ * The durable row a SHOWN pointer leaves — ONCE per directory per lived day.
778
+ *
779
+ * It was one row per wake, which is consistent with `wake.injected` and is
780
+ * still the wrong shape for the one question the row exists to answer.
781
+ * CONTRACT §8 names `handoff.shown`'s `ageDays` as the measurement that would
782
+ * settle the fortnight; measured, 40 wakes of one session in one directory
783
+ * wrote 40 rows (adversarial review MINOR-2), so that distribution would have
784
+ * been dominated by a session re-waking rather than by distinct pickups.
785
+ *
786
+ * `dedupKey` is the store's own latch and returns 0 when it refuses a repeat,
787
+ * so "recorded" and "already recorded today" stay tellable apart. The key is
788
+ * the ROW's id and the lived day — never the directory, which is a path
789
+ * (§5 G10).
790
+ */
791
+ noteShown(h: Handoff, opts: { bytes: number; session?: string | null; day?: number }): void {
792
+ if (this.observer) {
793
+ this.emit("handoff.observer.standdown", undefined, { site: "noteShown" });
794
+ return;
795
+ }
796
+ const day = opts.day ?? this.store.livedDay();
797
+ let seq = 0;
798
+ try {
799
+ seq = this.store.appendEvent({
800
+ name: HANDOFF_SHOWN_EVENT,
801
+ day,
802
+ ref: h.id,
803
+ dedupKey: `${HANDOFF_SHOWN_EVENT}:${h.id}:${day}`,
804
+ payload: {
805
+ session: opts.session ?? null,
806
+ bytes: opts.bytes,
807
+ ageDays: h.writtenDay === null ? null : day - h.writtenDay,
808
+ version: h.version,
809
+ },
810
+ });
811
+ } catch {
812
+ /* a pointer that was shown and could not be logged was still shown */
813
+ }
814
+ this.emit(HANDOFF_SHOWN_EVENT, h.id, { bytes: opts.bytes, first: seq !== 0 });
815
+ }
816
+
817
+ /**
818
+ * NO ROOM FOR THE POINTER at this ceiling — the documented one-boundary lag,
819
+ * and a tripwire if it ever stops being temporary.
820
+ *
821
+ * It was ring-only, and `Counterpart.emit` pushes to an in-process ring while
822
+ * every hook is its own process, so the exact shape the brief asked the
823
+ * reviewer to hunt — "the pointer stops being delivered and nothing says so" —
824
+ * was real for the whole lag window (adversarial review MINOR-1). It is a
825
+ * REFUSAL row rather than a fourth event name: a cap turning the pointer away
826
+ * is this mechanism working out loud, which is what `handoff.refused` already
827
+ * means. Deduped per row per lived day, so a lag that lasts a day is one row
828
+ * and a lag that lasts a fortnight is fourteen.
829
+ */
830
+ noteNoRoom(h: Handoff, opts: { bytes: number; budget: number; day?: number }): void {
831
+ if (this.observer) return;
832
+ const day = opts.day ?? this.store.livedDay();
833
+ this.refuse(
834
+ "no-room",
835
+ { day, session: null, bytes: opts.bytes, budget: opts.budget },
836
+ { id: h.id, version: null, gate: null, redacted: null, showsForDays: null },
837
+ `${HANDOFF_REFUSED_EVENT}:no-room:${h.id}:${day}`,
838
+ h.id,
839
+ );
840
+ }
841
+
842
+ /**
843
+ * CLEAR THIS DIRECTORY'S POINTER — the retirement that had no door.
844
+ *
845
+ * CONTRACT open question 3, closed: the ask fires up to six times a session,
846
+ * so a session can write "half done" at the first and finish the work by the
847
+ * last, and leaving the field out leaves the stale pointer standing for
848
+ * whoever opens the directory next. A model that means "it is done" reaches
849
+ * for `handoff: ""`, which used to be total silence (adversarial review
850
+ * MAJOR-2b). A PRESENT but blank field is now this.
851
+ *
852
+ * The row is ARCHIVED, which is the ordinary means: the words stay readable
853
+ * on the row for an owner who asks for it by id, every reader here filters
854
+ * `archived: false` so the pointer is gone from the wake and from the
855
+ * reserve, and the next handoff for this directory mints a fresh row rather
856
+ * than reviving a retired one. An ABSENT field still means "leave what
857
+ * stands"; that is the ordinary case and it is right.
858
+ */
859
+ clear(scope: string, opts: { session?: string | null; day?: number } = {}): HandoffWrite {
860
+ const day = opts.day ?? this.store.livedDay();
861
+ const session = opts.session ?? null;
862
+ const none = { id: null, version: null, gate: null, redacted: null, showsForDays: null } as const;
863
+ if (this.observer) {
864
+ this.emit("handoff.observer.standdown", undefined, { site: "clear" });
865
+ return { ...none, written: false, reason: "observer", bytes: 0 };
866
+ }
867
+ const trimmed = scope.trim();
868
+ if (trimmed.length === 0 || sameDirectory(trimmed, this.store.dir)) {
869
+ return this.refuse("no-scope", { day, session, bytes: 0 }, none);
870
+ }
871
+ const h = readHandoff(this.store, trimmed);
872
+ if (h === null) {
873
+ // NOTHING TO CLEAR is not a failure and not a silence: a session that
874
+ // finished work in a directory that never had a pointer said something
875
+ // true, and the row says so.
876
+ return this.refuse("nothing-to-clear", { day, session, bytes: 0 }, none);
877
+ }
878
+ for (const id of [h.id, ...duplicateHandoffRows(this.store, trimmed)]) {
879
+ this.store.archive(id, "handoff-cleared");
880
+ }
881
+ this.store.appendEvent({
882
+ name: HANDOFF_CLEARED_EVENT,
883
+ day,
884
+ ref: h.id,
885
+ payload: { session, bytes: h.bytes, version: h.version },
886
+ });
887
+ this.emit(HANDOFF_CLEARED_EVENT, h.id, { bytes: h.bytes });
888
+ return { ...none, written: true, reason: "cleared", id: h.id, bytes: h.bytes };
889
+ }
890
+
891
+ /**
892
+ * A NAMED REFUSAL FROM A DOOR, for the shapes this module cannot judge for
893
+ * itself — today, a `handoff` field that is present and is not text. The
894
+ * adapter knows what arrived on the wire; the durable row is still this
895
+ * module's to write, so guarantee 3 has one owner.
896
+ */
897
+ refuseWrite(
898
+ reason: HandoffRefusal,
899
+ opts: { session?: string | null; day?: number } = {},
900
+ ): HandoffWrite {
901
+ const none = { id: null, version: null, gate: null, redacted: null, showsForDays: null } as const;
902
+ if (this.observer) {
903
+ this.emit("handoff.observer.standdown", undefined, { site: "refuseWrite" });
904
+ return { ...none, written: false, reason: "observer", bytes: 0 };
905
+ }
906
+ return this.refuse(
907
+ reason,
908
+ { day: opts.day ?? this.store.livedDay(), session: opts.session ?? null, bytes: 0 },
909
+ none,
910
+ );
911
+ }
912
+
913
+ /** One refusal, one ring event and one durable row. Every named refusal in
914
+ * this module comes through here, which is what makes guarantee 3 checkable
915
+ * in one place rather than at six call sites. */
916
+ private refuse(
917
+ reason: HandoffRefusal,
918
+ detail: { day: number; session: string | null; bytes: number } & Record<
919
+ string,
920
+ string | number | boolean | null
921
+ >,
922
+ base: Omit<HandoffWrite, "written" | "reason" | "bytes">,
923
+ dedupKey?: string,
924
+ ref?: string,
925
+ ): HandoffWrite {
926
+ const { day, ...payload } = detail;
927
+ this.emit(HANDOFF_REFUSED_EVENT, ref, { reason, bytes: detail.bytes });
928
+ try {
929
+ this.store.appendEvent({
930
+ name: HANDOFF_REFUSED_EVENT,
931
+ day,
932
+ ...(ref === undefined ? {} : { ref }),
933
+ ...(dedupKey === undefined ? {} : { dedupKey }),
934
+ payload: { reason, ...payload },
935
+ });
936
+ } catch {
937
+ /* a refusal that cannot be recorded is still a refusal */
938
+ }
939
+ return { ...base, written: false, reason, bytes: detail.bytes };
940
+ }
941
+ }
942
+
943
+ /**
944
+ * Two directory strings naming the same place, for the one comparison this
945
+ * module makes: is the scope the store's own directory? Canonicalisation is the
946
+ * ADAPTER's (`adapters/sessions.ts#canonicalScope`), and both live callers do
947
+ * it; this only has to survive a trailing slash.
948
+ */
949
+ function sameDirectory(a: string, b: string): boolean {
950
+ const norm = (s: string): string => s.replace(/\/+$/, "");
951
+ return norm(a.trim()) === norm(b.trim());
952
+ }
953
+
954
+ /** The title the row carries, so every id-listing surface names it in words. */
955
+ export function handoffTitle(scope: string): string {
956
+ return `Handoff — ${scope}`;
957
+ }