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,404 @@
1
+ /**
2
+ * THE SELF PAGE — one written page, the same every morning, kept in the store
3
+ * with its versions.
4
+ *
5
+ * Until now "Who I am:" was a rotating list of about twenty identity elements,
6
+ * re-ranked at every boundary, and the entity the store calls the self was a row
7
+ * whose body was its own name. A list that changes every morning is not a self;
8
+ * it is a query result. The owner's ruling of 2026-09-18 (plan §2 item 9): at
9
+ * wake the self is a page of prose, written in the first person, that any woken
10
+ * session may amend and the owner may write by hand, and that says out loud when
11
+ * there is nothing there yet. Promotion and reinforcement still decide what
12
+ * feeds it — they are untouched by this file; the page is where the growth
13
+ * shows.
14
+ *
15
+ * **One row, through the ordinary Store API.** `put` mints it, `revise` changes
16
+ * it (archiving the prior version first, §16 G4), `versions`/`readVersion` read
17
+ * what it used to say. Nothing here knows whether a body is a file or a column,
18
+ * so the floor can move underneath it (plan §3, F5) without this module noticing.
19
+ *
20
+ * **Where it sits, and why it survives sleep.** `type: "schema"`, `kind: "self"`,
21
+ * `meta.role = "page"` — the same shelf the identity core sits on, one role
22
+ * along. That placement is what keeps the sleep cycle off it, using only
23
+ * mechanisms that already existed:
24
+ *
25
+ * - `dedup` skips every schema row by name (`sleep/types.ts#isSchemaRow`), so
26
+ * the page is never merged into something that resembles it;
27
+ * - `prune` is blocked by `protected` (`physics#pruneVerdict`), which the row
28
+ * is born with — the page is the owner's and the self's standing ink, and
29
+ * the prune's own vocabulary already has a word for that;
30
+ * - `decay` and `consolidate` write physics columns and never prose, so the
31
+ * worst they can do is move a number on a row nothing ranks;
32
+ * - `scanActive` lists `{ type: "memory" }`, so the page can never enter a
33
+ * briefing lane as an element and be trimmed as one.
34
+ *
35
+ * Old VERSIONS of the page take the ordinary retention (owner ruling 1, 2026-09-18):
36
+ * `pruneSupersededVersions` deletes by `version_day` alone and has no exemption
37
+ * to make one for, which is the behaviour that ruling asked for.
38
+ *
39
+ * **The role is invisible to `schemas/`** — `toMetaRecord` returns null for any
40
+ * role but entity, belief and current-state, so the page is skipped by the
41
+ * index build rather than mis-filed in it.
42
+ */
43
+ import type { ProseDoc, Store } from "../store/index.js";
44
+
45
+ /** The `meta.role` that makes a schema row THE page. One per store. */
46
+ export const SELF_PAGE_ROLE = "page";
47
+
48
+ /** The durable row every accepted revision leaves. Read by `fired`. */
49
+ export const SELF_PAGE_REVISED_EVENT = "self.page.revised";
50
+
51
+ /**
52
+ * The durable row every REFUSED write leaves, beside the accepted ones rather
53
+ * than instead of them. Owner ruling 2's corollary (2026-09-18): a cap reports
54
+ * what it refused where the owner can see it — the 196 refused asks sat in the
55
+ * events table unseen for a fortnight.
56
+ */
57
+ export const SELF_PAGE_REFUSED_EVENT = "self.page.refused";
58
+
59
+ /**
60
+ * WHO WROTE THIS REVISION. Three authors, and the distinction is the reason the
61
+ * field exists: a page the owner typed and a page a nightly writer composed are
62
+ * both legitimate and are not the same claim. `writer` has no caller yet — it is
63
+ * S2's, and it is enumerated here so the row S2 writes needs no new vocabulary.
64
+ */
65
+ export const SELF_PAGE_AUTHORS = ["session", "owner", "writer"] as const;
66
+ export type SelfPageAuthor = (typeof SELF_PAGE_AUTHORS)[number];
67
+
68
+ /** The two headed sections (spec §15 item 1). The page carries them as prose. */
69
+ export const PAGE_CORE_HEADING = "Core";
70
+ export const PAGE_LATELY_HEADING = "Lately";
71
+
72
+ /**
73
+ * What a page looks like before anything has been earned — offered by the CLI
74
+ * and named in the tool description, never written by the engine. A store with
75
+ * no page says so; it does not get a page of placeholders minted for it.
76
+ */
77
+ export const PAGE_TEMPLATE = [
78
+ `## ${PAGE_CORE_HEADING}`,
79
+ "",
80
+ "Still forming.",
81
+ "",
82
+ `## ${PAGE_LATELY_HEADING}`,
83
+ "",
84
+ "Still forming.",
85
+ "",
86
+ ].join("\n");
87
+
88
+ /** The title the row carries, so every id-listing surface names it in words. */
89
+ export const PAGE_TITLE = "Who I am";
90
+
91
+ /**
92
+ * ONE ROW FOR THE LIFE OF THE PAGE, cleared or not (2026-09-18, second review).
93
+ *
94
+ * The first design archived the row on `--clear`. That read as "no page"
95
+ * correctly, but `revisePage` finds LIVE rows, so the next write — including the
96
+ * `--restore <seq>` the clear message itself recommends — minted a fresh row and
97
+ * left four versions with full attribution on a row no surface could reach. The
98
+ * undo mechanism closed behind the owner as he walked through it.
99
+ *
100
+ * So a clear is an ordinary REVISION to this body, with `meta.cleared` set. The
101
+ * row stays live and keeps its whole version chain; the body it replaced becomes
102
+ * an ordinary version, attributed like every other. Every reader — the wake, the
103
+ * doctor, the dashboard, the MCP read, the console — asks `readSelfPage`, which
104
+ * returns null for a cleared row, so the store reads as having no page exactly
105
+ * as if none had ever been written. The next write or restore revises the same
106
+ * row and drops the flag.
107
+ *
108
+ * Two properties fall out, and both are asserted: there is never more than one
109
+ * page row, live or archived; and nothing needs the event log to find the page
110
+ * or its history (attribution still reads it, and says "unrecorded" when a row
111
+ * has been pruned).
112
+ */
113
+ export const PAGE_CLEARED_BODY =
114
+ "This page has been cleared. Nothing stands here now; what it used to say is kept in this row's versions.";
115
+
116
+ /** `meta.cleared` on a page row: when, and why. Absent or null means live. */
117
+ export const PAGE_META_CLEARED = "cleared";
118
+
119
+ export interface PageCleared {
120
+ readonly on: string;
121
+ readonly reason: string;
122
+ }
123
+
124
+ /** The `cleared` marker on a page's prose meta, or null when the page stands. */
125
+ export function clearedMarker(meta: Record<string, unknown>): PageCleared | null {
126
+ const raw = meta[PAGE_META_CLEARED];
127
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
128
+ const rec = raw as Record<string, unknown>;
129
+ return {
130
+ on: typeof rec["on"] === "string" ? rec["on"] : "",
131
+ reason: typeof rec["reason"] === "string" ? rec["reason"] : "",
132
+ };
133
+ }
134
+
135
+ /** Prose meta the page keeps beside its body — the page's own provenance. */
136
+ export const PAGE_META_REVISED_ON = "revisedOn";
137
+ export const PAGE_META_REVISED_DAY = "revisedDay";
138
+ export const PAGE_META_BY = "by";
139
+ export const PAGE_META_REASON = "reason";
140
+
141
+ export interface SelfPage {
142
+ readonly id: string;
143
+ /** The page, verbatim. Never truncated here — see `renderPage`. */
144
+ readonly body: string;
145
+ readonly bytes: number;
146
+ /** The calendar date of the last revision, `YYYY-MM-DD`; "" when unrecorded. */
147
+ readonly revisedOn: string;
148
+ /** The lived day of the last revision; null when unrecorded. */
149
+ readonly revisedDay: number | null;
150
+ readonly by: SelfPageAuthor | null;
151
+ readonly reason: string | null;
152
+ /** `revision` on the row: 0 for a page written once and never amended. */
153
+ readonly version: number;
154
+ }
155
+
156
+ /**
157
+ * THE PAGE, or null. Shaped exactly like `findIdentityCore`, and reading prose
158
+ * for the same reason: box 2 indexes type/kind/band/archived and has no meta
159
+ * query (schemas/INTERFACE-GAPS §2). One store has one page; the first row with
160
+ * the role wins, and a second would be a category error no door here can make.
161
+ */
162
+ export function findSelfPage(store: Store): string | null {
163
+ const row = findPageRow(store);
164
+ if (row === null) return null;
165
+ // A CLEARED row is still the page's row — it holds the history — but it is not
166
+ // a page. Every reader that asks "is there a page" comes through here.
167
+ try {
168
+ return clearedMarker(store.readProse(row).meta) === null ? row : null;
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+
174
+ /**
175
+ * THE PAGE'S ROW, cleared or not. The surfaces that read the page's HISTORY —
176
+ * versions, restore — ask for this; the ones that read the PAGE ask
177
+ * `findSelfPage`. There is at most one, by construction: `revisePage` mints only
178
+ * when this returns null, and nothing archives it.
179
+ */
180
+ export function findPageRow(store: Store): string | null {
181
+ for (const id of store.list({ type: "schema", kind: "self", archived: false })) {
182
+ try {
183
+ if (store.readProse(id).meta["role"] === SELF_PAGE_ROLE) return id;
184
+ } catch {
185
+ continue;
186
+ }
187
+ }
188
+ return null;
189
+ }
190
+
191
+ /**
192
+ * Is THIS id the page's row? Used by the owner's console to send `remove` one
193
+ * door along (`self-page --clear`), and true of a CLEARED page too — a row that
194
+ * was the page is still not a row removal should tombstone.
195
+ */
196
+ export function isSelfPageRow(store: Store, id: string): boolean {
197
+ const row = store.row(id);
198
+ if (row === undefined || row.type !== "schema" || row.kind !== "self") return false;
199
+ try {
200
+ return store.readProse(id).meta["role"] === SELF_PAGE_ROLE;
201
+ } catch {
202
+ return false;
203
+ }
204
+ }
205
+
206
+ /**
207
+ * The page as a value, or null. To every reader in `self/` a page whose body
208
+ * will not read is absent, never a throw (§5 G7).
209
+ *
210
+ * **What is upstream of that changed with the floor** (schema v6), and the note
211
+ * this replaces was written on the floor before it. There used to be a THIRD
212
+ * state — the page's prose FILE deleted underneath the store — and it never got
213
+ * this far: `Schemas.load` reads every schema row at open, `readProseFile` threw
214
+ * `PROSE_FILE_MISSING`, and `Counterpart.open` took the whole session down with
215
+ * doctor reading RED (measured, `docs/adversarial-review-s1c-2026-09-20.md`
216
+ * MAJOR-1). There is no file to lose now, so that state is gone with it.
217
+ *
218
+ * What is left is two, and `Schemas.load` tells them apart:
219
+ *
220
+ * - **Tombstoned** — body and content hash both blank, which is what the
221
+ * owner's removal leaves (`store/operational.ts#rowTombstoned`). `load`
222
+ * SKIPS it and counts it, so the session still starts, and the deny-list
223
+ * answers anyone who asks for the id by name. A CLEARED page is a different
224
+ * thing again and is this function's own business: the row and its words are
225
+ * intact, a marker in `meta` says the owner emptied it, and the line below
226
+ * reads it as absent so the wake goes back to its empty-page behaviour.
227
+ * - **Its words went missing** — a blank body beside a real content hash, a
228
+ * state no write path produces. `MEMORY_BODY_MISSING` still comes out of
229
+ * `Schemas.load` and still stands the session down, on purpose: a store that
230
+ * lost a memory's words underneath itself is a fault the owner must see, not
231
+ * a page to quietly render as empty.
232
+ */
233
+ export function readSelfPage(store: Store): SelfPage | null {
234
+ const id = findPageRow(store);
235
+ if (id === null) return null;
236
+ let doc: ProseDoc;
237
+ try {
238
+ doc = store.readProse(id);
239
+ } catch {
240
+ return null;
241
+ }
242
+ // Cleared reads as absent, which is what makes the wake go back to its
243
+ // empty-page behaviour without anything else in the tree knowing the word.
244
+ if (clearedMarker(doc.meta) !== null) return null;
245
+ const row = store.row(id);
246
+ const by = doc.meta[PAGE_META_BY];
247
+ const revisedDay = doc.meta[PAGE_META_REVISED_DAY];
248
+ const revisedOn = doc.meta[PAGE_META_REVISED_ON];
249
+ const reason = doc.meta[PAGE_META_REASON];
250
+ return {
251
+ id,
252
+ body: doc.body,
253
+ bytes: byteLengthOf(doc.body),
254
+ revisedOn: typeof revisedOn === "string" ? revisedOn : "",
255
+ revisedDay: typeof revisedDay === "number" ? revisedDay : null,
256
+ by: isAuthor(by) ? by : null,
257
+ reason: typeof reason === "string" && reason.length > 0 ? reason : null,
258
+ version: row?.revision ?? 0,
259
+ };
260
+ }
261
+
262
+ function isAuthor(v: unknown): v is SelfPageAuthor {
263
+ return typeof v === "string" && (SELF_PAGE_AUTHORS as readonly string[]).includes(v);
264
+ }
265
+
266
+ /** Local so this file imports no renderer; identical to `identity.ts#byteLength`. */
267
+ function byteLengthOf(s: string): number {
268
+ return new TextEncoder().encode(s).length;
269
+ }
270
+
271
+ // ── what the wake prints ────────────────────────────────────────────────────
272
+
273
+ export interface RenderedPage {
274
+ /** The body as it will be injected — the whole page, or a cut one. */
275
+ readonly text: string;
276
+ readonly bytes: number;
277
+ /** True when the cap cut it; the marker line is already part of `text`. */
278
+ readonly truncated: boolean;
279
+ /** The page's own bytes, whole, whatever was rendered. */
280
+ readonly wholeBytes: number;
281
+ }
282
+
283
+ /**
284
+ * The marker a cut page carries, so a reader can tell a page that ends from a
285
+ * page that was stopped. It names both numbers and the door to the whole thing:
286
+ * a truncation nobody can measure is indistinguishable from a short page, which
287
+ * is the scar the wake's own sentinel exists for (§1 G2).
288
+ */
289
+ export function truncationMarker(shown: number, whole: number): string {
290
+ return `[This page is ${whole} bytes; the wake shows the first ${shown}. Run 'counterparts self-page' to read it whole.]`;
291
+ }
292
+
293
+ /**
294
+ * Cut a page to fit, AT A BOUNDARY IT CHOSE. Paragraph first, then line, then —
295
+ * only when a single paragraph is larger than the whole cap — bytes, because a
296
+ * page that renders nothing is worse than a page that ends mid-sentence with a
297
+ * marker saying so.
298
+ *
299
+ * The marker is inside the cap: what the composition is handed is what it costs.
300
+ */
301
+ export function renderPage(body: string, capBytes: number): RenderedPage {
302
+ const whole = byteLengthOf(body);
303
+ if (whole <= capBytes) {
304
+ return { text: body, bytes: whole, truncated: false, wholeBytes: whole };
305
+ }
306
+ // Reserve the marker's room first. The marker states the bytes shown, which
307
+ // changes its own length; the reserve is computed against the widest marker
308
+ // this page could produce (the whole page's own byte count in both slots),
309
+ // so the result is bounded without solving a second fixed point.
310
+ const reserve = byteLengthOf(truncationMarker(whole, whole)) + 2;
311
+ // A cap that cannot even hold the MARKER renders nothing rather than blowing
312
+ // through the cap to explain itself: the caller's ceiling is the promise, and
313
+ // a wake this small has an over-budget tripwire of its own to fire. Only
314
+ // reachable under ~103 bytes of room (adversarial review m5).
315
+ if (capBytes < reserve) return { text: "", bytes: 0, truncated: true, wholeBytes: whole };
316
+ const room = Math.max(0, capBytes - reserve);
317
+ const kept = cutAtBoundary(body, room);
318
+ const shown = byteLengthOf(kept);
319
+ const text = kept.length === 0 ? truncationMarker(0, whole) : `${kept}\n\n${truncationMarker(shown, whole)}`;
320
+ return { text, bytes: byteLengthOf(text), truncated: true, wholeBytes: whole };
321
+ }
322
+
323
+ /**
324
+ * A boundary is only worth taking if it KEEPS most of the room.
325
+ *
326
+ * Adversarial review of PR #138, measured at the real 6,144-byte cap: the rule
327
+ * "cut at the last blank line" is a trap for the most ordinary page a model
328
+ * writes. A page that opens `## Core\n\n` and then runs as a bullet list — or as
329
+ * one long paragraph — has its only `\n\n` at byte 7, so the last-blank-line
330
+ * cut kept `## Core` and threw away 6,030 bytes of room. Two shapes of a ~9.5 KB
331
+ * page rendered **110 bytes**: a heading, a marker, and no identity at all in a
332
+ * wake whose list the page had just suppressed. The write was accepted with a
333
+ * reassuring `over-wake-cap` warning, so nothing on any surface said so.
334
+ *
335
+ * A quarter, and not a half: a page whose only paragraph break in the window
336
+ * sits at 2.5 KB of a 6 KB room (one medium paragraph, then one very long one)
337
+ * should take that clean 2.5 KB cut rather than fall through to a mid-sentence
338
+ * one. The fallback is reached only when the page genuinely offers no boundary,
339
+ * which is the single-long-paragraph shape — and there a mid-sentence cut with a
340
+ * marker naming both numbers is the correct and only answer.
341
+ */
342
+ export const BOUNDARY_KEEP_SHARE = 0.25;
343
+
344
+ function cutAtBoundary(body: string, room: number): string {
345
+ if (room <= 0) return "";
346
+ const bytes = new TextEncoder().encode(body);
347
+ if (bytes.length <= room) return body;
348
+ // Decode the prefix that fits, dropping a split code point rather than
349
+ // rendering its replacement character.
350
+ const prefix = new TextDecoder("utf-8", { fatal: false }).decode(bytes.slice(0, room));
351
+ const clean = prefix.replace(/�+$/u, "");
352
+ // The floor is in CHARACTERS, because the indices it is compared against are:
353
+ // `lastIndexOf` counts characters and `room` counts bytes, so on multibyte
354
+ // prose a byte floor rejects clean breaks that are past the share in chars.
355
+ const floor = clean.length * BOUNDARY_KEEP_SHARE;
356
+ const paragraph = clean.lastIndexOf("\n\n");
357
+ if (paragraph > floor) return clean.slice(0, paragraph).trimEnd();
358
+ const line = clean.lastIndexOf("\n");
359
+ if (line > floor) return clean.slice(0, line).trimEnd();
360
+ return clean.trimEnd();
361
+ }
362
+
363
+ // ── reading the page's own shape ────────────────────────────────────────────
364
+
365
+ export interface PageSections {
366
+ readonly core: string;
367
+ readonly lately: string;
368
+ /** Anything before the first heading, or the whole body when it has none. */
369
+ readonly preamble: string;
370
+ /** False when the page carries neither heading — still a page, just prose. */
371
+ readonly headed: boolean;
372
+ }
373
+
374
+ /**
375
+ * Split a page at its own headings, for the surfaces that show the two parts
376
+ * apart (the dashboard, the console). The WAKE never calls this: it prints the
377
+ * page as is, because a page reassembled from parts is a page this engine wrote.
378
+ */
379
+ export function pageSections(body: string): PageSections {
380
+ const find = (heading: string): number => {
381
+ const re = new RegExp(`^#{1,6}\\s*${heading}\\s*$`, "im");
382
+ return body.search(re);
383
+ };
384
+ const core = find(PAGE_CORE_HEADING);
385
+ const lately = find(PAGE_LATELY_HEADING);
386
+ if (core < 0 && lately < 0) {
387
+ return { core: "", lately: "", preamble: body.trim(), headed: false };
388
+ }
389
+ const first = core < 0 ? lately : lately < 0 ? core : Math.min(core, lately);
390
+ const section = (start: number): string => {
391
+ if (start < 0) return "";
392
+ const rest = body.slice(start);
393
+ const nl = rest.indexOf("\n");
394
+ const afterHeading = nl < 0 ? "" : rest.slice(nl + 1);
395
+ const next = afterHeading.search(/^#{1,6}\s+\S/m);
396
+ return (next < 0 ? afterHeading : afterHeading.slice(0, next)).trim();
397
+ };
398
+ return {
399
+ core: section(core),
400
+ lately: section(lately),
401
+ preamble: body.slice(0, first).trim(),
402
+ headed: true,
403
+ };
404
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Every `self/` knob, in one visible place — the shape `physics/` and `recall/`
3
+ * use, for the same reason: a threshold hiding in a function body cannot be
4
+ * audited.
5
+ *
6
+ * **CAL = calibration-required** (scar §2.8). Values marked CAL are v1's live
7
+ * calibration, inherited as the best surviving record of what real use moved.
8
+ * They are a starting point, not a v2 measurement; `tools/replay` re-earns them.
9
+ *
10
+ * **The total wake budget is deliberately NOT here.** v1's 9,000 bytes was 90% of
11
+ * one host's injection cliff; in v2 the ceiling is a host capability the caller
12
+ * reports (contract §4, scar §2.18). `BriefingRequest.budgetBytes` is required at
13
+ * the call, and there is no constant anywhere in this module to fall back to.
14
+ *
15
+ * Structural (never tunable, never ablatable): the composed budget, the
16
+ * header/sentinel pair, the trim order existing and being declared, the freeze
17
+ * itself, the observer refusal, pre-render-not-render-on-wake.
18
+ */
19
+
20
+ export interface SelfTunables {
21
+ // ── briefing lanes ────────────────────────────────────────────────────────
22
+ /** Most identity elements considered for the briefing. The BUDGET is the real
23
+ * bound; this only stops a pathological store from composing a megabyte to
24
+ * throw it away. CAL. [v1 self-index: 16 elements] */
25
+ IDENTITY_MAX: number;
26
+ /** The largest fraction of the COMPOSED BUDGET the identity lane may take
27
+ * **while the other lanes have content to spend the rest on**. Not a lane
28
+ * budget (contract §5 G2 — the total still governs): it is how the total is
29
+ * SPLIT when lanes compete, applied by whole elements and released back to
30
+ * identity when nothing else can use the room. CAL.
31
+ *
32
+ * Measured 2026-09-03/04 on the live host: a migrated store's identity
33
+ * elements run ~1.1 KB each, identity trims LAST, so the wake delivered to
34
+ * every session was 8 identity elements filling all 9,000 bytes — craft 0,
35
+ * threads 0, hints 0, horizon 0 — while v1's wake the same day carried 20
36
+ * elements across four lanes. 0.5 leaves ~4.5 KB for the other four lanes at
37
+ * that ceiling, which is v1's whole non-identity wake, and still gives
38
+ * identity four of the long migrated elements (or ~20 v2-native ones). */
39
+ IDENTITY_SHARE: number;
40
+ /** Most craft (skill-kind) elements considered. CAL. */
41
+ CRAFT_MAX: number;
42
+ /** Most open threads considered. CAL. [v1 threads lane: count-capped at 12] */
43
+ THREADS_MAX: number;
44
+ /** Most warm-shelf hints considered. CAL. */
45
+ HINTS_MAX: number;
46
+ /** Most arriving occasions considered. CAL. */
47
+ HORIZON_MAX: number;
48
+ /** A non-identity element must reach this decayed strength to be craft or a
49
+ * hint. Identity elements are constitutive and face no floor (contract §3:
50
+ * "identity is re-inhabited, not retrieved"). CAL. */
51
+ WARM_FLOOR: number;
52
+
53
+ // ── the self page (plan 2026-09-18, S1) ───────────────────────────────────
54
+ /**
55
+ * Bytes of the WAKE the page may take. A page longer than this renders cut, at
56
+ * a paragraph or line boundary, with a marker naming both numbers
57
+ * (`page.ts#renderPage`).
58
+ *
59
+ * Starting value: about 6 KB of the owner's 9,000-byte ceiling, which is the
60
+ * plan's own number and a number to tune rather than a rule. It is clamped to
61
+ * the caller's budget at the render so a page can never on its own be larger
62
+ * than the whole wake; when page plus furniture still will not fit, the floor
63
+ * publishes with `overBudget: true`, which is the tripwire that already exists
64
+ * for an under-floor ceiling.
65
+ */
66
+ PAGE_WAKE_BYTES: number;
67
+ /**
68
+ * The HARD write limit. A revision larger than this is refused with a durable
69
+ * row rather than silently cut, because the thing that gets cut at write time
70
+ * is the only copy. Between this and `PAGE_WAKE_BYTES` a write is accepted and
71
+ * WARNED: the page is kept whole and the wake shows a cut of it.
72
+ */
73
+ PAGE_MAX_BYTES: number;
74
+ /** Calendar days after which the wake says the page has not been revised.
75
+ * CALENDAR, not lived: the lived clock has run seven days across fifteen
76
+ * calendar ones on the owner's own store, so a lived window would report a
77
+ * fortnight of silence as three days (`adapters/fired.ts`, same reasoning). */
78
+ PAGE_STALE_DAYS: number;
79
+ /**
80
+ * WHAT "WHO I AM" SHOWS WHILE NO PAGE HAS BEEN WRITTEN — the owner's choice,
81
+ * and he has not made it yet, so it is one switch with two values.
82
+ *
83
+ * `true` (the default): the rotating identity list still renders, exactly as
84
+ * it does today, until a page exists. Deploying the page therefore changes
85
+ * nothing in the owner's wake until he or a session writes one, and on a
86
+ * brand-new store the list is empty anyway, so a new user meets the day-0 line
87
+ * either way.
88
+ *
89
+ * `false`: the list is gone the moment this ships, and "Who I am" says the
90
+ * page is still forming until one is written.
91
+ *
92
+ * A page that EXISTS replaces the list under both values (spec §15 item 4).
93
+ */
94
+ PAGE_EMPTY_SHOWS_LIST: boolean;
95
+ /**
96
+ * DOES THE PAGE LEAVE THE MACHINE with a composition that filters?
97
+ *
98
+ * `true` (the default): the crash-fallback interpreter is woken WITH the page.
99
+ * That is the owner's own decision of 2026-09-17 (spec §15 item 3) — the
100
+ * background writer gets as much of the self as is reasonable before it reads
101
+ * a transcript, so what it writes is not a stranger's paraphrase — and the
102
+ * transcript it is being handed already goes to the same provider on the same
103
+ * call. What goes out is exactly the page: the owner's and the session's own
104
+ * standing account of the self, cut to the same cap the wake uses.
105
+ *
106
+ * `false`: a filtering composition gets NO page, and its "Who I am" falls back
107
+ * to the identity list the `omit` predicate left standing — which is what that
108
+ * composition carried before the page existed.
109
+ *
110
+ * It is a switch and not an inference because the page is born `protected`,
111
+ * and `sweepFallback`'s own predicate holds protected rows back. The flag is
112
+ * the PRUNE's vocabulary (see `page.ts`), so it does not decide this by
113
+ * itself — but it is close enough to the question that the answer has to be
114
+ * written down rather than read off a flag that means something else.
115
+ */
116
+ PAGE_ON_EGRESS: boolean;
117
+
118
+ // ── the nightly page writer (S2, `self/writer.ts`) ────────────────────────
119
+ /**
120
+ * How much of the day's memories the writer is handed, in bytes. The writer
121
+ * reads one day, not a life, and the page it produces is capped at
122
+ * `PAGE_MAX_BYTES` — handing it more than it can use costs tokens and buys
123
+ * nothing. The cut is by salience, from the end, and what did not fit is
124
+ * COUNTED on the run's row, so a page written from half a day says so. CAL.
125
+ */
126
+ PAGE_WRITER_MEMORY_BYTES: number;
127
+ /** ...and a ceiling on the COUNT, so one day of very short memories cannot
128
+ * become a hundred bullets. CAL. */
129
+ PAGE_WRITER_MEMORY_MAX: number;
130
+ /**
131
+ * How many SESSIONS may be asked to do one day's writing, in session mode.
132
+ *
133
+ * Not a pacer — the scar this package carries about pacers is about the
134
+ * BLOCKED MOMENT at Stop, where one ask on one conjunction is the rule
135
+ * (CONTRACT §3). This ask rides beside the wake at SessionStart, the way the
136
+ * first-launch scope question does, and its cadence is the day boundary
137
+ * itself. The count exists because the first session of a morning may be deep
138
+ * in something else and never get to it; two is enough to make that survivable
139
+ * and small enough that a page nobody wants is not asked for all day. CAL.
140
+ */
141
+ PAGE_WRITER_ASKS_PER_DAY: number;
142
+
143
+ // ── budget telemetry ──────────────────────────────────────────────────────
144
+ /** Fraction of the budget at which the render reports pressure. A budget gets
145
+ * an event when APPROACHED and one when crossed (scar §2.4). [v1: 0.9] */
146
+ BUDGET_PRESSURE: number;
147
+
148
+ // ── the standing self-schema counter (contract §5 G4) ─────────────────────
149
+ /** Total bytes of self-kind + identity-band prose at which the counter trips.
150
+ * v1 measured ~72 KB of accumulated `currentState` before anyone noticed
151
+ * (earned-mechanism #5); the tripwire exists so the next time is measured. CAL. */
152
+ SCHEMA_BYTES_TRIP: number;
153
+ /** Fraction of the trip point that reports pressure. */
154
+ SCHEMA_BYTES_PRESSURE: number;
155
+
156
+ // ── episodes (behavioral-spec §13, all TUNABLE by name) ───────────────────
157
+ /** First ask needs this many real turns AND `FIRST_ASK_BYTES`... CAL. */
158
+ FIRST_ASK_TURNS: number;
159
+ /** ...or this many real bytes... CAL. */
160
+ FIRST_ASK_BYTES: number;
161
+ /** ...or bytes alone past this point, so a one-prompt agentic session still
162
+ * journals (§13 G1). CAL. */
163
+ SOLO_ASK_BYTES: number;
164
+ /** Further substance since the last ask, in turns, before another chapter —
165
+ * AND the byte threshold below, never or. CAL. */
166
+ REASK_TURNS: number;
167
+ /** Further substance since the last ask, in bytes, before another chapter. CAL. */
168
+ REASK_BYTES: number;
169
+ /**
170
+ * Asks ONE SESSION may raise ON ONE CALENDAR DAY. A backstop on the COUNT; the
171
+ * re-ask pair is what bounds the cadence, and the orphanable tail is measured
172
+ * against that pair, never hidden (§13 known gap). CAL.
173
+ *
174
+ * **The measurement against per-session, and why it no longer holds.** On
175
+ * 2026-09-04 a per-session cap of 6 was reached inside ONE evening
176
+ * conversation, and the cap moved to the lived day (later the calendar date,
177
+ * I32) at v1's day calibration: "a work day gets about three". That evening
178
+ * was measured under the OLD re-ask rule — two pacers, an OR, and a byte half
179
+ * a third of v1's, so the model's own chapter-writing reply could re-trigger
180
+ * the ask. The SAME DAY the rule became one pacer and an AND
181
+ * (`episodes.ts#askDue`: `sinceTurns >= REASK_TURNS && sinceBytes >=
182
+ * REASK_BYTES`). Under the AND, six asks in one session need roughly
183
+ * 6 + 5×8 = 46 real turns AND the bytes to go with them, so frequency is held
184
+ * by the pacer and this number is only a ceiling on a very long session.
185
+ *
186
+ * **What the day cap cost, measured 2026-09-17**
187
+ * (`docs/finding-12-diagnosis-2026-09-17.md`): shared across every session a
188
+ * calendar day held, it refused 196 of 264 Stop moments, and the crash-fallback
189
+ * sweep wrote 888 memories against the author's 193. The owner runs five or
190
+ * more sessions a day, so the day's four asks were spent before most sessions
191
+ * began — the author was not losing a fight, it was never invited. Per
192
+ * session, keeping the substance pacer, is the owner's ruling of 2026-09-17.
193
+ *
194
+ * **And why the session's whole life was too long a window, 2026-09-18.** A
195
+ * coordinating session spent all six inside one working day; its end-of-day
196
+ * handoff — the stretch most worth writing — was never offered the pen, and
197
+ * nothing could give the allowance back short of a new session. So the count
198
+ * is per session PER CALENDAR DAY (owner's ruling), on the store's own date
199
+ * rather than the lived day, for the reason I32 gave. Exhausting it inside one
200
+ * day still binds; for now that is accepted, and the pacer means six asks in a
201
+ * day is already about 46 real turns.
202
+ */
203
+ MAX_ASKS_PER_SESSION: number;
204
+ /** Lived days an episode may be re-ingested after its first ingest. The window
205
+ * CLOSES — a deliberate deviation from human reconsolidation (§13 G12). CAL. */
206
+ REGROW_WINDOW_DAYS: number;
207
+ }
208
+
209
+ export const SELF_TUNABLES: SelfTunables = {
210
+ IDENTITY_MAX: 24,
211
+ IDENTITY_SHARE: 0.5,
212
+ CRAFT_MAX: 8,
213
+ THREADS_MAX: 12,
214
+ HINTS_MAX: 8,
215
+ HORIZON_MAX: 6,
216
+ WARM_FLOOR: 0.35,
217
+
218
+ PAGE_WAKE_BYTES: 6_144,
219
+ PAGE_MAX_BYTES: 16_384,
220
+ PAGE_STALE_DAYS: 14,
221
+ PAGE_EMPTY_SHOWS_LIST: true,
222
+ PAGE_ON_EGRESS: true,
223
+
224
+ PAGE_WRITER_MEMORY_BYTES: 8_192,
225
+ PAGE_WRITER_MEMORY_MAX: 40,
226
+ PAGE_WRITER_ASKS_PER_DAY: 2,
227
+
228
+ BUDGET_PRESSURE: 0.9,
229
+
230
+ SCHEMA_BYTES_TRIP: 72_000,
231
+ SCHEMA_BYTES_PRESSURE: 0.75,
232
+
233
+ FIRST_ASK_TURNS: 6,
234
+ FIRST_ASK_BYTES: 4_000,
235
+ SOLO_ASK_BYTES: 12_000,
236
+ REASK_TURNS: 8,
237
+ REASK_BYTES: 8_000,
238
+ MAX_ASKS_PER_SESSION: 6,
239
+ REGROW_WINDOW_DAYS: 3,
240
+ };
241
+
242
+ export function withTunables(overrides: Partial<SelfTunables>): SelfTunables {
243
+ return { ...SELF_TUNABLES, ...overrides };
244
+ }