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,604 @@
1
+ /**
2
+ * Identity elements: ranking them for the briefing, enumerating them for the
3
+ * owner, and the standing byte counter that trips before the self-schema can
4
+ * dominate a prompt again.
5
+ *
6
+ * **Ranking is by strength, and that is the whole structure.** v1 kept a separate
7
+ * derived identity *index* — its own budget, its own warmth ordering, its own
8
+ * promotion path with zero production callers, and no reconciler — and it went
9
+ * stale on the day it was seeded (contract §4, behavioral-spec §1 known gap). Here
10
+ * identity elements are ordinary memories carrying strength, the briefing ranks
11
+ * them, and there is no second structure to go stale. Identity-band memories are
12
+ * decay-exempt in `physics/`, so their strength is their earned base: waking as
13
+ * yourself is not a competition, but the order of the telling is.
14
+ *
15
+ * Nothing in this file reads a body into a decision record. Ranking works on rows
16
+ * and physics; prose is read only for the `unresolved` flag (which the store has
17
+ * no index for — INTERFACE-GAPS #2) and text arrives at render time through the
18
+ * `Resolve` seam.
19
+ */
20
+ import type { Band, Kind, MemoryPhysics } from "../types.js";
21
+ import { strength } from "../physics/index.js";
22
+ import type { ProseDoc, Store } from "../store/index.js";
23
+ import type { SelfTunables } from "./tunables.js";
24
+
25
+ export type LaneName = "identity" | "craft" | "threads" | "hints" | "horizon";
26
+
27
+ /** One candidate line. Ids only — text is resolved at render time. */
28
+ export interface Ranked {
29
+ readonly id: string;
30
+ readonly lane: LaneName;
31
+ readonly kind: Kind;
32
+ readonly band: Band;
33
+ readonly strength: number;
34
+ readonly protected: boolean;
35
+ readonly bornDay: number;
36
+ /** Threads only: person-scoped debts trim last (behavioral-spec §1 G4). */
37
+ readonly personScoped: boolean;
38
+ /** Lived day this element last rendered in a wake; -1 never. Identity only. */
39
+ readonly lastRendered: number;
40
+ }
41
+
42
+ /**
43
+ * Meta key prefix for "this identity element last rendered on lived day N".
44
+ * Written by `Self.boundary` for the identity ids it KEPT (rendered, not
45
+ * merely ranked), read once per scan. The rotation below is the whole
46
+ * consumer.
47
+ */
48
+ export const RENDERED_PREFIX = "self.rendered.";
49
+
50
+ export function lastRenderedOf(store: Store): Map<string, number> {
51
+ const out = new Map<string, number>();
52
+ for (const [key, value] of store.metaWithPrefix(RENDERED_PREFIX)) {
53
+ const day = Number.parseInt(value, 10);
54
+ if (Number.isFinite(day)) out.set(key.slice(RENDERED_PREFIX.length), day);
55
+ }
56
+ return out;
57
+ }
58
+
59
+ export interface Scanned {
60
+ readonly id: string;
61
+ readonly kind: Kind;
62
+ readonly band: Band;
63
+ readonly physics: MemoryPhysics;
64
+ readonly doc: ProseDoc;
65
+ readonly strength: number;
66
+ readonly unresolved: boolean;
67
+ /** Who minted it (`mint.ts`'s channels, plus `"migrated"`). NULL on a pre-v4
68
+ * row whose provenance was never recorded. Carried here because the render
69
+ * dates a MIGRATED element differently — its encode date is an upper bound. */
70
+ readonly source: string | null;
71
+ readonly lastRendered: number;
72
+ }
73
+
74
+ /**
75
+ * One pass over the active memories. Called once per boundary render, never on
76
+ * the wake path (contract §5 G1: wake computes nothing).
77
+ */
78
+ export function scanActive(store: Store, day: number): Scanned[] {
79
+ const out: Scanned[] = [];
80
+ const rendered = lastRenderedOf(store);
81
+ for (const id of store.list({ type: "memory", archived: false })) {
82
+ const row = store.row(id);
83
+ if (row === undefined) continue;
84
+ let doc: ProseDoc;
85
+ let physics: MemoryPhysics;
86
+ try {
87
+ doc = store.readProse(id);
88
+ physics = store.physicsOf(id);
89
+ } catch {
90
+ // A memory whose prose has gone missing must not take the whole briefing
91
+ // down with it (contract §5 G7: the wake never fails the session). It is
92
+ // skipped here and stays visible in `store` telemetry.
93
+ continue;
94
+ }
95
+ out.push({
96
+ id,
97
+ kind: physics.kind,
98
+ band: row.band,
99
+ physics,
100
+ doc,
101
+ strength: strength(physics, day),
102
+ unresolved: doc.meta["unresolved"] === true,
103
+ source: row.source,
104
+ lastRendered: rendered.get(id) ?? -1,
105
+ });
106
+ }
107
+ return out;
108
+ }
109
+
110
+ function byStrength(a: Ranked, b: Ranked): number {
111
+ if (b.strength !== a.strength) return b.strength - a.strength;
112
+ if (a.bornDay !== b.bornDay) return a.bornDay - b.bornDay;
113
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
114
+ }
115
+
116
+ /**
117
+ * Identity ROTATES; it does not rank (CONTRACT §3: "re-inhabited, not
118
+ * retrieved — core memories are constitutive, not competed for in a ranker").
119
+ * Least-recently-rendered first, never-rendered ahead of everything, and only
120
+ * then strength, born-day, id. Measured 2026-09-14 on the owner's store
121
+ * (IMPROVEMENTS U6): eight identity elements tied at strength 1.0, the tie
122
+ * broke oldest-born-first, the three winners were the three written on
123
+ * migration day under a fresh clock, and 17 of 20 identity beliefs had never
124
+ * rendered. A strength sort with a smarter tie-break would rotate the eight;
125
+ * this rotates all of them.
126
+ */
127
+ function byRotation(a: Ranked, b: Ranked): number {
128
+ if (a.lastRendered !== b.lastRendered) return a.lastRendered - b.lastRendered;
129
+ return byStrength(a, b);
130
+ }
131
+
132
+ /**
133
+ * Threads order: person-scoped first, then oldest-opened first. The trim eats
134
+ * from the END of the lane, so long-held relational debts drop last
135
+ * (behavioral-spec §1 G4 — *truncation must never be iteration luck*).
136
+ */
137
+ function byThreadAge(a: Ranked, b: Ranked): number {
138
+ if (a.personScoped !== b.personScoped) return a.personScoped ? -1 : 1;
139
+ if (a.bornDay !== b.bornDay) return a.bornDay - b.bornDay;
140
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
141
+ }
142
+
143
+ function rank(s: Scanned, lane: LaneName): Ranked {
144
+ return {
145
+ id: s.id,
146
+ lane,
147
+ kind: s.kind,
148
+ band: s.band,
149
+ strength: s.strength,
150
+ protected: s.physics.protected,
151
+ bornDay: s.doc.bornDay,
152
+ personScoped: s.kind === "person",
153
+ lastRendered: s.lastRendered,
154
+ };
155
+ }
156
+
157
+ export interface Lanes {
158
+ identity: Ranked[];
159
+ craft: Ranked[];
160
+ threads: Ranked[];
161
+ hints: Ranked[];
162
+ horizon: Ranked[];
163
+ }
164
+
165
+ /**
166
+ * The contract's ordering, in one place:
167
+ *
168
+ * identity — every identity-band memory, least-recently-rendered first
169
+ * (`byRotation`); strength, born-day and id only break ties. Protected elements are INCLUDED: §14.1 G2's no-render
170
+ * rule guards the interpreter's schema slices — the falsification
171
+ * path — not the owner-facing wake (NOTES.md #2). A composition
172
+ * that is NOT owner-facing says so with `BoundaryRequest.omit`, and
173
+ * the sweep's wake copy passes exactly that predicate: protected and
174
+ * confidential rows never reach an interpreter's prompt, by either
175
+ * door.
176
+ * craft — skill-kind, not already in identity, above the warm floor. The
177
+ * procedural self is rendered as CONTENT, never a pointer (§1).
178
+ * threads — `unresolved` memories: person-scoped first, oldest-opened first.
179
+ * hints — everything else warm enough to be worth a nudge, strongest first.
180
+ * horizon — the caller's arriving occasions, in the order supplied
181
+ * (`prospective/` owns the ordering — INTERFACE-GAPS #3).
182
+ *
183
+ * A memory appears in exactly one lane: identity wins, then craft, then threads,
184
+ * then hints. Two lanes showing the same statement is budget spent twice.
185
+ */
186
+ export function rankLanes(
187
+ scanned: readonly Scanned[],
188
+ horizon: readonly Ranked[],
189
+ t: SelfTunables,
190
+ ): Lanes {
191
+ const identity: Ranked[] = [];
192
+ const craft: Ranked[] = [];
193
+ const threads: Ranked[] = [];
194
+ const hints: Ranked[] = [];
195
+
196
+ for (const s of scanned) {
197
+ if (s.band === "identity") {
198
+ identity.push(rank(s, "identity"));
199
+ continue;
200
+ }
201
+ if (s.unresolved) {
202
+ threads.push(rank(s, "threads"));
203
+ continue;
204
+ }
205
+ if (s.strength < t.WARM_FLOOR) continue;
206
+ if (s.kind === "skill") {
207
+ craft.push(rank(s, "craft"));
208
+ continue;
209
+ }
210
+ hints.push(rank(s, "hints"));
211
+ }
212
+
213
+ identity.sort(byRotation);
214
+ craft.sort(byStrength);
215
+ threads.sort(byThreadAge);
216
+ hints.sort(byStrength);
217
+
218
+ return {
219
+ identity: identity.slice(0, t.IDENTITY_MAX),
220
+ craft: craft.slice(0, t.CRAFT_MAX),
221
+ threads: threads.slice(0, t.THREADS_MAX),
222
+ hints: hints.slice(0, t.HINTS_MAX),
223
+ horizon: horizon.slice(0, t.HORIZON_MAX),
224
+ };
225
+ }
226
+
227
+ // ── enumeration (constitution 16, scar §2.19) ───────────────────────────────
228
+
229
+ /**
230
+ * Why an element is listed but cannot be shown.
231
+ *
232
+ * `removed` is the owner's erasure answering: the deny-list refuses the id by
233
+ * name, and the tombstone says it WAS permanent. `unreadable` is everything
234
+ * else — a row whose prose will not parse or has gone missing.
235
+ *
236
+ * The distinction is the whole point: an enumeration that silently dropped both
237
+ * would make "everything permanent is enumerable" a claim about the elements
238
+ * that happen to still work (scar §2.19), and a removed protected element would
239
+ * leave the permanent list without leaving a trace.
240
+ */
241
+ export type EnumeratedAbsence = "removed" | "unreadable";
242
+
243
+ /** The words an absent element carries where a title would go. */
244
+ export const ABSENT_TITLE: Record<EnumeratedAbsence, string> = {
245
+ removed: "[removed]",
246
+ unreadable: "[unreadable]",
247
+ };
248
+
249
+ export interface EnumeratedElement {
250
+ readonly id: string;
251
+ readonly kind: Kind;
252
+ readonly band: Band;
253
+ readonly strength: number;
254
+ readonly protected: boolean;
255
+ readonly promotedIdentity: boolean;
256
+ readonly title: string | null;
257
+ readonly bytes: number;
258
+ /** Null when the element is present and readable. Otherwise names WHY not. */
259
+ readonly absent: EnumeratedAbsence | null;
260
+ }
261
+
262
+ /**
263
+ * The identity band and the protected set, SIDE BY SIDE.
264
+ *
265
+ * They are different populations and the difference is the point: identity is
266
+ * what strength earned and physics can still move; protected is permanent ink no
267
+ * revision path can reach and no schema slice will ever contradict
268
+ * ("permanent-includes-permanently-wrong" is doctrine, §14.1 G2). Scar §2.19's
269
+ * criterion is that everything permanent is enumerable on demand — *a list, not a
270
+ * cadence* — and the pair read together is what makes an element that is both,
271
+ * or neither, visible at a glance.
272
+ *
273
+ * Reads are pure: this writes nothing and logs nothing (§14.1 G8).
274
+ */
275
+ export interface Enumeration {
276
+ readonly day: number;
277
+ readonly identity: EnumeratedElement[];
278
+ readonly protected: EnumeratedElement[];
279
+ /** Ids in both lists — permanent AND constitutive, the strictest class. */
280
+ readonly both: string[];
281
+ /** Protected elements that are NOT identity band: permanence without the band. */
282
+ readonly protectedOutsideIdentity: string[];
283
+ /** Ids in either half that could not be shown, with the reason. Never silent. */
284
+ readonly absences: { id: string; where: "identity" | "protected"; why: EnumeratedAbsence }[];
285
+ }
286
+
287
+ const encoder = new TextEncoder();
288
+
289
+ export function byteLength(s: string): number {
290
+ return encoder.encode(s).length;
291
+ }
292
+
293
+ function enumerateOne(store: Store, id: string, day: number): EnumeratedElement | null {
294
+ const row = store.row(id);
295
+ if (row === undefined) return null;
296
+ let doc: ProseDoc;
297
+ let physics: MemoryPhysics;
298
+ try {
299
+ doc = store.readProse(id);
300
+ physics = store.physicsOf(id);
301
+ } catch {
302
+ return null;
303
+ }
304
+ return {
305
+ id,
306
+ kind: physics.kind,
307
+ band: row.band,
308
+ strength: strength(physics, day),
309
+ protected: physics.protected,
310
+ promotedIdentity: physics.promotedIdentity,
311
+ title: doc.title ?? null,
312
+ bytes: byteLength(doc.body),
313
+ absent: null,
314
+ };
315
+ }
316
+
317
+ /**
318
+ * The entry an element gets when it is on a list it cannot be read from. It
319
+ * keeps its address, its family and its flags, and carries no strength and no
320
+ * bytes: it weighs nothing, because there is nothing left of it to weigh.
321
+ */
322
+ function absentElement(
323
+ id: string,
324
+ why: EnumeratedAbsence,
325
+ was: { kind: Kind; band: Band; protected: boolean; promotedIdentity: boolean },
326
+ ): EnumeratedElement {
327
+ return {
328
+ id,
329
+ kind: was.kind,
330
+ band: was.band,
331
+ strength: 0,
332
+ protected: was.protected,
333
+ promotedIdentity: was.promotedIdentity,
334
+ title: ABSENT_TITLE[why],
335
+ bytes: 0,
336
+ absent: why,
337
+ };
338
+ }
339
+
340
+ export function enumerate(store: Store, day: number): Enumeration {
341
+ const identity: EnumeratedElement[] = [];
342
+ const guarded: EnumeratedElement[] = [];
343
+ const absences: Enumeration["absences"] = [];
344
+ const denied = new Set(store.deniedIds());
345
+
346
+ const absentFromRow = (id: string, where: "identity" | "protected"): EnumeratedElement => {
347
+ // The row is still there; the CONTENT is not. A denied id says so by name —
348
+ // that is the deny-list answering before the prose does — and anything else
349
+ // is honestly "unreadable", which is a different problem with a different fix.
350
+ const why: EnumeratedAbsence = denied.has(id) ? "removed" : "unreadable";
351
+ const row = store.row(id);
352
+ absences.push({ id, where, why });
353
+ return absentElement(id, why, {
354
+ kind: (row?.kind ?? "fact") as Kind,
355
+ band: (row?.band ?? "episodic") as Band,
356
+ protected: row?.protected === 1,
357
+ promotedIdentity: row?.promoted_identity === 1,
358
+ });
359
+ };
360
+
361
+ for (const id of store.list({ band: "identity", archived: false })) {
362
+ const e = enumerateOne(store, id, day);
363
+ identity.push(e ?? absentFromRow(id, "identity"));
364
+ }
365
+ // Protection is a physics flag, not a band: an element can be permanent
366
+ // without ever having been promoted, which is exactly the case the pair makes
367
+ // visible. There is no `protected` filter on `list()` (INTERFACE-GAPS #2).
368
+ for (const id of store.list({ archived: false })) {
369
+ const e = enumerateOne(store, id, day);
370
+ if (e === null) {
371
+ // An unreadable row cannot be asked whether it was protected, so the
372
+ // permanent half has to ask the store instead of the row. A dark-but-not-
373
+ // yet-chased row still carries its flag; a chased one carries a tombstone.
374
+ const row = store.row(id);
375
+ if (row?.protected === 1) guarded.push(absentFromRow(id, "protected"));
376
+ continue;
377
+ }
378
+ if (e.protected) guarded.push(e);
379
+ }
380
+
381
+ // The chased half: rows the owner removed keep a tombstone saying what they
382
+ // WERE, so permanence and inspectability scale together even here (§2.19).
383
+ // Their skeleton row carries no flags any more — the tombstone is the record.
384
+ const listed = new Set([...identity, ...guarded].map((e) => e.id));
385
+ for (const gone of store.tombstones()) {
386
+ const was = {
387
+ kind: gone.kind,
388
+ band: gone.band,
389
+ protected: gone.wasProtected,
390
+ promotedIdentity: gone.wasPromotedIdentity,
391
+ };
392
+ if ((gone.wasPromotedIdentity || gone.band === "identity") && !listed.has(gone.id)) {
393
+ identity.push(absentElement(gone.id, "removed", was));
394
+ absences.push({ id: gone.id, where: "identity", why: "removed" });
395
+ }
396
+ if (gone.wasProtected && !guarded.some((e) => e.id === gone.id)) {
397
+ guarded.push(absentElement(gone.id, "removed", was));
398
+ absences.push({ id: gone.id, where: "protected", why: "removed" });
399
+ }
400
+ }
401
+
402
+ identity.sort((a, b) => b.strength - a.strength || (a.id < b.id ? -1 : 1));
403
+ guarded.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
404
+ absences.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : a.where < b.where ? -1 : 1));
405
+
406
+ const identityIds = new Set(identity.map((e) => e.id));
407
+ return {
408
+ day,
409
+ identity,
410
+ protected: guarded,
411
+ both: guarded.filter((e) => identityIds.has(e.id)).map((e) => e.id),
412
+ protectedOutsideIdentity: guarded.filter((e) => !identityIds.has(e.id)).map((e) => e.id),
413
+ absences,
414
+ };
415
+ }
416
+
417
+ // ── the identity core's HOME row (schemas/INTERFACE-GAPS #5) ────────────────
418
+
419
+ /**
420
+ * The identity core is a PLACE, not a claim, and not a second identity surface.
421
+ *
422
+ * `schemas/` refuses to birth `kind: "self"` in two independent layers — "one
423
+ * identity core; a second is a category error no evidence could justify" — so the
424
+ * one row that says *the self exists as an entity here* can only come from this
425
+ * module. Without it, `schemas/`'s placement rule degrades from
426
+ * `status-on-identity-refused` to `entity-unknown`: still a refusal, but the
427
+ * wrong one, and a silent weakening of the ~72 KB lesson (contract §5 G4) exactly
428
+ * where it matters most.
429
+ *
430
+ * What this is NOT: v1's identity *index* — its own budget, warmth ordering,
431
+ * promotion path and reconciler — which the contract drops and this build does
432
+ * not have. Identity STATEMENTS remain ordinary memories ranked by strength; this
433
+ * is one empty schema row carrying names, which is what "a newborn schema is
434
+ * empty except its names" means.
435
+ */
436
+ export const IDENTITY_CORE_ROLE = "entity";
437
+
438
+ export interface IdentityCoreSpec {
439
+ /** The core's name. This module never invents one (INTERFACE-GAPS #8). */
440
+ readonly name: string;
441
+ readonly aliases?: readonly string[];
442
+ }
443
+
444
+ /** The existing core, if one has been minted. At most one may exist. */
445
+ export function findIdentityCore(store: Store): string | null {
446
+ for (const id of store.list({ type: "schema", kind: "self", archived: false })) {
447
+ try {
448
+ if (store.readProse(id).meta["role"] === IDENTITY_CORE_ROLE) return id;
449
+ } catch {
450
+ continue;
451
+ }
452
+ }
453
+ return null;
454
+ }
455
+
456
+ /**
457
+ * The core's NAME, for the day-0 lane (`briefing.ts#identityCoreLine`).
458
+ *
459
+ * `ensureIdentityCore` writes the name into three places — title, body and
460
+ * `meta.name` — and `meta.name` is the one `schemas/` indexes, so it is read
461
+ * first, with the title as the fallback for a row written before that shape
462
+ * settled. Null when no core has been minted: this module invents no name
463
+ * (INTERFACE-GAPS #8), and a store installed without `--name` renders exactly
464
+ * what it rendered before.
465
+ *
466
+ * The CALLER is expected to have checked that the identity lane is empty first.
467
+ * This reads prose, so it belongs at a boundary and never on the wake path
468
+ * (contract §5 G1); on any store with even one identity element it is never
469
+ * reached.
470
+ */
471
+ export function identityCoreName(store: Store): string | null {
472
+ const id = findIdentityCore(store);
473
+ if (id === null) return null;
474
+ try {
475
+ const doc = store.readProse(id);
476
+ const name = doc.meta["name"];
477
+ if (typeof name === "string" && name.trim().length > 0) return name.trim();
478
+ const title = (doc.title ?? "").trim();
479
+ return title.length > 0 ? title : null;
480
+ } catch {
481
+ // A core whose prose will not read is not a reason to fail the wake (§5 G7).
482
+ return null;
483
+ }
484
+ }
485
+
486
+ // ── the standing self-schema byte counter (contract §5 G4) ──────────────────
487
+
488
+ export interface SchemaBytesReport {
489
+ readonly bytes: number;
490
+ readonly elements: number;
491
+ readonly trip: number;
492
+ readonly pressureAt: number;
493
+ readonly pressure: boolean;
494
+ readonly tripped: boolean;
495
+ /** The heaviest elements, id + bytes, so the report names its own cause. */
496
+ readonly heaviest: { id: string; bytes: number }[];
497
+ /**
498
+ * Fallback-minted self memories EXCLUDED from this weighing — the quarantine
499
+ * (owner ruling 2026-08-29, review F8): a model reading transcripts must not
500
+ * grow the self through the rumination pathway the CONTRACT forswears. They
501
+ * remain ordinary, recallable memories; here they are counted, never silently
502
+ * absent (scar §2.4). The first blind replay minted 205 of them and tripped
503
+ * this very valve seven times.
504
+ */
505
+ readonly quarantined: number;
506
+ /** The bytes those rows would have weighed — what the quarantine set aside. */
507
+ readonly quarantinedBytes: number;
508
+ /**
509
+ * Episodes EXCLUDED from this weighing (day-0 finding, 2026-09-03): the journal
510
+ * is `kind: self` prose, but it is not the self schema — v1's ~72 KB scar was
511
+ * status accreting on `self.md`, not the diary. Weighing 224 migrated chapters
512
+ * read the valve tripped at 3 MB on a store nobody had written to yet, and every
513
+ * authored chapter after would have kept it tripped. Counted, never absent.
514
+ */
515
+ readonly episodes: number;
516
+ readonly episodeBytes: number;
517
+ /**
518
+ * Migrated self rows EXCLUDED for the same reason the fallback rows are: the
519
+ * valve watches what THIS system accumulates on the self (§5 G4: "status does
520
+ * not accumulate"), and v1's thousand self-kind traces arrived in one write.
521
+ * They remain ordinary, recallable memories; here they are counted.
522
+ */
523
+ readonly migrated: number;
524
+ readonly migratedBytes: number;
525
+ }
526
+
527
+ /**
528
+ * Status does not accumulate on the self. v1's `currentState` reached ~72 KB of
529
+ * self-narration before anyone measured it — the counter exists so the next time
530
+ * is a tripwire and not an archaeology project (earned-mechanism #5, scar §2.4:
531
+ * an event when APPROACHED and an event when crossed).
532
+ */
533
+ export function schemaBytes(store: Store, day: number, t: SelfTunables): SchemaBytesReport {
534
+ const seen = new Set<string>();
535
+ const weighed: { id: string; bytes: number }[] = [];
536
+ let quarantined = 0;
537
+ let quarantinedBytes = 0;
538
+ let episodes = 0;
539
+ let episodeBytes = 0;
540
+ let migrated = 0;
541
+ let migratedBytes = 0;
542
+ for (const id of [
543
+ ...store.list({ band: "identity", archived: false }),
544
+ ...store.list({ kind: "self", archived: false }),
545
+ ]) {
546
+ if (seen.has(id)) continue;
547
+ seen.add(id);
548
+ // The quarantine (see the report field). Two exemptions, both earned:
549
+ // identity-band rows got there by a counted crossing (nothing is born into
550
+ // identity), and PROTECTED rows are a deliberate owner act — and since
551
+ // `enumerate()` renders every protected row, exempting them here keeps the
552
+ // measured set equal to the rendered set (PR-2 review should-fix 2: a
553
+ // weighed prompt byte must never be invisible to the byte valve).
554
+ const row = store.row(id);
555
+ if (row !== undefined && row.type === "episode" && row.band !== "identity" && row.protected !== 1) {
556
+ episodes += 1;
557
+ const e = enumerateOne(store, id, day);
558
+ if (e !== null) episodeBytes += e.bytes;
559
+ continue;
560
+ }
561
+ if (
562
+ row !== undefined &&
563
+ row.source === "migrated" &&
564
+ row.band !== "identity" &&
565
+ row.protected !== 1
566
+ ) {
567
+ migrated += 1;
568
+ const m = enumerateOne(store, id, day);
569
+ if (m !== null) migratedBytes += m.bytes;
570
+ continue;
571
+ }
572
+ if (
573
+ row !== undefined &&
574
+ row.source === "fallback" &&
575
+ row.band !== "identity" &&
576
+ row.protected !== 1
577
+ ) {
578
+ quarantined += 1;
579
+ const q = enumerateOne(store, id, day);
580
+ if (q !== null) quarantinedBytes += q.bytes;
581
+ continue;
582
+ }
583
+ const e = enumerateOne(store, id, day);
584
+ if (e !== null) weighed.push({ id, bytes: e.bytes });
585
+ }
586
+ const bytes = weighed.reduce((n, w) => n + w.bytes, 0);
587
+ weighed.sort((a, b) => b.bytes - a.bytes || (a.id < b.id ? -1 : 1));
588
+ const pressureAt = Math.round(t.SCHEMA_BYTES_TRIP * t.SCHEMA_BYTES_PRESSURE);
589
+ return {
590
+ bytes,
591
+ elements: weighed.length,
592
+ trip: t.SCHEMA_BYTES_TRIP,
593
+ pressureAt,
594
+ pressure: bytes >= pressureAt,
595
+ tripped: bytes >= t.SCHEMA_BYTES_TRIP,
596
+ heaviest: weighed.slice(0, 5),
597
+ quarantined,
598
+ quarantinedBytes,
599
+ episodes,
600
+ episodeBytes,
601
+ migrated,
602
+ migratedBytes,
603
+ };
604
+ }