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,286 @@
1
+ /**
2
+ * `encode/` — the shared vocabulary of the bouncer.
3
+ *
4
+ * A PROPOSAL is what an author declares it learned. It is not a memory: it has no
5
+ * id, no strength, no row. Everything here describes the pre-durable world, which
6
+ * is the whole point of the module — gates run on proposals, before anything is
7
+ * durable (CONTRACT §5 G2, behavioral-spec §3 G3).
8
+ */
9
+
10
+ import type { Kind, Salience } from "../types.js";
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // The proposal
14
+ // ---------------------------------------------------------------------------
15
+
16
+ /**
17
+ * A typed, attributed feeling as DECLARED. Absent means null, never neutral
18
+ * (CONTRACT §3, behavioral-spec §4.2 G5). Encode never assigns a type to an
19
+ * untyped feeling — retro-typing is forbidden.
20
+ */
21
+ export interface Feeling {
22
+ /** The type word. Empty/blank is NOT "neutral" — it is a refusal. */
23
+ type: string;
24
+ /** The cited quote the span must contain. STRIPPED before durability. */
25
+ quote: string;
26
+ /** Who felt it. `SELF_SUBJECT` is the only value the exemption recognizes. */
27
+ subject: string;
28
+ }
29
+
30
+ /** The feeling as it survives into durable state: the quote is gone (§3). */
31
+ export interface DurableFeeling {
32
+ type: string;
33
+ subject: string;
34
+ }
35
+
36
+ /** The one subject the emotion exemption recognizes. It cannot widen (§5 G5). */
37
+ export const SELF_SUBJECT = "self";
38
+
39
+ /**
40
+ * The author-supplied salience dimensions. `novelty` is deliberately absent:
41
+ * novelty is COMPUTED as prediction error against the schema slice, never
42
+ * claimed (CONTRACT §3, physics §5.1).
43
+ */
44
+ export interface ClaimedDimensions {
45
+ relevance: number;
46
+ emotional: number;
47
+ predictive: number;
48
+ }
49
+
50
+ export interface Proposal {
51
+ /** The author's handle for this proposal inside its chunk. Not an id. */
52
+ ref: string;
53
+ content: string;
54
+ kind: Kind;
55
+ scope?: string;
56
+ title?: string;
57
+ /** The author's claimed AGGREGATE salience — a FLOOR, never a value (physics §5.1). */
58
+ claimedSalience?: number | null;
59
+ dimensions?: ClaimedDimensions;
60
+ feeling?: Feeling | null;
61
+ aliases?: readonly string[];
62
+ /**
63
+ * Names and handles the operation would index (the ops rule, §3): a secret in a
64
+ * NAME rejects the whole operation — "a credential must never become an entity
65
+ * the store indexes" — and a matching key that never persists is exempt from
66
+ * hedging, because a name is not a claim.
67
+ */
68
+ handles?: readonly string[];
69
+ /** The declared revision target. Validated by `remember/`, not here. */
70
+ updates?: string | null;
71
+ /** An open loop is an ordinary memory with a flag (CONTRACT §4). */
72
+ unresolved?: boolean;
73
+ /**
74
+ * The emotion exemption, SET PER PROPOSAL BY THE ENGINE THAT MINTED IT
75
+ * (§5 G5). Encode VALIDATES it against this proposal's own span and subject;
76
+ * encode never infers it from content. A claim about someone else's interior
77
+ * always takes the ordinary path.
78
+ */
79
+ selfAuthoredFeeling?: boolean;
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Gate telemetry
84
+ // ---------------------------------------------------------------------------
85
+
86
+ /** The five checks. Every one of them runs on every proposal (§5 G2). */
87
+ export const GATES = ["secrets", "precision", "aliases", "emotion", "floor"] as const;
88
+ export type GateName = (typeof GATES)[number];
89
+
90
+ /** Channels are not gates: they are switchable capabilities beside the battery. */
91
+ export const CHANNELS = ["emotion-classifier", "semantic-preselection"] as const;
92
+ export type ChannelName = (typeof CHANNELS)[number];
93
+
94
+ /**
95
+ * Three distinct records per gate, plus the two ways of not acting (§5 G11,
96
+ * scar §2.4 — "did not fire", "was never asked", and "was switched off" are
97
+ * different facts, and the by-design case is flagged AT THE REFUSAL SITE).
98
+ *
99
+ * - `clear` ran; found nothing to act on
100
+ * - `fired` ran; content or a declared element was changed
101
+ * - `rejected` ran; the proposal is refused (terminal)
102
+ * - `refused-by-design` ran; a declared element was dropped because the design
103
+ * forbids it — not an error, not a bug
104
+ * - `not-invoked` ran; nothing of this gate's kind was declared
105
+ * - `stood-down` deliberately switched off
106
+ */
107
+ export type GateStatus =
108
+ | "clear"
109
+ | "fired"
110
+ | "rejected"
111
+ | "refused-by-design"
112
+ | "not-invoked"
113
+ | "stood-down";
114
+
115
+ /**
116
+ * The secrets gate's status union. `stood-down` IS NOT REPRESENTABLE (§5 G1):
117
+ * the non-ablatable guarantee is enforced in the type system, not by a comment.
118
+ */
119
+ export type SecretsGateStatus = Exclude<GateStatus, "stood-down">;
120
+
121
+ /** A channel's state. "off" is silence; "skipped" is loud (§5 G8). */
122
+ export type ChannelState = "ran" | "off" | "skipped";
123
+
124
+ export interface GateRecordBase {
125
+ status: GateStatus;
126
+ /** Why this status. Always present — a bare status cannot be told from a bug. */
127
+ reason: string;
128
+ /** Whether this gate can ever be switched off. False for all five checks. */
129
+ ablatable: boolean;
130
+ }
131
+
132
+ /** Content-by-reference: family + count. NEVER the secret, and never its hash —
133
+ * hashing a low-entropy credential is reversible (store §16 G9). */
134
+ export interface SecretFinding {
135
+ family: string;
136
+ count: number;
137
+ /** Where it was found: body, an alias, a handle, a feeling field, rendered context. */
138
+ site: string;
139
+ }
140
+
141
+ export interface SecretsGateRecord extends GateRecordBase {
142
+ gate: "secrets";
143
+ status: SecretsGateStatus;
144
+ ablatable: false;
145
+ findings: SecretFinding[];
146
+ /** Hash of the REDACTED text — safe to log, unlike the secret (§5 G10). */
147
+ contentHash: string;
148
+ }
149
+
150
+ export interface PrecisionGateRecord extends GateRecordBase {
151
+ gate: "precision";
152
+ /** What was softened, by kind and count. Never the quoted text itself. */
153
+ hedges: { kind: string; count: number }[];
154
+ }
155
+
156
+ export interface AliasGateRecord extends GateRecordBase {
157
+ gate: "aliases";
158
+ declared: number;
159
+ kept: number;
160
+ /** Per-alias verdicts, by position — an alias is author text, so never logged. */
161
+ dropped: { index: number; reason: string }[];
162
+ }
163
+
164
+ export interface EmotionGateRecord extends GateRecordBase {
165
+ gate: "emotion";
166
+ /** True only when the engine's exemption was set AND validated here. */
167
+ exemption: boolean;
168
+ /** The type word survives into telemetry: it is a closed vocabulary, not content. */
169
+ type: string | null;
170
+ quoteStripped: boolean;
171
+ }
172
+
173
+ export interface FloorGateRecord extends GateRecordBase {
174
+ gate: "floor";
175
+ chars: number;
176
+ words: number;
177
+ minChars: number;
178
+ minWords: number;
179
+ }
180
+
181
+ export type GateRecord =
182
+ | SecretsGateRecord
183
+ | PrecisionGateRecord
184
+ | AliasGateRecord
185
+ | EmotionGateRecord
186
+ | FloorGateRecord;
187
+
188
+ export interface ChannelRecord {
189
+ channel: ChannelName;
190
+ state: ChannelState;
191
+ reason: string;
192
+ }
193
+
194
+ // ---------------------------------------------------------------------------
195
+ // Verdicts
196
+ // ---------------------------------------------------------------------------
197
+
198
+ export type RefusalReason =
199
+ | "secret-in-name"
200
+ | "empty-after-redaction"
201
+ | "content-empty"
202
+ | "content-stub"
203
+ | "content-too-short"
204
+ | "content-too-few-words";
205
+
206
+ export interface AcceptedProposal {
207
+ ref: string;
208
+ accepted: true;
209
+ kind: Kind;
210
+ /** Redacted and hedged. This is what may become canonical. */
211
+ content: string;
212
+ contentHash: string;
213
+ title?: string;
214
+ scope?: string;
215
+ aliases: string[];
216
+ feeling: DurableFeeling | null;
217
+ salience: Salience;
218
+ updates: string | null;
219
+ unresolved: boolean;
220
+ records: GateRecord[];
221
+ }
222
+
223
+ export interface RefusedProposal {
224
+ ref: string;
225
+ accepted: false;
226
+ kind: Kind;
227
+ /** The FIRST blocking reason. `blockedBy` carries every one of them. */
228
+ reason: RefusalReason;
229
+ blockedBy: RefusalReason[];
230
+ records: GateRecord[];
231
+ }
232
+
233
+ export type GatedProposal = AcceptedProposal | RefusedProposal;
234
+
235
+ // ---------------------------------------------------------------------------
236
+ // Durable-state intents — the whole surface by which encode can move anything
237
+ // ---------------------------------------------------------------------------
238
+
239
+ /**
240
+ * Encode itself writes NOTHING. It returns INTENTS for its caller to apply, and
241
+ * a fully-gated chunk returns none of them (§5 G3, scar §7's element-level rider:
242
+ * "nothing from a rejected chunk may touch warmth, gradient, occurrences, or
243
+ * ledger evidence").
244
+ *
245
+ * Every kind of durable state a chunk could move is named here, so "moves zero
246
+ * durable state" is asserted per state kind rather than per happy path.
247
+ */
248
+ export type DurableEffect =
249
+ | { effect: "memory.create"; ref: string; kind: Kind; contentHash: string }
250
+ | { effect: "entity.mention"; schemaId: string; ref: string }
251
+ /** `targetId` is the DECLARATION as written — encode resolves nothing. Its
252
+ * applier is `core/revision.ts`, one apply per effect (see `chunk.ts`). */
253
+ | { effect: "revision.challenge"; targetId: string; ref: string }
254
+ | { effect: "prediction.check"; schemaId: string; ref: string; outcome: string };
255
+
256
+ /**
257
+ * A prediction check the author made against a shown schema. Carried through only
258
+ * when the chunk was not fully gated — the exact leak scar §7(b) records.
259
+ */
260
+ export interface PredictionCheck {
261
+ schemaId: string;
262
+ /** The proposal that made the check; null for a chunk-level check. */
263
+ ref: string | null;
264
+ outcome: "confirmed" | "contradicted" | "unmentioned";
265
+ }
266
+
267
+ // ---------------------------------------------------------------------------
268
+ // Events — content-by-reference, always (§5 G10)
269
+ // ---------------------------------------------------------------------------
270
+
271
+ export interface EncodeEvent {
272
+ event: string;
273
+ ref?: string;
274
+ data?: Record<string, string | number | boolean | null>;
275
+ }
276
+
277
+ export class EncodeError extends Error {
278
+ readonly code: string;
279
+ readonly detail: Record<string, unknown>;
280
+ constructor(code: string, detail: Record<string, unknown> = {}) {
281
+ super(`${code} ${JSON.stringify(detail)}`);
282
+ this.name = "EncodeError";
283
+ this.code = code;
284
+ this.detail = detail;
285
+ }
286
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The ONE whole-word definition, and the ONE normalization the content floor
3
+ * uses.
4
+ *
5
+ * Substring name matching is gone, settled by measurement (CONTRACT §4): the self
6
+ * schema is *named* "self", so 21% of its matches came from the English inside
7
+ * "myself", "itself", and "self-contained" — dragging ~100 KB of identity core
8
+ * into prompts about nothing of the sort while the schemas the span actually
9
+ * named went unshown.
10
+ *
11
+ * Behavioral-spec §8 G3: whole-word matching has ONE definition, SHARED WITH
12
+ * SCHEMA BIRTH. `schemas/` must import this function rather than write its own,
13
+ * or the two drift and a name that "was in the span" for one is not for the
14
+ * other. That is why it lives in its own file with no other dependencies.
15
+ */
16
+
17
+ /**
18
+ * What counts as inside a word. Hyphens and apostrophes ARE word characters,
19
+ * which is the whole point: it is precisely because `-` does not break a word
20
+ * that "self" fails to match "self-contained" — the measured false positive.
21
+ * A multi-word term like "claude code" still matches, because the boundary test
22
+ * only looks at the characters on either END of the term.
23
+ */
24
+ const WORD_CHAR = "[\\p{L}\\p{N}_'’-]";
25
+
26
+ export function escapeRegExp(s: string): string {
27
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28
+ }
29
+
30
+ /**
31
+ * A regex matching `term` as a whole word. Case-insensitive, deliberately and
32
+ * without an option: an option is how two callers drift apart, and "verbatim in
33
+ * the source" is a claim about the WORDS, not about the shift key (NOTES.md).
34
+ */
35
+ export function wholeWordRegex(term: string, flags = "iu"): RegExp {
36
+ const t = escapeRegExp(term.trim());
37
+ return new RegExp(`(?<!${WORD_CHAR})${t}(?!${WORD_CHAR})`, flags);
38
+ }
39
+
40
+ /** True when `term` occurs in `haystack` as a whole word. Empty terms never match. */
41
+ export function occursAsWholeWord(haystack: string, term: string): boolean {
42
+ const t = term.trim();
43
+ if (t.length === 0) return false;
44
+ return wholeWordRegex(t).test(haystack);
45
+ }
46
+
47
+ /** How many whole-word occurrences. Used for per-channel attribution, not counts of text. */
48
+ export function countWholeWord(haystack: string, term: string): number {
49
+ const t = term.trim();
50
+ if (t.length === 0) return 0;
51
+ const re = wholeWordRegex(t, "giu");
52
+ let n = 0;
53
+ while (re.exec(haystack) !== null) n += 1;
54
+ return n;
55
+ }
56
+
57
+ /**
58
+ * The floor's normalization: case-folded, punctuation and markdown scaffolding
59
+ * removed, whitespace collapsed. The stub list is matched against THIS, exactly
60
+ * — never as a substring (§3), so "keeps a TODO list in vim" survives.
61
+ */
62
+ export function normalizeForFloor(text: string): string {
63
+ return text
64
+ .toLowerCase()
65
+ .replace(/[`*_~>#\[\]()]/g, " ")
66
+ .replace(/[^\p{L}\p{N}\s/-]/gu, " ")
67
+ .replace(/\s+/g, " ")
68
+ .trim();
69
+ }
70
+
71
+ /** Word count over the normalized form. */
72
+ export function countWords(text: string): number {
73
+ const n = normalizeForFloor(text);
74
+ return n.length === 0 ? 0 : n.split(" ").length;
75
+ }
@@ -0,0 +1,199 @@
1
+ # `handoff/` — CONTRACT
2
+
3
+ ## 1. Purpose
4
+
5
+ Carry, for one directory, *where the work stands and what to pick up next* — and stop
6
+ carrying it. One live pointer per place, delivered at the wake of a session that opens
7
+ there, and never a memory.
8
+
9
+ ## 2. Brain analog
10
+
11
+ **Prospective working context**, not episodic memory: the note you leave on the bench about
12
+ the half-finished job, which is useful for a fortnight and then is clutter. Human memory
13
+ keeps this in a different register from what was *learned* — it is bound to the place and
14
+ the task, it does not consolidate overnight, and it is not part of who you are.
15
+
16
+ **Named deviation** (constitution line 12): the brain does not keep a per-directory ledger.
17
+ The directory stands in for the place-and-task binding a person gets for free, because in
18
+ this host a directory is what a piece of work *is*.
19
+
20
+ ## 3. Keeps
21
+
22
+ - **The lane itself.** [v1] `task-state` — an expiring, non-consolidating store of "what I
23
+ was doing here". v1 had it, it worked, and the clean-room rebuild dropped it. The spec's
24
+ §6.4 and §15 item 6 are where it comes back, in the owner's words: today he types "prep a
25
+ handoff so we can pick up from here in a new session", and he wants that to happen on its
26
+ own.
27
+ - **One ask, one pacer.** [v2, `self/CONTRACT.md` §13 G3's scar] The handoff is a FIELD on
28
+ the `session_end` call the end-of-session ask already names. There is no second ask, no
29
+ second tool and no second pacer; growing the blocked moment back into two asks is the
30
+ measured failure that scar is named for.
31
+ - **Refused, never cut.** [v2, S1's rule] Past `HANDOFF_MAX_BYTES` the write is refused with
32
+ a named reason: what gets cut at write time is the only copy.
33
+ - **Every entrance passes the battery.** [v2, SEAMS H] A handoff is prose written in a hurry
34
+ at the end of a session, which is exactly the kind of text a credential gets pasted into.
35
+ - **A cap reports what it refused, where the owner will see it.** [owner ruling 2's
36
+ corollary, 2026-09-18] Refusals are durable rows, not silence.
37
+ - **Furniture, not an element.** [v2, the self page's placement] The pointer carries no
38
+ `- ` bullet, enters no lane, and leaves `counts` and the sentinel's `elements=` true of
39
+ the bundle that holds it.
40
+
41
+ ## 4. Drops / simplifies
42
+
43
+ - **No forgetting mechanism of its own.** The pointer stops showing after
44
+ `HANDOFF_LIFE_DAYS` lived days; the row is then let go by the ordinary prune, because it
45
+ is born unprotected in the episodic band with nothing on any salience dimension. Adding a
46
+ sweep for it would be a second forgetting for one row (constitution line 15).
47
+ - **No archived row per revision.** A newer handoff for the same directory REVISES the same
48
+ row, so the one it replaces is an ordinary version, bounded by the ordinary version
49
+ retention. The self page's precedent; the alternative leaves superseded rows for every
50
+ reader of `list()` to skip.
51
+ - **No doctor line.** The fired view carries both halves, and a handoff that nobody left is
52
+ not a fault. A handoff row whose WORDS have gone missing is a different matter and is not
53
+ this module's line to print: on the v6 floor a tombstoned row is skipped by
54
+ `Schemas.load` and the session starts normally, and a FAULTED one (blank body, a hash
55
+ that still names it) stands the session down as `MEMORY_BODY_MISSING` — which `verify`
56
+ names by id and `counterparts remove <id>` clears. Both measured, both tested.
57
+ - **No second lane in the wake, and no new trim order.** The pointer is reserved for, not
58
+ ranked.
59
+ - **No scope registry of its own.** The directory arrives as a string from the adapter that
60
+ resolved it (`adapters/scopes.ts`); this module canonicalises nothing.
61
+
62
+ ## 5. Contract
63
+
64
+ **Inputs** — a body, a canonical directory, a session id (or null), the lived-day clock,
65
+ and a gate (`bridge.episodeGate`, injected).
66
+ **Outputs** — one schema row per directory with `meta.role = "handoff"`; a two-line pointer
67
+ block for a given directory and day; four durable event names (`written`, `shown`,
68
+ `cleared`, `refused`).
69
+
70
+ **Guarantees** — **[M]** mechanized, **[A]** advisory:
71
+
72
+ 1. **[M] It is never a memory.** It is out of the recall scan (`recall/activate.ts`), it
73
+ takes no use credit even when a session expands it by id
74
+ (`counterpart.ts#creditReferences`), it is skipped by dedup (`sleep/types.ts#isSchemaRow`),
75
+ it is invisible to the schemas index (`toMetaRecord` returns null for its role), and
76
+ `scanActive` lists `{ type: "memory" }` so it can reach no briefing lane. With `uses` and
77
+ `reinforced_days` structurally pinned at zero, `physics#promotionEligibility` can never
78
+ be satisfied and the row can never cross into the identity band.
79
+ 2. **[M] One live row per directory.** A second write revises the first; the body it
80
+ replaces is a readable version on the same row. Last writer wins, loser kept.
81
+ 3. **[M] The body is refused past `HANDOFF_MAX_BYTES`, never truncated**, and every refusal
82
+ is named and durable — except under observer, where nothing at all is written. Every
83
+ refusal in this module goes through one private seam, so that is checkable in one place;
84
+ the two shapes that used to escape it (`no-scope` short-circuited at the MCP door, and a
85
+ present-but-blank field, which was total silence) were the adversarial review's MAJOR-2
86
+ and are closed.
87
+ 3b. **[M] A `handoff` field that is PRESENT and blank RETIRES the directory's pointer.**
88
+ The row is archived by the ordinary means, its words stay readable on it, and one
89
+ `handoff.cleared` row says so. An ABSENT field means "leave what stands"; a field that is
90
+ not text is a named, durable refusal. This is the only retirement there is, and the tool
91
+ description says so.
92
+ 4. **[M] Credentials are redacted or the write is refused**, by the same battery every other
93
+ entrance passes, and the writer is told which happened.
94
+ 5. **[M] The pointer expires in LIVED days.** After `HANDOFF_LIFE_DAYS` it is not shown and
95
+ no row claims it was. A handoff with no recorded lived day has already expired.
96
+ 6. **[M] With no live handoff in the store, the wake is byte-identical to what this tree
97
+ composed before this module existed.** The delivery splice happens only when a pointer is
98
+ found, and the compose-budget reserve is taken only while some directory holds a live
99
+ one. Proved by `tools/wake-dump.ts` against another checkout, `diff` exit 0; the
100
+ adversarial review widened the same proof to 2,824 compositions with the same result.
101
+ 7. **[M] The pointer never puts the bundle over the host's ceiling.** Its room is reserved
102
+ out of the compose budget at the boundary (see §6 for who pays); at delivery a bundle
103
+ that would still exceed the ceiling is delivered WITHOUT the pointer rather than over the
104
+ limit, and that drop leaves a durable `handoff.refused{reason: "no-room"}` row, deduped
105
+ per row per lived day.
106
+ 7b. **[M] It never gets a vector** (`store/#noVector`, asked at all three doors:
107
+ `indexOne` at write time, `unembeddedIds` for the backfill, `embedOne` for a caller
108
+ naming an id). One could not reach a turn — `activate` skips the row — but it would give
109
+ the prose this module calls the likeliest to carry a token a second representation
110
+ outside its row, and put a floor under the embed backlog `doctor` watches. The SELF PAGE
111
+ is excluded by the same rule as a working default (2026-09-20, the coordinating session's
112
+ ask — not an owner ruling, and revisable); the journal is NOT, and
113
+ why is in `INTERFACE-GAPS.md` §7. The LEXICAL index still holds both, so the owner can
114
+ still find a row by searching for it.
115
+ 8. **[M] The sentinel stays true.** The splice re-solves the byte fixed point so the opening
116
+ comment and the tail sentinel both state the delivered total, and the lane counts and
117
+ `elements=` are untouched.
118
+ 9. **[M] Nothing in a payload is a directory path or a body.** Telemetry is ids, counts,
119
+ bytes, reasons and flags (store §5 G10); which directory a row is about is on the row.
120
+ 10. **[A] The wording of the pointer's two lines is advisory.** What is mechanized is that a
121
+ pointer states its date, a first line of SUBSTANCE (headings are skipped) and its id,
122
+ names the door to the whole of it, and carries no control or bidi-override character
123
+ into the bundle.
124
+
125
+ ## 6. Where it sits in the wake's order — who pays, when, and how much
126
+
127
+ The pointer is **furniture at the foot of the bundle**, above the tail sentinel and below
128
+ every lane. It is not in `TRIM_ORDER`, which is a LANE order: the trim loop pops elements,
129
+ and the pointer is not an element.
130
+
131
+ **An earlier draft of this section said the pointer "never causes a trim". That was the
132
+ reverse of the mechanism, and the adversarial review of 2026-09-20 measured it.** What is
133
+ true:
134
+
135
+ - **The reserve is what causes the trim.** `reserveBytes` is subtracted from the compose
136
+ budget, so the trim loop runs against a smaller ceiling and pops lane elements *to make
137
+ room for the pointer*. A memory is dropped so a handoff can be shown.
138
+ - **The reserve is store-wide; the pointer is per-directory.** One bundle is published per
139
+ store. A handoff written in project A shrinks the wake composed for every session in
140
+ every directory of that store, and a session in project B pays for a pointer it will
141
+ never be handed.
142
+ - **What that cost was, measured, at the flat 448-byte reserve:** at a 1,200-byte ceiling a
143
+ session in a directory with no handoff lost 4 of its 6 identity elements; at 2,000, 4 of
144
+ 13; at 3,000, 5 of 23. At the 9,000 the parallel run uses, the lane caps bind before the
145
+ byte ceiling does and the cost is zero.
146
+ - **What it is now.** Two changes, both in `reserveBytes`, and neither of them a second
147
+ budgeter: the reserve is sized to the pointer block that ACTUALLY EXISTS (the widest live
148
+ one, one per directory) plus a small margin, capped at the widest block this module can
149
+ produce; and it is **not taken at all** unless the ceiling is at least
150
+ `HANDOFF_RESERVE_MIN_BUDGET_MULTIPLE` times it. Below that the reserve is zero, no lane
151
+ pays anything, and the pointer is simply not carried at that ceiling — `handoff.refused
152
+ {reason: "no-room"}` says so, once per row per lived day.
153
+ - **At delivery**, a bundle that would still exceed the ceiling drops the pointer whole
154
+ while every lane element stays.
155
+
156
+ So the order of who gives up bytes, stated plainly: **above the share rule's threshold the
157
+ pointer is paid for first, out of the compose budget, by whatever lane the trim order
158
+ reaches — store-wide. Below it the pointer gives up everything and the lanes give up
159
+ nothing.** A fortnight of working context is worth less than a memory, and the threshold is
160
+ where this module says so in numbers rather than in a sentence.
161
+
162
+ **Worktrees, and why they are not a surprise.** The directory a session is filed under is
163
+ `CLAUDE_PROJECT_DIR` where the host sets it (`bin/hook.ts#startDirectory`,
164
+ `mcp/server.ts#hostScope`), which stays put when a session `cd`s or enters a git worktree.
165
+ So a session launched at a repo root and working inside `.claude/worktrees/x` shares the
166
+ repo's pointer, and a session *launched* inside the worktree gets its own. Both are
167
+ defensible; what would not be is neither being written down.
168
+
169
+ ## 7. Scars honored
170
+
171
+ **§2.3** (delivery telemetry is distinct from render telemetry — `handoff.written` and
172
+ `handoff.shown` are two rows because "we wrote one" is not "a session was handed one") ·
173
+ **§2.18** (the host's ceiling is reported, never invented, and the reserve is what makes it
174
+ survive a delivery-time splice) · **§1 G2** (both comment lines state the delivered total) ·
175
+ **§1 G7** (a store that will not answer never fails a wake) · **observer G3** (an instrument
176
+ does not log its own refusal) · **§13 G3** (one ask at the blocked moment).
177
+
178
+ ## 8. Open questions
179
+
180
+ 1. **Is the share rule's threshold right?** `HANDOFF_RESERVE_MIN_BUDGET_MULTIPLE` is 8,
181
+ which turns the reserve on from about 2,400 bytes of ceiling. It is a judgement about
182
+ what a pointer is worth against a memory, made once, in numbers; the owner's hosts all
183
+ report far more than that, so nothing he runs is near it today.
184
+ 2. **Does the host's own file memory duplicate this?** The spec names it as the thing to
185
+ watch in real use (§15 item 6). A directory with a `CLAUDE.md` that already says where
186
+ the work stands may be carrying the same sentence twice.
187
+ 3. **Is a fortnight right?** `HANDOFF_LIFE_DAYS` is a guess with a reason, not a measurement.
188
+ The row to watch is `handoff.shown`'s `ageDays`, which is now ONE row per directory per
189
+ lived day — before that it was one per wake, and the distribution would have been
190
+ dominated by a session re-waking rather than by distinct pickups. Read it as written; no
191
+ further dedupe is needed.
192
+ 4. **CLOSED (2026-09-20): a stale pointer now has a one-word retirement.** The ask fires up
193
+ to six times a session, so a session can write "half done" early and finish by the last
194
+ ask. Sending the field PRESENT and blank clears the directory's pointer (§5 G3b). What
195
+ remains open is whether models actually reach for it; the row to watch is
196
+ `handoff.cleared` against `handoff.written`.
197
+ 5. **Should an expired row be archived rather than left to the prune?** Today it sits live
198
+ and unread for the 90 lived days `D_FLOOR_DAYS` asks for. That is correct and it is also
199
+ a row `list()` walks for three months after it stopped mattering.