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,383 @@
1
+ /**
2
+ * The pending file — co-activation deltas ON DISK, between the process that
3
+ * noticed them and the process that writes them down.
4
+ *
5
+ * **Why it exists.** `coactivate()` accumulates pair deltas in an in-process
6
+ * buffer and `flush()` turns them into edge rows. On a host whose every hook is
7
+ * a fresh process those two halves run in different processes: the credit pass
8
+ * runs inside a Stop hook, and the flush runs in the detached worker that Stop
9
+ * spawns. For the whole of the parallel run the buffer therefore died at hook
10
+ * exit and no edge was ever written. The first fix ran the flush inside the
11
+ * hook, which works — and puts two SQLite writes on a path that meets the
12
+ * worker's own write lock (I38: `database is locked` in 3 of 8 runs, and an
13
+ * adversarial probe measured 5.3 s per write under a held lock, with the drained
14
+ * deltas recorded nowhere afterwards). This file is the other answer, and it is
15
+ * the lesson this week already taught in `sessions.ts`: **a value one hook
16
+ * writes and a later process reads has to be on disk.**
17
+ *
18
+ * So the hook appends; the worker claims, applies and removes. The hook takes no
19
+ * database lock for association at all.
20
+ *
21
+ * **Where it lives, and why not the top level.** `<dataDir>/sessions/association/`.
22
+ * `Store.assertLayout()` runs in the store's CONSTRUCTOR and refuses any
23
+ * top-level entry it cannot classify, so a new top-level file would stop every
24
+ * store opened by code that predates it — and after a deploy the MCP servers of
25
+ * already-running sessions are exactly that code. `sessions/` is already
26
+ * classified (host state, `backup: false`), `adapters/expansions.ts` already
27
+ * keeps a log inside it for the same reason, and a SUBDIRECTORY is also out of
28
+ * `pruneSessions`'s reach: it removes files, and its `rmSync` without
29
+ * `recursive` leaves a directory alone.
30
+ *
31
+ * `SESSIONS_DIR` is spelled again here rather than imported: `adapters/` are
32
+ * leaves and core may not import one. The name is classified in
33
+ * `store/paths.ts` LAYOUT, and `test/sessions.test.ts` pins the two spellings
34
+ * against each other.
35
+ *
36
+ * Four rules the code below mechanizes:
37
+ *
38
+ * 1. **Appends are appends.** One `appendFileSync` per line with `O_APPEND`,
39
+ * each line small, so two hook processes writing at once interleave whole
40
+ * lines rather than clobbering each other.
41
+ * 2. **Nothing here throws at a caller.** A hook may not fail its host
42
+ * (`claude-code/CONTRACT.md` §5 G2); every entry point reports a failure
43
+ * in its return value instead.
44
+ * 3. **A claim is a rename ASIDE** (the choreography `remember/spans.ts`
45
+ * already carries): a concurrent append lands in a fresh pending file and
46
+ * cannot be destroyed by the claim, and a claim whose apply failed is left
47
+ * where it is, for the next run to find.
48
+ * 4. **Counts, ids and weights only.** Never a byte of any memory's text.
49
+ */
50
+ import {
51
+ appendFileSync,
52
+ mkdirSync,
53
+ readFileSync,
54
+ readdirSync,
55
+ renameSync,
56
+ rmSync,
57
+ statSync,
58
+ utimesSync,
59
+ } from "node:fs";
60
+ import { randomBytes } from "node:crypto";
61
+ import { join } from "node:path";
62
+
63
+ import type { PairDelta } from "./edges.js";
64
+
65
+ /** The registry directory core spells for itself — see the header. */
66
+ const SESSIONS_DIR = "sessions";
67
+ /** One directory of our own inside it, so `pruneSessions` cannot reach the file. */
68
+ export const ASSOCIATION_DIR = "association";
69
+ export const PENDING_FILE = "pending.jsonl";
70
+ export const CLAIMS_DIR = "claims";
71
+
72
+ /**
73
+ * **CAL.** Pairs per line. A line is written with one `appendFileSync` and two
74
+ * hooks can be writing at the same moment, so it is kept far below any
75
+ * plausible atomic-write size: sixteen pairs is well under a kilobyte at the id
76
+ * lengths this store mints.
77
+ */
78
+ export const PENDING_PAIRS_PER_LINE = 16;
79
+
80
+ /**
81
+ * **CAL.** How large the pending file may get before a pass is dropped instead
82
+ * of appended.
83
+ *
84
+ * A ceiling, not a target: the ordinary file is emptied by the worker seconds
85
+ * after it is written. The owner's store shows what ordinary means — 214 credit
86
+ * passes, six of which credited two or more memories, so a day of real work is
87
+ * a few hundred bytes. The size is set against the OTHER end: a pass crediting
88
+ * 64 memories at once is 2,016 pairs and measured 186 KB of lines, and a
89
+ * megabyte leaves room for several of those on top of a worker that has not run
90
+ * for a week.
91
+ */
92
+ export const PENDING_MAX_BYTES = 1024 * 1024;
93
+
94
+ /**
95
+ * **CAL.** The slack above the cap that the drop MARKERS may use. A drop is
96
+ * counted in a line of its own (~60 bytes) so the next apply can report it;
97
+ * past this the file takes nothing at all and the drop is in-process only.
98
+ */
99
+ export const PENDING_MARKER_SLACK_BYTES = 16 * 1024;
100
+
101
+ /**
102
+ * **CAL.** How long a claim may go untouched before another run takes it over.
103
+ *
104
+ * A claim is TOUCHED when it is taken (`claimPending` sets its mtime to the
105
+ * claim time), so this age is time since the claim, not time since the last
106
+ * append — `renameSync` keeps the pending file's mtime, and measured from that
107
+ * a claim taken during a quiet stretch looked hours old the moment it was made,
108
+ * which let a second worker steal it from a live one and apply the same deltas
109
+ * twice (second adversarial review, 2026-09-17). The window has to outlive the
110
+ * whole worker, not only one apply: the worker's watchdog is five minutes
111
+ * (`claude-code/config.ts` WATCHDOG_MS), a worker the watchdog killed releases
112
+ * nothing, and a live one may still be inside its apply. Ten minutes is twice
113
+ * that. Shorter than `remember/`'s span window on purpose: a claim that failed
114
+ * is work already earned and waiting, and it should land soon after.
115
+ */
116
+ export const PENDING_STALE_CLAIM_MS = 10 * 60_000;
117
+
118
+ export function associationDir(dataDir: string): string {
119
+ return join(dataDir, SESSIONS_DIR, ASSOCIATION_DIR);
120
+ }
121
+
122
+ export function pendingPath(dataDir: string): string {
123
+ return join(associationDir(dataDir), PENDING_FILE);
124
+ }
125
+
126
+ export function claimsDir(dataDir: string): string {
127
+ return join(associationDir(dataDir), CLAIMS_DIR);
128
+ }
129
+
130
+ /** What one append did. `code` names the failure when there was one. */
131
+ export interface PendingAppend {
132
+ readonly ok: boolean;
133
+ /** Lines written — a pass is several when it carries many pairs. */
134
+ readonly lines: number;
135
+ /** Pairs that reached the file. */
136
+ readonly pairs: number;
137
+ /** Pairs the cap refused, counted in a marker line so an apply can report it. */
138
+ readonly droppedPairs: number;
139
+ readonly code: string | null;
140
+ }
141
+
142
+ /** One line of the file, read back. A pass may span several. */
143
+ interface PendingLine {
144
+ readonly at: number;
145
+ readonly day: number;
146
+ readonly pairs: PairDelta[];
147
+ readonly dropped: number;
148
+ }
149
+
150
+ /** A claim file, renamed aside and read. Counts, ids and weights only. */
151
+ export interface PendingClaim {
152
+ readonly path: string;
153
+ /** Lines carried — passes, or the fragments of a large pass. */
154
+ readonly passes: number;
155
+ readonly deltas: PairDelta[];
156
+ /** The newest lived day any carried line named; the day the apply stamps. */
157
+ readonly day: number | null;
158
+ /** The oldest carried line's timestamp, for "how old was this work". */
159
+ readonly oldestAt: number | null;
160
+ /** Pairs the cap dropped while this file was the pending one. */
161
+ readonly droppedPairs: number;
162
+ /** Lines that were not JSON. Counted, never silently swallowed. */
163
+ readonly corrupt: number;
164
+ }
165
+
166
+ function codeOf(err: unknown): string {
167
+ if (err !== null && typeof err === "object") {
168
+ const code = (err as { code?: unknown }).code;
169
+ if (typeof code === "string") return code;
170
+ const name = (err as { name?: unknown }).name;
171
+ if (typeof name === "string") return name;
172
+ }
173
+ return "UNKNOWN";
174
+ }
175
+
176
+ function sizeOf(path: string): number {
177
+ try {
178
+ return statSync(path).size;
179
+ } catch {
180
+ return 0;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Append what one credit pass buffered. Returns what landed; never throws.
186
+ *
187
+ * **The cap drops the NEWEST pass, and says so in a line.** Dropping the oldest
188
+ * would mean rewriting the file, and a rewrite races every hook that is
189
+ * appending to it — the one way this file could lose work nobody counted. A
190
+ * delta is re-earnable by construction (the next co-activation of the same pair
191
+ * earns it again); a lost line of somebody else's is not. The drop's count goes
192
+ * into a marker line, so the next apply reports it instead of the loss being
193
+ * visible only in a ring inside a process that is about to exit.
194
+ */
195
+ export function appendPendingDeltas(
196
+ dataDir: string,
197
+ deltas: readonly PairDelta[],
198
+ opts: { day: number; at: number },
199
+ ): PendingAppend {
200
+ if (deltas.length === 0) return { ok: true, lines: 0, pairs: 0, droppedPairs: 0, code: null };
201
+ const path = pendingPath(dataDir);
202
+ try {
203
+ mkdirSync(associationDir(dataDir), { recursive: true });
204
+ const size = sizeOf(path);
205
+ if (size >= PENDING_MAX_BYTES) {
206
+ if (size >= PENDING_MAX_BYTES + PENDING_MARKER_SLACK_BYTES) {
207
+ return { ok: false, lines: 0, pairs: 0, droppedPairs: deltas.length, code: "PENDING_FULL" };
208
+ }
209
+ const marker = JSON.stringify({ at: opts.at, day: opts.day, dropped: deltas.length });
210
+ appendFileSync(path, `${marker}\n`, { encoding: "utf8", mode: 0o600 });
211
+ return { ok: true, lines: 1, pairs: 0, droppedPairs: deltas.length, code: "PENDING_FULL" };
212
+ }
213
+ let lines = 0;
214
+ for (let i = 0; i < deltas.length; i += PENDING_PAIRS_PER_LINE) {
215
+ const chunk = deltas.slice(i, i + PENDING_PAIRS_PER_LINE);
216
+ const line = JSON.stringify({
217
+ at: opts.at,
218
+ day: opts.day,
219
+ p: chunk.map((d) => [d.a, d.b, d.delta]),
220
+ });
221
+ appendFileSync(path, `${line}\n`, { encoding: "utf8", mode: 0o600 });
222
+ lines += 1;
223
+ }
224
+ return { ok: true, lines, pairs: deltas.length, droppedPairs: 0, code: null };
225
+ } catch (err) {
226
+ return { ok: false, lines: 0, pairs: 0, droppedPairs: deltas.length, code: codeOf(err) };
227
+ }
228
+ }
229
+
230
+ function parseLine(raw: string): PendingLine | null {
231
+ let entry: unknown;
232
+ try {
233
+ entry = JSON.parse(raw);
234
+ } catch {
235
+ return null;
236
+ }
237
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return null;
238
+ const rec = entry as Record<string, unknown>;
239
+ const at = typeof rec["at"] === "number" ? rec["at"] : null;
240
+ const day = typeof rec["day"] === "number" && Number.isFinite(rec["day"]) && rec["day"] >= 0 ? Math.floor(rec["day"]) : null;
241
+ if (at === null || day === null) return null;
242
+ const dropped = typeof rec["dropped"] === "number" ? rec["dropped"] : 0;
243
+ const pairs: PairDelta[] = [];
244
+ const p = rec["p"];
245
+ if (Array.isArray(p)) {
246
+ for (const item of p) {
247
+ if (!Array.isArray(item) || item.length < 3) continue;
248
+ const [a, b, delta] = item as [unknown, unknown, unknown];
249
+ if (typeof a !== "string" || typeof b !== "string" || typeof delta !== "number") continue;
250
+ if (a.length === 0 || b.length === 0 || !Number.isFinite(delta) || delta <= 0) continue;
251
+ pairs.push({ a, b, delta });
252
+ }
253
+ }
254
+ return { at, day, pairs, dropped };
255
+ }
256
+
257
+ function readClaim(path: string): PendingClaim {
258
+ let text = "";
259
+ try {
260
+ text = readFileSync(path, "utf8");
261
+ } catch {
262
+ return { path, passes: 0, deltas: [], day: null, oldestAt: null, droppedPairs: 0, corrupt: 0 };
263
+ }
264
+ const deltas: PairDelta[] = [];
265
+ let passes = 0;
266
+ let corrupt = 0;
267
+ let droppedPairs = 0;
268
+ let day: number | null = null;
269
+ let oldestAt: number | null = null;
270
+ for (const raw of text.split("\n")) {
271
+ if (raw.trim().length === 0) continue;
272
+ const line = parseLine(raw);
273
+ if (line === null) {
274
+ corrupt += 1;
275
+ continue;
276
+ }
277
+ passes += 1;
278
+ droppedPairs += line.dropped;
279
+ for (const d of line.pairs) deltas.push(d);
280
+ day = day === null ? line.day : Math.max(day, line.day);
281
+ oldestAt = oldestAt === null ? line.at : Math.min(oldestAt, line.at);
282
+ }
283
+ return { path, passes, deltas, day, oldestAt, droppedPairs, corrupt };
284
+ }
285
+
286
+ /** A claim's age is measured from the moment it was taken (see
287
+ * `PENDING_STALE_CLAIM_MS`). A touch that fails leaves the rename's mtime, and
288
+ * the claim then only looks OLDER than it is, which is the safe direction for
289
+ * the next run's takeover. */
290
+ function touch(path: string, now: number): void {
291
+ try {
292
+ utimesSync(path, now / 1000, now / 1000);
293
+ } catch {
294
+ /* see above */
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Take the pending file and any claim a dead run left behind — each as its own
300
+ * unit of work, oldest first.
301
+ *
302
+ * **Rename, not a lock.** The live file is renamed into `claims/`, so a hook
303
+ * appending at that moment lands in a fresh pending file and its line cannot be
304
+ * destroyed by this claim (the choreography `remember/spans.ts` §2 G6 carries).
305
+ *
306
+ * **A stale claim is re-claimed by renaming it again**, under this run's own id.
307
+ * Two workers racing for the same orphan therefore cannot both take it: the
308
+ * loser's rename meets an ENOENT and it moves on. A rename preserves the file's
309
+ * mtime, so an orphan that has been passed along still reads its true age.
310
+ *
311
+ * Nothing here removes a file. `releasePending` does that, and only after the
312
+ * deltas have landed — a claim whose apply failed is left exactly where it is.
313
+ */
314
+ export function claimPending(
315
+ dataDir: string,
316
+ opts: { now?: number; staleMs?: number } = {},
317
+ ): PendingClaim[] {
318
+ const now = opts.now ?? Date.now();
319
+ const staleMs = opts.staleMs ?? PENDING_STALE_CLAIM_MS;
320
+ const id = `apc_${randomBytes(6).toString("hex")}`;
321
+ const dir = claimsDir(dataDir);
322
+ const claims: PendingClaim[] = [];
323
+ try {
324
+ mkdirSync(dir, { recursive: true });
325
+ } catch {
326
+ return claims;
327
+ }
328
+ try {
329
+ renameSync(pendingPath(dataDir), join(dir, `${id}.jsonl`));
330
+ touch(join(dir, `${id}.jsonl`), now);
331
+ claims.push(readClaim(join(dir, `${id}.jsonl`)));
332
+ } catch {
333
+ /* nothing pending, or a rename this process may not make: the orphans below
334
+ are still worth looking for. */
335
+ }
336
+ let orphans: string[] = [];
337
+ try {
338
+ orphans = readdirSync(dir);
339
+ } catch {
340
+ return claims;
341
+ }
342
+ let taken = 0;
343
+ for (const name of orphans) {
344
+ if (!name.endsWith(".jsonl") || name.startsWith(`${id}.`) || name === `${id}.jsonl`) continue;
345
+ const from = join(dir, name);
346
+ try {
347
+ if (now - statSync(from).mtimeMs < staleMs) continue;
348
+ taken += 1;
349
+ const to = join(dir, `${id}.carried${taken}.jsonl`);
350
+ renameSync(from, to);
351
+ touch(to, now);
352
+ claims.push(readClaim(to));
353
+ } catch {
354
+ /* another run took it first, or it cannot be read: not this run's work. */
355
+ }
356
+ }
357
+ return claims.sort((x, y) => (x.oldestAt ?? 0) - (y.oldestAt ?? 0));
358
+ }
359
+
360
+ /**
361
+ * Remove a claim whose deltas have landed. Called ONLY after the apply
362
+ * succeeded — a claim that failed stays on disk for the next run.
363
+ *
364
+ * The rename is the second attempt at the same job: a claim file this process
365
+ * cannot remove would be applied again by a later run, which is the one
366
+ * direction `associate/CONTRACT.md` §5 G4 rules out, and a file moved out of
367
+ * `claims/` is no longer claimable. `stuck` is true when neither worked, and
368
+ * the caller counts it rather than hiding it (`INTERFACE-GAPS.md` §3).
369
+ */
370
+ export function releasePending(claim: PendingClaim): { released: boolean; stuck: boolean; code: string | null } {
371
+ try {
372
+ rmSync(claim.path, { force: true });
373
+ return { released: true, stuck: false, code: null };
374
+ } catch (err) {
375
+ const code = codeOf(err);
376
+ try {
377
+ renameSync(claim.path, `${claim.path}.applied`);
378
+ return { released: true, stuck: false, code };
379
+ } catch {
380
+ return { released: false, stuck: true, code };
381
+ }
382
+ }
383
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Spreading activation — a PURE traversal.
3
+ *
4
+ * Seeds plus edge data in, activation contributions out. It reads no store, calls
5
+ * no model, and writes nothing: the graph arrives as two functions the caller
6
+ * supplies (`edgesFrom`, `conducts`), which is what makes the erase test
7
+ * expressible at all — "a removed id stops conducting" is a property of the
8
+ * predicate, not of a deletion that has to be chased through a cache.
9
+ *
10
+ * `recall/` CAN consume this as a fourth channel beside cue, semantic and arrival
11
+ * (its NOTES.md §7 already names the seam and says the gate does not change).
12
+ * **It is not wired in here** — see INTERFACE-GAPS.md §1, which also records the
13
+ * one real collision: a hop contribution can reach an UNCUED memory, and whether
14
+ * that memory may become a candidate is recall's hard gate (a) to decide.
15
+ *
16
+ * Bounds, all three of them structural:
17
+ * - **depth** — `HOPS` hops, and a node is expanded once, at the shallowest
18
+ * depth it was reached;
19
+ * - **fan** — a node's contribution is shared across its live edges
20
+ * (`FAN_NORMALIZATION`), so a hub cannot flood;
21
+ * - **size** — `MAX_SPREAD_NODES` expansions, and the result says when it hit
22
+ * the ceiling instead of quietly returning less.
23
+ */
24
+ import { conducts, edgeWeightAt } from "./edges.js";
25
+ import type { EdgeState } from "./edges.js";
26
+ import type { AssociateTunables } from "./tunables.js";
27
+
28
+ export interface Seed {
29
+ readonly id: string;
30
+ /** The activation this memory already has from the caller's own channels. */
31
+ readonly activation: number;
32
+ }
33
+
34
+ export interface SpreadInput {
35
+ readonly seeds: readonly Seed[];
36
+ /** Lived day (scar E8) — edges are decayed to it before anything conducts. */
37
+ readonly day: number;
38
+ readonly edgesFrom: (id: string) => readonly EdgeState[];
39
+ /**
40
+ * Does this id conduct? FALSE for anything that is not live memory: removed
41
+ * (deny-listed), archived, or superseded. Non-conducting nodes neither receive
42
+ * a contribution nor pass one along, and they are not in the fan denominator
43
+ * either — an erased id must not even shape the arithmetic between its former
44
+ * neighbours (contract G8, scar §2.2).
45
+ */
46
+ readonly conducts: (id: string) => boolean;
47
+ }
48
+
49
+ export interface Contribution {
50
+ readonly id: string;
51
+ /** The added activation, summed over every path that reached it. */
52
+ readonly activation: number;
53
+ /** Shallowest hop at which it was reached. */
54
+ readonly depth: number;
55
+ readonly paths: number;
56
+ }
57
+
58
+ export type SpreadStop = "exhausted" | "hop-limit" | "node-limit";
59
+
60
+ export interface SpreadResult {
61
+ readonly contributions: readonly Contribution[];
62
+ /** Nodes whose edges were read. */
63
+ readonly expanded: number;
64
+ /** Seeds and destinations refused by `conducts`. */
65
+ readonly blocked: number;
66
+ readonly stop: SpreadStop;
67
+ }
68
+
69
+ export function spread(input: SpreadInput, t: AssociateTunables): SpreadResult {
70
+ const acc = new Map<string, { activation: number; depth: number; paths: number }>();
71
+ const expandedAt = new Map<string, number>();
72
+ /** Seeds receive NO contribution: their activation is the caller's own, and a
73
+ * round trip (a → b → a) would hand it back to them as new evidence. The
74
+ * contributions are what the graph ADDS, never an echo (NOTES.md §6). */
75
+ const seedIds = new Set(input.seeds.map((s) => s.id));
76
+ let blocked = 0;
77
+ let expanded = 0;
78
+ let stop: SpreadStop = "exhausted";
79
+
80
+ let frontier: { id: string; carried: number }[] = [];
81
+ for (const s of input.seeds) {
82
+ if (!input.conducts(s.id)) {
83
+ blocked += 1;
84
+ continue;
85
+ }
86
+ if (s.activation > 0) frontier.push({ id: s.id, carried: s.activation });
87
+ }
88
+
89
+ for (let depth = 1; depth <= t.HOPS && frontier.length > 0; depth++) {
90
+ const next: { id: string; carried: number }[] = [];
91
+ for (const node of frontier) {
92
+ if (expandedAt.has(node.id)) continue;
93
+ if (expanded >= t.MAX_SPREAD_NODES) {
94
+ stop = "node-limit";
95
+ return finish(acc, expanded, blocked, stop);
96
+ }
97
+ expandedAt.set(node.id, depth);
98
+ expanded += 1;
99
+
100
+ const live: { dst: string; weight: number }[] = [];
101
+ for (const e of input.edgesFrom(node.id)) {
102
+ if (e.dst === node.id) continue;
103
+ const w = edgeWeightAt(e, input.day, t);
104
+ if (!conducts(w, t)) continue;
105
+ if (!input.conducts(e.dst)) {
106
+ blocked += 1;
107
+ continue;
108
+ }
109
+ live.push({ dst: e.dst, weight: w });
110
+ }
111
+ if (live.length === 0) continue;
112
+
113
+ const fan = t.FAN_NORMALIZATION ? live.reduce((sum, e) => sum + e.weight, 0) : 1;
114
+ if (fan <= 0) continue;
115
+ for (const e of live) {
116
+ if (seedIds.has(e.dst)) continue;
117
+ const gain = node.carried * t.HOP_DECAY * (e.weight / fan);
118
+ if (gain <= 0) continue;
119
+ const have = acc.get(e.dst);
120
+ if (have === undefined) acc.set(e.dst, { activation: gain, depth, paths: 1 });
121
+ else {
122
+ // Contributions SUM across paths — two co-active seeds pointing at the
123
+ // same memory say more than one does — while `depth` keeps the
124
+ // shallowest arrival (NOTES.md §6).
125
+ have.activation += gain;
126
+ have.paths += 1;
127
+ if (depth < have.depth) have.depth = depth;
128
+ }
129
+ if (!expandedAt.has(e.dst)) next.push({ id: e.dst, carried: gain });
130
+ }
131
+ }
132
+ frontier = next;
133
+ if (frontier.length > 0 && depth === t.HOPS) stop = "hop-limit";
134
+ }
135
+
136
+ return finish(acc, expanded, blocked, stop);
137
+ }
138
+
139
+ function finish(
140
+ acc: ReadonlyMap<string, { activation: number; depth: number; paths: number }>,
141
+ expanded: number,
142
+ blocked: number,
143
+ stop: SpreadStop,
144
+ ): SpreadResult {
145
+ const contributions = [...acc]
146
+ .map(([id, v]) => ({ id, activation: v.activation, depth: v.depth, paths: v.paths }))
147
+ .sort((a, b) => b.activation - a.activation || (a.id < b.id ? -1 : 1));
148
+ return { contributions, expanded, blocked, stop };
149
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Every knob in `associate/`, in one visible place — the shape `physics/` and
3
+ * `recall/` use, for the same reason: a constant hiding in a function body cannot
4
+ * be audited.
5
+ *
6
+ * **CAL = calibration-required** (scar §2.8: no threshold ships unmeasured against
7
+ * the real space). Where v1 has a live calibration it is quoted as the starting
8
+ * point, NOT a v2 measurement; where it has none, the entry says so out loud.
9
+ * `tools/replay` is where these get re-earned.
10
+ *
11
+ * Structural (never tunable, never ablatable): the ignorable tier trains nothing;
12
+ * the flush ordering (drain first, publish second) and its chosen failure
13
+ * direction; the observer refusal; the conducting predicate that keeps a removed
14
+ * or archived id from carrying activation.
15
+ */
16
+ import type { DecayShape, UseTier } from "../physics/index.js";
17
+
18
+ export interface AssociateTunables {
19
+ // ── the Hebbian update ───────────────────────────────────────────────────
20
+ /**
21
+ * The co-activation increment for a fully-credited pair — both endpoints
22
+ * REFERENCED by the reply. CAL, and one of the few constants here with NO
23
+ * ancestry at all: v1's harvest records the tier structure of credit (§10 G1)
24
+ * and never the edge increment, so there is no number to inherit. At 0.1 a
25
+ * pair reaches `EDGE_CAP` after ten co-activations that both mattered.
26
+ */
27
+ HEBB_RATE: number;
28
+ /**
29
+ * Edge credit for the WEAK tier — surfaced but unused. **Ships DISABLED (0)**
30
+ * on purpose: contract §4 says weak credit's numeric weight is not inherited
31
+ * and ships "bounded by fixtures naming what breaks on each side, or
32
+ * disabled", and no such fixture exists yet. v1's reinforcement weight for the
33
+ * weak tier was 0.25 (`physics.TUNABLES.W_SURFACED`) — recorded here as the
34
+ * calibration to re-earn, deliberately NOT wired in. See NOTES.md §2. CAL.
35
+ */
36
+ EDGE_WEAK_CREDIT: number;
37
+ /** Per-edge ceiling. An edge is a readiness, not an unbounded counter. */
38
+ EDGE_CAP: number;
39
+ /** At or below this weight an edge is DEAD: it conducts nothing and is
40
+ * eligible for eviction. Also the "live edge" test for the count cap. CAL. */
41
+ EDGE_FLOOR: number;
42
+
43
+ // ── homeostasis (§10 G2) ─────────────────────────────────────────────────
44
+ /** Cap on LIVE edges out of one node. Past it, the weakest are evicted. CAL. */
45
+ MAX_EDGES_PER_NODE: number;
46
+ /** Bound on the total outgoing weight of one node, enforced by PROPORTIONAL
47
+ * renormalization — synaptic scaling, not clipping: the node's edges keep
48
+ * their relative order and lose absolute weight together. CAL. */
49
+ MAX_OUT_WEIGHT: number;
50
+
51
+ // ── edge decay (physics family, own constants) ───────────────────────────
52
+ /** Edge stability, in LIVED days (scar E8). Shorter than memory's `S_BASE`
53
+ * (60): an association that stops being used should fade faster than the
54
+ * memories it joins, or the graph becomes a fossil record of every
55
+ * coincidence. CAL, no ancestry. */
56
+ S_EDGE: number;
57
+ /**
58
+ * The curve shape for edges. PINNED to exponential, and that is load-bearing
59
+ * rather than a taste: decay is realized into the stored weight at flush time
60
+ * (weight := decayed, last_day := d), which is exact only for a memoryless
61
+ * curve. Changing this shape requires a separate "last reinforced day" column,
62
+ * not a new constant (NOTES.md §4).
63
+ */
64
+ EDGE_DECAY_SHAPE: DecayShape;
65
+
66
+ // ── spreading activation (§9 TUNABLE, v1's live calibration) ─────────────
67
+ /** Hop limit. [v1: 2] CAL. */
68
+ HOPS: number;
69
+ /** Per-hop decay. [v1: 0.5] CAL. */
70
+ HOP_DECAY: number;
71
+ /** Fan normalization: a node's outgoing weight is shared among its edges, so a
72
+ * hub cannot flood. [v1: on] Structural-ish — off is an A/B arm, not a
73
+ * shipping mode. */
74
+ FAN_NORMALIZATION: boolean;
75
+ /** Nodes expanded in one traversal — a latency bound, and the reason a dense
76
+ * graph cannot turn one seed into a whole-store sweep. CAL. */
77
+ MAX_SPREAD_NODES: number;
78
+ }
79
+
80
+ export const TUNABLES: AssociateTunables = {
81
+ HEBB_RATE: 0.1,
82
+ EDGE_WEAK_CREDIT: 0,
83
+ EDGE_CAP: 1.0,
84
+ EDGE_FLOOR: 0.02,
85
+
86
+ MAX_EDGES_PER_NODE: 32,
87
+ MAX_OUT_WEIGHT: 4.0,
88
+
89
+ S_EDGE: 30,
90
+ EDGE_DECAY_SHAPE: "exponential",
91
+
92
+ HOPS: 2,
93
+ HOP_DECAY: 0.5,
94
+ FAN_NORMALIZATION: true,
95
+ MAX_SPREAD_NODES: 64,
96
+ };
97
+
98
+ export function withTunables(overrides: Partial<AssociateTunables> = {}): AssociateTunables {
99
+ return { ...TUNABLES, ...overrides };
100
+ }
101
+
102
+ /**
103
+ * The per-endpoint credit factor. **The ignorable tier is 0 and that is
104
+ * structural** (§10 G1, contract G1): a footnote trains nothing, in either
105
+ * direction, whatever the other endpoint did. The weak tier reads its factor
106
+ * from the CAL table above, where it ships disabled.
107
+ */
108
+ export function tierFactor(tier: UseTier, t: AssociateTunables): number {
109
+ switch (tier) {
110
+ case "referenced":
111
+ return 1;
112
+ case "surfaced":
113
+ return t.EDGE_WEAK_CREDIT;
114
+ case "footnoted":
115
+ default:
116
+ return 0;
117
+ }
118
+ }
119
+
120
+ /** The co-activation delta for one pair: the rate, graded by BOTH endpoints. */
121
+ export function pairCredit(a: UseTier, b: UseTier, t: AssociateTunables): number {
122
+ return t.HEBB_RATE * tierFactor(a, t) * tierFactor(b, t);
123
+ }