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,275 @@
1
+ /**
2
+ * Cues — what the turn is *about*, before anything is looked up.
3
+ *
4
+ * Two rules do most of the work here, both measured in v1:
5
+ *
6
+ * §9 G3 — **host boilerplate is stripped before cue extraction and before
7
+ * embedding.** Injected context, image placeholders and command echoes are not
8
+ * experience. (Measured: an image placeholder token surfaced an unrelated
9
+ * image-cache memory.) The strippers are a NAMED TABLE so a test can enumerate
10
+ * them; a regex buried in a function is not an auditable rule.
11
+ *
12
+ * §9 G4 — **cue matching is word-bounded and rarity-weighted.** A distinctive
13
+ * proper noun fires strongly; a name spanning the whole store contributes
14
+ * nothing. *Informativeness weighting replaces stop-lists* — there is no stop
15
+ * list in this file, deliberately: "the" scores zero because it is everywhere,
16
+ * which is the same reason a project name scores zero once every memory
17
+ * mentions it.
18
+ *
19
+ * Word-boundedness is inherited, not re-implemented: `tokenize` comes from the
20
+ * store's cache module, so a cue is tokenized byte-for-byte the way the index was
21
+ * built. A second tokenizer here would be the observer-predicate mistake in
22
+ * miniature (observer-mode.md G7).
23
+ *
24
+ * NO MODEL CALLS. Vectors are inputs (contract §5 G1) — this file has no network
25
+ * import and no client; the turn's embedding arrives from the caller or not at all,
26
+ * and its absence degrades to lexical-only rather than failing.
27
+ */
28
+ import { tokenize } from "../store/index.js";
29
+ import type { RecallTunables } from "./tunables.js";
30
+
31
+ /** One host-boilerplate stripper. Named, so the totality test can enumerate them. */
32
+ export interface Stripper {
33
+ readonly name: string;
34
+ readonly why: string;
35
+ readonly pattern: RegExp;
36
+ }
37
+
38
+ /**
39
+ * The strip table. Order is irrelevant (each pass is independent); membership is
40
+ * the point. `counterparts-injection` is the self-reference guard: recall's own
41
+ * render lands in the transcript, and re-cueing on it would make every surfaced
42
+ * memory permanently self-confirming.
43
+ */
44
+ export const STRIPPERS: readonly Stripper[] = [
45
+ {
46
+ name: "system-reminder",
47
+ why: "Host-injected context. Not the user's experience.",
48
+ pattern: /<system-reminder>[\s\S]*?<\/system-reminder>/gi,
49
+ },
50
+ {
51
+ name: "command-echo",
52
+ why: "Slash-command echoes and their stdout are the tool talking, not the turn.",
53
+ pattern:
54
+ /<(command-name|command-message|command-args|local-command-stdout|local-command-stderr)>[\s\S]*?<\/\1>/gi,
55
+ },
56
+ {
57
+ name: "image-placeholder",
58
+ why: "MEASURED (v1 §9 G3): an image placeholder token surfaced an unrelated image-cache memory.",
59
+ pattern: /\[(?:image|screenshot|attachment)[^\]]*\]/gi,
60
+ },
61
+ {
62
+ name: "data-uri",
63
+ why: "Base64 payloads mint thousands of junk tokens and no meaning.",
64
+ pattern: /data:[a-z]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi,
65
+ },
66
+ {
67
+ name: "counterparts-injection",
68
+ why: "Recall's own render. Re-cueing on it makes every surfaced memory self-confirming.",
69
+ pattern: /<!--\s*counterparts:recall[\s\S]*?counterparts:recall\/end[^>]*-->/gi,
70
+ },
71
+ {
72
+ name: "tool-result-block",
73
+ why: "Tool output is the environment answering, not the user speaking.",
74
+ pattern: /<(function_results|tool_result)>[\s\S]*?<\/\1>/gi,
75
+ },
76
+ ];
77
+
78
+ /** Strip host boilerplate. Returns the text and which strippers actually fired. */
79
+ export function stripBoilerplate(text: string): { text: string; stripped: string[] } {
80
+ let out = text;
81
+ const fired: string[] = [];
82
+ for (const s of STRIPPERS) {
83
+ const next = out.replace(s.pattern, " ");
84
+ if (next !== out) fired.push(s.name);
85
+ out = next;
86
+ }
87
+ return { text: out, stripped: fired };
88
+ }
89
+
90
+ /**
91
+ * The smallest store on which "this token spans the whole store" says anything.
92
+ *
93
+ * Rarity is a statement about ALTERNATIVES — a token is uninformative because
94
+ * the memories it does not distinguish exist. With one memory there are no
95
+ * alternatives, so "in every memory" and "in the only memory there is" are the
96
+ * same sentence, and reading the first one is a category error rather than a
97
+ * measurement. Below this size the store is read as one of exactly this size:
98
+ * the smallest store where the zero means what §9 G4 says it means.
99
+ *
100
+ * Definitional, not tunable — it is the domain of the rule, not a dial — so it
101
+ * lives here beside the function and not in `tunables.ts`.
102
+ */
103
+ export const MIN_RARITY_STORE = 2;
104
+
105
+ /**
106
+ * Informativeness (inverse document frequency), smoothed so it is defined for a
107
+ * two-document store and EXACTLY ZERO for a token that spans the whole store
108
+ * (for `storeSize >= MIN_RARITY_STORE` — see the constant for the one-memory
109
+ * degeneracy and why it is not an exception to the rule but its domain).
110
+ * That zero is the point: it is what replaces the stop list.
111
+ *
112
+ * MEASURED 2026-09-04, the bug that named the constant: on a store of ONE the
113
+ * literal reading returns `log((1 + 1) / (2 * 1))` = `log(1)` = exactly zero for
114
+ * every token, `buildCues` drops every zero-weight cue, and the index is never
115
+ * probed — so the first memory anyone writes was uncueable until a second,
116
+ * unrelated one arrived. `recall` answered `nothing-came, considered: 0,
117
+ * storeSize: 1` while the `handle` and `ids` paths returned the same memory.
118
+ */
119
+ export function informativeness(df: number, storeSize: number): number {
120
+ if (df <= 0 || storeSize <= 0) return 0;
121
+ return Math.max(0, Math.log((Math.max(storeSize, MIN_RARITY_STORE) + df) / (2 * df)));
122
+ }
123
+
124
+ /** Saturating term frequency: a word repeated ten times is not ten cues. */
125
+ export function tfFactor(tf: number): number {
126
+ if (tf <= 0) return 0;
127
+ return (2 * tf) / (tf + 1);
128
+ }
129
+
130
+ export interface Cue {
131
+ readonly token: string;
132
+ /** Rarity weight, after ambiguity discount and carry-over decay. */
133
+ readonly weight: number;
134
+ /** Occurrences in the turn (pre-saturation). */
135
+ readonly tf: number;
136
+ /** A handle pointing at more than one memory: fires at reduced weight AND
137
+ * trains nothing. Both halves — the training half is enforced in
138
+ * `Recall.resolveUse`, which is a real consumer, not a comment (scar §2.6). */
139
+ readonly ambiguous: boolean;
140
+ /** Carried from the previous turn at CARRY_DECAY, for one turn only. */
141
+ readonly carried: boolean;
142
+ }
143
+
144
+ export interface CueInput {
145
+ /** Already stripped. */
146
+ readonly text: string;
147
+ /** Cues carried from the previous turn (see `GateState.carriedCues`). */
148
+ readonly carried?: readonly string[];
149
+ /** handle -> memory ids. Caller-supplied until `encode/` owns an alias index
150
+ * (INTERFACE-GAPS.md #2). A handle with >= 2 ids is ambiguous. */
151
+ readonly aliases?: ReadonlyMap<string, readonly string[]>;
152
+ /** Live memory count, for informativeness. */
153
+ readonly storeSize: number;
154
+ /** token -> document frequency, measured against the index. */
155
+ readonly df: ReadonlyMap<string, number>;
156
+ }
157
+
158
+ /**
159
+ * Turn text -> weighted cues. Pure: every corpus statistic it needs arrives in
160
+ * `CueInput`, so this function is testable without a store and cannot smuggle in
161
+ * an I/O call on the hot path.
162
+ */
163
+ export function buildCues(input: CueInput, t: RecallTunables): Cue[] {
164
+ const counts = new Map<string, number>();
165
+ for (const tok of tokenize(input.text)) {
166
+ if (tok.length < t.MIN_CUE_LENGTH) continue;
167
+ counts.set(tok, (counts.get(tok) ?? 0) + 1);
168
+ }
169
+ const cues: Cue[] = [];
170
+ const seen = new Set<string>();
171
+ for (const [token, tf] of counts) {
172
+ const df = input.df.get(token) ?? 0;
173
+ const idf = informativeness(df, input.storeSize);
174
+ if (idf <= 0) continue;
175
+ const ids = input.aliases?.get(token);
176
+ const ambiguous = ids !== undefined && ids.length >= 2;
177
+ const weight = idf * tfFactor(tf) * (ambiguous ? t.AMBIGUOUS_WEIGHT : 1);
178
+ if (weight <= 0) continue;
179
+ seen.add(token);
180
+ cues.push({ token, weight, tf, ambiguous, carried: false });
181
+ }
182
+ for (const token of input.carried ?? []) {
183
+ if (seen.has(token)) continue;
184
+ const df = input.df.get(token) ?? 0;
185
+ const idf = informativeness(df, input.storeSize);
186
+ if (idf <= 0) continue;
187
+ const ids = input.aliases?.get(token);
188
+ const ambiguous = ids !== undefined && ids.length >= 2;
189
+ const weight = idf * t.CARRY_DECAY * (ambiguous ? t.AMBIGUOUS_WEIGHT : 1);
190
+ if (weight <= 0) continue;
191
+ seen.add(token);
192
+ cues.push({ token, weight, tf: 0, ambiguous, carried: true });
193
+ }
194
+ cues.sort((a, b) => b.weight - a.weight || (a.token < b.token ? -1 : 1));
195
+ return cues.slice(0, t.MAX_CUES);
196
+ }
197
+
198
+ // ---------------------------------------------------------------------------
199
+ // Affect — turn-gated, and that gate is the safety property (§9 G10, G11)
200
+ // ---------------------------------------------------------------------------
201
+
202
+ /**
203
+ * A small, NAMED list of stated-feeling words. This is not a stop list wearing a
204
+ * hat: informativeness weighting answers "which words are cues", and this answers
205
+ * a different question — "does the present turn carry feeling at all". v1's
206
+ * emotion rule is stated-only (never inferred), so a fixed vocabulary is the
207
+ * honest implementation and its smallness is visible rather than hidden in a model.
208
+ */
209
+ export const FEELING_WORDS: readonly string[] = [
210
+ "afraid", "angry", "anxious", "ashamed", "bitter", "dread", "excited", "frustrated",
211
+ "grateful", "grief", "guilty", "happy", "hurt", "lonely", "nervous", "overwhelmed",
212
+ "proud", "regret", "relieved", "sad", "scared", "stressed", "terrified", "tired",
213
+ "upset", "worried",
214
+ ];
215
+
216
+ /**
217
+ * SUBJECT-position first person only. "me", "us" and "our" are deliberately
218
+ * absent: *"she told me that Robin was upset"* is a third party's feeling
219
+ * reported to the speaker, and reading it as the speaker's own is precisely the
220
+ * mood-congruent overgeneralization G11 exists to prevent.
221
+ */
222
+ const FIRST_PERSON = new Set(["i", "im", "ive", "id", "my", "mine", "myself", "we", "weve"]);
223
+
224
+ /** Scanning back stops here: another subject owns the feeling. */
225
+ const THIRD_PERSON = new Set(["he", "she", "they", "her", "his", "their", "theyre", "you", "youre"]);
226
+
227
+ const FEELING = new Set(FEELING_WORDS);
228
+
229
+ export interface AffectSignal {
230
+ /** ANY subject stated a feeling. The FLAG is subject-inclusive (§9 G11). */
231
+ readonly stated: boolean;
232
+ /** The speaker stated their OWN feeling. The retrieval CUE is first-person
233
+ * only — the guard against mood-congruent overgeneralization (§9 G11). */
234
+ readonly selfFelt: boolean;
235
+ /** The feeling word that fired, for telemetry. Content-by-reference: it is a
236
+ * vocabulary index, not turn text. */
237
+ readonly word: string | null;
238
+ }
239
+
240
+ /** Look back this far for a first-person subject ("I have been feeling pretty tired"). */
241
+ const SUBJECT_WINDOW = 5;
242
+
243
+ /**
244
+ * Affect detection is NOT index matching, so it does not use the store's
245
+ * `tokenize`: that one drops tokens shorter than two characters, which throws
246
+ * away the single most important word here — "I". The subject rule of §9 G11 is
247
+ * unimplementable on a tokenizer that cannot see the first person.
248
+ */
249
+ function words(text: string): string[] {
250
+ return text
251
+ .toLowerCase()
252
+ .replace(/['’]/g, "")
253
+ .split(/[^a-z0-9]+/)
254
+ .filter((w) => w.length > 0);
255
+ }
256
+
257
+ export function detectAffect(text: string): AffectSignal {
258
+ const toks = words(text);
259
+ let stated = false;
260
+ let word: string | null = null;
261
+ for (let i = 0; i < toks.length; i++) {
262
+ const tok = toks[i];
263
+ if (tok === undefined || !FEELING.has(tok)) continue;
264
+ stated = true;
265
+ word ??= tok;
266
+ // Nearest subject wins: scan backwards and stop at whichever comes first.
267
+ for (let j = i - 1; j >= Math.max(0, i - SUBJECT_WINDOW); j--) {
268
+ const back = toks[j];
269
+ if (back === undefined) continue;
270
+ if (THIRD_PERSON.has(back)) break;
271
+ if (FIRST_PERSON.has(back)) return { stated: true, selfFelt: true, word: tok };
272
+ }
273
+ }
274
+ return { stated, selfFelt: false, word };
275
+ }