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,239 @@
1
+ /**
2
+ * THE OQ4 PROBE — is the "quietly available / ignorable" framing actually
3
+ * ignorable to a model? (CONTRACT §7, open question 4; v1 shipped the phrasing
4
+ * as a deliberate probe and never measured it.)
5
+ *
6
+ * The measurement, from rows the store already keeps and nothing else:
7
+ *
8
+ * `recall.decision` — per turn, the footnote ids DELIVERED (`footnotes[].id`)
9
+ * `recall.credit` — per session-ending boundary, the ids the assistant
10
+ * EXPANDED through deliberate recall (`expandedIds`)
11
+ *
12
+ * For each session: footnotes delivered (distinct ids), and how many of those
13
+ * the assistant expanded IN THE SAME SESSION — the one behaviour the header is
14
+ * meant to invite or not. "Same session", not "later": the rows carry no turn
15
+ * order across the two names, so an id expanded on turn 2 and footnoted on
16
+ * turn 9 counts; the bias is the same on both sides of the before/after.
17
+ * Aggregated by calendar date so a change to the header (one string,
18
+ * `render.ts#FRAMING.footnoteHeader`) reads as a before/after on the same
19
+ * table. No model, no prose, no ranking; ids and counts only.
20
+ *
21
+ * A day is MEASURED only when at least one `recall.credit` row exists for it.
22
+ * `expandedIds` reached the credit row with the credit seam (2026-09-14); a
23
+ * day with decision rows and no credit rows prints "-", not 0.000 — nothing
24
+ * recorded what was expanded, so nothing is known. Zero and unknown never
25
+ * share a glyph.
26
+ *
27
+ * What this does NOT claim: causation. A session that expanded nothing may
28
+ * have had nothing worth expanding. The probe answers "did the behaviour move
29
+ * when the string moved", which is the question OQ4 asks, and leaves the
30
+ * ruling to the owner.
31
+ */
32
+
33
+ /**
34
+ * Rows a console fetches per event name. The store's `eventLog` defaults to
35
+ * 500, oldest first, which would silently drop the NEWEST rows — the step-1
36
+ * side of the table — once the log grows past it (review of #104, H1). The
37
+ * dashboard reads under the same ceiling.
38
+ */
39
+ export const PROBE_ROW_CEILING = 20_000;
40
+
41
+ export interface ProbeRow {
42
+ readonly name: string;
43
+ readonly day: number;
44
+ /** JSON as stored. Unparseable rows are counted, never thrown on. */
45
+ readonly payload: string | null;
46
+ }
47
+
48
+ export interface ProbeSession {
49
+ readonly session: string;
50
+ readonly date: string | null;
51
+ readonly turns: number;
52
+ readonly footnotesDelivered: number;
53
+ readonly loudDelivered: number;
54
+ readonly expanded: number;
55
+ /** Footnote ids delivered in this session that were also expanded in it. */
56
+ readonly footnotesExpanded: number;
57
+ /** `recall.credit` rows seen for this session; 0 means expansion was never recorded. */
58
+ readonly credits: number;
59
+ }
60
+
61
+ export interface ProbeDay {
62
+ readonly date: string;
63
+ readonly sessions: number;
64
+ readonly turns: number;
65
+ readonly footnotesDelivered: number;
66
+ readonly footnotesExpanded: number;
67
+ readonly expanded: number;
68
+ /** `recall.credit` rows on this date. A day with none is unmeasured. */
69
+ readonly credits: number;
70
+ /** footnotesExpanded / footnotesDelivered; null when nothing was delivered
71
+ * OR when no credit row exists for the day (unmeasured, not zero). */
72
+ readonly ratio: number | null;
73
+ }
74
+
75
+ export interface ProbeReport {
76
+ readonly sessions: ProbeSession[];
77
+ readonly days: ProbeDay[];
78
+ readonly decisions: number;
79
+ readonly credits: number;
80
+ readonly unparseable: number;
81
+ /** Over MEASURED days only (at least one credit row). */
82
+ readonly totals: {
83
+ readonly footnotesDelivered: number;
84
+ readonly footnotesExpanded: number;
85
+ readonly ratio: number | null;
86
+ };
87
+ /** Days with decision rows and no credit row, and the footnotes they delivered. */
88
+ readonly unmeasured: { readonly days: number; readonly footnotesDelivered: number };
89
+ }
90
+
91
+ interface Acc {
92
+ session: string;
93
+ date: string | null;
94
+ turns: number;
95
+ footnotes: Set<string>;
96
+ loud: Set<string>;
97
+ expanded: Set<string>;
98
+ credits: number;
99
+ }
100
+
101
+ function ids(v: unknown): string[] {
102
+ if (!Array.isArray(v)) return [];
103
+ const out: string[] = [];
104
+ for (const x of v) {
105
+ if (typeof x === "string") out.push(x);
106
+ else if (x !== null && typeof x === "object" && typeof (x as { id?: unknown }).id === "string") {
107
+ out.push((x as { id: string }).id);
108
+ }
109
+ }
110
+ return out;
111
+ }
112
+
113
+ export function probeOQ4(rows: readonly ProbeRow[]): ProbeReport {
114
+ const acc = new Map<string, Acc>();
115
+ let decisions = 0;
116
+ let credits = 0;
117
+ let unparseable = 0;
118
+ const get = (session: string, date: string | null): Acc => {
119
+ let a = acc.get(session);
120
+ if (a === undefined) {
121
+ a = { session, date, turns: 0, footnotes: new Set(), loud: new Set(), expanded: new Set(), credits: 0 };
122
+ acc.set(session, a);
123
+ }
124
+ if (a.date === null && date !== null) a.date = date;
125
+ return a;
126
+ };
127
+ for (const row of rows) {
128
+ if (row.name !== "recall.decision" && row.name !== "recall.credit") continue;
129
+ let p: Record<string, unknown>;
130
+ try {
131
+ p = JSON.parse(row.payload ?? "") as Record<string, unknown>;
132
+ if (p === null || typeof p !== "object") throw new Error("not an object");
133
+ } catch {
134
+ unparseable += 1;
135
+ continue;
136
+ }
137
+ const session = typeof p["session"] === "string" ? p["session"] : null;
138
+ if (session === null) {
139
+ unparseable += 1;
140
+ continue;
141
+ }
142
+ const date = typeof p["date"] === "string" ? p["date"] : null;
143
+ const a = get(session, date);
144
+ if (row.name === "recall.decision") {
145
+ decisions += 1;
146
+ a.turns += 1;
147
+ for (const id of ids(p["footnotes"])) a.footnotes.add(id);
148
+ for (const id of ids(p["surfaced"])) a.loud.add(id);
149
+ } else {
150
+ credits += 1;
151
+ a.credits += 1;
152
+ for (const id of ids(p["expandedIds"])) a.expanded.add(id);
153
+ }
154
+ }
155
+
156
+ const sessions: ProbeSession[] = [];
157
+ for (const a of acc.values()) {
158
+ let hit = 0;
159
+ for (const id of a.footnotes) if (a.expanded.has(id)) hit += 1;
160
+ sessions.push({
161
+ session: a.session,
162
+ date: a.date,
163
+ turns: a.turns,
164
+ footnotesDelivered: a.footnotes.size,
165
+ loudDelivered: a.loud.size,
166
+ expanded: a.expanded.size,
167
+ footnotesExpanded: hit,
168
+ credits: a.credits,
169
+ });
170
+ }
171
+ sessions.sort((x, y) => (x.date ?? "").localeCompare(y.date ?? "") || x.session.localeCompare(y.session));
172
+
173
+ const byDay = new Map<string, { sessions: number; turns: number; fd: number; fe: number; ex: number; cr: number }>();
174
+ for (const s of sessions) {
175
+ const key = s.date ?? "undated";
176
+ const d = byDay.get(key) ?? { sessions: 0, turns: 0, fd: 0, fe: 0, ex: 0, cr: 0 };
177
+ d.sessions += 1;
178
+ d.turns += s.turns;
179
+ d.fd += s.footnotesDelivered;
180
+ d.fe += s.footnotesExpanded;
181
+ d.ex += s.expanded;
182
+ d.cr += s.credits;
183
+ byDay.set(key, d);
184
+ }
185
+ const days: ProbeDay[] = [...byDay.entries()]
186
+ .sort(([a], [b]) => a.localeCompare(b))
187
+ .map(([date, d]) => ({
188
+ date,
189
+ sessions: d.sessions,
190
+ turns: d.turns,
191
+ footnotesDelivered: d.fd,
192
+ footnotesExpanded: d.fe,
193
+ expanded: d.ex,
194
+ credits: d.cr,
195
+ ratio: d.fd === 0 || d.cr === 0 ? null : d.fe / d.fd,
196
+ }));
197
+
198
+ const measured = days.filter((d) => d.credits > 0);
199
+ const fd = measured.reduce((n, d) => n + d.footnotesDelivered, 0);
200
+ const fe = measured.reduce((n, d) => n + d.footnotesExpanded, 0);
201
+ const unmeasuredDays = days.filter((d) => d.credits === 0);
202
+ return {
203
+ sessions,
204
+ days,
205
+ decisions,
206
+ credits,
207
+ unparseable,
208
+ totals: { footnotesDelivered: fd, footnotesExpanded: fe, ratio: fd === 0 ? null : fe / fd },
209
+ unmeasured: {
210
+ days: unmeasuredDays.length,
211
+ footnotesDelivered: unmeasuredDays.reduce((n, d) => n + d.footnotesDelivered, 0),
212
+ },
213
+ };
214
+ }
215
+
216
+ /** The table a console prints. One line per day, then the totals over measured days. */
217
+ export function renderProbe(report: ProbeReport): string[] {
218
+ const lines: string[] = [];
219
+ lines.push("OQ4 probe — footnotes delivered vs. later expanded, by calendar date");
220
+ lines.push(`rows: ${report.decisions} recall.decision, ${report.credits} recall.credit, ${report.unparseable} unparseable`);
221
+ lines.push("");
222
+ lines.push("date sessions turns footnotes expanded-footnotes expanded-total credits ratio");
223
+ for (const d of report.days) {
224
+ lines.push(
225
+ `${d.date.padEnd(11)} ${String(d.sessions).padStart(8)} ${String(d.turns).padStart(5)} ${String(d.footnotesDelivered).padStart(9)} ${String(d.footnotesExpanded).padStart(18)} ${String(d.expanded).padStart(14)} ${String(d.credits).padStart(7)} ${d.ratio === null ? " -" : d.ratio.toFixed(3)}`,
226
+ );
227
+ }
228
+ lines.push("");
229
+ const t = report.totals;
230
+ lines.push(
231
+ `measured: ${t.footnotesDelivered} footnotes delivered, ${t.footnotesExpanded} expanded in the same session${t.ratio === null ? "" : ` (${(t.ratio * 100).toFixed(1)}%)`}`,
232
+ );
233
+ if (report.unmeasured.days > 0) {
234
+ lines.push(
235
+ `unmeasured: ${report.unmeasured.days} day(s) with no recall.credit row, ${report.unmeasured.footnotesDelivered} footnotes delivered — "-" is unknown, not zero`,
236
+ );
237
+ }
238
+ return lines;
239
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Reference resolution (CONTRACT §9.2) — which memories a session's replies
3
+ * actually USED, decided from the assistant's own turns and nothing else.
4
+ *
5
+ * This is the consumer INTERFACE-GAPS §5 said had no home: `resolveUse` routes
6
+ * a DECIDED tier to physics, and until this module nothing decided one. The
7
+ * live consequence, measured 2026-09-14 on the owner's store: every memory
8
+ * minted since launch sat at `uses = 0`, `reinforced_days = 0`, so nothing new
9
+ * could ever cross into the semantic or identity bands (IMPROVEMENTS U10).
10
+ *
11
+ * THE RULE (owner ruling 2026-09-14): a memory is credited when the assistant
12
+ * EXPANDED it through deliberate recall, or QUOTED it at content level. Never
13
+ * for being named in prose, never for being surfaced, never for being rendered
14
+ * in a wake. Reinforcement is for thinking with a memory, not for having been
15
+ * shown it.
16
+ *
17
+ * Two doors, and what each one can see:
18
+ *
19
+ * **Expanded.** The assistant called the recall tool with `ids` or a
20
+ * `handle`. The call is an assistant turn; its `input` is the evidence. Ids
21
+ * are taken from the tool call's input ONLY — never parsed out of prose. The
22
+ * fixture: on 2026-09-14 the model wrote five `[mem_…]` ids into a reply
23
+ * having read none of them (IMPROVEMENTS U5). A `handle` that is not itself a
24
+ * memory id is counted `unresolvedHandles` and credits nothing here: this
25
+ * module resolves nothing fuzzily, and the tool's own answer was already
26
+ * exact or not-found.
27
+ *
28
+ * **Quoted.** A run of `QUOTE_WINDOW_WORDS` consecutive words of a memory's
29
+ * body appears verbatim (normalized) in an assistant `conversation` turn.
30
+ * Only a memory that surfaced LOUD is a candidate: a footnoted memory showed
31
+ * the model nothing but an 80-byte title, so any quote of it is naming, and a
32
+ * memory the model expanded is credited by the expansion. Paraphrase misses.
33
+ * That is the contract's bar — precision over recall: a false "used" pollutes
34
+ * learning permanently, a miss merely leaves weak credit — and the reason
35
+ * bansai's IDF token overlap (`consolidate/thread-match.ts`) was NOT ported:
36
+ * an overlap score credits co-mention, a verbatim window credits use.
37
+ *
38
+ * What this module never does: read the store (bodies arrive on the input),
39
+ * call a model, read a file, or judge agreement. A memory the assistant
40
+ * expanded and then argued with is credited — contradiction is engagement,
41
+ * and physics §5.5 counts distinct days, not endorsement.
42
+ *
43
+ * Pure and synchronous: the boundary hook runs under a latency budget, so the
44
+ * caller passes a `deadline` and the resolver stops between candidates rather
45
+ * than truncating silently — an overrun is REPORTED (`budgetExceeded`), and
46
+ * what was decided before it stands.
47
+ */
48
+
49
+ export const QUOTE_WINDOW_WORDS = 8;
50
+
51
+ /**
52
+ * Owner ruling 2026-09-14 (R3, review of #99): a matching window must carry at
53
+ * least this many NON-stopword tokens, or it is boilerplate, not a quote.
54
+ * Repro that forced it: body "I think it would be a good idea to keep …" and a
55
+ * reply "I think it would be a good idea to move on" share eight words and
56
+ * say nothing about the memory.
57
+ */
58
+ export const QUOTE_CONTENT_WORDS = 3;
59
+
60
+ /** Function words that carry no content. Small on purpose: the floor is a
61
+ * guard against boilerplate, not a linguistics project. */
62
+ export const STOPWORDS: ReadonlySet<string> = new Set([
63
+ "a", "an", "the", "and", "or", "but", "so", "if", "then", "than", "as", "at", "by", "for", "from",
64
+ "in", "into", "of", "on", "onto", "to", "up", "with", "without", "about", "over", "under",
65
+ "i", "me", "my", "we", "us", "our", "you", "your", "he", "him", "his", "she", "her", "it", "its",
66
+ "they", "them", "their", "this", "that", "these", "those", "there", "here", "what", "which", "who",
67
+ "is", "am", "are", "was", "were", "be", "been", "being", "do", "does", "did", "have", "has", "had",
68
+ "will", "would", "can", "could", "should", "may", "might", "must", "shall",
69
+ "not", "no", "yes", "just", "very", "really", "also", "too", "only", "still", "even", "again",
70
+ "think", "thought", "good", "idea", "keep", "make", "made", "get", "got", "go", "going", "want",
71
+ "like", "know", "see", "say", "said", "way", "thing", "things", "some", "any", "all", "more", "most",
72
+ "one", "two", "how", "when", "where", "why", "because", "well", "now", "let", "lets",
73
+ ]);
74
+
75
+ /** A memory id as the store mints them. Anything else is not an address. */
76
+ export const MEMORY_ID = /^mem_[0-9a-f]{12,16}$/;
77
+
78
+ export type ReferenceHow = "expanded" | "quoted";
79
+
80
+ export interface ReferenceCandidate {
81
+ readonly id: string;
82
+ /** Only `surfaced` is quotable; `footnoted` is listed for the accounting. */
83
+ readonly tier: "surfaced" | "footnoted";
84
+ /** Canonical body. Never rendered anywhere by this module. */
85
+ readonly body: string;
86
+ }
87
+
88
+ export interface ReferenceInput {
89
+ /** Assistant `conversation` text for the slice under judgment, in order. */
90
+ readonly assistantTurns: readonly string[];
91
+ /** Raw `ids` / `handle` values from recall tool calls in the same slice. */
92
+ readonly expansions: readonly string[];
93
+ readonly candidates: readonly ReferenceCandidate[];
94
+ /** `Date.now()`-comparable; the resolver stops between candidates past it. */
95
+ readonly deadline?: number;
96
+ readonly now?: () => number;
97
+ }
98
+
99
+ export interface ReferenceUse {
100
+ readonly memoryId: string;
101
+ readonly how: ReferenceHow;
102
+ }
103
+
104
+ export interface ReferenceResult {
105
+ readonly uses: readonly ReferenceUse[];
106
+ readonly expanded: number;
107
+ readonly quoted: number;
108
+ /** Candidates looked at before the deadline (or all of them). */
109
+ readonly considered: number;
110
+ /** Loud candidates never compared because the deadline hit first. */
111
+ readonly skippedForBudget: number;
112
+ readonly unresolvedHandles: number;
113
+ readonly budgetExceeded: boolean;
114
+ }
115
+
116
+ /** Lowercase alphanumeric words, in order. The one normalization, used on both sides. */
117
+ export function normalizeWords(text: string): string[] {
118
+ return text
119
+ .toLowerCase()
120
+ .replace(/[^a-z0-9]+/g, " ")
121
+ .trim()
122
+ .split(" ")
123
+ .filter((w) => w.length > 0);
124
+ }
125
+
126
+ /** Content tokens in a run of words: what is left after the stopwords. */
127
+ export function contentWords(words: readonly string[]): number {
128
+ let n = 0;
129
+ for (const w of words) if (!STOPWORDS.has(w)) n += 1;
130
+ return n;
131
+ }
132
+
133
+ /**
134
+ * True when some `window`-word run of `body` appears verbatim in `text` AND
135
+ * that run carries at least `QUOTE_CONTENT_WORDS` content tokens (R3). A run
136
+ * of function words shared by two sentences is boilerplate, not a quote.
137
+ * O(|text| + |body|): the text's windows go into a set once, the body's are
138
+ * looked up.
139
+ */
140
+ export function quotesWindow(body: string, text: string, window: number = QUOTE_WINDOW_WORDS): boolean {
141
+ const t = normalizeWords(text);
142
+ const b = normalizeWords(body);
143
+ if (t.length < window || b.length < window) return false;
144
+ const seen = new Set<string>();
145
+ for (let i = 0; i + window <= t.length; i++) seen.add(t.slice(i, i + window).join(" "));
146
+ for (let i = 0; i + window <= b.length; i++) {
147
+ const run = b.slice(i, i + window);
148
+ if (seen.has(run.join(" ")) && contentWords(run) >= QUOTE_CONTENT_WORDS) return true;
149
+ }
150
+ return false;
151
+ }
152
+
153
+ export function resolveReferences(input: ReferenceInput): ReferenceResult {
154
+ const now = input.now ?? Date.now;
155
+ const uses: ReferenceUse[] = [];
156
+ const credited = new Set<string>();
157
+ let unresolvedHandles = 0;
158
+
159
+ // Door one: expansions. Exact addresses only, each memory once.
160
+ for (const raw of input.expansions) {
161
+ const id = raw.trim();
162
+ if (!MEMORY_ID.test(id)) {
163
+ unresolvedHandles += 1;
164
+ continue;
165
+ }
166
+ if (credited.has(id)) continue;
167
+ credited.add(id);
168
+ uses.push({ memoryId: id, how: "expanded" });
169
+ }
170
+ const expanded = uses.length;
171
+
172
+ // Door two: verbatim windows against what surfaced loud, one turn at a
173
+ // time: a quote split across two assistant turns is not a quote.
174
+ const turns = input.assistantTurns.filter((t) => t.trim().length > 0);
175
+ let considered = 0;
176
+ let skippedForBudget = 0;
177
+ let budgetExceeded = false;
178
+ for (const c of input.candidates) {
179
+ if (input.deadline !== undefined && now() > input.deadline) {
180
+ budgetExceeded = true;
181
+ if (c.tier === "surfaced" && !credited.has(c.id)) skippedForBudget += 1;
182
+ continue;
183
+ }
184
+ considered += 1;
185
+ if (c.tier !== "surfaced" || credited.has(c.id)) continue;
186
+ if (turns.some((text) => quotesWindow(c.body, text))) {
187
+ credited.add(c.id);
188
+ uses.push({ memoryId: c.id, how: "quoted" });
189
+ }
190
+ }
191
+
192
+ return {
193
+ uses,
194
+ expanded,
195
+ quoted: uses.length - expanded,
196
+ considered,
197
+ skippedForBudget,
198
+ unresolvedHandles,
199
+ budgetExceeded,
200
+ };
201
+ }