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,1054 @@
1
+ /**
2
+ * `physics/` — all the arithmetic of memory on one page.
3
+ *
4
+ * Implements CONTRACT.md §5 exactly (including the 2026-08-25 rewrites of §5.3
5
+ * bands and §5.6 revision). PURE FUNCTIONS ONLY: no I/O, no model calls, no
6
+ * imports beyond `../types.js` and this module's own clock. Guarantee 1 is a test
7
+ * that asserts precisely that.
8
+ *
9
+ * Nothing here mutates its arguments. Every state-changing operation returns the
10
+ * NEXT values for the caller to persist, plus the verdict and the reason for it.
11
+ * Reasons are first-class: a bare boolean cannot be told apart from a bug
12
+ * (scar §2.4 — "a number in a log is not a monitor").
13
+ *
14
+ * Implementation choices where the contract is silent are recorded in NOTES.md.
15
+ */
16
+
17
+ import type { Band, Kind, MemoryPhysics, Salience } from "../types.js";
18
+ import { BOUNDARY_HOUR_DEFAULT } from "./clock.js";
19
+
20
+ export { dayKey, livedDay, livedDaysBetween } from "./clock.js";
21
+ export type { Band, Kind, MemoryPhysics, Salience } from "../types.js";
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // The TUNABLE table — every constant in physics, in one visible place.
25
+ // CAL = calibration-required: it must ship with a recorded measurement against
26
+ // the real space, or ship disabled (scar §2.8, guarantee 11).
27
+ // ---------------------------------------------------------------------------
28
+
29
+ export const TUNABLES = {
30
+ // --- §5.2 strength ---
31
+ /** Repetition credit per use [v0, verbatim]. */
32
+ REP_PER_USE: 0.12,
33
+ /** Repetition cap. With CONS_BONUS this tops out at 0.70, structurally below
34
+ * THETA_ID = 0.85 — guarantee 4 is arithmetic, not a check [v0; v1 §10 G11]. */
35
+ REP_CAP: 0.5,
36
+ /** Consolidation bonus [v0, verbatim]. */
37
+ CONS_BONUS: 0.2,
38
+
39
+ // --- §5.3 bands ---
40
+ /** Semantic floor, evaluated on DECAYED strength (§5.3 rewrite). */
41
+ THETA_SEM: 0.5,
42
+ /** Identity floor, evaluated on `base` — one half of promotion eligibility. */
43
+ THETA_ID: 0.85,
44
+ /** Distinct lived days of reinforcement required to promote (owner ruling N = 3).
45
+ * Same number, same ancestry, as the slow-kind revision pace (Amendment 15). */
46
+ N_PROMOTION_DAYS: 3,
47
+ /**
48
+ * The salience-claim ceiling for a FALLBACK-minted memory (owner ruling
49
+ * 2026-08-29, the authorship doctrine's salience half): the experiencer's own
50
+ * "remember this" commands the full 0-1 floor — lived testimony, the analog
51
+ * of affect stamping a memory vivid at encoding — but the crash fallback's
52
+ * author is a model retelling a transcript after the fact, and a reteller's
53
+ * claim is CAPPED. The first blind replay showed why: 97.9% of sweep mints
54
+ * self-claimed importance (mode 0.8), parking ~75% of the store above
55
+ * THETA_SEM with no independent check (review F5). 0.6 clears the semantic
56
+ * floor (a crashed day still matters) and sits structurally below THETA_ID.
57
+ * WORKING DEFAULT — to be revisited against the re-run's watch metrics.
58
+ */
59
+ SWEEP_CLAIM_CEILING: 0.6,
60
+ /**
61
+ * CAL. The claimed floor an AUTHORED memory gets when its author claimed
62
+ * nothing — the authorship doctrine's other half, measured 2026-09-04 on the
63
+ * live parallel-run store: all 48 authored memories carried
64
+ * relevance/emotional/predictive = 0, so an unclaimed note's `sal(m)` was
65
+ * ZERO. It was the weakest thing in the store, first to decay, and (now that
66
+ * `challengeForce = strength x sal`) any revision it declared pushed with no
67
+ * force at all — the exact inversion of "the experiencer's testimony is
68
+ * trusted". Silence is the common case: the asks never say to set salience.
69
+ *
70
+ * WHY THIS NUMBER, and it is arithmetic rather than taste:
71
+ * - `AUTHORED_DEFAULT_CLAIM + CONS_BONUS = 0.45 < THETA_SEM = 0.5`, and the
72
+ * largest `wSal` is 1.0, so a defaulted memory CANNOT reach the semantic
73
+ * band on the default alone — not even after consolidation. It gets there
74
+ * only by being used (rep 0.3 needs 3 credited days) or by an author
75
+ * actually claiming something. That is the structural form of v1's scar:
76
+ * a mode-0.8 self-claim parked ~75% of the store above THETA_SEM.
77
+ * - 0.25 < 0.34, the measured mean of the claims authors DID make, so
78
+ * staying silent says strictly less than speaking.
79
+ * - 0.25 < SWEEP_CLAIM_CEILING = 0.6: the default is a floor under the
80
+ * lived channel, not a promotion of it over the retelling channel.
81
+ * - It buys survival rather than rank: at kind `fact` (S = 60 lived days)
82
+ * strength falls below PHI_PRUNE = 0.02 after ~152 lived days instead of
83
+ * being prunable from birth.
84
+ * ENGINE-SET off the mint CHANNEL, exactly like `SWEEP_CLAIM_CEILING`; an
85
+ * explicit claim, however low, is never overridden. WORKING DEFAULT.
86
+ */
87
+ AUTHORED_DEFAULT_CLAIM: 0.25,
88
+
89
+ // --- §5.4 decay ---
90
+ /** Stability base, lived days. Reproduces v0's -0.015/day over ~a month. */
91
+ S_BASE: 60,
92
+ /** Use-stability coupling; logarithmic so a well-used memory slows without
93
+ * becoming immortal. */
94
+ BETA: 0.5,
95
+ /** Local rollover hour for the active-day clock (see clock.ts). */
96
+ BOUNDARY_HOUR: BOUNDARY_HOUR_DEFAULT,
97
+ /** CAL / open question 1 — a three-way decided by replay, not by taste.
98
+ * v1 ran flat, this page defaults exponential, engram upgraded to power-law
99
+ * (Ebbinghaus / Wixted / Jost). `tools/replay` runs all three. */
100
+ DECAY_SHAPE: "exponential" as DecayShape,
101
+ /** CAL. Power-law exponent, used only when DECAY_SHAPE === "power-law". */
102
+ POWER_LAW_PSI: 1.0,
103
+
104
+ // --- §5.1 salience ---
105
+ /** CAL. Size of the nearest-neighbour slice in E(m) for novelty (v1's top-M). */
106
+ K_NEAREST: 8,
107
+
108
+ // --- §5.5 reinforcement ---
109
+ /** Retrospective credit weights by tier. The ignorable tier never trains. */
110
+ W_REFERENCED: 1.0,
111
+ W_SURFACED: 0.25,
112
+ W_FOOTNOTED: 0.0,
113
+
114
+ // --- §5.6 revision ---
115
+ /** Pressure stability, lived days. Same curve FAMILY as memory decay, its own
116
+ * constant: challenge persistence is not the target's use history (NOTES.md). */
117
+ S_PRESSURE: 60,
118
+ /** Slow-kind daily force cap (iota >= SLOW_KIND_IOTA: self, person). Without
119
+ * it, one flawless claimed-maximal challenge (F = 1.0) crosses even the
120
+ * highest self bar (0.9) in a single day, and the ratified "one odd act
121
+ * doesn't rewrite your model of a friend" ~3-day property is an
122
+ * approximation, not a bound. 0.35 x 3 days > 0.9 max bar => >= 3 lived days
123
+ * is now arithmetic. Fast kinds are deliberately uncapped: world-state
124
+ * should flip on one clear correction. TUNABLE. */
125
+ F_DAY_CAP_SLOW: 0.35,
126
+ /** The iota threshold above which a kind is "slow" for the daily cap. */
127
+ SLOW_KIND_IOTA: 0.8,
128
+ /** Lived days a superseded version stays resolvable. TUNABLE default —
129
+ * assistant-recommended, explicitly NOT an owner ruling. */
130
+ H_SUPERSEDED_DAYS: 90,
131
+
132
+ // --- §5.7 dedup ---
133
+ /** CAL, and the sharpest instance of scar §2.8: in v1's embedding space
134
+ * arbitrary same-corpus pairs sat at median cosine 0.576, so an intuited
135
+ * floor is inert. Do not ship this number unmeasured. */
136
+ TAU_DUP: 0.95,
137
+
138
+ // --- §5.8 forgetting ---
139
+ /** CAL, and the one constant here with NO ancestry — v1 never pruned, so there
140
+ * is no measurement to inherit (open question 5). */
141
+ PHI_PRUNE: 0.02,
142
+ /** CAL, same provenance gap as PHI_PRUNE. Lived days of dwell before a floor
143
+ * memory may be pruned. */
144
+ D_FLOOR_DAYS: 90,
145
+
146
+ // --- guarantee 12: the symmetry counter (scar §2.10) ---
147
+ /** Stated expected ceiling on up-moves : down-moves. v1's ratchet read
148
+ * 279:0 — this is the tripwire that would have fired. CAL. */
149
+ SYMMETRY_MAX_UP_DOWN_RATIO: 4,
150
+ /** Below this many moves, the answer is "never asked", not "healthy"
151
+ * (scar §2.4: "did not fire" and "was never asked" are different records). */
152
+ SYMMETRY_MIN_SAMPLE: 20,
153
+
154
+ // --- §5.2 per-kind physics [v1 §4.3] ---
155
+ /** CAL, all of it. v1 recorded which ARM DRIVES, not a weight, so every
156
+ * non-driving omega below is a proposed reading, not a measurement
157
+ * (open question 3 asks whether the 0.4s exist at all). */
158
+ KINDS: {
159
+ // driver (v1) omega_sal omega_rep kappa iota
160
+ self: { wSal: 1.0, wRep: 0.0, kappa: 0.7, iota: 0.9 },
161
+ person: { wSal: 1.0, wRep: 0.0, kappa: 0.75, iota: 0.8 },
162
+ entity: { wSal: 1.0, wRep: 1.0, kappa: 0.85, iota: 0.5 },
163
+ skill: { wSal: 0.4, wRep: 1.0, kappa: 0.5, iota: 0.25 },
164
+ place: { wSal: 0.4, wRep: 1.0, kappa: 0.85, iota: 0.25 },
165
+ fact: { wSal: 1.0, wRep: 1.0, kappa: 1.0, iota: 0.2 },
166
+ } as const satisfies Record<Kind, KindPhysics>,
167
+ } as const;
168
+
169
+ export interface KindPhysics {
170
+ /** Weight on the salience arm of `base` (§5.2). */
171
+ wSal: number;
172
+ /** Weight on the repetition arm of `base` (§5.2). */
173
+ wRep: number;
174
+ /** Decay multiplier — it DIVIDES stability: fact (1.00) erodes fastest,
175
+ * skill (0.50) slowest (§5.4). */
176
+ kappa: number;
177
+ /** Revision inertia — the fraction of the target's strength a challenge must
178
+ * out-sum to land (§5.6). */
179
+ iota: number;
180
+ }
181
+
182
+ export type DecayShape = "exponential" | "flat" | "power-law";
183
+
184
+ export function kindPhysics(kind: Kind): KindPhysics {
185
+ return TUNABLES.KINDS[kind];
186
+ }
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // Small shared arithmetic
190
+ // ---------------------------------------------------------------------------
191
+
192
+ export function clamp01(x: number): number {
193
+ return x < 0 ? 0 : x > 1 ? 1 : x;
194
+ }
195
+
196
+ /** Distinct reinforced lived days; an absent field reads as 0 (the
197
+ * promotion-blocking direction, so an un-migrated row cannot be promoted). */
198
+ export function reinforcedDays(m: Pick<MemoryPhysics, "reinforcedDays">): number {
199
+ return m.reinforcedDays ?? 0;
200
+ }
201
+
202
+ /** Cosine similarity over caller-supplied vectors. Physics never fetches one. */
203
+ export function cosine(a: readonly number[], b: readonly number[]): number {
204
+ if (a.length !== b.length) {
205
+ throw new Error(`cosine: dimension mismatch ${a.length} vs ${b.length}`);
206
+ }
207
+ let dot = 0;
208
+ let na = 0;
209
+ let nb = 0;
210
+ for (let i = 0; i < a.length; i++) {
211
+ const x = a[i] ?? 0;
212
+ const y = b[i] ?? 0;
213
+ dot += x * y;
214
+ na += x * x;
215
+ nb += y * y;
216
+ }
217
+ if (na === 0 || nb === 0) return 0;
218
+ return dot / (Math.sqrt(na) * Math.sqrt(nb));
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // §5.1 Salience, fixed at encoding
223
+ // ---------------------------------------------------------------------------
224
+
225
+ /**
226
+ * novelty = 1 - max cos( v(m), v(e) ) over the schema slice E(m).
227
+ *
228
+ * E(m) EMPTY — a blind chunk — yields `null`, RECORDED, never defaulted to a
229
+ * number (scar §2.9: blind encoding must be countable, not invisible).
230
+ * Vectors are inputs; this module never fetches one.
231
+ */
232
+ export function novelty(
233
+ v: readonly number[],
234
+ context: readonly (readonly number[])[],
235
+ ): number | null {
236
+ if (context.length === 0) return null;
237
+ let best = -1;
238
+ for (const e of context) best = Math.max(best, cosine(v, e));
239
+ return clamp01(1 - best);
240
+ }
241
+
242
+ /** True when novelty could not be computed — the countable blind-write case. */
243
+ export function isBlindEncoding(s: Salience): boolean {
244
+ return s.novelty === null;
245
+ }
246
+
247
+ /**
248
+ * sal(m) = mean of the salience dimensions, floored by the author's claim.
249
+ *
250
+ * With novelty present that is v0's verbatim mean of four. With novelty null it
251
+ * is the mean of the THREE author-supplied dimensions — the null case specified,
252
+ * not implicit (review finding 2), and never a defaulted zero or one.
253
+ */
254
+ export function sal(s: Salience): number {
255
+ const dims: number[] = [s.relevance, s.emotional, s.predictive];
256
+ if (s.novelty !== null) dims.unshift(s.novelty);
257
+ let sum = 0;
258
+ for (const x of dims) sum += clamp01(x);
259
+ const mean = sum / dims.length;
260
+ return clamp01(Math.max(mean, s.claimed ?? 0));
261
+ }
262
+
263
+ /** The mean of the stored dimensions alone, ignoring any claimed floor. */
264
+ export function computedSal(s: Salience): number {
265
+ return sal({ ...s, claimed: null });
266
+ }
267
+
268
+ export interface SalienceLiftEvent {
269
+ readonly event: "salience.lifted";
270
+ readonly computed: number;
271
+ /** The claim as the author made it (clamped to [0,1] at intake), pre-CAP.
272
+ * Telemetry must carry it, or the re-run's watch metrics cannot propose
273
+ * the right ceiling. */
274
+ readonly claimed: number;
275
+ /** The claim actually stored (post-cap): what `sal(m)` will honor. */
276
+ readonly applied: number;
277
+ /** The ceiling this claim was subject to (1 for lived testimony). */
278
+ readonly ceiling: number;
279
+ /** True when the raw claim exceeded the ceiling and was cut down to it. */
280
+ readonly capped: boolean;
281
+ }
282
+
283
+ /**
284
+ * The claim the author never made. Kept SEPARATE from `salience.lifted` on
285
+ * purpose: the lift metric is "how often does an author's claim out-rank the
286
+ * computed dimensions", and folding a defaulted floor into it would read every
287
+ * silent note as a claim and destroy the number the ceiling decision needs.
288
+ */
289
+ export interface SalienceDefaultEvent {
290
+ readonly event: "salience.defaulted";
291
+ /** The mean of the stored dimensions — 0 for the case this exists for. */
292
+ readonly computed: number;
293
+ /** The floor applied, i.e. `TUNABLES.AUTHORED_DEFAULT_CLAIM`. */
294
+ readonly floor: number;
295
+ /** What `sal(m)` will honor with the default in place. */
296
+ readonly applied: number;
297
+ }
298
+
299
+ export interface SeamClamp {
300
+ /** The salience to store: dimensions untouched, claim recorded as the floor. */
301
+ salience: Salience;
302
+ /** True only when an AUTHOR's own claim out-ranked the computed dimensions.
303
+ * A defaulted floor is never a lift — see `SalienceDefaultEvent`. */
304
+ lifted: boolean;
305
+ blind: boolean;
306
+ /** True when the author's raw claim was cut to the ceiling. */
307
+ capped: boolean;
308
+ /** True when the author claimed nothing and the channel's default floor was
309
+ * applied in its place. Recorded on the row as `meta.claimedDefault`. */
310
+ defaulted: boolean;
311
+ /** The raw claim when it was capped, else null — the minting seam preserves
312
+ * it in prose meta so the un-capped testimony is never silently lost. */
313
+ rawClaim: number | null;
314
+ event: SalienceLiftEvent | null;
315
+ defaultEvent: SalienceDefaultEvent | null;
316
+ }
317
+
318
+ /**
319
+ * The proposal -> memory seam (guarantee 2). A claimed salience is a FLOOR:
320
+ * `sal(m) >= sal_claimed(m)`, clamped here, and ANY LIFT EMITS AN EVENT.
321
+ * The stored dimensions are never rewritten to satisfy the claim, so salience
322
+ * stays fixed at birth and a null novelty stays null.
323
+ *
324
+ * `ceiling` is the authorship doctrine's salience half (owner ruling
325
+ * 2026-08-29): lived testimony — the experiencer's own deposit — passes 1, the
326
+ * full floor; a retelling author (the crash-fallback sweep) passes
327
+ * `TUNABLES.SWEEP_CLAIM_CEILING`, and a raw claim above it is CUT to it, with
328
+ * the cut recorded on the event and the raw claim handed back for prose meta.
329
+ * The cap runs here and nowhere else, exactly like the floor ("clamped here,
330
+ * once" stays literally true).
331
+ *
332
+ * `defaultClaim` is the same idea in the other direction and the same kind of
333
+ * engine-set number: when the author claimed NOTHING, the channel's default
334
+ * floor stands in (`TUNABLES.AUTHORED_DEFAULT_CLAIM` for the lived channel,
335
+ * `null` — nothing at all — for every other). Silence is not testimony, so a
336
+ * default is recorded as `defaulted`, never as a lift; and an explicit claim,
337
+ * however low, is never overridden, because the branch is on `claimed === null`
338
+ * and nothing else.
339
+ */
340
+ export function clampSalienceAtSeam(
341
+ dims: Salience,
342
+ claimedSal: number | null,
343
+ ceiling = 1,
344
+ defaultClaim: number | null = null,
345
+ ): SeamClamp {
346
+ const raw = claimedSal === null ? null : clamp01(claimedSal);
347
+ const capped = raw !== null && raw > ceiling;
348
+ const defaulted = raw === null && defaultClaim !== null;
349
+ const claimed =
350
+ raw === null ? (defaultClaim === null ? null : clamp01(defaultClaim)) : Math.min(raw, ceiling);
351
+ const salience: Salience = { ...dims, claimed };
352
+ const computed = computedSal(salience);
353
+ const lifted = !defaulted && claimed !== null && claimed > computed;
354
+ return {
355
+ salience,
356
+ lifted,
357
+ blind: isBlindEncoding(salience),
358
+ capped,
359
+ defaulted,
360
+ rawClaim: capped ? raw : null,
361
+ event:
362
+ lifted || capped
363
+ ? {
364
+ event: "salience.lifted",
365
+ computed,
366
+ claimed: raw as number,
367
+ applied: sal(salience),
368
+ ceiling,
369
+ capped,
370
+ }
371
+ : null,
372
+ defaultEvent: defaulted
373
+ ? {
374
+ event: "salience.defaulted",
375
+ computed,
376
+ floor: claimed as number,
377
+ applied: sal(salience),
378
+ }
379
+ : null,
380
+ };
381
+ }
382
+
383
+ // ---------------------------------------------------------------------------
384
+ // §5.2 Strength — the one number
385
+ // ---------------------------------------------------------------------------
386
+
387
+ export function rep(m: Pick<MemoryPhysics, "uses">): number {
388
+ return Math.min(TUNABLES.REP_PER_USE * m.uses, TUNABLES.REP_CAP);
389
+ }
390
+
391
+ export function cons(m: Pick<MemoryPhysics, "consolidated">): number {
392
+ return m.consolidated ? TUNABLES.CONS_BONUS : 0;
393
+ }
394
+
395
+ /**
396
+ * base = max( omega_sal x sal, omega_rep x rep ) + cons.
397
+ *
398
+ * A MAX, never a product, and age is NOT an input [v1 Appendix A #1] — "a
399
+ * formative one-shot consolidates without repetition" is true only because of
400
+ * the max. Monotone non-decreasing (guarantee 3): salience is fixed, uses only
401
+ * rise, consolidation only turns on.
402
+ */
403
+ export function base(m: MemoryPhysics): number {
404
+ const k = kindPhysics(m.kind);
405
+ return Math.max(k.wSal * sal(m.salience), k.wRep * rep(m)) + cons(m);
406
+ }
407
+
408
+ /** Stability S, in lived days. kappa DIVIDES (§5.4). */
409
+ export function stability(m: Pick<MemoryPhysics, "kind" | "uses">): number {
410
+ return (
411
+ (TUNABLES.S_BASE * (1 + TUNABLES.BETA * Math.log(1 + Math.max(0, m.uses)))) /
412
+ kindPhysics(m.kind).kappa
413
+ );
414
+ }
415
+
416
+ /** The decay curve itself, over an elapsed lived-day interval. */
417
+ export function decayCurve(
418
+ elapsedDays: number,
419
+ s: number,
420
+ shape: DecayShape = TUNABLES.DECAY_SHAPE,
421
+ ): number {
422
+ const dt = Math.max(0, elapsedDays);
423
+ switch (shape) {
424
+ case "flat":
425
+ return Math.max(0, 1 - dt / s);
426
+ case "power-law":
427
+ return Math.pow(1 + dt / s, -TUNABLES.POWER_LAW_PSI);
428
+ case "exponential":
429
+ default:
430
+ return Math.exp(-dt / s);
431
+ }
432
+ }
433
+
434
+ /**
435
+ * D(m, d) — Ebbinghaus over LIVED days.
436
+ *
437
+ * Identity-band memories are decay-exempt (D = 1): the named deviation of §2 —
438
+ * flashbulb memories do fade in humans, here they do not. Everything else rides
439
+ * the curve from its last credited use. Idempotent by construction: D is a pure
440
+ * function of d, so there is no step to run twice (guarantee 5, scar E8).
441
+ */
442
+ export function decay(m: MemoryPhysics, d: number, shape: DecayShape = TUNABLES.DECAY_SHAPE): number {
443
+ if (m.promotedIdentity) return 1;
444
+ return decayCurve(d - m.lastUsedDay, stability(m), shape);
445
+ }
446
+
447
+ export function strength(m: MemoryPhysics, d: number, shape: DecayShape = TUNABLES.DECAY_SHAPE): number {
448
+ return clamp01(base(m) * decay(m, d, shape));
449
+ }
450
+
451
+ // ---------------------------------------------------------------------------
452
+ // §5.3 Bands
453
+ // ---------------------------------------------------------------------------
454
+
455
+ /**
456
+ * band = identity if promoted; semantic if DECAYED strength >= THETA_SEM;
457
+ * episodic otherwise.
458
+ *
459
+ * Nothing is born into identity, whatever salience is claimed: identity is
460
+ * entered only by inheriting it through a declared revision, or by the explicit
461
+ * counted promotion crossing of `promotionEligibility()`. Semantic and episodic
462
+ * are evaluated on decayed strength, so a faded semantic memory demotes and
463
+ * gains the prune exit — every band names its way out (scar §2.17).
464
+ */
465
+ export function band(m: MemoryPhysics, d: number, shape: DecayShape = TUNABLES.DECAY_SHAPE): Band {
466
+ if (m.promotedIdentity) return "identity";
467
+ return strength(m, d, shape) >= TUNABLES.THETA_SEM ? "semantic" : "episodic";
468
+ }
469
+
470
+ export type PromotionReason =
471
+ | "eligible"
472
+ | "already-identity"
473
+ | "base-below-identity-threshold"
474
+ | "insufficient-distinct-days";
475
+
476
+ export interface PromotionVerdict {
477
+ eligible: boolean;
478
+ /** The first blocking reason, or "eligible". */
479
+ reason: PromotionReason;
480
+ /** Every blocking reason — promotion needs ALL conditions, so all are reported. */
481
+ blockedBy: PromotionReason[];
482
+ base: number;
483
+ reinforcedDays: number;
484
+ requiredDays: number;
485
+ threshold: number;
486
+ }
487
+
488
+ /**
489
+ * Promotion eligibility (§5.3): `base >= THETA_ID` AND reinforcement on
490
+ * >= N = 3 DISTINCT lived days. Evaluated at consolidation by `sleep/`.
491
+ * Note it is `base`, not decayed strength: promotion is about what the memory
492
+ * earned, not about how recently it was touched.
493
+ */
494
+ export function promotionEligibility(m: MemoryPhysics): PromotionVerdict {
495
+ const b = base(m);
496
+ const days = reinforcedDays(m);
497
+ const blockedBy: PromotionReason[] = [];
498
+ if (m.promotedIdentity) blockedBy.push("already-identity");
499
+ if (b < TUNABLES.THETA_ID) blockedBy.push("base-below-identity-threshold");
500
+ if (days < TUNABLES.N_PROMOTION_DAYS) blockedBy.push("insufficient-distinct-days");
501
+ return {
502
+ eligible: blockedBy.length === 0,
503
+ reason: blockedBy[0] ?? "eligible",
504
+ blockedBy,
505
+ base: b,
506
+ reinforcedDays: days,
507
+ requiredDays: TUNABLES.N_PROMOTION_DAYS,
508
+ threshold: TUNABLES.THETA_ID,
509
+ };
510
+ }
511
+
512
+ export type ConsolidationReason =
513
+ | "eligible"
514
+ | "already-consolidated"
515
+ | "archived"
516
+ | "born-today"
517
+ | "below-semantic-floor";
518
+
519
+ export interface ConsolidationVerdict {
520
+ eligible: boolean;
521
+ /** The first blocking reason, or "eligible". */
522
+ reason: ConsolidationReason;
523
+ /** Every blocking reason — consolidation needs ALL conditions (scar §2.4). */
524
+ blockedBy: ConsolidationReason[];
525
+ band: Band;
526
+ birthDay: number;
527
+ }
528
+
529
+ /**
530
+ * Consolidation eligibility (SEAMS item M), mirroring `promotionEligibility`:
531
+ * a memory that has survived at least one lived day past its birth and now sits
532
+ * at or above the semantic floor is eligible. `consolidated` is worth
533
+ * `+CONS_BONUS` to `base` for the rest of the memory's life (§5.2), so deciding
534
+ * WHEN it turns on is arithmetic and belongs here — `sleep/` executes a crossing
535
+ * it does not define, exactly as it does for promotion.
536
+ *
537
+ * **There is deliberately NO reinforcement requirement.** "A formative one-shot
538
+ * consolidates without repetition" is a property `base` protects with a `max`,
539
+ * and a repetition gate here would quietly repeal it.
540
+ *
541
+ * Nothing consolidates on the day it was encoded, whatever it claims for itself:
542
+ * sleep consolidates yesterday's experience. A memory already in the identity
543
+ * band is past the semantic floor by definition and is not blocked by it.
544
+ */
545
+ export function consolidationEligibility(
546
+ m: MemoryPhysics,
547
+ d: number,
548
+ opts: { archived?: boolean } = {},
549
+ shape: DecayShape = TUNABLES.DECAY_SHAPE,
550
+ ): ConsolidationVerdict {
551
+ const b = band(m, d, shape);
552
+ const blockedBy: ConsolidationReason[] = [];
553
+ if (opts.archived === true) blockedBy.push("archived");
554
+ if (m.consolidated) blockedBy.push("already-consolidated");
555
+ if (d <= m.birthDay) blockedBy.push("born-today");
556
+ if (b !== "semantic" && !m.promotedIdentity) blockedBy.push("below-semantic-floor");
557
+ return {
558
+ eligible: blockedBy.length === 0,
559
+ reason: blockedBy[0] ?? "eligible",
560
+ blockedBy,
561
+ band: b,
562
+ birthDay: m.birthDay,
563
+ };
564
+ }
565
+
566
+ export interface PromotionCrossing {
567
+ readonly event: "band.promoted";
568
+ readonly day: number;
569
+ readonly kind: Kind;
570
+ readonly base: number;
571
+ readonly reinforcedDays: number;
572
+ }
573
+
574
+ export interface PromotionOutcome {
575
+ promoted: boolean;
576
+ verdict: PromotionVerdict;
577
+ /** The explicit, counted crossing record — never an emergent side effect
578
+ * (scar §2.4). Null when the memory was not eligible. */
579
+ crossing: PromotionCrossing | null;
580
+ next: Pick<MemoryPhysics, "promotedIdentity"> | null;
581
+ }
582
+
583
+ export function promote(m: MemoryPhysics, d: number): PromotionOutcome {
584
+ const verdict = promotionEligibility(m);
585
+ if (!verdict.eligible) return { promoted: false, verdict, crossing: null, next: null };
586
+ return {
587
+ promoted: true,
588
+ verdict,
589
+ crossing: {
590
+ event: "band.promoted",
591
+ day: d,
592
+ kind: m.kind,
593
+ base: verdict.base,
594
+ reinforcedDays: verdict.reinforcedDays,
595
+ },
596
+ next: { promotedIdentity: true },
597
+ };
598
+ }
599
+
600
+ // ---------------------------------------------------------------------------
601
+ // Guarantee 12 — the symmetry counter (scar §2.10)
602
+ // ---------------------------------------------------------------------------
603
+
604
+ const BAND_RANK: Record<Band, number> = { episodic: 0, semantic: 1, identity: 2 };
605
+
606
+ export function bandMove(from: Band, to: Band): "up" | "down" | "none" {
607
+ const delta = BAND_RANK[to] - BAND_RANK[from];
608
+ return delta > 0 ? "up" : delta < 0 ? "down" : "none";
609
+ }
610
+
611
+ export type SymmetryReason =
612
+ | "within-expectation"
613
+ | "ratchet-suspected"
614
+ | "reverse-ratchet-suspected"
615
+ | "never-asked";
616
+
617
+ export interface SymmetryCheck {
618
+ ok: boolean;
619
+ reason: SymmetryReason;
620
+ kind: Kind;
621
+ up: number;
622
+ down: number;
623
+ /** up : down. Infinity when nothing ever moved down — v1's exact shape. */
624
+ ratio: number;
625
+ expectedMax: number;
626
+ }
627
+
628
+ /**
629
+ * Up-moves and down-moves, counted separately, PER KIND, against a stated
630
+ * expected ratio (guarantee 12). This is the tripwire v1 lacked: it ran
631
+ * 279 up-moves against zero down-moves for three days and nothing fired.
632
+ * Below the minimum sample the answer is "never-asked", not "healthy".
633
+ */
634
+ export function symmetryCheck(kind: Kind, counts: { up: number; down: number }): SymmetryCheck {
635
+ const { up, down } = counts;
636
+ const ratio = down === 0 ? (up === 0 ? 0 : Infinity) : up / down;
637
+ const expectedMax = TUNABLES.SYMMETRY_MAX_UP_DOWN_RATIO;
638
+ const shape = { kind, up, down, ratio, expectedMax };
639
+ if (up + down < TUNABLES.SYMMETRY_MIN_SAMPLE) {
640
+ return { ok: true, reason: "never-asked", ...shape };
641
+ }
642
+ if (ratio > expectedMax) return { ok: false, reason: "ratchet-suspected", ...shape };
643
+ if (up > 0 && down / up > expectedMax) {
644
+ return { ok: false, reason: "reverse-ratchet-suspected", ...shape };
645
+ }
646
+ return { ok: true, reason: "within-expectation", ...shape };
647
+ }
648
+
649
+ // ---------------------------------------------------------------------------
650
+ // §5.5 Reinforcement
651
+ // ---------------------------------------------------------------------------
652
+
653
+ export type UseTier = "referenced" | "surfaced" | "footnoted";
654
+
655
+ export const USE_TIER_WEIGHT: Record<UseTier, number> = {
656
+ referenced: TUNABLES.W_REFERENCED,
657
+ surfaced: TUNABLES.W_SURFACED,
658
+ footnoted: TUNABLES.W_FOOTNOTED,
659
+ };
660
+
661
+ export type CreditReason =
662
+ | "credited"
663
+ | "ignorable-tier"
664
+ | "birth-day"
665
+ | "already-credited-today"
666
+ | "stale-day";
667
+
668
+ export interface CreditOutcome {
669
+ credited: boolean;
670
+ reason: CreditReason;
671
+ w: number;
672
+ /** State to persist. Identical to the input state when nothing was credited. */
673
+ next: Pick<MemoryPhysics, "uses" | "lastUsedDay" | "reinforcedDays">;
674
+ }
675
+
676
+ /**
677
+ * Graded retrospective reinforcement (§5.5). At most ONE credited occasion per
678
+ * memory per lived day, never on its birth day [v1 §10 G9], and the ignorable
679
+ * (footnoted) tier never trains. Credit is resolved at the boundary, when the
680
+ * reply is known — this function is the arithmetic, not the trigger.
681
+ *
682
+ * A credited use also resets the forgetting curve: `lastUsedDay := d` raises
683
+ * S through `uses`, so the next interval is longer — the testing effect.
684
+ */
685
+ export function creditUse(m: MemoryPhysics, d: number, tier: UseTier): CreditOutcome {
686
+ const w = USE_TIER_WEIGHT[tier];
687
+ const days = reinforcedDays(m);
688
+ const unchanged = { uses: m.uses, lastUsedDay: m.lastUsedDay, reinforcedDays: days };
689
+ if (w <= 0) return { credited: false, reason: "ignorable-tier", w, next: unchanged };
690
+ if (d === m.birthDay) return { credited: false, reason: "birth-day", w, next: unchanged };
691
+ if (d < m.lastUsedDay) return { credited: false, reason: "stale-day", w, next: unchanged };
692
+ if (d === m.lastUsedDay) return { credited: false, reason: "already-credited-today", w, next: unchanged };
693
+ return {
694
+ credited: true,
695
+ reason: "credited",
696
+ w,
697
+ next: { uses: m.uses + w, lastUsedDay: d, reinforcedDays: days + 1 },
698
+ };
699
+ }
700
+
701
+ // ---------------------------------------------------------------------------
702
+ // §5.6 Revision — declared, pressure-accumulated, no second object
703
+ // ---------------------------------------------------------------------------
704
+
705
+ /** The challenging memory, as physics sees it: its own state plus its declaration. */
706
+ export interface Challenge {
707
+ id: string;
708
+ /** The `updates: <memory-id>` field, DECLARED BY THE WRITER. There is no
709
+ * inferred-revision path (guarantee 7). */
710
+ declaredUpdates: string | null;
711
+ physics: MemoryPhysics;
712
+ }
713
+
714
+ export type ChallengeReason =
715
+ | "revised"
716
+ | "below-bar"
717
+ | "no-declared-target"
718
+ | "target-mismatch"
719
+ | "already-challenged-today"
720
+ | "stale-day";
721
+
722
+ export interface ChallengeLogEntry {
723
+ readonly event: "revision.pressure";
724
+ readonly day: number;
725
+ readonly challengerId: string;
726
+ readonly force: number;
727
+ readonly pressureAfter: number;
728
+ readonly bar: number;
729
+ }
730
+
731
+ export interface ChallengeOutcome {
732
+ verdict: "revise" | "hold";
733
+ credited: boolean;
734
+ reason: ChallengeReason;
735
+ /** F(new -> old) for this challenge; 0 when nothing was credited. */
736
+ force: number;
737
+ /** P(old) decayed to day d, before this challenge. */
738
+ pressureBefore: number;
739
+ pressureAfter: number;
740
+ /** iota(kind) x strength(old, d) — what the pressure has to beat. */
741
+ bar: number;
742
+ next: Pick<MemoryPhysics, "pressure" | "lastChallengedDay">;
743
+ /** Every increment is logged — the pressure history IS the evidence record. */
744
+ log: ChallengeLogEntry | null;
745
+ }
746
+
747
+ /**
748
+ * F(new -> old) = strength(new, d) x sal(new) — author-assessed evidence weight.
749
+ *
750
+ * NOVELTY PLAYS NO ROLE HERE by design (review condition (c)): it was doing
751
+ * double duty as detector and magnitude, and because novelty is computed against
752
+ * context that CONTAINS the target when the author was informed, it rewarded
753
+ * blind challenges over informed ones. The declaration carries intent; sal
754
+ * carries magnitude.
755
+ */
756
+ export function challengeForce(
757
+ challenger: MemoryPhysics,
758
+ d: number,
759
+ shape: DecayShape = TUNABLES.DECAY_SHAPE,
760
+ ): number {
761
+ return strength(challenger, d, shape) * sal(challenger.salience);
762
+ }
763
+
764
+ /**
765
+ * P(old) decayed to day d. Same curve family as memory, keyed to the last
766
+ * challenge day, so an abandoned challenge FADES instead of lying in ambush.
767
+ * Pressure decays even against an identity-band target: D = 1 exempts the
768
+ * memory, never the pressure standing against it.
769
+ */
770
+ export function pressureAt(
771
+ m: Pick<MemoryPhysics, "pressure" | "lastChallengedDay">,
772
+ d: number,
773
+ shape: DecayShape = TUNABLES.DECAY_SHAPE,
774
+ ): number {
775
+ if (m.pressure <= 0 || m.lastChallengedDay === null) return 0;
776
+ return m.pressure * decayCurve(d - m.lastChallengedDay, TUNABLES.S_PRESSURE, shape);
777
+ }
778
+
779
+ /** iota(kind) x strength(old, d) — the revision bar. */
780
+ export function revisionBar(
781
+ target: MemoryPhysics,
782
+ d: number,
783
+ shape: DecayShape = TUNABLES.DECAY_SHAPE,
784
+ ): number {
785
+ return kindPhysics(target.kind).iota * strength(target, d, shape);
786
+ }
787
+
788
+ /**
789
+ * One declared challenge landing on one target on lived day d (§5.6, rewritten
790
+ * 2026-08-25). Order of operations: decay P to d, add F, compare.
791
+ *
792
+ * P(old) += F(new -> old)
793
+ * REVISE iff P(old) > iota(kind(old)) x strength(old, d)
794
+ *
795
+ * ONE credited challenge per target per lived day — no session can spam a belief
796
+ * into flipping. The pressure is a FIELD ON THE TARGET ROW; there is no second
797
+ * object, so scar §2.2's dangling-ledger family cannot recur.
798
+ */
799
+ export function applyChallenge(
800
+ targetId: string,
801
+ target: MemoryPhysics,
802
+ challenge: Challenge,
803
+ d: number,
804
+ shape: DecayShape = TUNABLES.DECAY_SHAPE,
805
+ ): ChallengeOutcome {
806
+ const bar = revisionBar(target, d, shape);
807
+ const pressureBefore = pressureAt(target, d, shape);
808
+ const unchanged = { pressure: target.pressure, lastChallengedDay: target.lastChallengedDay };
809
+ const refuse = (reason: ChallengeReason): ChallengeOutcome => ({
810
+ verdict: "hold",
811
+ credited: false,
812
+ reason,
813
+ force: 0,
814
+ pressureBefore,
815
+ pressureAfter: pressureBefore,
816
+ bar,
817
+ next: unchanged,
818
+ log: null,
819
+ });
820
+
821
+ if (challenge.declaredUpdates === null) return refuse("no-declared-target");
822
+ if (challenge.declaredUpdates !== targetId) return refuse("target-mismatch");
823
+ if (target.lastChallengedDay !== null && d === target.lastChallengedDay) {
824
+ return refuse("already-challenged-today");
825
+ }
826
+ if (target.lastChallengedDay !== null && d < target.lastChallengedDay) return refuse("stale-day");
827
+
828
+ const rawForce = challengeForce(challenge.physics, d, shape);
829
+ const slow = kindPhysics(target.kind).iota >= TUNABLES.SLOW_KIND_IOTA;
830
+ const force = slow ? Math.min(rawForce, TUNABLES.F_DAY_CAP_SLOW) : rawForce;
831
+ const pressureAfter = pressureBefore + force;
832
+ const revise = pressureAfter > bar;
833
+ return {
834
+ verdict: revise ? "revise" : "hold",
835
+ credited: true,
836
+ reason: revise ? "revised" : "below-bar",
837
+ force,
838
+ pressureBefore,
839
+ pressureAfter,
840
+ bar,
841
+ next: { pressure: pressureAfter, lastChallengedDay: d },
842
+ log: {
843
+ event: "revision.pressure",
844
+ day: d,
845
+ challengerId: challenge.id,
846
+ force,
847
+ pressureAfter,
848
+ bar,
849
+ },
850
+ };
851
+ }
852
+
853
+ export interface SupersedeRecord {
854
+ readonly event: "memory.superseded";
855
+ readonly predecessorId: string;
856
+ readonly successorId: string;
857
+ readonly day: number;
858
+ /** Superseded versions stay RESOLVABLE until this lived day (guarantee 9).
859
+ * Nothing in physics deletes one. */
860
+ readonly resolvableUntilDay: number;
861
+ }
862
+
863
+ export function supersedeRecord(
864
+ predecessorId: string,
865
+ successorId: string,
866
+ d: number,
867
+ ): SupersedeRecord {
868
+ return {
869
+ event: "memory.superseded",
870
+ predecessorId,
871
+ successorId,
872
+ day: d,
873
+ resolvableUntilDay: d + TUNABLES.H_SUPERSEDED_DAYS,
874
+ };
875
+ }
876
+
877
+ export function supersededResolvable(supersededOnDay: number, d: number): boolean {
878
+ return d - supersededOnDay <= TUNABLES.H_SUPERSEDED_DAYS;
879
+ }
880
+
881
+ /**
882
+ * The successor's revision-relevant seed state on REVISE. Pressure resets to 0,
883
+ * and identity membership is INHERITED (§5.3(a)) unless the caller declares the
884
+ * revision a demotion — the only way out of the identity band.
885
+ */
886
+ export function successorSeed(
887
+ target: MemoryPhysics,
888
+ opts: { inheritIdentity?: boolean } = {},
889
+ ): Pick<MemoryPhysics, "promotedIdentity" | "pressure" | "lastChallengedDay"> {
890
+ const inherit = opts.inheritIdentity ?? true;
891
+ return {
892
+ promotedIdentity: inherit ? target.promotedIdentity : false,
893
+ pressure: 0,
894
+ lastChallengedDay: null,
895
+ };
896
+ }
897
+
898
+ // ---------------------------------------------------------------------------
899
+ // §5.7 Dedup
900
+ // ---------------------------------------------------------------------------
901
+
902
+ export type DedupReason =
903
+ | "declared-revision-never-merged"
904
+ | "revision-successor-never-merged"
905
+ | "identical-content-hash"
906
+ | "cosine-at-or-above-tau"
907
+ | "below-tau"
908
+ | "no-similarity-supplied";
909
+
910
+ export interface DedupInput {
911
+ /** The id of the ORIGINAL this candidate would merge into. */
912
+ originalId: string;
913
+ /** The candidate's `updates:` declaration, if it made one. */
914
+ declaredUpdates: string | null;
915
+ /**
916
+ * True when merging this pair would archive a revision's SUCCESSOR — either
917
+ * because the two rows stand in a direct successor relation (one was minted by
918
+ * revising, carrying the other's words), or because the candidate is a
919
+ * successor and the pair is same-hash. The second case is sound for the same
920
+ * reason as the first: a successor's body IS its challenger's body by
921
+ * construction, so any same-hash group it belongs to is that challenger plus
922
+ * ordinary twins of the same sentence, and none of those is what the revision
923
+ * produced. Lineage is a store fact, so the caller reads it and supplies it
924
+ * here — the same division of labour as `sameContentHash`.
925
+ */
926
+ revisionSuccessorPair?: boolean;
927
+ /** Content hashes, supplied by the caller. */
928
+ sameContentHash?: boolean;
929
+ /** cos( v(new), v(orig) ), supplied by the caller. Null when no vector exists. */
930
+ cosine?: number | null;
931
+ }
932
+
933
+ export interface DedupVerdict {
934
+ verdict: "merge" | "leave-alone";
935
+ reason: DedupReason;
936
+ /** The whole effect of a merge: uses(orig) += 1. Never a rewrite, never a blend. */
937
+ effect: { usesDelta: number } | null;
938
+ }
939
+
940
+ /**
941
+ * Dedup (§5.7). Ambiguous near-duplicates are LEFT ALONE (owner decision) —
942
+ * accepted rent, paid for zero substrate confabulation [v1 §4.2 G9].
943
+ *
944
+ * A memory that declares `updates:` is NEVER deduplicated into its target
945
+ * (guarantee 8): otherwise a topically-close refutation merges into the belief
946
+ * it refutes and REINFORCES it — scar §2.10's one-way ratchet, rebuilt by
947
+ * accident. The declaration is checked FIRST, before hash and before cosine.
948
+ *
949
+ * The declaration's other half, and the same refusal (guarantee 8b): **a
950
+ * revision's SUCCESSOR and the challenger it was made from are never merged
951
+ * into each other, in either direction**. A revision mints the successor with
952
+ * the challenger's own words — that is what winning an argument means here
953
+ * (§5.6) — so the two bodies are identical BY CONSTRUCTION and every dedup pass
954
+ * after the crossing finds them. Checked before hash and cosine, because the
955
+ * hash is precisely what is guaranteed to match.
956
+ */
957
+ export function dedupVerdict(input: DedupInput): DedupVerdict {
958
+ if (input.declaredUpdates !== null && input.declaredUpdates === input.originalId) {
959
+ return { verdict: "leave-alone", reason: "declared-revision-never-merged", effect: null };
960
+ }
961
+ if (input.revisionSuccessorPair === true) {
962
+ return { verdict: "leave-alone", reason: "revision-successor-never-merged", effect: null };
963
+ }
964
+ if (input.sameContentHash === true) {
965
+ return { verdict: "merge", reason: "identical-content-hash", effect: { usesDelta: 1 } };
966
+ }
967
+ const cos = input.cosine ?? null;
968
+ if (cos === null) {
969
+ return { verdict: "leave-alone", reason: "no-similarity-supplied", effect: null };
970
+ }
971
+ if (cos >= TUNABLES.TAU_DUP) {
972
+ return { verdict: "merge", reason: "cosine-at-or-above-tau", effect: { usesDelta: 1 } };
973
+ }
974
+ return { verdict: "leave-alone", reason: "below-tau", effect: null };
975
+ }
976
+
977
+ // ---------------------------------------------------------------------------
978
+ // §5.8 Forgetting
979
+ // ---------------------------------------------------------------------------
980
+
981
+ export type PruneReason =
982
+ | "prunable"
983
+ | "above-floor"
984
+ | "dwell-too-short"
985
+ | "band-not-episodic"
986
+ | "protected"
987
+ | "in-live-revision-chain";
988
+
989
+ /** Counts, kind, dates. NEVER a body and NEVER a content hash (scar §2.20). */
990
+ export interface PruneRecord {
991
+ readonly event: "memory.pruned";
992
+ readonly day: number;
993
+ readonly kind: Kind;
994
+ readonly band: Band;
995
+ readonly birthDay: number;
996
+ readonly lastUsedDay: number;
997
+ readonly uses: number;
998
+ readonly strength: number;
999
+ }
1000
+
1001
+ export interface PruneVerdict {
1002
+ prune: boolean;
1003
+ reason: PruneReason;
1004
+ /** Every failing gate, not just the first — all five are named. */
1005
+ blockedBy: PruneReason[];
1006
+ strength: number;
1007
+ band: Band;
1008
+ dwellDays: number;
1009
+ record: PruneRecord | null;
1010
+ }
1011
+
1012
+ /**
1013
+ * The ONLY physics-driven removal (§5.8), gated on all five conditions. No
1014
+ * model, on any path, holds delete power — this returns a verdict and a record;
1015
+ * it deletes nothing itself. Everything else merely fades: a low-strength memory
1016
+ * is still present and still retrievable by a strong enough cue.
1017
+ */
1018
+ export function pruneVerdict(
1019
+ m: MemoryPhysics,
1020
+ d: number,
1021
+ ctx: { inLiveRevisionChain: boolean },
1022
+ shape: DecayShape = TUNABLES.DECAY_SHAPE,
1023
+ ): PruneVerdict {
1024
+ const s = strength(m, d, shape);
1025
+ const b = band(m, d, shape);
1026
+ const dwellDays = d - m.lastUsedDay;
1027
+ const blockedBy: PruneReason[] = [];
1028
+ if (s >= TUNABLES.PHI_PRUNE) blockedBy.push("above-floor");
1029
+ if (dwellDays < TUNABLES.D_FLOOR_DAYS) blockedBy.push("dwell-too-short");
1030
+ if (b !== "episodic") blockedBy.push("band-not-episodic");
1031
+ if (m.protected) blockedBy.push("protected");
1032
+ if (ctx.inLiveRevisionChain) blockedBy.push("in-live-revision-chain");
1033
+ const prune = blockedBy.length === 0;
1034
+ return {
1035
+ prune,
1036
+ reason: blockedBy[0] ?? "prunable",
1037
+ blockedBy,
1038
+ strength: s,
1039
+ band: b,
1040
+ dwellDays,
1041
+ record: prune
1042
+ ? {
1043
+ event: "memory.pruned",
1044
+ day: d,
1045
+ kind: m.kind,
1046
+ band: b,
1047
+ birthDay: m.birthDay,
1048
+ lastUsedDay: m.lastUsedDay,
1049
+ uses: m.uses,
1050
+ strength: s,
1051
+ }
1052
+ : null,
1053
+ };
1054
+ }