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,237 @@
1
+ /**
2
+ * The decay tick — synaptic downscaling, as a cache refresh.
3
+ *
4
+ * What this phase does: recompute `strength(m, d)` and `band(m, d)` for every
5
+ * live memory and materialize the result into the ranking cache (box 3) — and,
6
+ * since 2026-09-14, write each row's band back to the box-2 `band` column when
7
+ * the column disagrees with the arithmetic.
8
+ *
9
+ * What it does NOT do, and cannot: apply a decay STEP to canonical state.
10
+ * Strength is a pure function of stored state and the lived day, so there is no
11
+ * "step" to apply and nothing to double-apply. `uses`, `lastUsedDay` and the
12
+ * prose are untouched. v1 materialized decay into canonical files (~1.9K file
13
+ * writes a day); v2 received that as an open choice with the evidence attached
14
+ * (behavioral-spec §11) and declined it, and still declines it.
15
+ *
16
+ * THE BAND COLUMN IS THE ONE EXCEPTION, and it is a reconciliation rather than a
17
+ * materialization (IMPROVEMENTS U8, 2026-09-14). `band(m, d)` is the same pure
18
+ * function either way; the column existed as a fossil — episodic at mint,
19
+ * identity at promotion, and never "semantic" — so on the live store 869 rows
20
+ * were semantic in the cache and episodic in the table, and every surface that
21
+ * read the column (the `status` tool's `byBand`) reported a number the system
22
+ * itself did not believe. A pass that EMITS `band.transition` rows and leaves
23
+ * the table contradicting them is a pass that lies in two places at once
24
+ * (constitution 16). So: one UPDATE per row whose column is wrong, never a
25
+ * strength write, never a row that already agrees — a caught-up store writes a
26
+ * handful a day, and a replayed day writes nothing at all. See `NOTES.md` §5.
27
+ *
28
+ * THE SKIP LIST IS BEHAVIOR, and each skip is reported separately (§3, v1 §11
29
+ * G5). Note what "skipped" means here: because the recompute is arithmetic, an
30
+ * identity-band memory is not branched around — `physics.decay()` returns D = 1
31
+ * for it, so the exemption IS the arithmetic. The category is still counted,
32
+ * because "how many rows did not move, and why" is the question the telemetry
33
+ * exists to answer, and a category that is structurally zero is a different
34
+ * record from one that never fired (scar §2.4).
35
+ *
36
+ * CALM BY DEFAULT (v1 §11 G8): a row is written only when it actually moves
37
+ * past `DECAY_QUANTUM` or changes band. A quiet day writes almost nothing.
38
+ *
39
+ * AND — since 2026-08-25 — THIS IS THE ONE PLACE BAND MOVES ARE COUNTED BY
40
+ * DIRECTION, which is what makes `physics.symmetryCheck` (guarantee 12, scar
41
+ * §2.10) a live tripwire instead of a function nobody calls.
42
+ *
43
+ * One place, deliberately, and the reason is arithmetic. Every way a band can
44
+ * change is visible HERE, because `band(m, d)` is a pure function of stored
45
+ * state and this pass reads it for every live row against its last reading:
46
+ *
47
+ * - a DECAY DEMOTION (semantic→episodic) is only ever a number falling back
48
+ * under `THETA_SEM`, so this pass is the only place it exists at all —
49
+ * it was v1's dominant crossing, 268 of 345;
50
+ * - a REVISION-DRIVEN demotion is the same fact: a challenged memory's
51
+ * strength moves, and the next tick reads the new band. `schemas/` writes
52
+ * no band and neither does `supersede` — a source scan says so;
53
+ * - the IDENTITY CROSSING is a decision `consolidate/` makes and records for
54
+ * itself, and it becomes a band move here on the next tick, because
55
+ * `promotedIdentity` makes `band()` answer "identity".
56
+ *
57
+ * Counting the crossing at the promotion site TOO would count it twice — the
58
+ * cache diff has no way to know a move was already recorded — and a
59
+ * double-counted up-move is a ratchet tripwire lying in the ratchet's own
60
+ * direction. So the promotion's up-move is counted one lived day later, which
61
+ * is a lag in a counter whose sample threshold is 20 moves across the whole
62
+ * history, and is the price of having exactly one definition of a crossing.
63
+ */
64
+
65
+ import { band, bandMove, strength } from "../physics/index.js";
66
+ import { TUNABLES as PHYSICS } from "../physics/index.js";
67
+ import { rowToPhysics } from "../store/operational.js";
68
+ import { TUNABLES } from "./tunables.js";
69
+ import type { BandTransition, PhaseCtx, PhaseOutcome } from "./types.js";
70
+ import { countSkip, emptyOutcome, isJournal, recordBandTransition } from "./types.js";
71
+ import type { StrengthCache, StrengthRow } from "./strength-cache.js";
72
+
73
+ /** Skip categories, enumerated so a zero is distinguishable from an absence. */
74
+ export const DECAY_SKIPS = [
75
+ "archived",
76
+ "removed",
77
+ /** The journal, which is a source and not a memory (`types.ts#isJournal`). */
78
+ "journal",
79
+ "identity-band",
80
+ "reinforced-today",
81
+ "at-floor",
82
+ "under-audit",
83
+ "unchanged",
84
+ ] as const;
85
+
86
+ export type DecaySkip = (typeof DECAY_SKIPS)[number];
87
+
88
+ export interface DecayResult extends PhaseOutcome {
89
+ /** The rows written this cycle — ids and numbers, never text. */
90
+ written: readonly StrengthRow[];
91
+ /**
92
+ * Band crossings this tick, BY DIRECTION (guarantee 12). v1's dominant
93
+ * crossing was the semantic→episodic decay demotion — 268 of 345 — and this
94
+ * pass is the only place one is observable, because a demotion is not a
95
+ * decision anybody makes: it is the arithmetic falling back under `THETA_SEM`.
96
+ */
97
+ transitions: readonly BandTransition[];
98
+ /**
99
+ * Rows whose box-2 `band` column disagreed with `band(m, d)` and was brought
100
+ * to it this pass (U8). It is a RECONCILIATION count, not a crossing count:
101
+ * `transitions` is the crossing record and is read off the cache diff, while
102
+ * this is "how many rows did the table have wrong". On a caught-up store it is
103
+ * the same handful as the crossings; the first pass after this shipped carries
104
+ * the whole backlog, which is the number worth seeing once.
105
+ *
106
+ * It is ALSO `PhaseOutcome.reconciled`, which is how it reaches the phase
107
+ * report and the durable `sleep.cycle` row; this field is the name the phase's
108
+ * own callers already use. Counted under observer too — only the write is
109
+ * gated on `apply`.
110
+ */
111
+ bandsReconciled: number;
112
+ }
113
+
114
+ export function runDecay(ctx: PhaseCtx, cache: StrengthCache | null): DecayResult {
115
+ const out = emptyOutcome();
116
+ for (const skip of DECAY_SKIPS) out.skipped[skip] = 0;
117
+
118
+ const { store, day } = ctx;
119
+ const denied = new Set(store.deniedIds());
120
+ const prior = cache === null ? new Map<string, StrengthRow>() : cache.readAll();
121
+ const written: StrengthRow[] = [];
122
+ const transitions: BandTransition[] = [];
123
+ let bandsReconciled = 0;
124
+ const ids = store.list();
125
+
126
+ let index = 0;
127
+ for (const id of ids) {
128
+ if (out.examined >= ctx.budget) {
129
+ out.budgetExhausted = true;
130
+ out.skippedForBudget = ids.length - index;
131
+ break;
132
+ }
133
+ index += 1;
134
+ const row = store.row(id);
135
+ if (row === undefined) continue;
136
+ if (denied.has(id)) {
137
+ countSkip(out, "removed");
138
+ continue;
139
+ }
140
+ if (row.archived === 1) {
141
+ countSkip(out, "archived");
142
+ continue;
143
+ }
144
+ // The journal is a source, not a memory: it is not examined, so it cannot
145
+ // move a band or write a strength row (`types.ts#isJournal`).
146
+ if (isJournal(row)) {
147
+ countSkip(out, "journal");
148
+ continue;
149
+ }
150
+ out.examined += 1;
151
+
152
+ const p = rowToPhysics(row);
153
+ const s = strength(p, day);
154
+ const b = band(p, day);
155
+
156
+ // The named skip categories. They are reported, not branched on: the
157
+ // arithmetic already produces the right number for each.
158
+ if (p.promotedIdentity) countSkip(out, "identity-band");
159
+ if (p.lastUsedDay === day) countSkip(out, "reinforced-today");
160
+ if (s < PHYSICS.PHI_PRUNE) countSkip(out, "at-floor");
161
+
162
+ // THE BAND OF RECORD (U8), and why it is here rather than inside the
163
+ // `moved` branch below. `moved` is a question about the CACHE — has this row
164
+ // changed since its last reading — and a row whose cache was right all along
165
+ // while the table was wrong answers "no" forever. Asking the column directly
166
+ // is what makes the reconciliation total: after a pass that was not cut
167
+ // short by the budget, no live non-journal row's column contradicts the
168
+ // arithmetic, which is exactly what `counterparts verify` now counts.
169
+ //
170
+ // THE COUNT IS NOT GATED ON `apply`, only the WRITE is. `PhaseCtx.apply`'s
171
+ // contract is that the read-only path walks the identical code and computes
172
+ // the identical verdicts — it simply never reaches a write — and
173
+ // `sleep.observer.report`'s `would` rides on that. Counting inside the
174
+ // `apply` branch made an observer report 0 disagreements on a store with
175
+ // 869 of them, which is the one number an instrument exists to print.
176
+ const wrong = row.band !== b;
177
+ if (wrong) {
178
+ bandsReconciled += 1;
179
+ if (ctx.apply) store.setBand(id, b, day);
180
+ }
181
+
182
+ const was = prior.get(id);
183
+ const moved =
184
+ was === undefined ||
185
+ was.band !== b ||
186
+ Math.abs(was.strength - s) >= TUNABLES.DECAY_QUANTUM;
187
+ if (!moved) {
188
+ // A ROW THE PASS ACTED ON IS NOT AN UNCHANGED ROW, even when the cache had
189
+ // nothing to say about it. On the exact U8 shape — the column wrong and
190
+ // the ranking cache already right — `moved` is false for every row, and
191
+ // counting those as `unchanged` is what made `runCycle` issue 869 UPDATEs
192
+ // and then file the phase as `ran-nothing-found` / `nothing-to-do`. Either
193
+ // or, never both: the row is counted once, in the category that is true.
194
+ if (wrong) out.changed += 1;
195
+ else countSkip(out, "unchanged");
196
+ continue;
197
+ }
198
+ // A CROSSING, not a first reading. `was === undefined` is the cache filling
199
+ // in — a fresh store, or the tick after `rebuildCache()` dropped box 3 — and
200
+ // counting those as up-moves would hand the ratchet tripwire a burst of
201
+ // fabricated promotions on exactly the days it is least able to tell.
202
+ if (was !== undefined && was.band !== b) {
203
+ const direction = bandMove(was.band, b);
204
+ if (direction !== "none") {
205
+ const transition: BandTransition = {
206
+ id,
207
+ kind: row.kind,
208
+ from: was.band,
209
+ to: b,
210
+ direction,
211
+ site: "decay",
212
+ day,
213
+ };
214
+ transitions.push(transition);
215
+ recordBandTransition(ctx, transition);
216
+ }
217
+ }
218
+ written.push({ id, strength: s, band: b, day });
219
+ out.changed += 1;
220
+ ctx.step("item", { index, id });
221
+ }
222
+
223
+ // A PASS THAT ONLY RECONCILED STILL DID SOMETHING. The old guard asked the
224
+ // cache alone, so the U8 catch-up — 869 columns rewritten, no strength row
225
+ // moved — left no ring event at all, and the one pass worth watching was the
226
+ // one the log could not see.
227
+ if (ctx.apply && cache !== null && (written.length > 0 || bandsReconciled > 0)) {
228
+ if (written.length > 0) cache.write(written);
229
+ ctx.event("sleep.decay.materialized", undefined, {
230
+ rows: written.length,
231
+ examined: out.examined,
232
+ bandsReconciled,
233
+ day,
234
+ });
235
+ }
236
+ return { ...out, reconciled: bandsReconciled, written, transitions, bandsReconciled };
237
+ }
@@ -0,0 +1,373 @@
1
+ /**
2
+ * The dedup pass — physics' verdicts over cache-provided candidates.
3
+ *
4
+ * The rule that matters most is a REFUSAL: **a memory that declares `updates:`
5
+ * is never merged into its target** (`physics/` §5.7, CONTRACT §5 G9). A
6
+ * refutation is topically as close to the belief it refutes as anything in the
7
+ * store; merging it would credit a use to that belief and reinforce it. That is
8
+ * scar §2.10's one-way ratchet, rebuilt by accident. Physics checks the
9
+ * declaration FIRST, before hash and before cosine, and this phase never
10
+ * second-guesses it.
11
+ *
12
+ * **Candidates are the cache's job, not physics'.** The shipped default is
13
+ * lexical and free: identical content hashes, read from box 2. An
14
+ * embedding-backed source (cosine over box 3) is INJECTED, is permitted
15
+ * arithmetic rather than a generative call (§4), and is isolated per call — if
16
+ * it throws, the pass degrades to hash-only and says so, rather than failing the
17
+ * cycle (scar E1). Ambiguous near-duplicates are left alone (§5.7, owner
18
+ * decision): accepted rent, paid for zero substrate confabulation.
19
+ *
20
+ * The same refusal has a second half, found 2026-09-04 on the first store that
21
+ * ever crossed the pressure bar: **a revision's successor is never the losing
22
+ * candidate of a same-hash merge** (`revisionSuccessorPair` and the wider clause
23
+ * in `runDedup` below). The declaration guard cannot reach it — that declaration
24
+ * names the PREDECESSOR — and the successor's body IS its challenger's body by
25
+ * construction, so the merge fired on the revision's own evening and the revised
26
+ * belief stopped being a belief. The rule is stated as "never the loser" rather
27
+ * than as a pair, because a THIRD row with the same text (the same sentence
28
+ * noted twice) takes the original's seat and the pair relation reads false
29
+ * against it — and then the element loses its only live version.
30
+ *
31
+ * The same refusal has a THIRD half, and it is the widest of the three: **a
32
+ * `type: "schema"` row is not a dedup candidate at all** (`types.ts#isSchemaRow`,
33
+ * read where the live set is built, so both candidate sources are covered by
34
+ * construction). A belief is a standing claim about a person or a thing, with
35
+ * its own revision machinery and its own refusal to blend (`schemas/` §5.6,
36
+ * §5 G1, §5 G4); "these two say the same thing, so they are one thing" is a
37
+ * claim about NOTES. Probe H, found by the adversarial review on 2026-09-04:
38
+ * an `addBelief` with statement X and a memory with body X, born the same day,
39
+ * no revision anywhere — the belief lost the tie-break and stopped being a
40
+ * belief. Migration settles the DIRECTION of that loss and not its frequency:
41
+ * migrated elements were minted at the import day while migrated memories kept
42
+ * their v1 birth day, so on any such pair the memory is never younger and the
43
+ * element always loses — but a pair needs two distinct v1 items whose gated
44
+ * text is byte-identical, and how often that happened is unknown until the
45
+ * owner's dry run counts it. G9b is NOT made redundant by this: `revision.ts`'s identity arm mints
46
+ * its successor as `type: "memory"`, and only G9b stands between that row and
47
+ * the challenger whose words it carries.
48
+ *
49
+ * **A merge is `uses(original) += 1` and the duplicate ARCHIVES.** Both halves
50
+ * are load-bearing. Without the credit the merge is a deletion; without the
51
+ * exit the same pair is found again tomorrow and credited again — a uses ratchet
52
+ * and a direct breach of the replay-idempotence guarantee (§5 G3). Archive, not
53
+ * delete: the duplicate keeps its prose and its id.
54
+ */
55
+
56
+ import { dedupVerdict } from "../physics/index.js";
57
+ import type { DedupReason } from "../physics/index.js";
58
+ import { rowToPhysics } from "../store/operational.js";
59
+ import { hashText } from "../store/prose.js";
60
+ import { ACCOMMODATION_SOURCE, MERGE_ARCHIVE_REASON, MERGE_RECORD_PREFIX } from "./tunables.js";
61
+ import type { MergeRecord, PhaseCtx, PhaseOutcome, SleepStore } from "./types.js";
62
+ import { countSkip, emptyOutcome, isJournal, isSchemaRow } from "./types.js";
63
+
64
+ export interface DedupPair {
65
+ readonly candidateId: string;
66
+ readonly originalId: string;
67
+ readonly sameContentHash?: boolean;
68
+ /** cos(v(candidate), v(original)); null when no vector exists. */
69
+ readonly cosine?: number | null;
70
+ }
71
+
72
+ export interface DedupCandidateInput {
73
+ readonly store: SleepStore;
74
+ readonly day: number;
75
+ /** Live (non-archived, non-removed) ids, in store order. */
76
+ readonly liveIds: readonly string[];
77
+ }
78
+
79
+ export type DedupCandidateSource = (input: DedupCandidateInput) => readonly DedupPair[];
80
+
81
+ export interface DedupResult extends PhaseOutcome {
82
+ readonly merged: readonly MergeRecord[];
83
+ readonly leftAlone: Readonly<Record<string, number>>;
84
+ /** True when the injected candidate source failed and the pass fell back. */
85
+ readonly degradedToLexical: boolean;
86
+ }
87
+
88
+ export function mergeRecordKey(id: string): string {
89
+ return `${MERGE_RECORD_PREFIX}${id}`;
90
+ }
91
+
92
+ /**
93
+ * The shipped candidate source: identical INTERPRETATIONS, hashed here.
94
+ *
95
+ * Note what is deliberately not used: `memories.content_hash`. Since the floor
96
+ * (2026-09-20) it addresses the BODY — `hashText(body)`, one definition across
97
+ * both tables — so two memories that differ only in title now hash the same,
98
+ * which makes it a fine exact-duplicate test and still the wrong tool here: it
99
+ * cannot see a NEAR duplicate, which is what this pass is for. Before the floor
100
+ * it addressed the whole
101
+ * serialized prose document, id and frontmatter included, so two distinct
102
+ * memories can never share one — it is a change detector, not a duplicate
103
+ * detector. The duplicate question is about the body, which is the memory
104
+ * (`store/prose.ts`: "The interpretation. This *is* the memory").
105
+ *
106
+ * The hash is computed in memory and never recorded: prune records are
107
+ * content-by-reference and carry no hash at all (scar §2.20).
108
+ *
109
+ * The ORIGINAL is the earliest-born member of a group (ties broken by id, so the
110
+ * choice is deterministic and a replay picks the same original).
111
+ */
112
+ export function contentHashCandidates(input: DedupCandidateInput): DedupPair[] {
113
+ const groups = new Map<string, { id: string; birthDay: number }[]>();
114
+ for (const id of input.liveIds) {
115
+ const row = input.store.row(id);
116
+ if (row === undefined) continue;
117
+ let bodyHash: string;
118
+ try {
119
+ bodyHash = hashText(input.store.read(id).doc.body);
120
+ } catch {
121
+ continue;
122
+ }
123
+ const list = groups.get(bodyHash) ?? [];
124
+ list.push({ id, birthDay: row.birth_day });
125
+ groups.set(bodyHash, list);
126
+ }
127
+ const pairs: DedupPair[] = [];
128
+ for (const members of groups.values()) {
129
+ if (members.length < 2) continue;
130
+ members.sort((a, b) => a.birthDay - b.birthDay || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
131
+ const original = members[0];
132
+ if (original === undefined) continue;
133
+ for (const dup of members.slice(1)) {
134
+ pairs.push({ candidateId: dup.id, originalId: original.id, sameContentHash: true });
135
+ }
136
+ }
137
+ return pairs;
138
+ }
139
+
140
+ /**
141
+ * The author's `updates:` declaration, read from canonical prose meta. There is
142
+ * no inferred-revision path: if the writer did not declare it, it is not one
143
+ * (`physics/` guarantee 7). See INTERFACE-GAPS.md §4 — the minting seam must
144
+ * actually persist this field for the refusal to have anything to read.
145
+ */
146
+ export function declaredUpdates(store: SleepStore, id: string): string | null {
147
+ try {
148
+ const value = store.read(id).doc.meta["updates"];
149
+ return typeof value === "string" && value.length > 0 ? value : null;
150
+ } catch {
151
+ return null;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * The declaration's OTHER half, read off the row instead of the prose.
157
+ *
158
+ * A revision mints its successor with the challenger's own words — the winning
159
+ * statement IS the new belief (`schemas/` §5.6) — so the successor and the
160
+ * challenger share a body BY CONSTRUCTION, exactly the way an ingested memory
161
+ * shares one with its episode. `declaredUpdates` cannot see it: that
162
+ * declaration names the PREDECESSOR, and the successor has a fresh id. Left
163
+ * alone, the tie-break (birth day, then id — and `mem_` sorts before `sch_`)
164
+ * archived the successor into the challenger on the revision's own evening, and
165
+ * the revised belief stopped being a belief. Found 2026-09-04, the first store
166
+ * that ever crossed the pressure bar.
167
+ *
168
+ * Two columns say it, and no prose read is needed: `source` is
169
+ * `"accommodation"` — written at exactly two sites, both of them supersedes
170
+ * with lineage (`schemas/index.ts` for both element arms, `revision.ts` for the
171
+ * identity arm; the belief arm climbs a bar and the current-state arm does not,
172
+ * so "under pressure" would only describe one of them) — and `origin_ref` is
173
+ * the challenger the successor was made from.
174
+ */
175
+ export function revisionSuccessorOf(store: SleepStore, id: string): string | null {
176
+ const row = store.row(id);
177
+ if (row === undefined || row.source !== ACCOMMODATION_SOURCE) return null;
178
+ return row.origin_ref;
179
+ }
180
+
181
+ /**
182
+ * The pair relation, checked BOTH WAYS, because which row the tie-break calls
183
+ * the original is an accident of ids.
184
+ */
185
+ export function revisionSuccessorPair(store: SleepStore, a: string, b: string): boolean {
186
+ return revisionSuccessorOf(store, a) === b || revisionSuccessorOf(store, b) === a;
187
+ }
188
+
189
+ export function runDedup(ctx: PhaseCtx, source?: DedupCandidateSource): DedupResult {
190
+ const out = emptyOutcome();
191
+ out.skipped["already-archived"] = 0;
192
+ out.skipped["self-pair"] = 0;
193
+ out.skipped["journal"] = 0;
194
+ out.skipped["schema"] = 0;
195
+ const leftAlone: Record<string, number> = {};
196
+ const merged: MergeRecord[] = [];
197
+ let degradedToLexical = false;
198
+
199
+ const { store, day } = ctx;
200
+ const denied = new Set(store.deniedIds());
201
+ const live = new Set<string>();
202
+ for (const id of store.list()) {
203
+ const row = store.row(id);
204
+ if (row === undefined || row.archived === 1 || denied.has(id)) continue;
205
+ // NOT THE JOURNAL (`types.ts#isJournal`). The memory ingested from an
206
+ // episode carries the episode's own prose, so the two share a content hash
207
+ // BY CONSTRUCTION. Found 2026-09-04, the first time anything actually
208
+ // ingested an episode: dedup merged the fresh memory into the journal at
209
+ // the very boundary that minted it, leaving the episode with no live memory
210
+ // and its idempotency key pointing at an archived row. A journal is not a
211
+ // duplicate of the memory made from it, in either direction.
212
+ if (isJournal(row)) {
213
+ // Counted, not passed over in silence — G15 says "a named skip in each
214
+ // phase", and until 2026-09-05 this one arm was the exception.
215
+ countSkip(out, "journal");
216
+ continue;
217
+ }
218
+ // NOT A SCHEMA ROW (`types.ts#isSchemaRow`). A belief is a standing claim
219
+ // with its own machinery for changing, not a note that can turn out to be
220
+ // a copy of another note. Excluding it HERE rather than at each candidate
221
+ // source is what makes the rule total: `contentHashCandidates` and any
222
+ // injected cosine source both read `liveIds`, so neither can see an
223
+ // element to propose it. Probe H, NOTES §12, closed 2026-09-05.
224
+ if (isSchemaRow(row)) {
225
+ countSkip(out, "schema");
226
+ continue;
227
+ }
228
+ live.add(id);
229
+ }
230
+ const liveIds = [...live];
231
+ const input: DedupCandidateInput = { store, day, liveIds };
232
+
233
+ const pairs: DedupPair[] = contentHashCandidates(input);
234
+ if (source !== undefined) {
235
+ try {
236
+ pairs.push(...source(input));
237
+ } catch (err) {
238
+ // Scar E1: an embedding lookup degrades to empty-and-logged, never throws
239
+ // into the cycle. Lexical candidates already found still stand.
240
+ degradedToLexical = true;
241
+ ctx.event("sleep.dedup.degraded", undefined, { error: errorName(err) });
242
+ }
243
+ }
244
+
245
+ let index = 0;
246
+ for (const pair of pairs) {
247
+ if (out.examined >= ctx.budget) {
248
+ out.budgetExhausted = true;
249
+ out.skippedForBudget = pairs.length - index;
250
+ break;
251
+ }
252
+ index += 1;
253
+ if (pair.candidateId === pair.originalId) {
254
+ countSkip(out, "self-pair");
255
+ continue;
256
+ }
257
+ if (!live.has(pair.candidateId) || !live.has(pair.originalId)) {
258
+ // An INJECTED source is not obliged to have read `liveIds`, so name what
259
+ // actually stood the pair down. "already-archived" for a live belief
260
+ // would be a false reason in the one report a reader looks at (§5 G6,
261
+ // scar §2.4), and a phase that mislabels its refusals is a phase whose
262
+ // refusals nobody can audit.
263
+ const kind = excludedKind(store, pair.candidateId) ?? excludedKind(store, pair.originalId);
264
+ countSkip(out, kind ?? "already-archived");
265
+ continue;
266
+ }
267
+ out.examined += 1;
268
+
269
+ const verdict = dedupVerdict({
270
+ originalId: pair.originalId,
271
+ declaredUpdates: declaredUpdates(store, pair.candidateId),
272
+ // The pair relation, PLUS the wider truth it is a special case of: an
273
+ // accommodation row can never be the losing candidate of a SAME-HASH
274
+ // merge. Its body IS its challenger's body by construction
275
+ // (`schemas/index.ts` mints it from `readProse(challengerId).body`), so
276
+ // every same-hash group it belongs to is that challenger plus ordinary
277
+ // twins of the same text — and none of those is the thing the revision
278
+ // produced. Without this clause a twin born EARLIER takes the original's
279
+ // seat, the pair relation reads false against it, and the element loses
280
+ // its only live version. The cosine path is deliberately untouched: a
281
+ // merely SIMILAR row is an ordinary near-duplicate question.
282
+ revisionSuccessorPair:
283
+ revisionSuccessorPair(store, pair.candidateId, pair.originalId) ||
284
+ (pair.sameContentHash === true && revisionSuccessorOf(store, pair.candidateId) !== null),
285
+ ...(pair.sameContentHash !== undefined ? { sameContentHash: pair.sameContentHash } : {}),
286
+ ...(pair.cosine !== undefined ? { cosine: pair.cosine } : {}),
287
+ });
288
+ if (verdict.verdict !== "merge" || verdict.effect === null) {
289
+ leftAlone[verdict.reason] = (leftAlone[verdict.reason] ?? 0) + 1;
290
+ // Mirrored into the phase report's skip map, prefixed, so every named
291
+ // physics reason reaches the cycle report a reader actually looks at.
292
+ countSkip(out, `left-alone:${verdict.reason}`);
293
+ continue;
294
+ }
295
+
296
+ // OWNER RULING 2026-09-14 (R1, review of #99): a merge is NOT engagement.
297
+ // A duplicate authored again bumps `uses` (the record of the re-encounter,
298
+ // as before) and never a reinforced day: promotion to identity stays gated
299
+ // on the assistant EXPANDING or QUOTING a memory (recall §9.2), and three
300
+ // near-duplicate deposits on three days must not walk a memory into
301
+ // identity with zero use. `credit` says so on the record, so the row
302
+ // cannot be read as a physics credit that was refused.
303
+ let credit = "not-applied";
304
+ if (ctx.apply) {
305
+ const originalRow = store.row(pair.originalId);
306
+ if (originalRow === undefined) {
307
+ countSkip(out, "already-archived");
308
+ continue;
309
+ }
310
+ const p = rowToPhysics(originalRow);
311
+ store.updatePhysics(pair.originalId, { uses: p.uses + verdict.effect.usesDelta });
312
+ credit = "uses-only";
313
+ }
314
+ const record: MergeRecord = {
315
+ event: "memory.merged",
316
+ day,
317
+ candidateId: pair.candidateId,
318
+ originalId: pair.originalId,
319
+ reason: verdict.reason,
320
+ usesDelta: verdict.effect.usesDelta,
321
+ credit,
322
+ };
323
+ if (ctx.apply) {
324
+ // Record first, exactly as the prune does: a merge nobody could account
325
+ // for afterwards is a silent loss of a memory's separate existence.
326
+ store.setMeta(mergeRecordKey(pair.candidateId), JSON.stringify(record));
327
+ store.appendEvent?.({
328
+ name: record.event,
329
+ day,
330
+ ref: pair.candidateId,
331
+ dedupKey: mergeRecordKey(pair.candidateId),
332
+ payload: { ...record },
333
+ });
334
+ // The WHOLE effect of a merge: the `uses` bump above, and the candidate's
335
+ // exit. Never a rewrite, never a blend (§5.7).
336
+ store.archive(pair.candidateId, MERGE_ARCHIVE_REASON);
337
+ }
338
+ live.delete(pair.candidateId);
339
+ merged.push(record);
340
+ out.changed += 1;
341
+ ctx.event("sleep.merged", pair.candidateId, {
342
+ original: pair.originalId,
343
+ reason: verdict.reason,
344
+ usesDelta: verdict.effect.usesDelta,
345
+ day,
346
+ });
347
+ ctx.step("item", { index, id: pair.candidateId });
348
+ }
349
+
350
+ return { ...out, merged, leftAlone, degradedToLexical };
351
+ }
352
+
353
+ /**
354
+ * Which standing exclusion, if any, put this id outside the live set. Returns
355
+ * the skip name the phase reports, so the two exclusions are named the same
356
+ * way whether the candidate source respected `liveIds` or not.
357
+ */
358
+ function excludedKind(store: SleepStore, id: string): "schema" | "journal" | null {
359
+ const row = store.row(id);
360
+ if (row === undefined) return null;
361
+ if (isSchemaRow(row)) return "schema";
362
+ if (isJournal(row)) return "journal";
363
+ return null;
364
+ }
365
+
366
+ function errorName(err: unknown): string {
367
+ if (err !== null && typeof err === "object" && "code" in err) {
368
+ return String((err as { code: unknown }).code);
369
+ }
370
+ return err instanceof Error ? err.name : "UNKNOWN";
371
+ }
372
+
373
+ export type { DedupReason };