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,1744 @@
1
+ /**
2
+ * The web dashboard's JSON views — the same read surface the terminal views use
3
+ * (`DashboardSource`), shaped for a page instead of for a column of text.
4
+ *
5
+ * Four rules travel from the terminal adapter unchanged, and they are the reason
6
+ * this file exists rather than a handful of ad-hoc handlers in the server:
7
+ *
8
+ * 1. **Render-time id resolution, everywhere.** Nothing below emits text that
9
+ * was stored beside an id. Every id becomes words at the moment the request
10
+ * is served, through `reveal()` — so a removed memory reads as removed in a
11
+ * panel built from a three-day-old event (scar §2.20).
12
+ * 2. **Confidential rows are withheld the way every other surface withholds
13
+ * them** (`reveal.ts`). The row stays visible — id, band, strength, its dot
14
+ * in the constellation — and only the sentence is gone. A memory the owner
15
+ * cannot see the existence of would be the worse failure.
16
+ * 3. **Absence has two words.** `(none yet)` — asked, and the answer is zero.
17
+ * `(never run)` — never asked. Every panel says which; none is blank
18
+ * (scar §2.4, `NOTES.md`).
19
+ * 4. **Totality.** Kinds, bands, cycle phases and durable event names come
20
+ * from `registries.ts`, which derives them from the live core. A member
21
+ * with nothing to report is a row that says so.
22
+ *
23
+ * The journal is excluded from every memory census here, exactly as `status.ts`
24
+ * and `browse.ts` exclude it: an episode is the SOURCE a memory was made from,
25
+ * it sits outside every sleep phase, and counting it would make the census wrong
26
+ * by the number of days lived.
27
+ */
28
+ import { band, rep, sal, strength, symmetryCheck, TUNABLES as PHYSICS } from "../../../core/physics/index.js";
29
+ import { TUNABLES as SCHEMA_TUNABLES } from "../../../core/schemas/index.js";
30
+ import {
31
+ MARKER_UNSET,
32
+ MERGE_ARCHIVE_REASON,
33
+ PRUNE_ARCHIVE_REASON,
34
+ isJournal,
35
+ readMarker,
36
+ } from "../../../core/sleep/index.js";
37
+ import { FRAMING, LANE_ORDER, pageSections } from "../../../core/self/index.js";
38
+ import type { PageVersion } from "../../../core/self/index.js";
39
+ import type { Band, Kind } from "../../../core/types.js";
40
+ import { NEVER, NONE, num } from "../layout.js";
41
+ import { BANDS, CYCLE_PHASES, DURABLE_EVENTS, DURABLE_EVENT_NAMES, KINDS } from "../registries.js";
42
+ import type { DurableEventName } from "../registries.js";
43
+ import type { DashboardSource } from "../source.js";
44
+ import { contestedBeliefs } from "../stories.js";
45
+ import { FLOW_EDGES, FLOW_NODES, NO_EVENT_OF_ITS_OWN, UNLOGGED_PATH, eventsOfNode, findNode } from "./flow.js";
46
+ import type { NodeKey } from "./flow.js";
47
+ import { narrate } from "./narrate.js";
48
+ import type { NarratedEvent } from "./narrate.js";
49
+ import { WITHHELD, gistOfDoc, reveal, revealHere } from "./reveal.js";
50
+
51
+ /** How many rows a feed hands back unless asked otherwise. */
52
+ export const FEED_LIMIT = 40;
53
+ /** The event-log read ceiling. The log is bounded-retention anyway. */
54
+ const LOG_CEILING = 20_000;
55
+
56
+ // ─────────────────────────────────────────────────────────────────────────────
57
+ // shared shaping
58
+ // ─────────────────────────────────────────────────────────────────────────────
59
+
60
+ export interface MemoryLine {
61
+ readonly id: string;
62
+ readonly text: string;
63
+ readonly confidential: boolean;
64
+ readonly kind: Kind;
65
+ readonly band: Band;
66
+ /** The band column as recorded — a birth fossil, kept beside the live one. */
67
+ readonly recordedBand: Band;
68
+ readonly strength: number;
69
+ readonly salience: number;
70
+ readonly uses: number;
71
+ readonly bornDay: number;
72
+ readonly lastUsedDay: number;
73
+ readonly ageDays: number;
74
+ readonly protected: boolean;
75
+ readonly promoted: boolean;
76
+ readonly pressure: number;
77
+ readonly archived: string | null;
78
+ /**
79
+ * True for a `schema` row — an entity, or a belief about one.
80
+ *
81
+ * It is in this census because the physics runs on it like anything else and
82
+ * every distribution on the memories page should cover it. It is NOT a
83
+ * memory, and counting it as one made the overview's headline disagree with
84
+ * the console: 145 against `counterparts status`'s 121 memories plus 24
85
+ * beliefs and entities, on the same store, at the same moment.
86
+ */
87
+ readonly schema: boolean;
88
+ /** True when the row would not read at all — listed, never dropped. */
89
+ readonly unreadable: boolean;
90
+ }
91
+
92
+ interface CensusOptions {
93
+ readonly includeArchived?: boolean;
94
+ }
95
+
96
+ /**
97
+ * Every live memory, with its physics computed for today. One pass; every panel
98
+ * on the memories page is a fold over this array, so the page cannot disagree
99
+ * with itself about how many memories there are.
100
+ */
101
+ function census(src: DashboardSource, opts: CensusOptions = {}): MemoryLine[] {
102
+ const store = src.store;
103
+ const day = store.livedDay();
104
+ const filter = opts.includeArchived === true ? {} : { archived: false };
105
+ const out: MemoryLine[] = [];
106
+ for (const id of store.list(filter)) {
107
+ const row = store.row(id);
108
+ if (row === undefined) continue;
109
+ // The journal is not a memory. See the file header.
110
+ if (isJournal(row)) continue;
111
+ try {
112
+ const physics = store.physicsOf(id);
113
+ const doc = store.readProse(id);
114
+ const g = gistOfDoc(doc, 96);
115
+ const live = band(physics, day);
116
+ out.push({
117
+ id,
118
+ text: g.text,
119
+ confidential: g.confidential,
120
+ kind: row.kind,
121
+ band: live,
122
+ recordedBand: row.band,
123
+ strength: strength(physics, day),
124
+ salience: sal(physics.salience),
125
+ uses: physics.uses,
126
+ bornDay: physics.birthDay,
127
+ lastUsedDay: physics.lastUsedDay,
128
+ ageDays: Math.max(0, day - physics.birthDay),
129
+ protected: physics.protected === true,
130
+ promoted: physics.promotedIdentity === true,
131
+ pressure: physics.pressure,
132
+ archived: row.archived === 1 ? (row.archived_reason ?? "archived") : null,
133
+ schema: row.type === "schema",
134
+ unreadable: false,
135
+ });
136
+ } catch {
137
+ // A removed row, or prose that will not read. It is still a real row, so
138
+ // it is a named absence in the list rather than a silent subtraction.
139
+ out.push({
140
+ id,
141
+ text: reveal(store, id, 96).label,
142
+ confidential: false,
143
+ kind: row.kind,
144
+ band: row.band,
145
+ recordedBand: row.band,
146
+ strength: 0,
147
+ salience: 0,
148
+ uses: 0,
149
+ bornDay: 0,
150
+ lastUsedDay: 0,
151
+ ageDays: 0,
152
+ protected: row.protected === 1,
153
+ promoted: row.promoted_identity === 1,
154
+ pressure: row.pressure,
155
+ archived: row.archived === 1 ? (row.archived_reason ?? "archived") : null,
156
+ schema: row.type === "schema",
157
+ unreadable: true,
158
+ });
159
+ }
160
+ }
161
+ // Strongest first, ties by id — the same order `browse.ts` lists in, so the
162
+ // two surfaces answer "what is strong today" the same way, and so a caller
163
+ // that takes the head of this list gets a defined row rather than whatever
164
+ // SQLite happened to return first.
165
+ out.sort((a, b) => b.strength - a.strength || (a.id < b.id ? -1 : 1));
166
+ return out;
167
+ }
168
+
169
+ function countMap<T extends string>(rows: readonly { readonly [K in keyof MemoryLine]: MemoryLine[K] }[], key: "kind" | "band"): Map<T, number> {
170
+ const m = new Map<T, number>();
171
+ for (const r of rows) {
172
+ const v = r[key] as unknown as T;
173
+ m.set(v, (m.get(v) ?? 0) + 1);
174
+ }
175
+ return m;
176
+ }
177
+
178
+ /** The absence word for a count. Two words, deliberately (`NOTES.md`). */
179
+ function absenceFor(count: number, everAsked: boolean): string | null {
180
+ if (count > 0) return null;
181
+ return everAsked ? NONE : NEVER;
182
+ }
183
+
184
+ /** Live memories, journal and schema rows excluded. The number the console
185
+ * prints after `Memories:`, and the number every surface here must agree on. */
186
+ function memoriesHeld(src: DashboardSource): number {
187
+ return census(src).filter((r) => !r.schema).length;
188
+ }
189
+
190
+ function eventsNamed(src: DashboardSource, name: string): number {
191
+ return src.store.eventLog({ name, limit: LOG_CEILING }).length;
192
+ }
193
+
194
+ // ─────────────────────────────────────────────────────────────────────────────
195
+ // meta — what this dashboard is pointed at
196
+ // ─────────────────────────────────────────────────────────────────────────────
197
+
198
+ export interface MetaView {
199
+ readonly dir: string;
200
+ readonly day: number;
201
+ readonly lastActive: string | null;
202
+ readonly observer: true;
203
+ readonly retentionDays: number;
204
+ /** True when nothing has ever been stored. The page says so on purpose. */
205
+ readonly empty: boolean;
206
+ /**
207
+ * HOW MANY ROWS THE STORE HOLDS RIGHT NOW — a fingerprint, not a headline.
208
+ *
209
+ * An open page polls the event log to know whether anything happened, and
210
+ * that is a wrong question: a deposit that writes no durable event never moves
211
+ * the log's sequence, so a page left open reports the old count forever
212
+ * (design review, 2026-09-04 — the only wrong number left on any screen). This
213
+ * is the cheap thing a poll can compare to notice a deposit that left no trace
214
+ * in the log.
215
+ *
216
+ * The case that MOTIVATED it has since gone away: `counterparts note` was the
217
+ * example, and since `gate.deposit` (2026-09-05, replay §2a) the authored door
218
+ * writes a row like every other door, so a note moves the sequence and takes
219
+ * the event branch. This stays as the belt it always was — a store seeded
220
+ * around the door, a migration, any future write that leaves no row — and
221
+ * because a fingerprint that is only correct while one particular writer
222
+ * happens to log is not a fingerprint.
223
+ *
224
+ * It counts every row, including the journal and the archived, which is why
225
+ * it is not called `held`: nothing should ever render it as a memory count.
226
+ */
227
+ readonly rows: number;
228
+ readonly generatedAt: number;
229
+ }
230
+
231
+ /** An empty string is the store's "never moved", not a date. */
232
+ function lastActive(raw: string | undefined): string | null {
233
+ return raw === undefined || raw.trim().length === 0 ? null : raw;
234
+ }
235
+
236
+ export function metaView(src: DashboardSource): MetaView {
237
+ const store = src.store;
238
+ const rows = store.list().length;
239
+ return {
240
+ dir: store.dir,
241
+ day: store.livedDay(),
242
+ lastActive: lastActive(store.getMeta("lastActiveDate")),
243
+ observer: true,
244
+ retentionDays: store.retentionDays,
245
+ empty: rows === 0,
246
+ rows,
247
+ generatedAt: Date.now(),
248
+ };
249
+ }
250
+
251
+ // ─────────────────────────────────────────────────────────────────────────────
252
+ // overview
253
+ // ─────────────────────────────────────────────────────────────────────────────
254
+
255
+ export interface Tile {
256
+ readonly label: string;
257
+ readonly value: string;
258
+ readonly note: string;
259
+ readonly accent: "cyan" | "purple" | "amber" | "teal" | "red";
260
+ /** True when the value is an absence marker, not a number. */
261
+ readonly absent: boolean;
262
+ }
263
+
264
+ export interface BarRow {
265
+ readonly label: string;
266
+ readonly count: number;
267
+ readonly fraction: number;
268
+ readonly note: string;
269
+ readonly absent: string | null;
270
+ }
271
+
272
+ export interface ContestedRow {
273
+ readonly id: string;
274
+ readonly headId: string | null;
275
+ readonly about: string;
276
+ /** What it said at its own address, shown around the point it diverges. */
277
+ readonly began: string;
278
+ /** What it says now, shown around the same point. */
279
+ readonly now: string;
280
+ /** Both, whole — for a tooltip and for anyone who wants the sentence. */
281
+ readonly beganFull: string;
282
+ readonly nowFull: string;
283
+ readonly pressure: number;
284
+ readonly bar: number;
285
+ readonly fraction: number;
286
+ readonly revised: boolean;
287
+ readonly challenges: number;
288
+ readonly lastChallengedDay: number | null;
289
+ }
290
+
291
+ export interface ChapterRow {
292
+ readonly id: string;
293
+ readonly title: string;
294
+ readonly day: number;
295
+ readonly bytes: number;
296
+ /** The chapter's opening, in the first person. Never the whole entry. */
297
+ readonly opening: string;
298
+ }
299
+
300
+ export interface OverviewView {
301
+ readonly opening: string;
302
+ readonly tiles: Tile[];
303
+ readonly bands: BarRow[];
304
+ readonly bandNote: string;
305
+ readonly feed: NarratedEvent[];
306
+ /**
307
+ * `promotedDay` is the lived day this element crossed into the band, read off
308
+ * the `band.promoted` record, or null where no such record exists (a seeded
309
+ * or migrated core was never watched crossing). It is here because `strength`
310
+ * on an identity row is a TAUTOLOGY: every element in the band is at 1.00 by
311
+ * construction, so fifteen rows of `strength 1.00` said one thing fifteen
312
+ * times (design review, 2026-09-04, ranked #2). The day it earned the band is
313
+ * the fact that varies — and where the store never recorded one, the row says
314
+ * nothing there rather than inventing a day or repeating the tautology.
315
+ */
316
+ readonly identity: { id: string; text: string; kind: Kind; band: Band; strength: number; promotedDay: number | null; bornDay: number; lastUsedDay: number; confidential: boolean }[];
317
+ readonly identityAbsent: string | null;
318
+ readonly guarded: { id: string; text: string; kind: Kind; bornDay: number; lastUsedDay: number; confidential: boolean }[];
319
+ readonly guardedAbsent: string | null;
320
+ readonly contested: ContestedRow[];
321
+ readonly contestedAbsent: string | null;
322
+ readonly chapters: ChapterRow[];
323
+ readonly chaptersAbsent: string | null;
324
+ }
325
+
326
+ const BAND_GLOSS: Record<Band, string> = {
327
+ episodic: "still an episode; forgettable, and most stay here",
328
+ semantic: "settled into what I know",
329
+ identity: "constitutive — and physics can still move it",
330
+ };
331
+
332
+ export function overviewView(src: DashboardSource, feedLimit = FEED_LIMIT): OverviewView {
333
+ const store = src.store;
334
+ const day = store.livedDay();
335
+ const rows = census(src);
336
+ // A SCHEMA ROW IS NOT A MEMORY. The census keeps both, because the bands and
337
+ // kinds below are true of both and the physics runs on both — but the number
338
+ // in the headline tile is the one a person compares against the console, and
339
+ // the console says memories. See `MemoryLine.schema`.
340
+ const held = rows.filter((r) => !r.schema);
341
+ const beliefs = rows.length - held.length;
342
+ const archived = census(src, { includeArchived: true }).filter((r) => r.archived !== null);
343
+ const journal = chapters(src, 5);
344
+ const journalCount = store.list().filter((id) => {
345
+ const row = store.row(id);
346
+ return row !== undefined && isJournal(row);
347
+ }).length;
348
+ const e = src.self.enumerate(day);
349
+ const wake = src.self.wake();
350
+ const contested = contestedRows(src);
351
+ const byBand = countMap<Band>(rows, "band");
352
+ const peak = Math.max(1, ...BANDS.map((b) => byBand.get(b) ?? 0));
353
+ const everLived = day > 0 || rows.length > 0 || journalCount > 0;
354
+ // The lived day each element crossed into the identity band, where the store
355
+ // watched it happen. Read once for the panel rather than once per row.
356
+ const promotedDays = new Map<string, number>();
357
+ for (const row of store.eventLog({ name: "band.promoted", limit: LOG_CEILING })) {
358
+ if (row.ref !== null && !promotedDays.has(row.ref)) promotedDays.set(row.ref, row.day);
359
+ }
360
+
361
+ const tiles: Tile[] = [
362
+ {
363
+ label: "lived days",
364
+ value: String(day),
365
+ note:
366
+ lastActive(store.getMeta("lastActiveDate")) === null
367
+ ? "the clock has never moved"
368
+ : `last of them ${lastActive(store.getMeta("lastActiveDate")) ?? ""}`,
369
+ accent: "cyan",
370
+ absent: day === 0,
371
+ },
372
+ { label: "memories held", value: String(held.length), note: "live, journal excluded", accent: "cyan", absent: held.length === 0 },
373
+ {
374
+ label: "beliefs and entities",
375
+ value: String(beliefs),
376
+ note: "held like memories, counted apart",
377
+ accent: "teal",
378
+ absent: beliefs === 0,
379
+ },
380
+ { label: "archived", value: String(archived.length), note: "held, not gone", accent: "teal", absent: archived.length === 0 },
381
+ { label: "journal entries", value: String(journalCount), note: "chapters — these do not decay", accent: "purple", absent: journalCount === 0 },
382
+ { label: "identity band", value: String(e.identity.length), note: "what strength earned", accent: "purple", absent: e.identity.length === 0 },
383
+ { label: "protected", value: String(e.protected.length), note: "permanent ink, no revision reaches it", accent: "amber", absent: e.protected.length === 0 },
384
+ {
385
+ label: "contested beliefs",
386
+ value: String(contested.length),
387
+ note: contested.length === 0 ? "nothing has argued with me" : "arguments in progress or settled",
388
+ accent: contested.some((c) => c.fraction >= 1) ? "amber" : "teal",
389
+ absent: contested.length === 0,
390
+ },
391
+ {
392
+ label: "last cycle",
393
+ value: lastCycleDay(src) === null ? NEVER : `day ${lastCycleDay(src)}`,
394
+ note: "the newest phase marker I hold",
395
+ accent: "teal",
396
+ absent: lastCycleDay(src) === null,
397
+ },
398
+ {
399
+ label: "wake bytes",
400
+ value: wake.ok ? String(wake.bytes) : NEVER,
401
+ note: wake.ok ? "composed and waiting for the next session" : `nothing waiting (${wake.reason})`,
402
+ accent: wake.ok ? "cyan" : "amber",
403
+ absent: !wake.ok,
404
+ },
405
+ ];
406
+
407
+ const opening =
408
+ day === 0 && rows.length === 0
409
+ ? "I have not lived a day yet. Everything below is what I would be able to tell you, and the honest word for how much of it I know is on each panel."
410
+ : `I have lived ${day} ${day === 1 ? "day" : "days"}. I am holding ${held.length} ${held.length === 1 ? "memory" : "memories"}` +
411
+ (beliefs === 0 ? "" : ` and ${beliefs} ${beliefs === 1 ? "belief or entity" : "beliefs and entities"}`) +
412
+ (archived.length === 0 ? "" : `, with ${archived.length} more archived`) +
413
+ (journalCount === 0 ? "." : `, beside ${journalCount} journal ${journalCount === 1 ? "entry" : "entries"} that do not decay.`);
414
+
415
+ return {
416
+ opening,
417
+ tiles,
418
+ bands: BANDS.map((b) => {
419
+ const count = byBand.get(b) ?? 0;
420
+ return {
421
+ label: b,
422
+ count,
423
+ fraction: count / peak,
424
+ note: BAND_GLOSS[b],
425
+ absent: absenceFor(count, everLived),
426
+ };
427
+ }),
428
+ bandNote:
429
+ "Memories start episodic and climb only by being used on separate days. Most fade where they started — that is the design, not a shortfall.",
430
+ feed: activityView(src, { limit: feedLimit }).events,
431
+ identity: e.identity.slice(0, 12).map((el) => {
432
+ const r = reveal(store, el.id, 90);
433
+ return {
434
+ id: el.id,
435
+ text: r.text ?? r.label,
436
+ kind: el.kind,
437
+ band: el.band,
438
+ strength: el.strength,
439
+ promotedDay: promotedDays.get(el.id) ?? null,
440
+ ...livedDays(src, el.id),
441
+ confidential: r.confidential,
442
+ };
443
+ }),
444
+ identityAbsent: e.identity.length === 0 ? (everLived ? NONE : NEVER) : null,
445
+ guarded: e.protected.slice(0, 12).map((el) => {
446
+ const r = reveal(store, el.id, 90);
447
+ return {
448
+ id: el.id,
449
+ text: r.text ?? r.label,
450
+ kind: el.kind,
451
+ ...livedDays(src, el.id),
452
+ confidential: r.confidential,
453
+ };
454
+ }),
455
+ guardedAbsent: e.protected.length === 0 ? (everLived ? NONE : NEVER) : null,
456
+ contested,
457
+ contestedAbsent: contested.length === 0 ? (everLived ? NONE : NEVER) : null,
458
+ chapters: journal,
459
+ chaptersAbsent: journal.length === 0 ? (everLived ? NONE : NEVER) : null,
460
+ };
461
+ }
462
+
463
+ /**
464
+ * THE TWO LIVED DAYS — born, and last used.
465
+ *
466
+ * These are the row's metadata now, and the calendar date is not; it has moved
467
+ * to the modal, where there is room to say what it means. The reason is a
468
+ * measurement (design review, 2026-09-04): the identity panel rendered fifteen
469
+ * rows of `learned 2026-09-04` under fifteen rows of `strength 1.00`, so two of
470
+ * the three fields a reader could see never varied, and the panel read as a
471
+ * table of one fact repeated. It was filed as a limitation of the demo store.
472
+ * It was not: `learnedOn` is the day a row ENTERED this store, which in a store
473
+ * built or migrated in one run is the same morning for everything in it, while
474
+ * the lived days are what the physics actually ran on and they spread across
475
+ * the whole month. The more interesting fact was already in the store and the
476
+ * row was showing the other one.
477
+ *
478
+ * `lastUsedDay` is also the one that keeps moving: it is what "this is still
479
+ * load-bearing" looks like as a number.
480
+ */
481
+ function livedDays(src: DashboardSource, id: string): { bornDay: number; lastUsedDay: number } {
482
+ try {
483
+ const physics = src.store.physicsOf(id);
484
+ return { bornDay: physics.birthDay, lastUsedDay: physics.lastUsedDay };
485
+ } catch {
486
+ return { bornDay: 0, lastUsedDay: 0 };
487
+ }
488
+ }
489
+
490
+ function lastCycleDay(src: DashboardSource): number | null {
491
+ let newest: number | null = null;
492
+ for (const phase of CYCLE_PHASES) {
493
+ const marker = readMarker(src.store, phase);
494
+ if (marker.health === "torn" || marker.day === MARKER_UNSET) continue;
495
+ newest = newest === null ? marker.day : Math.max(newest, marker.day);
496
+ }
497
+ return newest;
498
+ }
499
+
500
+ function contestedRows(src: DashboardSource): ContestedRow[] {
501
+ const store = src.store;
502
+ const out: ContestedRow[] = [];
503
+ for (const [rootId] of contestedBeliefs(src)) {
504
+ if (rootId === undefined) continue;
505
+ let story;
506
+ try {
507
+ story = src.schemas.story(rootId);
508
+ } catch {
509
+ continue;
510
+ }
511
+ // UNFOLLOWED for the origin. `reveal` walks the supersede chain, so both
512
+ // ends resolved to the SAME row and the page rendered "it began as X" and
513
+ // "it now says X" as byte-identical strings — the one surface whose whole
514
+ // job is to show a change showed none. The retained prose at the original
515
+ // address is what "it began as" means, and `stories.ts` reads it the same
516
+ // way for the same reason.
517
+ const began = revealHere(store, rootId, FULL);
518
+ const now = reveal(store, story.headId, FULL);
519
+ const [beganShown, nowShown] = divergentPair(
520
+ began.text ?? began.label,
521
+ now.text ?? now.label,
522
+ );
523
+ let about = NONE;
524
+ try {
525
+ const entityId = store.readProse(story.headId).meta["entityId"];
526
+ if (typeof entityId === "string") {
527
+ const r = reveal(store, entityId, 60);
528
+ about = r.text ?? r.label;
529
+ }
530
+ } catch {
531
+ about = NONE;
532
+ }
533
+ out.push({
534
+ id: rootId,
535
+ headId: story.headId,
536
+ about,
537
+ began: beganShown,
538
+ now: nowShown,
539
+ beganFull: began.text ?? began.label,
540
+ nowFull: now.text ?? now.label,
541
+ pressure: story.pressure,
542
+ bar: story.bar,
543
+ fraction: story.bar > 0 ? Math.min(1.4, story.pressure / story.bar) : 0,
544
+ revised: story.headId !== rootId,
545
+ challenges: story.increments.length,
546
+ lastChallengedDay: story.lastChallengedDay,
547
+ });
548
+ }
549
+ return out.sort((a, b) => b.fraction - a.fraction || (a.id < b.id ? -1 : 1));
550
+ }
551
+
552
+ /** Wide enough that a statement is read whole before anything is cut. */
553
+ const FULL = 400;
554
+
555
+ /** `text`, cut to `width`, ending in an ellipsis so a cut is visible as one. */
556
+ function clipTo(text: string, width: number): string {
557
+ return text.length <= width ? text : `${text.slice(0, width - 1).trimEnd()}…`;
558
+ }
559
+
560
+ /**
561
+ * TWO VERSIONS OF ONE STATEMENT, SHOWN AROUND THE POINT THEY DIVERGE.
562
+ *
563
+ * A revision usually keeps most of its sentence — that is what makes it a
564
+ * revision rather than a new belief — so truncating both from character zero
565
+ * shows the identical prefix twice and cuts the change off the end. The window
566
+ * starts a little before the first character that differs, on a word boundary,
567
+ * with a leading ellipsis when it is not the start of the sentence.
568
+ *
569
+ * Two strings that really are identical come back identical; the caller decides
570
+ * what to say about that (a belief whose successor says the same thing is a
571
+ * fact worth reading, not a bug to hide).
572
+ */
573
+ export function divergentPair(a: string, b: string, width = 150): [string, string] {
574
+ if (a === b) return [clipTo(a, width), clipTo(b, width)];
575
+ let i = 0;
576
+ const shared = Math.min(a.length, b.length);
577
+ while (i < shared && a[i] === b[i]) i += 1;
578
+ let start = i;
579
+ while (start > 0 && !/\s/.test(a[start - 1] ?? "")) start -= 1;
580
+ // Enough lead-in that the changed clause has a subject, never so much that
581
+ // the window is spent on text both versions share.
582
+ const lead = Math.min(start, Math.floor(width / 3));
583
+ const from = start - lead;
584
+ const head = from > 0 ? "…" : "";
585
+ return [`${head}${clipTo(a.slice(from), width)}`, `${head}${clipTo(b.slice(from), width)}`];
586
+ }
587
+
588
+ function chapters(src: DashboardSource, limit: number): ChapterRow[] {
589
+ const store = src.store;
590
+ const out: ChapterRow[] = [];
591
+ for (const id of store.list({ archived: false })) {
592
+ const row = store.row(id);
593
+ if (row === undefined || !isJournal(row)) continue;
594
+ try {
595
+ const doc = store.readProse(id);
596
+ const body = doc.body.trim();
597
+ const opening = firstSentences(body, 260);
598
+ out.push({
599
+ id,
600
+ title: doc.title ?? "an unnamed chapter",
601
+ day: doc.bornDay,
602
+ bytes: new TextEncoder().encode(body).length,
603
+ opening,
604
+ });
605
+ } catch {
606
+ out.push({ id, title: reveal(store, id, 60).label, day: 0, bytes: 0, opening: "" });
607
+ }
608
+ }
609
+ return out.sort((a, b) => b.day - a.day || (a.id < b.id ? -1 : 1)).slice(0, limit);
610
+ }
611
+
612
+ /** The first prose of a chapter, bounded. Headings skipped; never the whole entry. */
613
+ function firstSentences(body: string, max: number): string {
614
+ const lines = body
615
+ .split("\n")
616
+ .map((l) => l.trim())
617
+ .filter((l) => l.length > 0 && !l.startsWith("#") && !l.startsWith("<!--"));
618
+ const joined = lines.join(" ");
619
+ return joined.length <= max ? joined : `${joined.slice(0, max).trimEnd()}…`;
620
+ }
621
+
622
+ // ─────────────────────────────────────────────────────────────────────────────
623
+ // memories
624
+ // ─────────────────────────────────────────────────────────────────────────────
625
+
626
+ export interface KindRow {
627
+ readonly kind: Kind;
628
+ readonly count: number;
629
+ readonly meanStrength: number;
630
+ readonly absent: string | null;
631
+ readonly wSal: number;
632
+ readonly wRep: number;
633
+ readonly kappa: number;
634
+ readonly iota: number;
635
+ readonly gloss: string;
636
+ }
637
+
638
+ export interface HubRow {
639
+ readonly id: string;
640
+ readonly text: string;
641
+ readonly confidential: boolean;
642
+ readonly weight: number;
643
+ readonly degree: number;
644
+ }
645
+
646
+ export interface MemoriesView {
647
+ readonly day: number;
648
+ readonly total: number;
649
+ readonly points: MemoryLine[];
650
+ readonly distribution: { from: number; to: number; count: number }[];
651
+ readonly bands: BarRow[];
652
+ readonly kinds: KindRow[];
653
+ readonly hubs: HubRow[];
654
+ readonly hubsAbsent: string | null;
655
+ readonly pointsAbsent: string | null;
656
+ readonly note: string;
657
+ }
658
+
659
+ const KIND_GLOSS: Record<Kind, string> = {
660
+ self: "who I am — salience only, and the slowest to be argued out of",
661
+ person: "someone I know — salience carries it, repetition does not",
662
+ entity: "a thing in the world — both arms count",
663
+ skill: "how to do something — repetition is nearly all of it, and it erodes slowest",
664
+ place: "somewhere — repetition-driven, slow to erode",
665
+ fact: "a plain fact — erodes fastest, and the cheapest to overturn",
666
+ };
667
+
668
+ export function memoriesView(src: DashboardSource, opts: { limit?: number } = {}): MemoriesView {
669
+ const store = src.store;
670
+ const day = store.livedDay();
671
+ const rows = census(src);
672
+ const limit = opts.limit ?? 4000;
673
+ const byKind = countMap<Kind>(rows, "kind");
674
+ const byBand = countMap<Band>(rows, "band");
675
+ const peak = Math.max(1, ...BANDS.map((b) => byBand.get(b) ?? 0));
676
+ const everLived = day > 0 || rows.length > 0;
677
+
678
+ const meanByKind = new Map<Kind, number[]>();
679
+ for (const r of rows) {
680
+ const list = meanByKind.get(r.kind) ?? [];
681
+ list.push(r.strength);
682
+ meanByKind.set(r.kind, list);
683
+ }
684
+
685
+ const buckets = 20;
686
+ const distribution = Array.from({ length: buckets }, (_, i) => ({
687
+ from: i / buckets,
688
+ to: (i + 1) / buckets,
689
+ count: 0,
690
+ }));
691
+ for (const r of rows) {
692
+ const i = Math.min(buckets - 1, Math.max(0, Math.floor(r.strength * buckets)));
693
+ const bucket = distribution[i];
694
+ if (bucket !== undefined) bucket.count += 1;
695
+ }
696
+
697
+ return {
698
+ day,
699
+ total: rows.length,
700
+ points: rows.slice(0, limit),
701
+ pointsAbsent: rows.length === 0 ? (everLived ? NONE : NEVER) : null,
702
+ distribution,
703
+ bands: BANDS.map((b) => {
704
+ const count = byBand.get(b) ?? 0;
705
+ return { label: b, count, fraction: count / peak, note: BAND_GLOSS[b], absent: absenceFor(count, everLived) };
706
+ }),
707
+ kinds: KINDS.map((kind) => {
708
+ const count = byKind.get(kind) ?? 0;
709
+ const list = meanByKind.get(kind) ?? [];
710
+ const tunables = PHYSICS.KINDS[kind];
711
+ return {
712
+ kind,
713
+ count,
714
+ meanStrength: list.length === 0 ? 0 : list.reduce((a, b) => a + b, 0) / list.length,
715
+ absent: absenceFor(count, everLived),
716
+ wSal: tunables.wSal,
717
+ wRep: tunables.wRep,
718
+ kappa: tunables.kappa,
719
+ iota: tunables.iota,
720
+ gloss: KIND_GLOSS[kind],
721
+ };
722
+ }),
723
+ hubs: hubs(src, 15),
724
+ hubsAbsent: hubs(src, 1).length === 0 ? (everLived ? NONE : NEVER) : null,
725
+ note: "Every dot is one memory — or one of the beliefs and entities the schemas hold, which decay and consolidate the same way and are counted apart only where a headline says memories. How many lived days old across, how strong up, how much it mattered at encoding as its size. Colour is the band it is in today, computed now — not the band it was born into.",
726
+ };
727
+ }
728
+
729
+ function hubs(src: DashboardSource, limit: number): HubRow[] {
730
+ const store = src.store;
731
+ const weight = new Map<string, { w: number; d: number }>();
732
+ for (const id of store.list({ archived: false })) {
733
+ const row = store.row(id);
734
+ if (row === undefined || isJournal(row)) continue;
735
+ for (const edge of store.edgesFrom(id)) {
736
+ for (const end of [id, edge.dst]) {
737
+ const cur = weight.get(end) ?? { w: 0, d: 0 };
738
+ cur.w += edge.weight;
739
+ cur.d += 1;
740
+ weight.set(end, cur);
741
+ }
742
+ }
743
+ }
744
+ return [...weight.entries()]
745
+ .sort((a, b) => b[1].w - a[1].w || (a[0] < b[0] ? -1 : 1))
746
+ .slice(0, limit)
747
+ .map(([id, v]) => {
748
+ const r = reveal(store, id, 72);
749
+ return { id, text: r.text ?? r.label, confidential: r.confidential, weight: v.w, degree: v.d };
750
+ });
751
+ }
752
+
753
+ // ─────────────────────────────────────────────────────────────────────────────
754
+ // one memory, opened
755
+ // ─────────────────────────────────────────────────────────────────────────────
756
+
757
+ export interface MemoryDetail {
758
+ readonly found: boolean;
759
+ readonly id: string;
760
+ readonly headId: string | null;
761
+ readonly askedFor: string | null;
762
+ /**
763
+ * True when this row is a JOURNAL entry rather than a memory. It matters on
764
+ * an inspection surface: an episode is the source a memory was made from, it
765
+ * sits outside every sleep phase, and the physics below it is recorded but
766
+ * never acted on. Printing its strength without saying that would invite the
767
+ * owner to read a number the engine ignores.
768
+ */
769
+ readonly journal: boolean;
770
+ readonly title: string;
771
+ readonly text: string;
772
+ readonly confidential: boolean;
773
+ /**
774
+ * Which record this is — the revision it is on, and the hash of the text
775
+ * above.
776
+ *
777
+ * This pair replaced the memory file's path in the modal's subtitle. The path
778
+ * named a filesystem layout, and a store is not its layout: what identifies a
779
+ * memory is its id, and what identifies THIS reading of it is the revision and
780
+ * the hash. The id the copy button hands over is `id`.
781
+ *
782
+ * `contentHash` is blank when the body is withheld — see below.
783
+ */
784
+ readonly revision: number;
785
+ readonly contentHash: string;
786
+ readonly kind: Kind;
787
+ readonly band: Band;
788
+ readonly recordedBand: string;
789
+ readonly strength: number;
790
+ readonly salience: { relevance: number; emotional: number; predictive: number; novelty: number | null; claimed: number | null; combined: number };
791
+ readonly repetition: number;
792
+ readonly uses: number;
793
+ readonly reinforcedDays: number;
794
+ readonly bornDay: number;
795
+ readonly lastUsedDay: number;
796
+ readonly learnedOn: string;
797
+ readonly happenedOn: string | null;
798
+ readonly consolidated: boolean;
799
+ readonly promoted: boolean;
800
+ readonly protected: boolean;
801
+ readonly pressure: number;
802
+ readonly bar: number | null;
803
+ readonly archived: string | null;
804
+ readonly removal: { stage: string; actor: string; reason: string | null; at: number }[];
805
+ readonly edges: { id: string; text: string; weight: number; confidential: boolean }[];
806
+ readonly points: { role: string; id: string; text: string }[];
807
+ readonly versions: { seq: number; reason: string; day: number; became: string }[];
808
+ readonly prospective: { date: string; state: string; fires: number; precision: string }[];
809
+ readonly absence: string | null;
810
+ }
811
+
812
+ export function memoryDetail(src: DashboardSource, id: string): MemoryDetail {
813
+ const store = src.store;
814
+ const day = store.livedDay();
815
+ const r = reveal(store, id, 120);
816
+ const empty = {
817
+ found: false,
818
+ id,
819
+ headId: r.headId,
820
+ askedFor: null,
821
+ journal: false,
822
+ title: "",
823
+ text: "",
824
+ confidential: false,
825
+ revision: 0,
826
+ contentHash: "",
827
+ kind: "fact" as Kind,
828
+ band: "episodic" as Band,
829
+ recordedBand: "—",
830
+ strength: 0,
831
+ salience: { relevance: 0, emotional: 0, predictive: 0, novelty: null, claimed: null, combined: 0 },
832
+ repetition: 0,
833
+ uses: 0,
834
+ reinforcedDays: 0,
835
+ bornDay: 0,
836
+ lastUsedDay: 0,
837
+ learnedOn: "—",
838
+ happenedOn: null,
839
+ consolidated: false,
840
+ promoted: false,
841
+ protected: false,
842
+ pressure: 0,
843
+ bar: null,
844
+ archived: null,
845
+ removal: store.removalRecord(id).map((x) => ({ stage: x.stage, actor: x.actor, reason: x.reason, at: x.at })),
846
+ edges: [],
847
+ points: [],
848
+ versions: [],
849
+ prospective: [],
850
+ absence: r.label,
851
+ } satisfies MemoryDetail;
852
+
853
+ if (!r.present || r.headId === null) return empty;
854
+ const headId = r.headId;
855
+ let doc;
856
+ let row;
857
+ let physics;
858
+ try {
859
+ doc = store.readProse(headId);
860
+ row = store.row(headId);
861
+ physics = store.physicsOf(headId);
862
+ } catch {
863
+ return empty;
864
+ }
865
+ const g = gistOfDoc(doc, 120);
866
+
867
+ const points: { role: string; id: string; text: string }[] = [];
868
+ const push = (role: string, target: unknown): void => {
869
+ if (typeof target !== "string") return;
870
+ const rr = reveal(store, target, 80);
871
+ points.push({ role, id: target, text: rr.text ?? rr.label });
872
+ };
873
+ if (row?.superseded_by !== null && row?.superseded_by !== undefined) push("became", row.superseded_by);
874
+ push("hangs on", doc.meta["entityId"]);
875
+ push("revised", doc.meta["updates"]);
876
+ const grounded = doc.meta["groundedIn"];
877
+ if (Array.isArray(grounded)) for (const gid of grounded) push("grounded in", gid);
878
+
879
+ return {
880
+ found: true,
881
+ id: headId,
882
+ headId,
883
+ askedFor: headId === id ? null : id,
884
+ journal: row === undefined ? false : isJournal(row),
885
+ title: doc.title ?? "",
886
+ // The BODY is the memory, and this is the owner's own window onto their own
887
+ // store (constitution line 6). A confidential body is the one exception, and
888
+ // it is withheld here exactly as it is withheld in recall.
889
+ text: g.confidential ? WITHHELD : doc.body.trim(),
890
+ confidential: g.confidential,
891
+ revision: row?.revision ?? 0,
892
+ // A hash of a withheld body is a derivative of withheld text, on the one
893
+ // surface whose job is withholding it. It is a confirmation oracle for an
894
+ // exactly-guessed secret rather than a way to recover one, but this is the
895
+ // wrong place to be interesting. The modal renders `""` as `—`.
896
+ contentHash: g.confidential ? "" : (row?.content_hash ?? ""),
897
+ kind: physics.kind,
898
+ band: band(physics, day),
899
+ recordedBand: `${row?.band ?? "—"} (set day ${row?.band_day ?? "—"})`,
900
+ strength: strength(physics, day),
901
+ salience: {
902
+ relevance: physics.salience.relevance,
903
+ emotional: physics.salience.emotional,
904
+ predictive: physics.salience.predictive,
905
+ novelty: physics.salience.novelty,
906
+ claimed: physics.salience.claimed ?? null,
907
+ combined: sal(physics.salience),
908
+ },
909
+ repetition: rep(physics),
910
+ uses: physics.uses,
911
+ reinforcedDays: physics.reinforcedDays ?? 0,
912
+ bornDay: physics.birthDay,
913
+ lastUsedDay: physics.lastUsedDay,
914
+ learnedOn: doc.learnedOn,
915
+ happenedOn: doc.happenedOn ?? null,
916
+ consolidated: physics.consolidated === true,
917
+ promoted: physics.promotedIdentity === true,
918
+ protected: physics.protected === true,
919
+ pressure: physics.pressure,
920
+ bar: physics.pressure > 0 ? barFor(src, headId) : null,
921
+ archived: row?.archived === 1 ? (row.archived_reason ?? "archived") : null,
922
+ removal: store.removalRecord(headId).map((x) => ({ stage: x.stage, actor: x.actor, reason: x.reason, at: x.at })),
923
+ edges: store.edgesFrom(headId).map((edge) => {
924
+ const rr = reveal(store, edge.dst, 72);
925
+ return { id: edge.dst, text: rr.text ?? rr.label, weight: edge.weight, confidential: rr.confidential };
926
+ }),
927
+ points,
928
+ versions: store.versions(headId).map((v) => ({
929
+ seq: v.seq,
930
+ reason: v.reason,
931
+ day: v.version_day,
932
+ became: v.successor_id === null ? "revised in place" : (reveal(store, v.successor_id, 72).label),
933
+ })),
934
+ prospective: store.prospectiveFor(headId).map((p) => ({
935
+ date: p.event_date,
936
+ state: p.state,
937
+ fires: p.fires,
938
+ precision: p.precision,
939
+ })),
940
+ absence: null,
941
+ };
942
+ }
943
+
944
+ function barFor(src: DashboardSource, id: string): number | null {
945
+ try {
946
+ return src.schemas.story(id).bar;
947
+ } catch {
948
+ return null;
949
+ }
950
+ }
951
+
952
+ // ─────────────────────────────────────────────────────────────────────────────
953
+ // search
954
+ // ─────────────────────────────────────────────────────────────────────────────
955
+
956
+ export interface SearchView {
957
+ readonly q: string;
958
+ readonly hits: { id: string; score: number; text: string; kind: Kind; band: Band; strength: number; confidential: boolean }[];
959
+ readonly absent: string | null;
960
+ }
961
+
962
+ export function searchView(src: DashboardSource, q: string, limit = 25): SearchView {
963
+ const store = src.store;
964
+ const day = store.livedDay();
965
+ const query = q.trim();
966
+ if (query.length === 0) return { q: "", hits: [], absent: NEVER };
967
+ let raw: { id: string; score: number }[];
968
+ try {
969
+ raw = store.search(query, limit * 2);
970
+ } catch {
971
+ return { q: query, hits: [], absent: NONE };
972
+ }
973
+ const hits: SearchView["hits"] = [];
974
+ for (const hit of raw) {
975
+ const row = store.row(hit.id);
976
+ // The journal is searchable in the owner's editor; it is not a memory here.
977
+ if (row === undefined || isJournal(row)) continue;
978
+ const r = reveal(store, hit.id, 100);
979
+ let s = 0;
980
+ let b: Band = row.band;
981
+ try {
982
+ const physics = store.physicsOf(hit.id);
983
+ s = strength(physics, day);
984
+ b = band(physics, day);
985
+ } catch {
986
+ /* a row that will not read is still a hit; it lists with a named absence */
987
+ }
988
+ hits.push({
989
+ id: hit.id,
990
+ score: hit.score,
991
+ text: r.text ?? r.label,
992
+ kind: row.kind,
993
+ band: b,
994
+ strength: s,
995
+ confidential: r.confidential,
996
+ });
997
+ if (hits.length >= limit) break;
998
+ }
999
+ return { q: query, hits, absent: hits.length === 0 ? NONE : null };
1000
+ }
1001
+
1002
+ // ─────────────────────────────────────────────────────────────────────────────
1003
+ // mind — identity, the briefing, the journal, the revision stories
1004
+ // ─────────────────────────────────────────────────────────────────────────────
1005
+
1006
+ export interface WakeLane {
1007
+ /** The lane's own heading, as the briefing writes it. */
1008
+ readonly heading: string;
1009
+ /** The lane name, when this is one of `self/`'s lanes; null for the preface. */
1010
+ readonly lane: string | null;
1011
+ /** One element per line, bullets stripped. Verbatim otherwise. */
1012
+ readonly items: string[];
1013
+ }
1014
+
1015
+ export interface StoryBeat {
1016
+ readonly day: number;
1017
+ readonly challenger: string;
1018
+ readonly force: number;
1019
+ readonly pressureAfter: number;
1020
+ readonly bar: number;
1021
+ readonly fraction: number;
1022
+ /** One clause, in prose. Never an id: an id in a sentence is a leak. */
1023
+ readonly verdict: string;
1024
+ /** What it became, when it became something — as words, resolved now. */
1025
+ readonly became: string | null;
1026
+ /** The successor's address, for a link. Kept OUT of `verdict`. */
1027
+ readonly becameId: string | null;
1028
+ readonly crossed: boolean;
1029
+ }
1030
+
1031
+ export interface StoryView extends ContestedRow {
1032
+ readonly beats: StoryBeat[];
1033
+ readonly beatsAbsent: string | null;
1034
+ }
1035
+
1036
+ export interface MindView {
1037
+ readonly opening: string;
1038
+ readonly identity: { id: string; text: string; kind: Kind; band: Band; strength: number; bytes: number; bornDay: number; lastUsedDay: number; confidential: boolean }[];
1039
+ readonly identityAbsent: string | null;
1040
+ readonly guarded: { id: string; text: string; kind: Kind; band: Band; strength: number; bytes: number; bornDay: number; lastUsedDay: number; confidential: boolean }[];
1041
+ readonly guardedAbsent: string | null;
1042
+ readonly both: string[];
1043
+ readonly protectedOutsideIdentity: { id: string; text: string }[];
1044
+ readonly unreadable: { id: string; label: string }[];
1045
+ readonly wake: {
1046
+ readonly ok: boolean;
1047
+ readonly reason: string;
1048
+ readonly bytes: number;
1049
+ readonly preface: string | null;
1050
+ readonly lanes: WakeLane[];
1051
+ readonly absent: string | null;
1052
+ };
1053
+ /**
1054
+ * THE WRITTEN PAGE, and what it used to say (2026-09-18, S1). Read-only, like
1055
+ * everything else here: the dashboard shows the page and its versions and
1056
+ * offers no door to write one — the doors are the MCP tool and the console.
1057
+ *
1058
+ * The BODIES ride along rather than a diff. The current dashboard has no
1059
+ * precedent for rendering a change between two revisions (`divergentPair` is
1060
+ * a side-by-side of two CONTESTED statements, not a text diff), and a page is
1061
+ * prose a person reads rather than a field that changed — so this is the
1062
+ * simple list the brief named as the fallback, newest first.
1063
+ */
1064
+ readonly page: {
1065
+ readonly present: boolean;
1066
+ readonly body: string;
1067
+ readonly bytes: number;
1068
+ readonly revisedOn: string;
1069
+ readonly by: string | null;
1070
+ readonly reason: string | null;
1071
+ readonly version: number;
1072
+ readonly stale: boolean;
1073
+ readonly core: string;
1074
+ readonly lately: string;
1075
+ readonly headed: boolean;
1076
+ } | null;
1077
+ /** The honest absence line when no page has been written. */
1078
+ readonly pageAbsent: string | null;
1079
+ /** Each body labelled with the write that PRODUCED it, and with what replaced
1080
+ * it named separately — `store.revise` stores the replacing reason on the row
1081
+ * it archives, so the two must not share a word (adversarial review M3). */
1082
+ readonly pageVersions: PageVersion[];
1083
+ readonly chapters: ChapterRow[];
1084
+ readonly chaptersAbsent: string | null;
1085
+ readonly stories: StoryView[];
1086
+ readonly storiesAbsent: string | null;
1087
+ }
1088
+
1089
+ export function mindView(src: DashboardSource): MindView {
1090
+ const store = src.store;
1091
+ const day = store.livedDay();
1092
+ const e = src.self.enumerate(day);
1093
+ const wake = src.self.wake();
1094
+ const page = src.self.page();
1095
+ const sections = pageSections(page?.body ?? "");
1096
+ const everLived = day > 0 || store.list().length > 0;
1097
+ const seen = new Set(e.identity.map((el) => el.id));
1098
+ const unreadable = store
1099
+ .list({ band: "identity", archived: false })
1100
+ .filter((id) => !seen.has(id))
1101
+ .map((id) => ({ id, label: reveal(store, id, 72).label }));
1102
+
1103
+ const shape = (el: { id: string; kind: Kind; band: Band; strength: number; bytes: number }): MindView["identity"][number] => {
1104
+ const r = reveal(store, el.id, 120);
1105
+ return {
1106
+ id: el.id,
1107
+ text: r.text ?? r.label,
1108
+ kind: el.kind,
1109
+ band: el.band,
1110
+ strength: el.strength,
1111
+ bytes: el.bytes,
1112
+ ...livedDays(src, el.id),
1113
+ confidential: r.confidential,
1114
+ };
1115
+ };
1116
+
1117
+ return {
1118
+ opening:
1119
+ `On lived day ${day} I hold ${e.identity.length} ${e.identity.length === 1 ? "element" : "elements"} in the identity band and ` +
1120
+ `${e.protected.length} under protection. The first is what repetition and salience earned, and physics can still move it; ` +
1121
+ "the second is ink no revision path reaches — including a revision that would be right.",
1122
+ identity: e.identity.map(shape),
1123
+ identityAbsent: e.identity.length === 0 ? (everLived ? NONE : NEVER) : null,
1124
+ guarded: e.protected.map(shape),
1125
+ guardedAbsent: e.protected.length === 0 ? (everLived ? NONE : NEVER) : null,
1126
+ both: e.both,
1127
+ protectedOutsideIdentity: e.protectedOutsideIdentity.map((id) => {
1128
+ const r = reveal(store, id, 90);
1129
+ return { id, text: r.text ?? r.label };
1130
+ }),
1131
+ unreadable,
1132
+ wake: {
1133
+ ok: wake.ok,
1134
+ reason: wake.reason,
1135
+ bytes: wake.bytes,
1136
+ preface: wake.preface,
1137
+ lanes: wake.ok ? wakeLanes(wake.text) : [],
1138
+ absent: wake.ok ? null : everLived ? NONE : NEVER,
1139
+ },
1140
+ page:
1141
+ page === null
1142
+ ? null
1143
+ : {
1144
+ present: true,
1145
+ body: page.body,
1146
+ bytes: page.bytes,
1147
+ revisedOn: page.revisedOn,
1148
+ by: page.by,
1149
+ reason: page.reason,
1150
+ version: page.version,
1151
+ stale: src.self.pageStale(page),
1152
+ // The three the type declares, NAMED — a spread of `pageSections`
1153
+ // also carried `preamble` into the JSON, which `tsc` cannot catch
1154
+ // through a spread (adversarial review n2).
1155
+ core: sections.core,
1156
+ lately: sections.lately,
1157
+ headed: sections.headed,
1158
+ },
1159
+ pageAbsent: page === null ? (everLived ? NONE : NEVER) : null,
1160
+ // NOT guarded on the live page: a CLEARED page has no live row and still has
1161
+ // a history, and the console lists it. Two surfaces answering "what did the
1162
+ // page used to say" differently is the same class of mismatch the version
1163
+ // reasons were (M3). `pageVersions` handles the no-live-row case itself.
1164
+ pageVersions: src.self.pageVersions(),
1165
+ chapters: chapters(src, 12),
1166
+ chaptersAbsent: chapters(src, 1).length === 0 ? (everLived ? NONE : NEVER) : null,
1167
+ stories: storyViews(src),
1168
+ storiesAbsent: contestedRows(src).length === 0 ? (everLived ? NONE : NEVER) : null,
1169
+ };
1170
+ }
1171
+
1172
+ /**
1173
+ * The briefing as it actually renders, split at its own lane headings.
1174
+ *
1175
+ * This is the one place the dashboard shows composed TEXT rather than a shape,
1176
+ * and it is deliberate: the wake bundle is what the next session will read, so
1177
+ * "what would I say on waking" is unanswerable from a byte count. Nothing is
1178
+ * persisted — the bundle is read from the store at request time like every other
1179
+ * value on the page, and its own trailing sentinel comment is dropped because it
1180
+ * is bookkeeping, not something the assistant says.
1181
+ */
1182
+ export function wakeLanes(text: string): WakeLane[] {
1183
+ // The lane names and their headings are TAKEN FROM `self/` — `LANE_ORDER` and
1184
+ // `FRAMING` — never retyped here. A renamed lane heading would otherwise leave
1185
+ // this splitter silently returning one enormous lane called "the preface",
1186
+ // which is precisely the quiet-wrong-answer shape the registries exist against.
1187
+ const headings = new Map<string, string>();
1188
+ for (const lane of LANE_ORDER) headings.set(FRAMING[lane], lane);
1189
+
1190
+ const lanes: { heading: string; lane: string | null; items: string[] }[] = [];
1191
+ let current: { heading: string; lane: string | null; items: string[] } = {
1192
+ heading: "How this arrives",
1193
+ lane: null,
1194
+ items: [],
1195
+ };
1196
+ for (const raw of text.split("\n")) {
1197
+ const line = raw.trim();
1198
+ // The sentinel is bookkeeping, not something the assistant says.
1199
+ if (line.startsWith("<!--")) continue;
1200
+ if (line.length === 0) continue;
1201
+ const lane = headings.get(line);
1202
+ // A markdown heading counts too, so a future briefing that uses one still
1203
+ // splits rather than collapsing into a single block.
1204
+ const mdHeading = /^#{1,6}\s+(.*)$/.exec(line);
1205
+ if (lane !== undefined || mdHeading !== null) {
1206
+ if (current.items.length > 0) lanes.push(current);
1207
+ current = {
1208
+ heading: lane === undefined ? (mdHeading?.[1] ?? line) : line,
1209
+ lane: lane ?? null,
1210
+ items: [],
1211
+ };
1212
+ continue;
1213
+ }
1214
+ current.items.push(line.replace(/^[-*]\s+/, ""));
1215
+ }
1216
+ if (current.items.length > 0) lanes.push(current);
1217
+ return lanes;
1218
+ }
1219
+
1220
+ function storyViews(src: DashboardSource): StoryView[] {
1221
+ const store = src.store;
1222
+ return contestedRows(src).map((row) => {
1223
+ let story;
1224
+ try {
1225
+ story = src.schemas.story(row.id);
1226
+ } catch {
1227
+ return { ...row, beats: [], beatsAbsent: NONE };
1228
+ }
1229
+
1230
+ const beats: StoryBeat[] = story.increments
1231
+ .slice()
1232
+ .sort((a, b) => a.day - b.day)
1233
+ .map((inc) => {
1234
+ const crossed = inc.pressureAfter >= inc.bar;
1235
+ const step = story.lineage.find((l) => l.id === inc.targetId && l.successorId !== null);
1236
+ const successorId = crossed ? (step?.successorId ?? null) : null;
1237
+ const became = successorId === null ? null : reveal(store, successorId, 96).text;
1238
+ // The verdict is a CLAUSE, and the numbers it is about are already in
1239
+ // their own fields: "0.598 of 0.470" beside the word REVISED read as a
1240
+ // numerator larger than its denominator with nothing saying that is
1241
+ // exactly what clearing a bar looks like.
1242
+ const verdict = crossed
1243
+ ? step === undefined || step.successorId === null
1244
+ ? "it cleared the bar — but I find no supersession recorded"
1245
+ : "it cleared the bar, and I changed my mind"
1246
+ : "under the bar — held";
1247
+ const c = reveal(store, inc.challengerId, 72);
1248
+ return {
1249
+ day: inc.day,
1250
+ challenger: c.text ?? c.label,
1251
+ force: inc.force,
1252
+ pressureAfter: inc.pressureAfter,
1253
+ bar: inc.bar,
1254
+ fraction: inc.bar > 0 ? Math.min(1.3, inc.pressureAfter / inc.bar) : 0,
1255
+ verdict,
1256
+ became,
1257
+ becameId: successorId,
1258
+ crossed,
1259
+ };
1260
+ });
1261
+ return {
1262
+ ...row,
1263
+ beats,
1264
+ beatsAbsent:
1265
+ beats.length === 0
1266
+ ? "(none yet) — this belief carries pressure but I hold no credited challenge for it: the increments predate the durable log, or were swept."
1267
+ : null,
1268
+ };
1269
+ });
1270
+ }
1271
+
1272
+ // ─────────────────────────────────────────────────────────────────────────────
1273
+ // activity
1274
+ // ─────────────────────────────────────────────────────────────────────────────
1275
+
1276
+ export interface ActivityView {
1277
+ readonly events: NarratedEvent[];
1278
+ readonly total: number;
1279
+ readonly lastSeq: number;
1280
+ readonly retentionDays: number;
1281
+ readonly bound: string;
1282
+ readonly absent: string | null;
1283
+ readonly vocabulary: { name: DurableEventName; count: number; description: string; absent: string | null; node: string | null }[];
1284
+ }
1285
+
1286
+ export function activityView(
1287
+ src: DashboardSource,
1288
+ opts: { limit?: number; name?: string; sinceSeq?: number } = {},
1289
+ ): ActivityView {
1290
+ const store = src.store;
1291
+ const limit = opts.limit ?? FEED_LIMIT;
1292
+ const filter: { name?: string; limit: number } = { limit: LOG_CEILING };
1293
+ if (opts.name !== undefined && opts.name.length > 0) filter.name = opts.name;
1294
+ const all = store.eventLog(filter);
1295
+ const since = opts.sinceSeq;
1296
+ const window = since === undefined ? all.slice(-limit).reverse() : all.filter((r) => r.seq > since);
1297
+ const events = window.map((row) => narrate(store, row));
1298
+ const lastSeq = all.length === 0 ? 0 : (all[all.length - 1]?.seq ?? 0);
1299
+ const everLived = store.livedDay() > 0 || store.list().length > 0;
1300
+
1301
+ return {
1302
+ events,
1303
+ total: all.length,
1304
+ lastSeq,
1305
+ retentionDays: store.retentionDays,
1306
+ bound:
1307
+ `I keep events for ${store.retentionDays} lived days; older ones are swept unless a replay latch holds them. ` +
1308
+ "This is what I still have, not everything that ever happened.",
1309
+ absent: events.length === 0 ? (everLived ? NONE : NEVER) : null,
1310
+ vocabulary: DURABLE_EVENT_NAMES.map((name) => {
1311
+ const count = eventsNamed(src, name);
1312
+ return {
1313
+ name,
1314
+ count,
1315
+ description: DURABLE_EVENTS[name],
1316
+ absent: count === 0 ? NEVER : null,
1317
+ node: (FLOW_NODES.find((nd) => eventsOfNode(nd.key).includes(name))?.key ?? null),
1318
+ };
1319
+ }),
1320
+ };
1321
+ }
1322
+
1323
+ export function eventDetail(src: DashboardSource, seq: number): { found: boolean; event: NarratedEvent | null } {
1324
+ const store = src.store;
1325
+ for (const row of store.eventLog({ limit: LOG_CEILING })) {
1326
+ if (row.seq === seq) return { found: true, event: narrate(store, row) };
1327
+ }
1328
+ return { found: false, event: null };
1329
+ }
1330
+
1331
+ // ─────────────────────────────────────────────────────────────────────────────
1332
+ // flow
1333
+ // ─────────────────────────────────────────────────────────────────────────────
1334
+
1335
+ export interface FlowNodeState {
1336
+ readonly key: NodeKey;
1337
+ readonly label: string;
1338
+ readonly sub: string;
1339
+ readonly x: number;
1340
+ readonly y: number;
1341
+ readonly w: number;
1342
+ readonly h: number;
1343
+ readonly accent: string;
1344
+ /** How many durable events this node has ever recorded, in the kept window. */
1345
+ readonly count: number;
1346
+ /** The honest state line drawn inside the box. */
1347
+ readonly state: string;
1348
+ /** True when the log has never carried a single event for this node. */
1349
+ readonly silent: boolean;
1350
+ }
1351
+
1352
+ export interface FlowView {
1353
+ readonly nodes: FlowNodeState[];
1354
+ readonly edges: typeof FLOW_EDGES;
1355
+ readonly lastSeq: number;
1356
+ readonly feed: NarratedEvent[];
1357
+ readonly note: string;
1358
+ }
1359
+
1360
+ export function flowView(src: DashboardSource, feedLimit = 24): FlowView {
1361
+ const store = src.store;
1362
+ // MEMORIES, not every row: the STORE node says "N memories held" and the
1363
+ // overview's tile says the same words, so they had better be the same number.
1364
+ const rows = census(src).filter((r) => !r.schema);
1365
+ const day = store.livedDay();
1366
+ const activity = activityView(src, { limit: feedLimit });
1367
+ const counts = new Map<NodeKey, number>();
1368
+ for (const v of activity.vocabulary) {
1369
+ if (v.node === null) continue;
1370
+ counts.set(v.node as NodeKey, (counts.get(v.node as NodeKey) ?? 0) + v.count);
1371
+ }
1372
+
1373
+ const nodes: FlowNodeState[] = FLOW_NODES.map((node) => {
1374
+ const count = counts.get(node.key) ?? 0;
1375
+ const silent = eventsOfNode(node.key).length === 0 || count === 0;
1376
+ return {
1377
+ key: node.key,
1378
+ label: node.label,
1379
+ sub: node.sub,
1380
+ x: node.x,
1381
+ y: node.y,
1382
+ w: node.w,
1383
+ h: node.h,
1384
+ accent: node.accent,
1385
+ count,
1386
+ state: nodeState(src, node.key, count, rows.length, day),
1387
+ silent,
1388
+ };
1389
+ });
1390
+
1391
+ return {
1392
+ nodes,
1393
+ edges: FLOW_EDGES,
1394
+ lastSeq: activity.lastSeq,
1395
+ feed: activity.events,
1396
+ note: "Only particles mean activity. A still diagram is a still machine — nothing here drifts for decoration.",
1397
+ };
1398
+ }
1399
+
1400
+ /** The one line inside a node's box: its own state, or the honest absence. */
1401
+ function nodeState(src: DashboardSource, key: NodeKey, count: number, memories: number, day: number): string {
1402
+ const store = src.store;
1403
+ switch (key) {
1404
+ case "store":
1405
+ return memories === 0 ? NONE : `${memories} memories held`;
1406
+ case "physics":
1407
+ return day === 0 ? NEVER : `day ${day} on the clock`;
1408
+ case "associate": {
1409
+ let edges = 0;
1410
+ for (const id of store.list({ archived: false })) edges += store.edgesFrom(id).length;
1411
+ return edges === 0 ? NONE : `${edges} directed edges`;
1412
+ }
1413
+ case "prospective": {
1414
+ let armed = 0;
1415
+ let fired = 0;
1416
+ for (const id of store.list({ archived: false })) {
1417
+ for (const p of store.prospectiveFor(id)) {
1418
+ if (p.state === "fired") fired += 1;
1419
+ else armed += 1;
1420
+ }
1421
+ }
1422
+ return armed + fired === 0 ? NONE : `${armed} waiting · ${fired} fired`;
1423
+ }
1424
+ case "self": {
1425
+ const e = src.self.enumerate(day);
1426
+ return e.identity.length === 0 && e.protected.length === 0
1427
+ ? NONE
1428
+ : `${e.identity.length} in the band · ${e.protected.length} permanent`;
1429
+ }
1430
+ case "wake": {
1431
+ const wake = src.self.wake();
1432
+ return wake.ok ? `${wake.bytes} bytes waiting` : NEVER;
1433
+ }
1434
+ case "schemas": {
1435
+ const entities = src.schemas.entities().length;
1436
+ return entities === 0 ? NONE : `${entities} entities`;
1437
+ }
1438
+ case "spans":
1439
+ // Turn capture writes no durable event; see NO_EVENT_OF_ITS_OWN. On a
1440
+ // store that has never lived a day the honest word is still `(never run)`
1441
+ // — "silent by design" would claim a design decision was exercised.
1442
+ return day === 0 ? NEVER : "silent by design";
1443
+ case "session": {
1444
+ const sessions = new Set<string>();
1445
+ for (const name of eventsOfNode("session")) {
1446
+ for (const row of store.eventLog({ name, limit: LOG_CEILING })) if (row.ref !== null) sessions.add(row.ref);
1447
+ }
1448
+ // The surfacing log names its session, so a store whose host wrote no
1449
+ // boundary rows can still say how many conversations it has seen.
1450
+ for (const row of store.eventLog({ name: "recall.decision", limit: LOG_CEILING })) {
1451
+ if (row.ref !== null) sessions.add(row.ref);
1452
+ }
1453
+ return sessions.size === 0 ? (day === 0 ? NEVER : NONE) : `${sessions.size} sessions seen`;
1454
+ }
1455
+ case "remember":
1456
+ // The door's own record is the ask's pacing row, which only a HOST
1457
+ // writes. What the door actually did is the count that came through it.
1458
+ return memories === 0 ? (day === 0 ? NEVER : NONE) : `${memories} came through`;
1459
+ case "encode":
1460
+ // NEITHER ABSENCE WORD IS TRUE HERE once anything is in the store: the
1461
+ // battery ran on every one of those memories. `(never run)` beside
1462
+ // STORE's `143 memories held` was a contradiction on the face of the
1463
+ // diagram. Both doors record now (`gate.chunk`, `gate.deposit`), so the
1464
+ // ordinary answer is a count — but a store holding memories that PREDATE
1465
+ // the gate log, or that were seeded around the door, still has none, and
1466
+ // that state gets its own sentence rather than a zero.
1467
+ if (count > 0) return `${count} recorded`;
1468
+ if (memories > 0) return `${memories} passed · no gate record for them`;
1469
+ return day === 0 ? NEVER : NONE;
1470
+ default:
1471
+ return count === 0 ? NEVER : `${count} recorded`;
1472
+ }
1473
+ }
1474
+
1475
+ export interface NodeDetailView {
1476
+ readonly found: boolean;
1477
+ readonly key: string;
1478
+ readonly label: string;
1479
+ readonly what: string;
1480
+ readonly analog: string;
1481
+ readonly breaks: string;
1482
+ readonly eventNames: string[];
1483
+ readonly noEventOfItsOwn: string | null;
1484
+ /** Work that is real and deliberately unrecorded. See `UNLOGGED_PATH`. */
1485
+ readonly unloggedPath: string | null;
1486
+ readonly recent: NarratedEvent[];
1487
+ readonly recentAbsent: string | null;
1488
+ readonly state: string;
1489
+ }
1490
+
1491
+ export function nodeDetail(src: DashboardSource, key: string, limit = 8): NodeDetailView {
1492
+ const node = findNode(key);
1493
+ if (node === undefined) {
1494
+ return {
1495
+ found: false,
1496
+ key,
1497
+ label: "",
1498
+ what: "",
1499
+ analog: "",
1500
+ breaks: "",
1501
+ eventNames: [],
1502
+ noEventOfItsOwn: null,
1503
+ unloggedPath: null,
1504
+ recent: [],
1505
+ recentAbsent: NEVER,
1506
+ state: "",
1507
+ };
1508
+ }
1509
+ const store = src.store;
1510
+ const names = eventsOfNode(node.key);
1511
+ const rows = [];
1512
+ for (const name of names) rows.push(...store.eventLog({ name, limit: LOG_CEILING }));
1513
+ rows.sort((a, b) => a.seq - b.seq);
1514
+ const recent = rows.slice(-limit).reverse().map((row) => narrate(store, row));
1515
+ const everLived = store.livedDay() > 0 || store.list().length > 0;
1516
+ return {
1517
+ found: true,
1518
+ key: node.key,
1519
+ label: node.label,
1520
+ what: node.what,
1521
+ analog: node.analog,
1522
+ breaks: node.breaks,
1523
+ eventNames: names,
1524
+ noEventOfItsOwn: NO_EVENT_OF_ITS_OWN[node.key] ?? null,
1525
+ unloggedPath: UNLOGGED_PATH[node.key] ?? null,
1526
+ recent,
1527
+ recentAbsent: recent.length === 0 ? (names.length === 0 ? null : everLived ? NONE : NEVER) : null,
1528
+ state: nodeState(src, node.key, rows.length, memoriesHeld(src), store.livedDay()),
1529
+ };
1530
+ }
1531
+
1532
+ // ─────────────────────────────────────────────────────────────────────────────
1533
+ // health
1534
+ // ─────────────────────────────────────────────────────────────────────────────
1535
+
1536
+ export interface HealthView {
1537
+ readonly phases: { phase: string; day: number | null; ago: number | null; torn: boolean; absent: string | null }[];
1538
+ readonly symmetry: { kind: Kind; up: number; down: number; reason: string; ok: boolean }[];
1539
+ readonly exits: { reason: string; count: number; gloss: string; absent: string | null }[];
1540
+ /**
1541
+ * ONE TABLE, LED BY ENGLISH. There were two — "what a host told me" over the
1542
+ * eleven `adapter.*` names, and "everything I can record durably" over all
1543
+ * nineteen — so seven identifiers were listed twice on one screen with
1544
+ * near-duplicate glosses, and the first thing the health tab showed a person
1545
+ * was 23 dotted names against a column of `(never run)` (design review,
1546
+ * 2026-09-04, §9 and ranked #4). The gloss each row already carried in its
1547
+ * third column now LEADS it and the dotted name is the second line, which is
1548
+ * the order a reader needs them in: what this records, then what it is
1549
+ * called. `adapter` says whether a host wrote it or the machinery did — the
1550
+ * only thing the split table was really saying — and `note` carries the
1551
+ * adapter-specific caveat the old table had room for.
1552
+ */
1553
+ readonly records: {
1554
+ name: DurableEventName;
1555
+ gloss: string;
1556
+ count: number;
1557
+ absent: string | null;
1558
+ adapter: boolean;
1559
+ note: string | null;
1560
+ }[];
1561
+ readonly heatmap: { days: number[]; names: string[]; cells: { day: number; name: string; count: number }[] };
1562
+ readonly removals: { id: string; label: string; stage: string; actor: string; reason: string | null; at: number }[];
1563
+ readonly removalsAbsent: string | null;
1564
+ readonly blind: readonly { readonly what: string; readonly why: string }[];
1565
+ }
1566
+
1567
+ /** The events an ADAPTER writes — the only ones that can tell the owner what a
1568
+ * host actually did with what was composed for it. */
1569
+ const ADAPTER_EVENTS: readonly DurableEventName[] = [
1570
+ "adapter.ask",
1571
+ "adapter.boundary",
1572
+ "adapter.recall",
1573
+ "adapter.wake.injected",
1574
+ "adapter.wake.delivered",
1575
+ "adapter.primacy.deliver",
1576
+ "adapter.primacy.standdown",
1577
+ "adapter.embed.backfill",
1578
+ "adapter.semantic.lag",
1579
+ "adapter.authorship.ask",
1580
+ "adapter.episode.ask",
1581
+ ];
1582
+
1583
+ const ADAPTER_NOTE: Partial<Record<DurableEventName, string>> = {
1584
+ "adapter.wake.injected": "bytes handed to the host, never the text",
1585
+ "adapter.wake.delivered": "whether the briefing was actually seen the next turn",
1586
+ "adapter.recall": "how long recall took, when the adapter recorded it",
1587
+ "adapter.ask": "asked, paced out, or capped for the day",
1588
+ "adapter.authorship.ask": "historical — nothing writes this now",
1589
+ "adapter.episode.ask": "historical — nothing writes this now",
1590
+ };
1591
+
1592
+ export function healthView(src: DashboardSource): HealthView {
1593
+ const store = src.store;
1594
+ const day = store.livedDay();
1595
+ const everLived = day > 0 || store.list().length > 0;
1596
+
1597
+ const phases = CYCLE_PHASES.map((phase) => {
1598
+ const marker = readMarker(store, phase);
1599
+ if (marker.health === "torn") {
1600
+ return { phase, day: null, ago: null, torn: true, absent: "torn marker" };
1601
+ }
1602
+ if (marker.day === MARKER_UNSET) return { phase, day: null, ago: null, torn: false, absent: NEVER };
1603
+ return { phase, day: marker.day, ago: Math.max(0, day - marker.day), torn: false, absent: null };
1604
+ });
1605
+
1606
+ const transitions = store.eventLog({ name: "band.transition", limit: LOG_CEILING });
1607
+ const symmetry = KINDS.map((kind) => {
1608
+ let up = 0;
1609
+ let down = 0;
1610
+ for (const row of transitions) {
1611
+ if (row.payload === null) continue;
1612
+ try {
1613
+ const p = JSON.parse(row.payload) as { kind?: string; direction?: string };
1614
+ if (p.kind !== kind) continue;
1615
+ if (p.direction === "up") up += 1;
1616
+ else if (p.direction === "down") down += 1;
1617
+ } catch {
1618
+ continue;
1619
+ }
1620
+ }
1621
+ const verdict = symmetryCheck(kind, { up, down });
1622
+ return { kind, up, down, reason: verdict.reason, ok: verdict.reason === "within-expectation" };
1623
+ });
1624
+
1625
+ const exitCounts = new Map<string, number>();
1626
+ for (const id of store.list()) {
1627
+ const row = store.row(id);
1628
+ if (row === undefined || row.archived !== 1) continue;
1629
+ const reason = row.archived_reason ?? "no reason recorded";
1630
+ exitCounts.set(reason, (exitCounts.get(reason) ?? 0) + 1);
1631
+ }
1632
+ const namedExits: [string, string][] = [
1633
+ [PRUNE_ARCHIVE_REASON, "let go at the floor — real forgetting, on physics' verdict alone"],
1634
+ [MERGE_ARCHIVE_REASON, "merged into a duplicate I already held"],
1635
+ [SCHEMA_TUNABLES.FADE_REASON, "faded out of my vocabulary"],
1636
+ ];
1637
+ const exits = namedExits.map(([reason, gloss]) => {
1638
+ const count = exitCounts.get(reason) ?? 0;
1639
+ return { reason, count, gloss, absent: absenceFor(count, everLived) };
1640
+ });
1641
+ for (const [reason, count] of exitCounts) {
1642
+ if (namedExits.some(([r]) => r === reason)) continue;
1643
+ exits.push({ reason, count, gloss: "recorded by whatever archived it", absent: null });
1644
+ }
1645
+
1646
+ // The merged record table. Every durable name appears exactly once — the
1647
+ // totality rule is unchanged, and the test still walks `DURABLE_EVENT_NAMES`
1648
+ // against it — but what HAS happened is ordered above what never has, so the
1649
+ // first screen of this tab is the log's actual contents rather than eleven
1650
+ // adapter names nobody has ever run. The order is stated on the page.
1651
+ const records = DURABLE_EVENT_NAMES.map((name) => {
1652
+ const count = eventsNamed(src, name);
1653
+ const adapter = ADAPTER_EVENTS.includes(name);
1654
+ return {
1655
+ name,
1656
+ gloss: DURABLE_EVENTS[name],
1657
+ count,
1658
+ absent: count === 0 ? NEVER : null,
1659
+ adapter,
1660
+ note: adapter ? (ADAPTER_NOTE[name] ?? "counts and reasons; never text") : null,
1661
+ };
1662
+ }).sort((a, b) => (b.count === a.count ? 0 : b.count - a.count));
1663
+
1664
+ // The heatmap: lived day × event name. Bounded to the last 21 lived days so a
1665
+ // long-lived store still fits on a screen without a scrollbar in two axes.
1666
+ const span = 21;
1667
+ const from = Math.max(0, day - span + 1);
1668
+ const days = Array.from({ length: Math.max(1, Math.min(span, day + 1)) }, (_, i) => from + i);
1669
+ const cells: { day: number; name: string; count: number }[] = [];
1670
+ for (const name of DURABLE_EVENT_NAMES) {
1671
+ const rows = store.eventLog({ name, sinceDay: from, limit: LOG_CEILING });
1672
+ const per = new Map<number, number>();
1673
+ for (const row of rows) per.set(row.day, (per.get(row.day) ?? 0) + 1);
1674
+ for (const d of days) cells.push({ day: d, name, count: per.get(d) ?? 0 });
1675
+ }
1676
+
1677
+ const removals = store.removalRecord().map((x) => ({
1678
+ id: x.memory_id,
1679
+ label: reveal(store, x.memory_id, 72).label,
1680
+ stage: x.stage,
1681
+ actor: x.actor,
1682
+ reason: x.reason,
1683
+ at: x.at,
1684
+ }));
1685
+
1686
+ return {
1687
+ phases,
1688
+ symmetry,
1689
+ exits,
1690
+ records,
1691
+ heatmap: { days, names: [...DURABLE_EVENT_NAMES], cells },
1692
+ removals,
1693
+ removalsAbsent: removals.length === 0 ? (everLived ? NONE : NEVER) : null,
1694
+ blind: BLIND_SPOTS,
1695
+ };
1696
+ }
1697
+
1698
+ /**
1699
+ * WHAT I CANNOT SEE — the named absences, in the shape the terminal `status`
1700
+ * view established: a number I do not durably hold is stated as a number I do
1701
+ * not hold, never invented to fill a panel. Every line here is a real gap, and
1702
+ * three of them are filed in `INTERFACE-GAPS.md`.
1703
+ */
1704
+ export const BLIND_SPOTS: readonly { readonly what: string; readonly why: string }[] = [
1705
+ {
1706
+ what: "What one cycle did.",
1707
+ why: "There is no durable per-cycle outcome record — the report goes back to its caller and is gone. What survives is each phase's completion marker and each row's archived-with-reason state, so every exit count on this page is SINCE BIRTH, never 'this cycle'.",
1708
+ },
1709
+ {
1710
+ what: "A protected element I can no longer read.",
1711
+ why: "Protection is a flag on the row whose physics stopped reading, so a removed protected element simply leaves the list. The identity band is queryable and that half is recovered above; this half is not (INTERFACE-GAPS §3).",
1712
+ },
1713
+ {
1714
+ what: "Recall latency, unless an adapter recorded it.",
1715
+ why: "The core times its own surfacing race and reports it in the decision row. A turn whose adapter wrote no `adapter.recall` leaves no latency behind at all.",
1716
+ },
1717
+ {
1718
+ what: "Anything older than the retention window.",
1719
+ why: "The event log is bounded telemetry, not canonical memory. Rows past the window are swept unless a replay latch holds them, so every count on this page is 'what I still have', not 'what ever happened'.",
1720
+ },
1721
+ {
1722
+ what: "Whether a memory was ever actually useful to you.",
1723
+ why: "I record that the reply used it, which is the closest thing I have. Whether it helped is a judgement only you can make, and nothing here should be read as evidence of it.",
1724
+ },
1725
+ {
1726
+ what: "Anything a host did not tell me.",
1727
+ why: "The wake bundle's arrival, the ask's outcome, the bytes injected — all of it reaches me only if the adapter wrote a row. Silence on this page is sometimes the adapter's silence, not the machine's.",
1728
+ },
1729
+ ];
1730
+
1731
+ /** Everything the terminal views print, as one number each — the JSON the app's
1732
+ * header badge reads without pulling a whole page. */
1733
+ export function pulse(src: DashboardSource): { day: number; memories: number; events: number; lastSeq: number } {
1734
+ const activity = activityView(src, { limit: 1 });
1735
+ return {
1736
+ day: src.store.livedDay(),
1737
+ memories: memoriesHeld(src),
1738
+ events: activity.total,
1739
+ lastSeq: activity.lastSeq,
1740
+ };
1741
+ }
1742
+
1743
+ export { census };
1744
+ export { num };