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,570 @@
1
+ /**
2
+ * `associate/` — Hebbian linking and spreading activation.
3
+ *
4
+ * Memories credited together in one turn become linked; recall spreads activation
5
+ * across those links. The module's spine:
6
+ *
7
+ * `tunables.ts` every knob, in one visible place (CAL where uncalibrated)
8
+ * `edges.ts` the edge arithmetic — increment, cap, lived-day decay, homeostasis
9
+ * `buffer.ts` the DECLARED durability exemption: per-turn deltas in memory
10
+ * `spread.ts` a pure traversal `recall/` can consume as a fourth channel
11
+ * `index.ts` the binding: observer stance, the flush ordering, telemetry
12
+ *
13
+ * Three properties are structural here and worth stating at the top:
14
+ *
15
+ * **OBSERVERS TRAIN NOTHING, checked before any other work** (contract G7, scar
16
+ * E7). `coactivate()` under an observer stance does not evaluate eligibility, does
17
+ * not compute a delta, and does not touch the buffer — an instrument leaves the
18
+ * graph exactly as it found it. The stand-down is EVENTED, because a stood-down
19
+ * instrument must be distinguishable from a broken hook.
20
+ *
21
+ * **AT MOST ONCE, and the direction of the failure is CHOSEN** (contract G4).
22
+ * `flush()` drains the buffer FIRST and publishes SECOND, and it never restores a
23
+ * drained batch. A crash between the two loses one flush's deltas; there is no
24
+ * ordering in which the same delta lands twice. Restore-on-failure is precisely
25
+ * the trap — if the write landed and the throw came afterwards, a restored buffer
26
+ * double-applies on retry, which is the inversion v1 shipped. Bounded loss is
27
+ * inside tolerance; doubling is what the contract rules out.
28
+ *
29
+ * **A FAILED PUBLISH EMITS NO SUCCESS EVENT** (contract G6, scar §2.4). The
30
+ * `associate.flush.done` event is emitted after `linkMany` returns, never before,
31
+ * and the failure arm emits `associate.flush.failed` with the dropped count.
32
+ */
33
+ import type { EdgeInput, EdgeRow, MemoryRow } from "../store/index.js";
34
+ import type { UseTier } from "../physics/index.js";
35
+ import { DeltaBuffer } from "./buffer.js";
36
+ import { conducts, edgeWeightAt, planFlush } from "./edges.js";
37
+ import type { EdgeState, Eviction, PairDelta } from "./edges.js";
38
+ import { spread } from "./spread.js";
39
+ import type { Seed, SpreadResult } from "./spread.js";
40
+ import { pairCredit, tierFactor, withTunables } from "./tunables.js";
41
+ import type { AssociateTunables } from "./tunables.js";
42
+
43
+ export * from "./buffer.js";
44
+ export * from "./edges.js";
45
+ export * from "./pending.js";
46
+ export * from "./spread.js";
47
+ export * from "./tunables.js";
48
+
49
+ /**
50
+ * The narrow store seam this module needs — six members, all of which `Store`
51
+ * already has. Narrow on purpose: it names the whole surface associate can reach
52
+ * (there is no delete on it, and there could not be), and it makes the crash
53
+ * points reachable in a test without a real database standing in for one.
54
+ */
55
+ export interface AssociateStore {
56
+ /** The ONE observer predicate, already derived by the store. Never re-derived
57
+ * here — a second definition is the leak `docs/observer-mode.md` G7 names. */
58
+ readonly observer: boolean;
59
+ livedDay(): number;
60
+ row(id: string): MemoryRow | undefined;
61
+ deniedIds(): string[];
62
+ edgesFrom(src: string): EdgeRow[];
63
+ linkMany(edges: readonly EdgeInput[]): void;
64
+ }
65
+
66
+ /** Telemetry: ids, counts, weights, reasons. NEVER body text or turn text. */
67
+ export interface AssociateEvent {
68
+ at: number;
69
+ name: string;
70
+ ref?: string;
71
+ data?: Record<string, string | number | boolean | null>;
72
+ }
73
+
74
+ export interface AssociateOptions {
75
+ store: AssociateStore;
76
+ /** Overrides on the CAL table. Every one is a calibration claim (scar §2.8). */
77
+ tunables?: Partial<AssociateTunables>;
78
+ onEvent?: (e: AssociateEvent) => void;
79
+ }
80
+
81
+ /** One memory that was credited this turn, with the tier the boundary resolved. */
82
+ export interface Credited {
83
+ readonly id: string;
84
+ readonly tier: UseTier;
85
+ }
86
+
87
+ export type MemberReason =
88
+ | "eligible"
89
+ | "ignorable-tier"
90
+ | "unknown-id"
91
+ | "removed"
92
+ | "archived"
93
+ | "superseded"
94
+ | "frozen-protected";
95
+
96
+ export interface MemberVerdict {
97
+ readonly id: string;
98
+ readonly reason: MemberReason;
99
+ }
100
+
101
+ export type CoactivateReason = "buffered" | "observer" | "too-few-members";
102
+
103
+ export interface CoactivateResult {
104
+ readonly reason: CoactivateReason;
105
+ /** Pairs whose delta was added to the buffer. */
106
+ readonly pairs: number;
107
+ /** Per-member verdicts — every exclusion names WHY (scar §2.4). */
108
+ readonly members: readonly MemberVerdict[];
109
+ readonly buffered: number;
110
+ }
111
+
112
+ export type FlushReason = "flushed" | "observer" | "nothing-buffered" | "busy" | "failed";
113
+
114
+ export interface FlushReport {
115
+ readonly reason: FlushReason;
116
+ readonly day: number;
117
+ /** Pairs drained from the buffer. */
118
+ readonly pairs: number;
119
+ /** Absolute edge rows written. */
120
+ readonly rows: number;
121
+ readonly evictions: readonly Eviction[];
122
+ readonly renormalized: number;
123
+ readonly nodesTouched: number;
124
+ /** Pairs dropped because an endpoint stopped conducting between the turn and
125
+ * the boundary — archived, superseded, or taken dark. */
126
+ readonly blocked: number;
127
+ /** Deltas that were drained and did NOT land. Non-zero only in the failure
128
+ * arm, where it is the chosen direction, counted rather than hidden. */
129
+ readonly dropped: number;
130
+ readonly error?: string;
131
+ /** The failure's stable CODE — the store's own where it has one, the error's
132
+ * name otherwise. `error` above is the message, which is for a human reading
133
+ * a report; a durable row takes this instead (store §5 G10). */
134
+ readonly code?: string;
135
+ }
136
+
137
+ /** A code for telemetry, never the message: the store's `code` where there is
138
+ * one, the error's name otherwise (store §5 G10 — messages can quote prose). */
139
+ function codeOf(err: unknown): string {
140
+ if (err !== null && typeof err === "object") {
141
+ const code = (err as { code?: unknown }).code;
142
+ if (typeof code === "string") return code;
143
+ const name = (err as { name?: unknown }).name;
144
+ if (typeof name === "string") return name;
145
+ }
146
+ return "UNKNOWN";
147
+ }
148
+
149
+ const EVENT_RING = 200;
150
+
151
+ export class Associate {
152
+ readonly tunables: AssociateTunables;
153
+ private readonly store: AssociateStore;
154
+ private readonly buffer = new DeltaBuffer();
155
+ private readonly onEvent: ((e: AssociateEvent) => void) | undefined;
156
+ private readonly ring: AssociateEvent[] = [];
157
+ private flushing = false;
158
+
159
+ constructor(opts: AssociateOptions) {
160
+ this.store = opts.store;
161
+ this.tunables = withTunables(opts.tunables);
162
+ this.onEvent = opts.onEvent;
163
+ }
164
+
165
+ /** The stance, read from the store and never re-derived (SEAMS queued item 4). */
166
+ get observer(): boolean {
167
+ return this.store.observer;
168
+ }
169
+
170
+ get pending(): number {
171
+ return this.buffer.size;
172
+ }
173
+
174
+ // ── the Hebbian update ─────────────────────────────────────────────────────
175
+
176
+ /**
177
+ * "Cells that fire together wire together" — the memories a single turn
178
+ * credited become pairwise stronger.
179
+ *
180
+ * Deviations, named (contract §2): credit is retrospective and GRADED, resolved
181
+ * at the boundary with the reply known, and **zero for the merely footnoted** —
182
+ * where in humans every retrieval trains. Nothing lands durably here: this
183
+ * accumulates into the declared buffer, and `flush()` publishes it.
184
+ */
185
+ coactivate(members: readonly Credited[]): CoactivateResult {
186
+ // Guarantee 7: checked FIRST, before eligibility, before arithmetic, before
187
+ // the buffer is even consulted.
188
+ if (this.observer) {
189
+ this.emit("associate.observer.skip", undefined, { site: "coactivate", members: members.length });
190
+ return { reason: "observer", pairs: 0, members: [], buffered: this.buffer.size };
191
+ }
192
+
193
+ const verdicts: MemberVerdict[] = [];
194
+ const eligible: Credited[] = [];
195
+ const seen = new Set<string>();
196
+ const denied = new Set(this.store.deniedIds());
197
+ for (const m of members) {
198
+ if (seen.has(m.id)) continue;
199
+ seen.add(m.id);
200
+ const reason = this.memberReason(m, denied);
201
+ verdicts.push({ id: m.id, reason });
202
+ if (reason === "eligible") eligible.push(m);
203
+ }
204
+
205
+ if (eligible.length < 2) {
206
+ return {
207
+ reason: "too-few-members",
208
+ pairs: 0,
209
+ members: verdicts,
210
+ buffered: this.buffer.size,
211
+ };
212
+ }
213
+
214
+ let pairs = 0;
215
+ for (let i = 0; i < eligible.length; i++) {
216
+ for (let j = i + 1; j < eligible.length; j++) {
217
+ const a = eligible[i] as Credited;
218
+ const b = eligible[j] as Credited;
219
+ const delta = pairCredit(a.tier, b.tier, this.tunables);
220
+ if (delta <= 0) continue;
221
+ this.buffer.add(a.id, b.id, delta);
222
+ pairs += 1;
223
+ }
224
+ }
225
+ this.emit("associate.coactivate", undefined, {
226
+ members: members.length,
227
+ eligible: eligible.length,
228
+ pairs,
229
+ buffered: this.buffer.size,
230
+ });
231
+ return { reason: "buffered", pairs, members: verdicts, buffered: this.buffer.size };
232
+ }
233
+
234
+ /**
235
+ * Take the buffer. **Public precisely so the crash point is reachable**: a
236
+ * caller that drains and does not publish has DROPPED those deltas, which is
237
+ * the chosen failure direction stated out loud rather than discovered in
238
+ * production. `flush()` is drain + publish.
239
+ *
240
+ * One other caller drains: the credit pass, which writes what it took to the
241
+ * pending file (`pending.ts`) because the process that can publish it is a
242
+ * different one. Draining and PERSISTING is not dropping — but a drain whose
243
+ * append then fails has dropped them, which is why that caller counts the
244
+ * append's answer (`counterpart.ts#publishCoactivation`).
245
+ */
246
+ drain(): PairDelta[] {
247
+ return this.buffer.drain();
248
+ }
249
+
250
+ /**
251
+ * Take deltas another process buffered — the worker's half of the pending
252
+ * file. They go into this process's buffer, so `flush()` publishes them
253
+ * through exactly the same plan, eligibility re-check and eviction path as
254
+ * deltas this process earned itself.
255
+ *
256
+ * An observer absorbs nothing, checked first, like `coactivate` (G7).
257
+ */
258
+ absorb(deltas: readonly PairDelta[]): number {
259
+ if (this.observer) {
260
+ this.emit("associate.observer.skip", undefined, { site: "absorb", deltas: deltas.length });
261
+ return 0;
262
+ }
263
+ let added = 0;
264
+ for (const d of deltas) {
265
+ // The buffer ignores these two, so counting them as absorbed would report
266
+ // work that no flush can ever do.
267
+ if (d.delta <= 0 || d.a === d.b) continue;
268
+ this.buffer.add(d.a, d.b, d.delta);
269
+ added += 1;
270
+ }
271
+ return added;
272
+ }
273
+
274
+ /** What is buffered right now — copies, for telemetry and tests. */
275
+ pendingDeltas(): PairDelta[] {
276
+ return this.buffer.pending();
277
+ }
278
+
279
+ /**
280
+ * Publish the buffered deltas. The ordering IS the guarantee — see the header.
281
+ *
282
+ * Contention (contract G5) is checked BEFORE the drain, so a busy flush leaves
283
+ * the buffer untouched and stays buffered rather than half-applying. Only
284
+ * in-process contention is enforced here; cross-process exclusion needs a lock
285
+ * the store does not offer (INTERFACE-GAPS.md §3).
286
+ */
287
+ flush(day?: number): FlushReport {
288
+ const d = day ?? this.store.livedDay();
289
+ const empty: FlushReport = {
290
+ reason: "nothing-buffered",
291
+ day: d,
292
+ pairs: 0,
293
+ rows: 0,
294
+ evictions: [],
295
+ renormalized: 0,
296
+ nodesTouched: 0,
297
+ blocked: 0,
298
+ dropped: 0,
299
+ };
300
+
301
+ if (this.observer) {
302
+ this.emit("associate.observer.skip", undefined, { site: "flush", buffered: this.buffer.size });
303
+ return { ...empty, reason: "observer" };
304
+ }
305
+ if (this.flushing) {
306
+ this.emit("associate.flush.busy", undefined, { buffered: this.buffer.size });
307
+ return { ...empty, reason: "busy", pairs: this.buffer.size };
308
+ }
309
+
310
+ this.flushing = true;
311
+ try {
312
+ // ── the point of no return ────────────────────────────────────────────
313
+ const deltas = this.buffer.drain();
314
+ if (deltas.length === 0) return empty;
315
+ return this.publish(deltas, d);
316
+ } finally {
317
+ this.flushing = false;
318
+ }
319
+ }
320
+
321
+ private publish(deltas: readonly PairDelta[], day: number): FlushReport {
322
+ const conductor = this.conductor();
323
+ // Re-checked at the boundary, not only at the turn: a memory can be archived,
324
+ // superseded, taken dark, or PINNED between the co-activation and the flush,
325
+ // and an arc that went under audit mid-session must not change (G9).
326
+ const trains = (id: string) => conductor(id) && this.store.row(id)?.protected !== 1;
327
+ const live: PairDelta[] = [];
328
+ let blocked = 0;
329
+ for (const p of deltas) {
330
+ if (trains(p.a) && trains(p.b)) live.push(p);
331
+ else blocked += 1;
332
+ }
333
+
334
+ const plan = planFlush(live, day, (id) => this.edgeStates(id), this.tunables);
335
+ const rows: EdgeInput[] = plan.rows.map((r) => ({
336
+ src: r.src,
337
+ dst: r.dst,
338
+ weight: r.weight,
339
+ day: r.lastDay,
340
+ }));
341
+
342
+ if (rows.length > 0) {
343
+ try {
344
+ this.store.linkMany(rows);
345
+ } catch (err) {
346
+ // NOT restored. If `linkMany` landed and the throw came after, a restored
347
+ // buffer would double-apply on the next flush — the one outcome the
348
+ // contract rules out. And NO success event: an event claiming an update
349
+ // that never landed is worse than silence (G6).
350
+ this.emit("associate.flush.failed", undefined, {
351
+ day,
352
+ pairs: deltas.length,
353
+ rows: rows.length,
354
+ dropped: live.length,
355
+ error: codeOf(err),
356
+ });
357
+ return {
358
+ reason: "failed",
359
+ day,
360
+ pairs: deltas.length,
361
+ rows: 0,
362
+ evictions: [],
363
+ renormalized: 0,
364
+ nodesTouched: plan.nodesTouched,
365
+ blocked,
366
+ dropped: live.length,
367
+ error: err instanceof Error ? err.message : String(err),
368
+ code: codeOf(err),
369
+ };
370
+ }
371
+ }
372
+
373
+ for (const ev of plan.evictions) {
374
+ this.emit("associate.edge.evicted", ev.src, {
375
+ dst: ev.dst,
376
+ priorWeight: ev.priorWeight,
377
+ reason: ev.reason,
378
+ });
379
+ }
380
+ this.emit("associate.flush.done", undefined, {
381
+ day,
382
+ pairs: deltas.length,
383
+ rows: rows.length,
384
+ blocked,
385
+ evicted: plan.evictions.length,
386
+ renormalized: plan.renormalized.length,
387
+ });
388
+ return {
389
+ reason: "flushed",
390
+ day,
391
+ pairs: deltas.length,
392
+ rows: rows.length,
393
+ evictions: plan.evictions,
394
+ renormalized: plan.renormalized.length,
395
+ nodesTouched: plan.nodesTouched,
396
+ blocked,
397
+ dropped: 0,
398
+ };
399
+ }
400
+
401
+ // ── spreading activation ───────────────────────────────────────────────────
402
+
403
+ /**
404
+ * Seeds → activation contributions, over the live graph at a lived day.
405
+ *
406
+ * A READ, and therefore allowed under observer: observers surface but train
407
+ * nothing (§15). Nothing here buffers a delta or writes a row.
408
+ */
409
+ spreadFrom(seeds: readonly Seed[], day?: number): SpreadResult {
410
+ const d = day ?? this.store.livedDay();
411
+ return spread(
412
+ {
413
+ seeds,
414
+ day: d,
415
+ edgesFrom: (id) => this.edgeStates(id),
416
+ conducts: this.conductor(),
417
+ },
418
+ this.tunables,
419
+ );
420
+ }
421
+
422
+ /** An edge's weight as it stands at a lived day — decay applied, nothing written. */
423
+ weightAt(src: string, dst: string, day?: number): number {
424
+ const d = day ?? this.store.livedDay();
425
+ const row = this.edgeStates(src).find((e) => e.dst === dst);
426
+ return row === undefined ? 0 : edgeWeightAt(row, d, this.tunables);
427
+ }
428
+
429
+ /** Does this pair conduct at this lived day? (Weight above the floor, both
430
+ * endpoints live.) The question a dashboard asks; also the erase assertion. */
431
+ linked(a: string, b: string, day?: number): boolean {
432
+ const d = day ?? this.store.livedDay();
433
+ const live = this.conductor();
434
+ if (!live(a) || !live(b)) return false;
435
+ return conducts(this.weightAt(a, b, d), this.tunables);
436
+ }
437
+
438
+ /**
439
+ * Scar §2.2's second half: a supersede must RETARGET the edges, or the
440
+ * successor starts cold while the old id keeps the association fingerprint.
441
+ *
442
+ * The old rows are not deleted — this module has no delete and the store
443
+ * exports none — they simply stop conducting, because a superseded id is not
444
+ * live memory. The successor INHERITS each live weight (`max`, not `+`, so a
445
+ * re-run is idempotent), symmetrically, capped.
446
+ *
447
+ * Nobody calls this yet: who fires it on supersede is a seam decision
448
+ * (INTERFACE-GAPS.md §4).
449
+ */
450
+ retargetOnSupersede(oldId: string, newId: string, day?: number): FlushReport {
451
+ const d = day ?? this.store.livedDay();
452
+ const empty: FlushReport = {
453
+ reason: "nothing-buffered",
454
+ day: d,
455
+ pairs: 0,
456
+ rows: 0,
457
+ evictions: [],
458
+ renormalized: 0,
459
+ nodesTouched: 0,
460
+ blocked: 0,
461
+ dropped: 0,
462
+ };
463
+ if (this.observer) {
464
+ this.emit("associate.observer.skip", undefined, { site: "retarget" });
465
+ return { ...empty, reason: "observer" };
466
+ }
467
+
468
+ const conductor = this.conductor();
469
+ const inherited = new Map<string, number>();
470
+ for (const e of this.edgeStates(oldId)) {
471
+ if (e.dst === newId) continue;
472
+ const w = edgeWeightAt(e, d, this.tunables);
473
+ if (!conducts(w, this.tunables) || !conductor(e.dst)) continue;
474
+ inherited.set(e.dst, Math.max(inherited.get(e.dst) ?? 0, w));
475
+ }
476
+ if (inherited.size === 0) return empty;
477
+
478
+ const cap = this.tunables.EDGE_CAP;
479
+ const forward = new Map(this.edgeStates(newId).map((e) => [e.dst, edgeWeightAt(e, d, this.tunables)]));
480
+ const rows: EdgeInput[] = [];
481
+ for (const [dst, w] of [...inherited].sort((x, y) => (x[0] < y[0] ? -1 : 1))) {
482
+ const back = this.edgeStates(dst).find((e) => e.dst === newId);
483
+ const backWeight = back === undefined ? 0 : edgeWeightAt(back, d, this.tunables);
484
+ rows.push({ src: newId, dst, weight: Math.min(cap, Math.max(forward.get(dst) ?? 0, w)), day: d });
485
+ rows.push({ src: dst, dst: newId, weight: Math.min(cap, Math.max(backWeight, w)), day: d });
486
+ }
487
+ try {
488
+ this.store.linkMany(rows);
489
+ } catch (err) {
490
+ this.emit("associate.retarget.failed", oldId, {
491
+ successor: newId,
492
+ rows: rows.length,
493
+ error: err instanceof Error ? err.name : "UNKNOWN",
494
+ });
495
+ return {
496
+ ...empty,
497
+ reason: "failed",
498
+ rows: 0,
499
+ dropped: inherited.size,
500
+ error: err instanceof Error ? err.message : String(err),
501
+ };
502
+ }
503
+ this.emit("associate.retarget", oldId, { successor: newId, edges: inherited.size, day: d });
504
+ return { ...empty, reason: "flushed", pairs: inherited.size, rows: rows.length, nodesTouched: inherited.size + 1 };
505
+ }
506
+
507
+ // ── telemetry ──────────────────────────────────────────────────────────────
508
+
509
+ events(name?: string): AssociateEvent[] {
510
+ return this.ring.filter((e) => name === undefined || e.name === name).map((e) => ({ ...e }));
511
+ }
512
+
513
+ // ── internals ──────────────────────────────────────────────────────────────
514
+
515
+ /** Why this member may (or may not) train. Every exclusion has a name. */
516
+ private memberReason(m: Credited, denied: ReadonlySet<string>): MemberReason {
517
+ if (tierFactor(m.tier, this.tunables) <= 0) return "ignorable-tier";
518
+ if (denied.has(m.id)) return "removed";
519
+ const row = this.store.row(m.id);
520
+ if (row === undefined) return "unknown-id";
521
+ // Superseded FIRST: `store.supersede` archives the old head as well, and
522
+ // "superseded" is the more informative of the two true answers.
523
+ if (row.superseded_by !== null) return "superseded";
524
+ if (row.archived === 1) return "archived";
525
+ // Guarantee 9: pinned memories are frozen in BOTH directions — an arc under
526
+ // audit does not change mid-audit. `protected` is the flag v2 has; "under
527
+ // audit" has no representation yet (NOTES.md §7).
528
+ if (row.protected === 1) return "frozen-protected";
529
+ return "eligible";
530
+ }
531
+
532
+ /**
533
+ * The conducting predicate: live memory only. A removed, archived or superseded
534
+ * id neither receives activation nor passes it on (contract G8) — and because
535
+ * edges are rows in the canonical operational database rather than a
536
+ * hand-serialized sidecar, there is no rebuild path that could reload them and
537
+ * resurrect the conduction (contract §4, scar §2.2).
538
+ */
539
+ private conductor(): (id: string) => boolean {
540
+ const denied = new Set(this.store.deniedIds());
541
+ const memo = new Map<string, boolean>();
542
+ return (id: string) => {
543
+ const have = memo.get(id);
544
+ if (have !== undefined) return have;
545
+ const row = denied.has(id) ? undefined : this.store.row(id);
546
+ const ok = row !== undefined && row.archived === 0 && row.superseded_by === null;
547
+ memo.set(id, ok);
548
+ return ok;
549
+ };
550
+ }
551
+
552
+ private edgeStates(id: string): EdgeState[] {
553
+ return this.store
554
+ .edgesFrom(id)
555
+ .map((r) => ({ src: r.src, dst: r.dst, weight: r.weight, lastDay: r.last_day }));
556
+ }
557
+
558
+ private emit(
559
+ name: string,
560
+ ref?: string,
561
+ data?: Record<string, string | number | boolean | null>,
562
+ ): void {
563
+ const event: AssociateEvent = { at: Date.now(), name };
564
+ if (ref !== undefined) event.ref = ref;
565
+ if (data !== undefined) event.data = data;
566
+ this.ring.push(event);
567
+ if (this.ring.length > EVENT_RING) this.ring.shift();
568
+ this.onEvent?.(event);
569
+ }
570
+ }