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,617 @@
1
+ /**
2
+ * The embeddings call — the SECOND place in this package that reaches a model
3
+ * API, and the only other network code that exists.
4
+ *
5
+ * `store/` has held the socket for an `Embedder` since it was written, and
6
+ * nothing ever constructed one: every memory this brain has minted so far
7
+ * recorded `novelty: null` with reason `no-chunk-vector`, and the replay review
8
+ * (2026-08-26, F4/F5) is the bill for that — self-assigned salience with no
9
+ * independent check, and a run whose report claimed pinned vectors over a
10
+ * `cache.embeddings` table holding zero rows. This file is the missing half.
11
+ *
12
+ * `interpret-client.ts` is the template, deliberately: same refusal shape, same
13
+ * telemetry discipline, same division of labour. The scars it points at point
14
+ * here too, with one addition of this file's own.
15
+ *
16
+ * **E1 — CHUNKED, WITH PER-CHUNK FAILURE ISOLATION.** This is the scar that
17
+ * shapes the whole file. Embeddings arrive in batches, and v1's lesson is that
18
+ * ONE bad item must not fail the run: a chunk that fails leaves its own slots
19
+ * `null` and NAMES itself in `failures`, while every sibling chunk's vectors
20
+ * stand. The unit of isolation is `TUNABLES.EMBED_BATCH_SIZE`, and it is the
21
+ * same unit as the provider's batch ceiling on purpose — one boundary, not two.
22
+ *
23
+ * **§2.18** — the credential comes from ONE environment variable this package
24
+ * names (`EMBED_KEY_ENV`), filled either by the environment or, where the host
25
+ * hands a process none, by the file the package's own config NAMES
26
+ * (`credentialsFile`, loaded at the entry point). v1's client accepted a
27
+ * `.env` found by CONVENTION; that half stays dropped (see `config.ts`).
28
+ * Missing means a NAMED refusal BEFORE any socket is opened.
29
+ *
30
+ * **§2.15** — the model id comes from this adapter's own `embed` seat, pinned,
31
+ * with its own knob; an expired placeholder refuses the call. A vector's
32
+ * generation is part of its identity — vectors from two models are not
33
+ * comparable — so a silently-swapped id would silently corrupt every cosine in
34
+ * the store.
35
+ *
36
+ * **§2.4** — "off", "refused" and "returned nothing" are three records, never
37
+ * one zero. `EmbedBatch` carries `requested`, `returned` and `failures`, so a
38
+ * caller can tell a switched-off embedder from a failing one.
39
+ *
40
+ * **Retries and timeouts are the INJECTOR's**, exactly as `interpret-client.ts`
41
+ * states for the interpreter: this file takes an `AbortSignal` and opens exactly
42
+ * one request per chunk. v1's client retried a 429 once, internally; that is not
43
+ * ported, because a retry policy hidden inside a client is a policy the caller
44
+ * cannot see, cannot count, and cannot turn off (a deliberate deviation from the
45
+ * donor, recorded here rather than silently).
46
+ *
47
+ * **The levers that replace it**, named so "the injector owns it" is a design
48
+ * and not a shrug — a caller implementing 429 backoff has, without editing this
49
+ * file:
50
+ *
51
+ * - `EmbedBatch.failures[]`, each carrying `code: "HTTP_ERROR"` and the
52
+ * `status` — so 429 is distinguishable from 500 and from a bad request, and
53
+ * `from`/`count` say exactly which inputs to re-ask for. Retrying is
54
+ * re-calling with that slice; nothing here is stateful.
55
+ * - the `embed.chunk.failed` event, same fields, for a caller that watches
56
+ * rates rather than return values.
57
+ * - `signal`, which stops the run at the next chunk boundary and reports
58
+ * `ABORTED` rather than pretending the remaining inputs were empty — a
59
+ * timeout is therefore the injector's `AbortSignal.timeout(ms)`, and a
60
+ * backoff sleep is the injector's, between calls.
61
+ *
62
+ * What this file will NOT do is sleep. A client that sleeps inside a batch holds
63
+ * a detached worker's watchdog budget hostage to a header the far end chose.
64
+ *
65
+ * There is no SDK and no dependency: `fetch` is the runtime's.
66
+ */
67
+ import type { Embedder } from "../../core/store/index.js";
68
+ import { hashText } from "../../core/store/index.js";
69
+
70
+ import { EMBED_KEY_ENV, TUNABLES, VOYAGE_ENDPOINT, embedSeat } from "./config.js";
71
+ import type { AdapterConfig } from "./config.js";
72
+ import type { FetchLike } from "./interpret-client.js";
73
+
74
+ /** Every way this client refuses, by name. A refusal is never a silent empty. */
75
+ export type EmbedRefusal =
76
+ | "NO_API_KEY"
77
+ | "SEAT_UNUSABLE"
78
+ | "NO_FETCH"
79
+ | "HTTP_ERROR"
80
+ | "NO_BODY"
81
+ | "BAD_RESPONSE"
82
+ | "WRONG_VECTOR_COUNT"
83
+ | "ABORTED";
84
+
85
+ export class EmbedError extends Error {
86
+ readonly code: EmbedRefusal;
87
+ readonly detail: Record<string, string | number>;
88
+
89
+ constructor(code: EmbedRefusal, detail: Record<string, string | number> = {}) {
90
+ super(`${code}${Object.keys(detail).length > 0 ? ` ${JSON.stringify(detail)}` : ""}`);
91
+ this.name = "EmbedError";
92
+ this.code = code;
93
+ this.detail = detail;
94
+ }
95
+ }
96
+
97
+ /** One chunk that failed, named — the countable half of E1. */
98
+ export interface ChunkFailure {
99
+ /** Index of the chunk within this call, not within the store. */
100
+ readonly chunk: number;
101
+ /** Where this chunk started in the caller's `texts` array. */
102
+ readonly from: number;
103
+ readonly count: number;
104
+ readonly code: EmbedRefusal;
105
+ readonly status?: number;
106
+ /**
107
+ * True when the bisector narrowed a 400 down to THIS ONE INPUT: the item is
108
+ * the poison, not the batch. `count` is 1 on every such failure, and the
109
+ * caller can act on it — retire the id, repair the text — instead of retrying
110
+ * a whole chunk that will fail the same way forever (I33).
111
+ */
112
+ readonly item?: boolean;
113
+ }
114
+
115
+ export interface EmbedBatch {
116
+ /** The seat's pinned id — the generation these vectors belong to. */
117
+ readonly model: string;
118
+ /** One slot per input, in input order. NULL where the chunk failed. */
119
+ readonly vectors: readonly (number[] | null)[];
120
+ readonly requested: number;
121
+ readonly returned: number;
122
+ readonly chunks: number;
123
+ readonly failures: readonly ChunkFailure[];
124
+ }
125
+
126
+ /** Telemetry: ids, counts, hashes, codes. Never the text being embedded. */
127
+ export type EmitFn = (name: string, data: Record<string, string | number | boolean | null>) => void;
128
+
129
+ export interface EmbedClientOptions {
130
+ config?: AdapterConfig;
131
+ /** Defaults to `globalThis.fetch`. A test supplies its own; nothing else does. */
132
+ fetch?: FetchLike;
133
+ /** Today, ISO — the date a placeholder seat's expiry is judged against. */
134
+ today?: string;
135
+ /** Texts per request. Defaults to the provider's ceiling; also the isolation unit. */
136
+ batchSize?: number;
137
+ onEvent?: EmitFn;
138
+ /** Aborts the request. The watchdog's hand on the socket; retries are its too. */
139
+ signal?: AbortSignal;
140
+ }
141
+
142
+ export type EmbedFn = (texts: readonly string[]) => Promise<EmbedBatch>;
143
+
144
+ /**
145
+ * Build the batched embeddings call.
146
+ *
147
+ * The two PRE-FLIGHT refusals — no credential, unusable seat — throw before any
148
+ * socket is opened, because neither is a per-chunk condition: no chunk of this
149
+ * call could have succeeded. Everything after that point is per-chunk, and a
150
+ * failure there is isolated rather than thrown (E1).
151
+ */
152
+ export function embedClient(opts: EmbedClientOptions = {}): EmbedFn {
153
+ const config = opts.config ?? {};
154
+ const doFetch = opts.fetch ?? ((globalThis as { fetch?: FetchLike }).fetch as FetchLike | undefined);
155
+ const today = opts.today ?? new Date().toISOString().slice(0, 10);
156
+ const emit = opts.onEvent ?? ((): void => {});
157
+ const batchSize = opts.batchSize ?? TUNABLES.EMBED_BATCH_SIZE;
158
+ /** Read through a call, never a narrowed local: the flag flips under us. */
159
+ const aborted = (): boolean => opts.signal?.aborted === true;
160
+
161
+ return async (texts: readonly string[]): Promise<EmbedBatch> => {
162
+ // ── the credential, from ONE source, checked BEFORE any socket ──────────
163
+ const key = process.env[EMBED_KEY_ENV];
164
+ if (key === undefined || key.trim().length === 0) {
165
+ emit("embed.refused", { code: "NO_API_KEY", env: EMBED_KEY_ENV, texts: texts.length });
166
+ throw new EmbedError("NO_API_KEY", { env: EMBED_KEY_ENV });
167
+ }
168
+ // ── the seat, whose placeholder expires (scar §2.15) ────────────────────
169
+ const seat = embedSeat(config, today);
170
+ if (!seat.usable) {
171
+ emit("embed.refused", { code: "SEAT_UNUSABLE", seat: seat.seat, status: seat.status });
172
+ throw new EmbedError("SEAT_UNUSABLE", { seat: seat.seat, status: seat.status });
173
+ }
174
+ if (doFetch === undefined) {
175
+ emit("embed.refused", { code: "NO_FETCH" });
176
+ throw new EmbedError("NO_FETCH", {});
177
+ }
178
+
179
+ const vectors: (number[] | null)[] = new Array<number[] | null>(texts.length).fill(null);
180
+ const failures: ChunkFailure[] = [];
181
+ let returned = 0;
182
+ let chunk = 0;
183
+
184
+ for (let from = 0; from < texts.length; from += batchSize) {
185
+ const slice = texts.slice(from, from + batchSize);
186
+ const index = chunk;
187
+ chunk += 1;
188
+ // The watchdog's hand landed. Stop opening sockets, say so by name, and
189
+ // leave the rest null — an abort is a REASON, not a batch of bad data.
190
+ if (aborted()) {
191
+ const rest = texts.length - from;
192
+ failures.push({ chunk: index, from, count: rest, code: "ABORTED" });
193
+ emit("embed.chunk.failed", { chunk: index, from, count: rest, code: "ABORTED", status: null });
194
+ break;
195
+ }
196
+ emit("embed.call", { chunk: index, from, count: slice.length, model: seat.id, seat: seat.status });
197
+ // THE BISECTING ATTEMPT (I33). One call for a healthy chunk; on a 400 —
198
+ // and only a 400 — it halves down to the offending item. Everything it
199
+ // records goes through the two collectors below, so the isolation unit
200
+ // changed without the caller's reading of `failures` changing.
201
+ const budget = { calls: callBudget(slice.length) };
202
+ await attempt(
203
+ {
204
+ doFetch,
205
+ key,
206
+ model: seat.id,
207
+ emit,
208
+ chunk: index,
209
+ budget,
210
+ ...(opts.signal === undefined ? {} : { signal: opts.signal }),
211
+ },
212
+ slice,
213
+ from,
214
+ (at, vec) => {
215
+ vectors[at] = vec;
216
+ returned += 1;
217
+ },
218
+ (failure) => {
219
+ failures.push(failure);
220
+ emit("embed.chunk.failed", {
221
+ chunk: failure.chunk,
222
+ from: failure.from,
223
+ count: failure.count,
224
+ code: failure.code,
225
+ status: failure.status ?? null,
226
+ item: failure.item === true,
227
+ });
228
+ },
229
+ aborted,
230
+ );
231
+ }
232
+
233
+ return { model: seat.id, vectors, requested: texts.length, returned, chunks: chunk, failures };
234
+ };
235
+ }
236
+
237
+ /**
238
+ * Make every input WELL-FORMED, for the request body and for nothing else.
239
+ *
240
+ * THE SURROGATE SCAR (I33). Two migrated memories carried a lone UTF-16
241
+ * surrogate in their title; `JSON.stringify` happily emits the escape, the
242
+ * provider answers `400 input is not valid UTF-8` for the WHOLE 64-text chunk,
243
+ * and because `missingVectors` returns a stable order the same head-64 was
244
+ * retried at every boundary for a week while 165 blind memories queued behind
245
+ * it.
246
+ *
247
+ * `toWellFormed()` is the runtime's own repair (bun has it; the regex is the
248
+ * fallback for a runtime that does not). A lone surrogate becomes U+FFFD — the
249
+ * same character the prose file's frontmatter already shows, so what gets
250
+ * embedded is what a reader sees.
251
+ *
252
+ * **THE BODY ONLY.** Nothing upstream is sanitized: the cache key
253
+ * (`createEmbedder`'s `keyOf`), `indexTextOf`, and `store.embedOne`'s lookup all
254
+ * stay on the ORIGINAL string. Sanitizing before the cache write would file the
255
+ * vector under a key the store never asks for, and the backfill would become a
256
+ * paid-for no-op that reports success — which is precisely the failure
257
+ * `vectors.ts` warns about two levels up.
258
+ */
259
+ export function wellFormed(input: readonly string[]): { input: string[]; changed: number } {
260
+ let changed = 0;
261
+ const out = input.map((text) => {
262
+ const native = (text as unknown as { toWellFormed?: () => string }).toWellFormed;
263
+ const fixed =
264
+ typeof native === "function"
265
+ ? native.call(text)
266
+ : // Lone surrogates only: a high not followed by a low, or a low not
267
+ // preceded by a high. A well-formed pair is left exactly as it is.
268
+ text.replace(LONE_SURROGATE, "\uFFFD");
269
+ if (fixed !== text) changed += 1;
270
+ return fixed;
271
+ });
272
+ return { input: out, changed };
273
+ }
274
+
275
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
276
+
277
+ /**
278
+ * The call budget one chunk's bisection may spend: `2·log2(n) + n`.
279
+ *
280
+ * A full binary split of n items costs at most 2n−1 calls, which for a 64-text
281
+ * chunk of entirely-poison inputs would be 127 round trips inside one detached
282
+ * worker's watchdog. This bound is generous for the real case (a handful of bad
283
+ * items) and hard for the pathological one; past it the remaining slice is
284
+ * recorded whole, exactly as a 500 would be.
285
+ */
286
+ export function callBudget(n: number): number {
287
+ return Math.ceil(2 * Math.log2(Math.max(n, 2))) + n;
288
+ }
289
+
290
+ interface AttemptContext {
291
+ doFetch: FetchLike;
292
+ key: string;
293
+ model: string;
294
+ emit: EmitFn;
295
+ /** The ORIGINAL chunk index; a bisected half is still that chunk's failure. */
296
+ chunk: number;
297
+ budget: { calls: number };
298
+ signal?: AbortSignal;
299
+ }
300
+
301
+ /**
302
+ * One slice, and — on an HTTP 400 — its halves, recursively, down to one item.
303
+ *
304
+ * 400 ONLY. A 429, a 5xx, an abort or a malformed body says nothing about WHICH
305
+ * input is bad: the whole slice failed for a reason the slice does not own, and
306
+ * splitting it would just multiply the same failure (and, for a 429, the rate
307
+ * that caused it). A 400 is the opposite — the provider read the body and
308
+ * refused it — so the poison is in there, and halving finds it in log2(n) steps.
309
+ */
310
+ async function attempt(
311
+ ctx: AttemptContext,
312
+ slice: readonly string[],
313
+ from: number,
314
+ land: (at: number, vec: number[]) => void,
315
+ fail: (failure: ChunkFailure) => void,
316
+ aborted: () => boolean,
317
+ ): Promise<void> {
318
+ if (slice.length === 0) return;
319
+ const whole = (code: EmbedRefusal, status?: number, item?: boolean): void => {
320
+ fail({
321
+ chunk: ctx.chunk,
322
+ from,
323
+ count: slice.length,
324
+ code,
325
+ ...(status === undefined ? {} : { status }),
326
+ ...(item === true ? { item: true } : {}),
327
+ });
328
+ };
329
+ if (ctx.budget.calls <= 0) {
330
+ // The bound, spent. Whatever is left is recorded the way a whole-chunk
331
+ // failure always was — never silently dropped.
332
+ //
333
+ // A remainder of ONE is still an item failure, and says so. Everything above
334
+ // this line got here because a 400 named its slice, so a single survivor of
335
+ // that descent is the poison whether or not the budget lasted long enough to
336
+ // ask one more time — and `vectors.ts` gates its give-up counter on exactly
337
+ // this flag, so leaving it off here would make the counter depend on how
338
+ // many calls the bisector happened to have left.
339
+ whole("HTTP_ERROR", 400, slice.length === 1);
340
+ return;
341
+ }
342
+ ctx.budget.calls -= 1;
343
+ let err: unknown;
344
+ try {
345
+ const got = await callOnce(ctx, slice);
346
+ for (let i = 0; i < got.length; i += 1) {
347
+ const vec = got[i];
348
+ if (vec !== undefined) land(from + i, vec);
349
+ }
350
+ ctx.emit("embed.done", { chunk: ctx.chunk, count: got.length, dim: got[0]?.length ?? 0 });
351
+ return;
352
+ } catch (caught) {
353
+ err = caught;
354
+ }
355
+ // E1: THIS slice fails. Its siblings do not, and the caller is told which one
356
+ // and why — a null vector with no reason is the shape v1's "one bad item
357
+ // failed the whole run" incident was made of.
358
+ const code: EmbedRefusal = aborted()
359
+ ? "ABORTED"
360
+ : err instanceof EmbedError
361
+ ? err.code
362
+ : "BAD_RESPONSE";
363
+ const rawStatus = err instanceof EmbedError ? err.detail["status"] : undefined;
364
+ const status = typeof rawStatus === "number" ? rawStatus : undefined;
365
+ if (code !== "HTTP_ERROR" || status !== 400 || aborted()) {
366
+ whole(code, status);
367
+ return;
368
+ }
369
+ if (slice.length === 1) {
370
+ // THE POISON, alone and named. `item: true` is what lets the backfill count
371
+ // this id out instead of re-asking for it forever (I33).
372
+ whole(code, status, true);
373
+ return;
374
+ }
375
+ const mid = Math.ceil(slice.length / 2);
376
+ ctx.emit("embed.bisect", { chunk: ctx.chunk, from, count: slice.length, status: 400 });
377
+ await attempt(ctx, slice.slice(0, mid), from, land, fail, aborted);
378
+ await attempt(ctx, slice.slice(mid), from + mid, land, fail, aborted);
379
+ }
380
+
381
+ /** ONE request. Every failure here is an `EmbedError` so the caller can name it. */
382
+ async function callOnce(ctx: AttemptContext, input: readonly string[]): Promise<number[][]> {
383
+ const { doFetch, key, model } = ctx;
384
+ // THE BODY, AND ONLY THE BODY (I33 — see `wellFormed`).
385
+ const sanitized = wellFormed(input);
386
+ if (sanitized.changed > 0) {
387
+ ctx.emit("embed.sanitized", { chunk: ctx.chunk, count: sanitized.changed });
388
+ }
389
+ const response = await doFetch(VOYAGE_ENDPOINT, {
390
+ method: "POST",
391
+ headers: {
392
+ "content-type": "application/json",
393
+ // The credential is a HEADER. Never a query parameter: a URL is logged by
394
+ // every proxy between here and there.
395
+ authorization: `Bearer ${key}`,
396
+ },
397
+ body: JSON.stringify({ model, input: sanitized.input }),
398
+ ...(ctx.signal === undefined ? {} : { signal: ctx.signal }),
399
+ });
400
+
401
+ if (!response.ok) throw new EmbedError("HTTP_ERROR", { status: response.status });
402
+
403
+ let body: unknown;
404
+ try {
405
+ body = await response.json();
406
+ } catch {
407
+ throw new EmbedError("NO_BODY", {});
408
+ }
409
+ const data = (body as { data?: unknown } | null)?.data;
410
+ if (!Array.isArray(data)) throw new EmbedError("BAD_RESPONSE", { reason: "no-data-array" });
411
+
412
+ const out: number[][] = [];
413
+ for (const row of data) {
414
+ const vec = (row as { embedding?: unknown } | null)?.embedding;
415
+ if (!Array.isArray(vec) || vec.length === 0 || !vec.every((n) => typeof n === "number")) {
416
+ throw new EmbedError("BAD_RESPONSE", { reason: "no-embedding" });
417
+ }
418
+ out.push(vec as number[]);
419
+ }
420
+ // A short answer is a FAILURE, not data — the embeddings analogue of E2. Slot
421
+ // n of the response is the vector for input n; a response that dropped one
422
+ // would silently attach every later vector to the wrong text.
423
+ if (out.length !== input.length) {
424
+ throw new EmbedError("WRONG_VECTOR_COUNT", { asked: input.length, got: out.length });
425
+ }
426
+ return out;
427
+ }
428
+
429
+ // ═══════════════════════════════════════════════════════════════════════════
430
+ // The store-facing half: a SYNC embedder over an async client
431
+ // ═══════════════════════════════════════════════════════════════════════════
432
+
433
+ /**
434
+ * `store.Embedder` is synchronous — `put` and `rebuildCache` are — and an HTTP
435
+ * call is not. That mismatch is real and this is where it is handled honestly
436
+ * rather than papered over:
437
+ *
438
+ * - `vector()` / `warm()` are the LIVE half. They are called from paths that
439
+ * can await (the authored gate, the sweep's apply), and every vector they
440
+ * fetch lands in the cache.
441
+ * - `embed` is the SYNC half the store holds. It never opens a socket. It
442
+ * answers from the cache the live half filled, and a MISS returns `null` —
443
+ * a counted "not exercised", never an empty vector. (A zero-length vector
444
+ * written into box 3 would be a dim-0 row that every cosine reads as 0.0
445
+ * similarity: a lie with a number on it, which is exactly what
446
+ * `computeNovelty`'s null-with-reason design exists to avoid.)
447
+ *
448
+ * The cache is keyed by (model, hash of text): the model, because vectors from
449
+ * two generations are not comparable; the HASH, because a cache keyed by text is
450
+ * a copy of the store's contents in memory with no lifecycle.
451
+ */
452
+ export interface LiveEmbedder {
453
+ /** The seat's pinned id — the generation this cache holds. */
454
+ readonly model: string;
455
+ /** The sync face `Store.open({ embed })` takes. Cache only; never a socket. */
456
+ readonly embed: Embedder;
457
+ /** Fetch (or serve) one vector. Returns null on any refusal — never throws. */
458
+ vector(text: string): Promise<number[] | null>;
459
+ /** Fetch many in one batched call. Returns how many landed. Never throws. */
460
+ warm(texts: readonly string[]): Promise<number>;
461
+ readonly stats: () => EmbedderStats;
462
+ }
463
+
464
+ export interface EmbedderStats {
465
+ /** Sync lookups the cache answered. */
466
+ readonly hits: number;
467
+ /** Sync lookups it could not — the countable `not-exercised` (replay §4). */
468
+ readonly misses: number;
469
+ readonly cached: number;
470
+ /** Texts the live half asked the provider for. */
471
+ readonly fetched: number;
472
+ /** Texts the provider did not return a vector for, by any cause. */
473
+ readonly failed: number;
474
+ /**
475
+ * The failures of the LAST fill, verbatim — reset at the start of each one.
476
+ *
477
+ * The codes used to exist only inside this module: `embed.partial` put them in
478
+ * an event, the event went to the runner's ring, and the ring died with the
479
+ * detached process. So `adapter.embed.backfill` carried `failed: 64` with no
480
+ * way to tell a 429 from a 400 from a dead seat, and I33 ran for a week
481
+ * looking like "the Voyage side is failing". The backfill persists these now.
482
+ */
483
+ readonly lastFailures: readonly ChunkFailure[];
484
+ }
485
+
486
+ export interface LiveEmbedderOptions extends EmbedClientOptions {
487
+ /** Injected so a test can exercise the whole path without a socket. */
488
+ client?: EmbedFn;
489
+ }
490
+
491
+ export function createEmbedder(opts: LiveEmbedderOptions = {}): LiveEmbedder {
492
+ const emit = opts.onEvent ?? ((): void => {});
493
+ const client = opts.client ?? embedClient(opts);
494
+ const model = embedSeat(opts.config ?? {}, opts.today ?? new Date().toISOString().slice(0, 10)).id;
495
+ const cache = new Map<string, number[]>();
496
+ let hits = 0;
497
+ let misses = 0;
498
+ let fetched = 0;
499
+ let failed = 0;
500
+ let lastFailures: readonly ChunkFailure[] = [];
501
+
502
+ const keyOf = (text: string): string => `${model}\0${hashText(text)}`;
503
+
504
+ const embed: Embedder = (text: string): number[] | null => {
505
+ const hit = cache.get(keyOf(text));
506
+ if (hit === undefined) {
507
+ misses += 1;
508
+ // Content-by-reference: the HASH of the text that missed, never the text.
509
+ emit("embed.cache.miss", { hash: hashText(text), model });
510
+ return null;
511
+ }
512
+ hits += 1;
513
+ return hit;
514
+ };
515
+
516
+ const fill = async (texts: readonly string[]): Promise<number> => {
517
+ // Per fill, not cumulative: the caller asks "what went wrong THIS run".
518
+ // BEFORE the early return, so a fill the cache answered entirely reports an
519
+ // empty list rather than the previous fill's codes.
520
+ lastFailures = [];
521
+ const wanted = [...new Set(texts.filter((t) => t.length > 0 && !cache.has(keyOf(t))))];
522
+ if (wanted.length === 0) return 0;
523
+ let landed = 0;
524
+ try {
525
+ const batch = await client(wanted);
526
+ fetched += wanted.length;
527
+ for (let i = 0; i < wanted.length; i += 1) {
528
+ const vec = batch.vectors[i];
529
+ const text = wanted[i];
530
+ if (vec === null || vec === undefined || text === undefined) {
531
+ failed += 1;
532
+ continue;
533
+ }
534
+ cache.set(keyOf(text), vec);
535
+ landed += 1;
536
+ }
537
+ lastFailures = batch.failures;
538
+ if (batch.failures.length > 0) {
539
+ emit("embed.partial", {
540
+ chunks: batch.chunks,
541
+ failed: batch.failures.length,
542
+ codes: batch.failures.map((f) => f.code).join(","),
543
+ });
544
+ }
545
+ } catch (err) {
546
+ // THE WHOLE CALL REFUSED, and it still owes a code (I33's own lesson,
547
+ // applied to the one path that was exempt from it). `embedClient` throws
548
+ // before it opens a socket for a missing key, a dead seat or no `fetch`,
549
+ // so `failures` was never built and `lastFailures` stayed EMPTY — which is
550
+ // how `adapter.embed.backfill` came to carry `failed: 64, codes: ""`, the
551
+ // unreadable row that field exists to abolish. One synthetic whole-slice
552
+ // entry, carrying the code and nothing else it cannot vouch for.
553
+ lastFailures = [
554
+ {
555
+ chunk: 0,
556
+ from: 0,
557
+ count: wanted.length,
558
+ code: err instanceof EmbedError ? err.code : "BAD_RESPONSE",
559
+ },
560
+ ];
561
+ // A refusal the whole call shares (no key, dead seat, no fetch). It is
562
+ // NULL to the caller: an embedder that cannot embed must never fail a
563
+ // deposit — box 3 is rebuildable, a memory is not.
564
+ //
565
+ // It is not re-emitted here. `embedClient` already emitted `embed.refused`
566
+ // with the code, through THIS emitter, and one refusal logged twice is a
567
+ // rate nobody can read. (An injected `client` that emits nothing is a test
568
+ // affordance; production always goes through the client above.)
569
+ failed += wanted.length;
570
+ }
571
+ return landed;
572
+ };
573
+
574
+ return {
575
+ model,
576
+ embed,
577
+ async vector(text: string): Promise<number[] | null> {
578
+ if (text.length === 0) return null;
579
+ const key = keyOf(text);
580
+ const hit = cache.get(key);
581
+ if (hit !== undefined) return hit;
582
+ await fill([text]);
583
+ return cache.get(key) ?? null;
584
+ },
585
+ warm: fill,
586
+ stats: (): EmbedderStats => ({
587
+ hits,
588
+ misses,
589
+ cached: cache.size,
590
+ fetched,
591
+ failed,
592
+ lastFailures: [...lastFailures],
593
+ }),
594
+ };
595
+ }
596
+
597
+ /**
598
+ * Build this host's embedder, or say — by returning null — that there is none.
599
+ * Both composition roots (`openAdapter`, `bin/runner.ts`) go through here, so
600
+ * "when is there an embedder" has ONE answer rather than one per entrance.
601
+ *
602
+ * THE KNOB IS THE GATE, NOT THE CREDENTIAL. A `VOYAGE_API_KEY` exported for some
603
+ * other tool is not consent to ship this store's text to a third party (v2's
604
+ * no-silent-egress rescope), so `embedder.enabled` must be explicitly true.
605
+ * When it is true and the key is missing, the client refuses BY NAME on its
606
+ * first call — `NO_API_KEY`, before any socket — and that check is the client's,
607
+ * never a second copy written here that could drift from it.
608
+ */
609
+ export function openEmbedder(
610
+ config: AdapterConfig,
611
+ opts: Omit<LiveEmbedderOptions, "config"> = {},
612
+ ): LiveEmbedder | null {
613
+ if (config.embedder?.enabled !== true) return null;
614
+ // An instrument opens no sockets (docs/observer-mode.md, scar E7).
615
+ if (config.observer === true) return null;
616
+ return createEmbedder({ config, ...opts });
617
+ }