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,542 @@
1
+ /**
2
+ * `sleep/` — the shapes the cycle is made of.
3
+ *
4
+ * Two rules govern everything here:
5
+ *
6
+ * 1. **Every outcome names its reason.** "Did not run", "ran and found nothing",
7
+ * and "failed" are three different records, never one falsy value
8
+ * (CONTRACT §5 G6, scar §2.4). A bare count in a report is not a monitor.
9
+ * 2. **Records are content-by-reference.** Ids, counts, kinds, days, verdicts.
10
+ * Never a body, and — for prune records specifically — never a content hash
11
+ * either (§5 G8, scar §2.20).
12
+ *
13
+ * The store is typed as a STRUCTURAL interface, not as the concrete `Store` class:
14
+ * sleep uses eleven methods, a test needs to fault-inject one of them, and a
15
+ * narrow seam is the difference between "prove the guarantee" and "fight the
16
+ * class". The real `Store` satisfies it structurally, unchanged.
17
+ */
18
+
19
+ import type { Band, Kind, MemoryPhysics } from "../types.js";
20
+ import type {
21
+ EventLogCensus,
22
+ EventPruneReport,
23
+ MemoryRow,
24
+ PruneReport as VersionPruneReport,
25
+ ProseType,
26
+ StoredMemory,
27
+ VersionRow,
28
+ } from "../store/index.js";
29
+ import type {
30
+ PromotionCrossing,
31
+ PromotionReason,
32
+ PruneRecord,
33
+ PruneReason,
34
+ SymmetryCheck,
35
+ } from "../physics/index.js";
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // The store seam
39
+ // ---------------------------------------------------------------------------
40
+
41
+ /**
42
+ * Exactly what the cycle needs from `store/`, and nothing else. Note what is
43
+ * ABSENT and cannot be added: there is no delete, no unlink, no remove. The
44
+ * floor prune is archival because there is no other verb to reach for.
45
+ */
46
+ export interface SleepStore {
47
+ readonly dir: string;
48
+ readonly observer: boolean;
49
+
50
+ // reads
51
+ livedDay(): number;
52
+ getMeta(key: string): string | undefined;
53
+ list(filter?: {
54
+ type?: ProseType;
55
+ kind?: Kind;
56
+ band?: Band;
57
+ archived?: boolean;
58
+ }): string[];
59
+ row(id: string): MemoryRow | undefined;
60
+ read(id: string): StoredMemory;
61
+ versions(id: string): VersionRow[];
62
+ deniedIds(): string[];
63
+
64
+ // writes
65
+ advanceClock(date: string): number;
66
+ setMeta(key: string, value: string): void;
67
+ archive(id: string, reason: string): void;
68
+ updatePhysics(id: string, patch: Partial<MemoryPhysics>): void;
69
+ setBand(id: string, band: Band, day: number): void;
70
+ pruneSupersededVersions(): VersionPruneReport;
71
+ /**
72
+ * The durable event log (SEAMS item K), OPTIONAL so this port stays satisfiable
73
+ * by any store-shaped object. Where it exists, each prune / promotion / merge
74
+ * record is appended beside its meta row, which is what makes the three
75
+ * queryable (INTERFACE-GAPS.md §3) without disturbing §5 G8's ordering: the
76
+ * meta row is still written FIRST and still gates the move.
77
+ *
78
+ * `dedupKey` carries the same per-id record key, so a replayed day appends
79
+ * nothing a second time (§5 G3) — the log is append-only and idempotent at once.
80
+ */
81
+ appendEvent?(input: {
82
+ name: string;
83
+ day: number;
84
+ ref?: string | null;
85
+ dedupKey?: string | null;
86
+ payload?: Record<string, unknown> | null;
87
+ }): number;
88
+ /**
89
+ * READING that same log, OPTIONAL for the same reason. The symmetry counter
90
+ * (physics guarantee 12) is a question about the WHOLE history, not about one
91
+ * cycle: `SYMMETRY_MIN_SAMPLE` is 20 moves, and a quiet day produces a
92
+ * handful. So the verdict is recomputed at every cycle end from the durable
93
+ * band-transition rows rather than from a counter somebody has to remember to
94
+ * increment — the log is the counter. A port without it gets no verdict and
95
+ * says so, which is `never-asked`, not health.
96
+ */
97
+ eventLog?(filter?: {
98
+ name?: string;
99
+ ref?: string;
100
+ sinceDay?: number;
101
+ limit?: number;
102
+ }): { name: string; day: number; ref: string | null; payload: string | null }[];
103
+ /**
104
+ * Box 3's ranking table (SEAMS item J), OPTIONAL for the same reason as
105
+ * `appendEvent`. Where the port provides it, the decay tick materializes
106
+ * strength/band THROUGH THE STORE instead of into `strength-cache.ts`'s side
107
+ * file — which is what gave box 3 two owners and one rebuild story
108
+ * (INTERFACE-GAPS.md §1). `rebuildCache()` drops the table with the rest.
109
+ */
110
+ setRanking?(rows: readonly { id: string; strength: number; band: Band; day: number }[]): void;
111
+ rankingAll?(): Map<string, { id: string; strength: number; band: Band; day: number }>;
112
+ /**
113
+ * SWEEPING that same log, OPTIONAL for the same reason as `appendEvent`: a
114
+ * port with no durable log has nothing to sweep, and the `log` phase says so
115
+ * by name (`no-durable-event-log`) rather than pretending it ran. `limit` is
116
+ * the cycle's per-pass cap, oldest rows first; latched rows (`dedupKey`) are
117
+ * the store's to keep at any age, not this module's to ask for. The census is
118
+ * the READ half: an observer's report and the kept-by-kind count come from it,
119
+ * and it never crosses the write seam.
120
+ */
121
+ pruneEvents?(opts?: { limit?: number }): EventPruneReport;
122
+ eventLogCensus?(): EventLogCensus;
123
+ }
124
+
125
+ // ---------------------------------------------------------------------------
126
+ // Phases
127
+ // ---------------------------------------------------------------------------
128
+
129
+ /**
130
+ * Phase order is BEHAVIOR, not implementation (CONTRACT §3 G5). The three
131
+ * consequences that must survive, in this list's own terms:
132
+ *
133
+ * - `decay` runs after the boundary's own writes — the cycle is spawned at a
134
+ * session end, so a same-lived-day reinforcement is already persisted when
135
+ * the strength cache is materialized.
136
+ * - revision-dependent work (`prune`, `dedup`, `versions`) runs after
137
+ * `consolidate`, so it sees this boundary's own supersedes and promotions.
138
+ * - `briefing` is the cycle's final CONTENT write. `log` runs after it and
139
+ * writes no content: it deletes telemetry rows past the retention window
140
+ * (§5 G16), and it is last so "what the cycle forgot" and "what the log
141
+ * dropped" are two reports, never one budget doing half of each
142
+ * (NOTES.md §13).
143
+ */
144
+ export const PHASES = [
145
+ "clock",
146
+ "decay",
147
+ "consolidate",
148
+ "prune",
149
+ "dedup",
150
+ "versions",
151
+ "briefing",
152
+ "log",
153
+ ] as const;
154
+
155
+ export type Phase = (typeof PHASES)[number];
156
+
157
+ /** Three outcomes that a boolean cannot tell apart, plus the failure arm. */
158
+ export type PhaseStatus = "ran" | "ran-nothing-found" | "did-not-run" | "failed";
159
+
160
+ export type PhaseReason =
161
+ | "completed"
162
+ | "nothing-to-do"
163
+ | "already-done-today"
164
+ | "not-due-this-cadence"
165
+ | "observer-report"
166
+ | "no-render-fn"
167
+ | "no-durable-event-log"
168
+ | "failed";
169
+
170
+ export interface PhaseReport {
171
+ readonly phase: Phase;
172
+ readonly status: PhaseStatus;
173
+ /** Always present. A phase that reports no reason is a phase nobody can debug. */
174
+ readonly reason: PhaseReason;
175
+ /** How many items the phase looked at. */
176
+ readonly examined: number;
177
+ /**
178
+ * How many items it acted on. Under observer this is the count it WOULD have
179
+ * acted on — `status` stays `did-not-run` so the two can never be confused.
180
+ */
181
+ readonly changed: number;
182
+ /** Skips, categorized. Each category is its own number (§3, v1 §11 G5). */
183
+ readonly skipped: Readonly<Record<string, number>>;
184
+ /** The work budget this phase was given. */
185
+ readonly budget: number;
186
+ /** True when the budget stopped the phase before its candidates ran out. */
187
+ readonly budgetExhausted: boolean;
188
+ /**
189
+ * Items left undone because the budget ran out. A BUDGET IS NOT A DEBT
190
+ * (§3, v1 §5 G4): this number is reported, and it is never carried forward as
191
+ * arrears — the marker still advances, and tomorrow starts fresh.
192
+ */
193
+ readonly skippedForBudget: number;
194
+ /**
195
+ * Rows whose canonical column this phase reconciled with the arithmetic —
196
+ * present on the decay phase (U8) and absent everywhere else. It is counted
197
+ * into `changed` (a reconciled row IS a row the phase acted on) and reported
198
+ * separately, because "869 rows the table had wrong" and "869 rows that
199
+ * crossed a band" are different facts (scar §2.4).
200
+ */
201
+ readonly reconciled?: number;
202
+ readonly markerBefore: number;
203
+ readonly markerAfter: number;
204
+ /** Machine-readable failure code. Present only when `status === "failed"`. */
205
+ readonly error?: string;
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // Crash injection — how the mid-cycle kill is proven
210
+ // ---------------------------------------------------------------------------
211
+
212
+ export type StepStage = "start" | "item" | "work-done" | "marked";
213
+
214
+ export interface CycleStep {
215
+ readonly phase: Phase;
216
+ readonly stage: StepStage;
217
+ /** Item index within the phase, for `stage === "item"`. */
218
+ readonly index?: number;
219
+ readonly id?: string;
220
+ }
221
+
222
+ /**
223
+ * The one error class `runCycle` does NOT degrade. Degrade-don't-abort (§5 G6)
224
+ * means a phase failure logs and the cycle continues — but a process kill is not
225
+ * a phase failure, and a test that could not tell them apart would prove nothing
226
+ * about crash resumption. Throwing this from `onStep` simulates the watchdog's
227
+ * hard kill: it propagates out of the cycle untouched, leaving markers exactly
228
+ * where the completed work left them.
229
+ */
230
+ export class CycleKilled extends Error {
231
+ readonly phase: Phase;
232
+ readonly stage: StepStage;
233
+ readonly index: number | undefined;
234
+
235
+ constructor(step: CycleStep) {
236
+ super(`CYCLE_KILLED ${step.phase}/${step.stage}`);
237
+ this.name = "CycleKilled";
238
+ this.phase = step.phase;
239
+ this.stage = step.stage;
240
+ this.index = step.index;
241
+ }
242
+ }
243
+
244
+ /**
245
+ * WHAT A CYCLE THAT DIES CARRIES OUT WITH IT.
246
+ *
247
+ * Degrade-don't-abort covers a phase that throws; it does not cover a throw from
248
+ * OUTSIDE a phase body — a marker advance, the clock, a hard kill from `onStep`.
249
+ * When one of those escapes there is no `CycleReport`, and a recorder with
250
+ * nothing to read writes a row of zeroes: seven phases that ran, a briefing that
251
+ * trimmed six elements, and a row that says `failed: 0, promoted: 0`. A week
252
+ * later that reads as a quiet clean night. It is the fabricated-zero failure
253
+ * (scar §2.4) arriving through an exception.
254
+ *
255
+ * So the escaping error carries the reports the cycle HAD, plus where the kill
256
+ * landed when the thrower said. The attachment is a symbol property, not a
257
+ * field: the error belongs to whoever threw it, and this must never collide with
258
+ * something they put there themselves.
259
+ */
260
+ export interface CyclePartial {
261
+ /** The phases that reached a verdict before the throw, in executed order. */
262
+ readonly phases: readonly PhaseReport[];
263
+ /** Every phase the cycle STARTED, which is one longer when it died mid-phase. */
264
+ readonly order: readonly Phase[];
265
+ /** Where the kill landed, when the error said (`CycleKilled` does). */
266
+ readonly phase?: Phase;
267
+ readonly stage?: StepStage;
268
+ }
269
+
270
+ const CYCLE_PARTIAL = Symbol.for("counterparts.sleep.cyclePartial");
271
+
272
+ export function attachCyclePartial(err: unknown, partial: CyclePartial): void {
273
+ if (err === null || (typeof err !== "object" && typeof err !== "function")) return;
274
+ try {
275
+ Object.defineProperty(err, CYCLE_PARTIAL, {
276
+ value: partial,
277
+ enumerable: false,
278
+ configurable: true,
279
+ });
280
+ } catch {
281
+ // A frozen error is still an error. Losing the attachment costs detail on
282
+ // one row; throwing here would replace the exception the caller must see.
283
+ }
284
+ }
285
+
286
+ export function cyclePartial(err: unknown): CyclePartial | null {
287
+ if (err === null || (typeof err !== "object" && typeof err !== "function")) return null;
288
+ const v = (err as Record<symbol, unknown>)[CYCLE_PARTIAL];
289
+ return v === undefined ? null : (v as CyclePartial);
290
+ }
291
+
292
+ // ---------------------------------------------------------------------------
293
+ // Telemetry
294
+ // ---------------------------------------------------------------------------
295
+
296
+ /** Ids, counts, kinds, days, reasons. Never body text (§5 G8, scar §2.20). */
297
+ export interface SleepEvent {
298
+ readonly at: number;
299
+ readonly name: string;
300
+ readonly ref?: string;
301
+ readonly data?: Readonly<Record<string, string | number | boolean | null>>;
302
+ }
303
+
304
+ // ---------------------------------------------------------------------------
305
+ // Per-phase records
306
+ // ---------------------------------------------------------------------------
307
+
308
+ /** The §5.3 crossing record, plus the id physics does not carry. */
309
+ export interface PromotionRecord extends PromotionCrossing {
310
+ readonly id: string;
311
+ }
312
+
313
+ /** A prune record as persisted: physics' record, plus the id it belongs to. */
314
+ export interface PrunedRecord {
315
+ readonly id: string;
316
+ readonly record: PruneRecord;
317
+ }
318
+
319
+ export interface MergeRecord {
320
+ readonly event: "memory.merged";
321
+ readonly day: number;
322
+ readonly candidateId: string;
323
+ readonly originalId: string;
324
+ readonly reason: string;
325
+ readonly usesDelta: number;
326
+ /**
327
+ * What the merge did to the original's physics: `uses-only` (owner ruling
328
+ * 2026-09-14, R1 — a merge is a re-encounter on the record, not engagement,
329
+ * so it never counts a reinforced day and can never promote a memory by
330
+ * itself), or `not-applied` under observer.
331
+ */
332
+ readonly credit: string;
333
+ }
334
+
335
+ /**
336
+ * ONE BAND CROSSING, WITH ITS DIRECTION — guarantee 12's missing input.
337
+ *
338
+ * Before this existed the decay pass reported rows CHANGED and nothing said
339
+ * which way they went, so `physics.symmetryCheck` — the tripwire written
340
+ * because v1 ran 279 up-moves against zero down-moves for three days and
341
+ * nothing fired — was enforced in one place and consumed by nobody. A counter
342
+ * nobody feeds is a tripwire that cannot trip (scar §2.10).
343
+ *
344
+ * `site` says which pass moved it, because the two are different facts: the
345
+ * decay materialization reads a band off the arithmetic, while the identity
346
+ * crossing is an explicit decision with a persisted record.
347
+ */
348
+ export interface BandTransition {
349
+ readonly id: string;
350
+ readonly kind: Kind;
351
+ readonly from: Band;
352
+ readonly to: Band;
353
+ readonly direction: "up" | "down";
354
+ readonly site: "decay" | "consolidate";
355
+ readonly day: number;
356
+ }
357
+
358
+ export const BAND_TRANSITION_EVENT = "band.transition";
359
+ /** The transition row's payload fields, in order — a G12 surface-set component
360
+ * (parallel-run CONTRACT §5 G12), pinned by `satisfies` at the append site. */
361
+ export const BAND_TRANSITION_FIELDS = ["kind", "from", "to", "direction", "site"] as const;
362
+ export type BandTransitionField = (typeof BAND_TRANSITION_FIELDS)[number];
363
+
364
+ /** The per-id, per-day latch: a replayed day re-appends nothing (§5 G3). */
365
+ export function bandTransitionKey(t: BandTransition): string {
366
+ return `${BAND_TRANSITION_EVENT}:${t.id}:${t.day}:${t.from}:${t.to}`;
367
+ }
368
+
369
+ /**
370
+ * Records one crossing in the durable log, beside the phase's own telemetry.
371
+ * `ctx.apply` guards it: an observer counts crossings and writes none.
372
+ */
373
+ export function recordBandTransition(ctx: PhaseCtx, t: BandTransition): void {
374
+ ctx.event("sleep.band.moved", t.id, {
375
+ kind: t.kind,
376
+ from: t.from,
377
+ to: t.to,
378
+ direction: t.direction,
379
+ site: t.site,
380
+ day: t.day,
381
+ });
382
+ if (!ctx.apply) return;
383
+ ctx.store.appendEvent?.({
384
+ name: BAND_TRANSITION_EVENT,
385
+ day: t.day,
386
+ ref: t.id,
387
+ dedupKey: bandTransitionKey(t),
388
+ payload: { kind: t.kind, from: t.from, to: t.to, direction: t.direction, site: t.site } satisfies Record<
389
+ BandTransitionField,
390
+ unknown
391
+ >,
392
+ });
393
+ }
394
+
395
+ /** Created-versus-exited, per kind, every cycle (§5 G13, scar §2.17). */
396
+ export interface KindCensus {
397
+ readonly created: number;
398
+ readonly exited: number;
399
+ }
400
+
401
+ // ---------------------------------------------------------------------------
402
+ // The cycle report
403
+ // ---------------------------------------------------------------------------
404
+
405
+ export interface CycleReport {
406
+ readonly day: number;
407
+ readonly date: string;
408
+ readonly observer: boolean;
409
+ /** The phase order actually executed — asserted, never assumed (§5 G5). */
410
+ readonly order: readonly Phase[];
411
+ readonly phases: readonly PhaseReport[];
412
+ readonly promoted: readonly PromotionRecord[];
413
+ readonly pruned: readonly PrunedRecord[];
414
+ readonly merged: readonly MergeRecord[];
415
+ /** Band crossings THIS cycle, by direction (guarantee 12's input). */
416
+ readonly bandTransitions: readonly BandTransition[];
417
+ /**
418
+ * The symmetry verdict per kind, computed at cycle end over the WHOLE durable
419
+ * transition history. Read `reason`, never `ok` alone: below
420
+ * `SYMMETRY_MIN_SAMPLE` the verdict is `never-asked` with `ok: true`, and
421
+ * "was never asked" is not "is healthy" (scar §2.4).
422
+ */
423
+ readonly symmetry: readonly SymmetryCheck[];
424
+ /** A kind with a zero exit count after bake-in is a defect (§5 G13). */
425
+ readonly census: Readonly<Record<Kind, KindCensus>>;
426
+ readonly events: readonly SleepEvent[];
427
+ }
428
+
429
+ export function phaseReport(report: CycleReport, phase: Phase): PhaseReport {
430
+ const found = report.phases.find((p) => p.phase === phase);
431
+ if (found === undefined) throw new Error(`no report for phase ${phase}`);
432
+ return found;
433
+ }
434
+
435
+ // ---------------------------------------------------------------------------
436
+ // What one phase is handed, and what it hands back
437
+ // ---------------------------------------------------------------------------
438
+
439
+ export interface PhaseCtx {
440
+ readonly store: SleepStore;
441
+ readonly day: number;
442
+ /**
443
+ * FALSE under observer. Every write in every phase is guarded by it, so the
444
+ * read-only report walks the identical code path and computes the identical
445
+ * verdicts — it simply never reaches a `WRITE_METHOD`. An observer that
446
+ * *attempted* a write and caught the refusal would be relying on the store's
447
+ * stand-down instead of proving its own (observer-mode.md G4).
448
+ */
449
+ readonly apply: boolean;
450
+ readonly budget: number;
451
+ /** Telemetry + the crash seam. Throwing `CycleKilled` from here kills the run. */
452
+ step(stage: StepStage, detail?: { index?: number; id?: string }): void;
453
+ event(name: string, ref?: string, data?: Record<string, string | number | boolean | null>): void;
454
+ }
455
+
456
+ export interface PhaseOutcome {
457
+ examined: number;
458
+ changed: number;
459
+ skipped: Record<string, number>;
460
+ budgetExhausted: boolean;
461
+ skippedForBudget: number;
462
+ /**
463
+ * OPTIONAL, and only the decay phase sets it: rows whose CANONICAL column the
464
+ * phase brought back to the arithmetic, as opposed to items it acted on
465
+ * (`changed`). It rides the outcome rather than the phase's own result type
466
+ * because `runPhase` is what writes the report, and a number that never
467
+ * reaches the report reaches nothing durable either — which was exactly U8's
468
+ * defect (`decay.ts#DecayResult.bandsReconciled`).
469
+ */
470
+ reconciled?: number;
471
+ }
472
+
473
+ export function emptyOutcome(): PhaseOutcome {
474
+ return { examined: 0, changed: 0, skipped: {}, budgetExhausted: false, skippedForBudget: 0 };
475
+ }
476
+
477
+ /** Counts a named skip reason. Reasons are enumerated, never summed into one. */
478
+ /**
479
+ * THE JOURNAL IS NOT SUBJECT TO FORGETTING, and this is the one predicate that
480
+ * says so — read by every phase rather than re-spelled in four.
481
+ *
482
+ * An episode is the owner's first-person account and the SOURCE of memories:
483
+ * "context and source, in that order, ingested ONCE as an ordinary memory"
484
+ * (`self/episodes.ts`). Forgetting applies to what was minted FROM an episode,
485
+ * never to the episode itself — the memory decays, consolidates, is merged and
486
+ * is eventually pruned like anything else, and the account it came from stays
487
+ * readable in the owner's own directory (constitution 6: the owner owns the
488
+ * data, in prose readable in any editor; 7: memory changes like human memory,
489
+ * which is a claim about MEMORIES).
490
+ *
491
+ * Measured 2026-09-04 on the live store: all 224 migrated episodes sit in the
492
+ * episodic band with zero on every salience dimension, so the prune pass would
493
+ * have archived the entire journal at the floor — and an archived episode stops
494
+ * reconciling, so the memories it had not yet minted would never exist. The
495
+ * same shape as the dedup finding a day earlier: phases that walk "every row"
496
+ * were written when every row was a memory.
497
+ */
498
+ export function isJournal(row: MemoryRow): boolean {
499
+ return row.type === "episode";
500
+ }
501
+
502
+ /**
503
+ * A SCHEMA ROW IS NOT A DUPLICATE CANDIDATE — read by `dedup.ts`, and by
504
+ * nothing else.
505
+ *
506
+ * Deliberately NOT the shape of `isJournal`, which every phase reads. Elements
507
+ * fade, take pressure, cross bands and are revised: they belong to decay,
508
+ * consolidate and prune exactly as memories do. The one phase they do not
509
+ * belong to is dedup, because "these two say the same thing, so they are one
510
+ * thing" is a claim about NOTES, and an element is a standing claim with its
511
+ * own machinery for changing — `schemas/` §5.6 (a belief changes only when a
512
+ * challenger's force beats its inertia, and the old version is kept with
513
+ * lineage), §5 G1 (no operation edits a belief), §5 G4 (near collisions refuse
514
+ * LOUDLY rather than merging). Duplicates among beliefs are that module's
515
+ * question; a sleep phase archiving one is generalization by blending, which
516
+ * constitution line 12 and the schemas contract both refuse by name.
517
+ *
518
+ * Probe H, filed on 2026-09-04 (NOTES §12) and closed here: an `addBelief`
519
+ * whose statement is X and an ordinary memory whose body is X, born the same
520
+ * lived day, with no revision anywhere. G9b cannot reach it — no accommodation
521
+ * row is involved — and `mem_` sorts before `sch_`, so the belief was archived
522
+ * `merged` and `beliefs(entity)` read empty. On a migrated store the DIRECTION
523
+ * of the loss is certain and its COUNT is not: `tools/migrate/apply.ts` minted
524
+ * every migrated element at the IMPORT day while migrated memories kept their
525
+ * v1 birth day, so the memory is never younger and the element always loses —
526
+ * but a collision needs two distinct v1 items whose gated text is
527
+ * byte-identical, and only a scan of the store can say how many there are.
528
+ */
529
+ export function isSchemaRow(row: MemoryRow): boolean {
530
+ return row.type === "schema";
531
+ }
532
+
533
+ export function countSkip(out: PhaseOutcome, reason: string, n = 1): void {
534
+ out.skipped[reason] = (out.skipped[reason] ?? 0) + n;
535
+ }
536
+
537
+ // ---------------------------------------------------------------------------
538
+ // Re-exports the callers of this module need
539
+ // ---------------------------------------------------------------------------
540
+
541
+ export type { PromotionCrossing, PromotionReason, PruneRecord, PruneReason, SymmetryCheck };
542
+ export type { MemoryRow, StoredMemory, VersionPruneReport };