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,284 @@
1
+ /**
2
+ * The gate battery — all five checks, one battery, on every proposal, before
3
+ * anything is durable (§5 G2, behavioral-spec §3 G3).
4
+ *
5
+ * ORDER matters, and only in one direction: secrets runs first, so nothing
6
+ * downstream ever handles an unredacted credential; the floor runs last, so it
7
+ * measures what would actually become canonical. Everything in between runs
8
+ * REGARDLESS of whether an earlier check already refused the proposal — a
9
+ * refusal short-circuit is how you end up with a battery that reports one reason
10
+ * and hides three, and "all five run" stops being checkable.
11
+ *
12
+ * Refusals collect the same way physics' verdicts do: `blockedBy` carries every
13
+ * reason, `reason` is the first. A refused proposal is not a failed batch (§3 G6);
14
+ * rejection is data.
15
+ */
16
+
17
+ import { hashText } from "../store/prose.js";
18
+ import { gateAliases } from "./aliases.js";
19
+ import { emotionClassifierRecord, gateEmotion } from "./emotion.js";
20
+ import { contentFloor } from "./floor.js";
21
+ import { hedgePrecision } from "./precision.js";
22
+ import { scanSecrets } from "./secrets.js";
23
+ import { tagSalience } from "./salience.js";
24
+ import type { NoveltyResult } from "./salience.js";
25
+ import { EncodeError } from "./types.js";
26
+ import type {
27
+ AcceptedProposal,
28
+ AliasGateRecord,
29
+ ChannelRecord,
30
+ EmotionGateRecord,
31
+ EncodeEvent,
32
+ FloorGateRecord,
33
+ GateRecord,
34
+ GatedProposal,
35
+ PrecisionGateRecord,
36
+ Proposal,
37
+ RefusalReason,
38
+ SecretFinding,
39
+ SecretsGateRecord,
40
+ } from "./types.js";
41
+
42
+ /**
43
+ * The battery's options. THERE IS NO KEY HERE THAT DISABLES A GATE, and the
44
+ * runtime guard below refuses any caller that invents one — a JavaScript caller
45
+ * with no types still cannot reach past the wall.
46
+ */
47
+ export interface BatteryOptions {
48
+ /** Overrides the emotion CLASSIFIER channel (not the emotion gate). */
49
+ emotionClassifier?: boolean;
50
+ }
51
+
52
+ /**
53
+ * Guarantee 1, enforced at runtime rather than asserted in prose: any option key
54
+ * that so much as mentions the gate is a refusal. Types stop TypeScript callers;
55
+ * this stops everyone else.
56
+ */
57
+ export function assertNoBypassOption(opts: object): void {
58
+ for (const key of Object.keys(opts)) {
59
+ if (/secret|redact|credential/i.test(key)) {
60
+ throw new EncodeError("SECRETS_GATE_NOT_ABLATABLE", { key });
61
+ }
62
+ }
63
+ }
64
+
65
+ export interface GateInput {
66
+ proposal: Proposal;
67
+ /** The span the proposal was written from. Never becomes durable itself. */
68
+ span: string;
69
+ /** Computed once per chunk and handed down (§5 G7). */
70
+ novelty: NoveltyResult;
71
+ }
72
+
73
+ export interface BatteryOutcome {
74
+ gated: GatedProposal;
75
+ events: EncodeEvent[];
76
+ channels: ChannelRecord[];
77
+ }
78
+
79
+ export function gateProposal(input: GateInput, opts: BatteryOptions = {}): BatteryOutcome {
80
+ assertNoBypassOption(opts);
81
+ const p = input.proposal;
82
+ const blockedBy: RefusalReason[] = [];
83
+ const events: EncodeEvent[] = [];
84
+ const secretFindings: SecretFinding[] = [];
85
+
86
+ // ── 1. secrets ────────────────────────────────────────────────────────────
87
+ // Handles first: the ops rule (§3). A credential must never become an entity
88
+ // the store indexes, so a secret in a NAME rejects the whole operation rather
89
+ // than being quietly redacted into a nonsense handle.
90
+ let secretInName = false;
91
+ for (const handle of p.handles ?? []) {
92
+ const scan = scanSecrets(handle, "handle");
93
+ if (scan.fired) {
94
+ secretInName = true;
95
+ secretFindings.push(...scan.findings);
96
+ }
97
+ }
98
+ if (secretInName) blockedBy.push("secret-in-name");
99
+
100
+ const bodyScan = scanSecrets(p.content, "body");
101
+ secretFindings.push(...bodyScan.findings);
102
+ if (bodyScan.emptyAfterRedaction) blockedBy.push("empty-after-redaction");
103
+
104
+ // ── 2. precision ──────────────────────────────────────────────────────────
105
+ const hedged = hedgePrecision(bodyScan.redacted, input.span);
106
+
107
+ // ── 3. aliases ────────────────────────────────────────────────────────────
108
+ const aliasResult = gateAliases(p.aliases, input.span);
109
+ secretFindings.push(...aliasResult.secretFindings);
110
+
111
+ // ── 4. emotion ────────────────────────────────────────────────────────────
112
+ const emotionResult = gateEmotion(p.feeling, input.span, p.selfAuthoredFeeling);
113
+ secretFindings.push(...emotionResult.secretFindings);
114
+
115
+ // ── 5. content floor ──────────────────────────────────────────────────────
116
+ const floor = contentFloor(hedged.text);
117
+ blockedBy.push(...floor.blockedBy);
118
+
119
+ // ── the records: one per gate, ALWAYS, whatever happened ──────────────────
120
+ const contentHash = hashText(hedged.text);
121
+ const secretsRecord: SecretsGateRecord = {
122
+ gate: "secrets",
123
+ ablatable: false,
124
+ findings: secretFindings,
125
+ contentHash,
126
+ status: secretInName
127
+ ? "rejected"
128
+ : bodyScan.emptyAfterRedaction
129
+ ? "rejected"
130
+ : secretFindings.length > 0
131
+ ? "fired"
132
+ : "clear",
133
+ reason: secretInName
134
+ ? "secret-in-name"
135
+ : bodyScan.emptyAfterRedaction
136
+ ? "empty-after-redaction"
137
+ : secretFindings.length > 0
138
+ ? "redacted"
139
+ : "no-credential-shapes-found",
140
+ };
141
+
142
+ const precisionRecord: PrecisionGateRecord = {
143
+ gate: "precision",
144
+ ablatable: false,
145
+ hedges: hedged.hedges,
146
+ status: hedged.fired ? "fired" : "clear",
147
+ reason: hedged.fired ? "hedged-unsourced-specifics" : "nothing-unsourced-to-soften",
148
+ };
149
+
150
+ const aliasRecord: AliasGateRecord = {
151
+ gate: "aliases",
152
+ ablatable: false,
153
+ declared: aliasResult.declared,
154
+ kept: aliasResult.kept.length,
155
+ dropped: aliasResult.dropped,
156
+ status:
157
+ aliasResult.declared === 0
158
+ ? "not-invoked"
159
+ : aliasResult.dropped.length > 0
160
+ ? "refused-by-design"
161
+ : "clear",
162
+ reason:
163
+ aliasResult.declared === 0
164
+ ? "no-aliases-declared"
165
+ : aliasResult.dropped.length > 0
166
+ ? (aliasResult.dropped[0]?.reason ?? "alias-dropped")
167
+ : "all-aliases-verbatim-and-clean",
168
+ };
169
+
170
+ const emotionRecord: EmotionGateRecord = {
171
+ gate: "emotion",
172
+ ablatable: false,
173
+ exemption: emotionResult.exemption,
174
+ type: emotionResult.feeling?.type ?? null,
175
+ quoteStripped: emotionResult.quoteStripped,
176
+ // An exemption-accepted feeling reports "fired" even when there was no quote
177
+ // to strip: a consumer grouping by status must be able to count exemption
178
+ // fires, and "clear" means "found nothing to act on".
179
+ status:
180
+ emotionResult.verdict === "no-feeling-declared"
181
+ ? "not-invoked"
182
+ : emotionResult.feeling === null
183
+ ? "refused-by-design"
184
+ : emotionResult.quoteStripped || emotionResult.exemption
185
+ ? "fired"
186
+ : "clear",
187
+ reason: emotionResult.verdict,
188
+ };
189
+
190
+ const floorRecord: FloorGateRecord = {
191
+ gate: "floor",
192
+ ablatable: false,
193
+ chars: floor.chars,
194
+ words: floor.words,
195
+ minChars: floor.minChars,
196
+ minWords: floor.minWords,
197
+ status: floor.ok ? "clear" : "rejected",
198
+ reason: floor.reason,
199
+ };
200
+
201
+ const records: GateRecord[] = [
202
+ secretsRecord,
203
+ precisionRecord,
204
+ aliasRecord,
205
+ emotionRecord,
206
+ floorRecord,
207
+ ];
208
+
209
+ const channels: ChannelRecord[] = [emotionClassifierRecord(opts.emotionClassifier)];
210
+
211
+ for (const r of records) {
212
+ if (r.status === "clear" || r.status === "not-invoked") continue;
213
+ events.push({
214
+ event: `gate.${r.gate}`,
215
+ ref: p.ref,
216
+ data: { status: r.status, reason: r.reason, kind: p.kind, contentHash },
217
+ });
218
+ }
219
+
220
+ if (blockedBy.length > 0) {
221
+ const first = blockedBy[0] ?? "content-empty";
222
+ events.push({
223
+ event: "encode.refused",
224
+ ref: p.ref,
225
+ data: { reason: first, blockedBy: blockedBy.join(","), kind: p.kind },
226
+ });
227
+ return {
228
+ gated: {
229
+ ref: p.ref,
230
+ accepted: false,
231
+ kind: p.kind,
232
+ reason: first,
233
+ blockedBy,
234
+ records,
235
+ },
236
+ events,
237
+ channels,
238
+ };
239
+ }
240
+
241
+ const tag = tagSalience(p.dimensions, p.claimedSalience, input.novelty);
242
+ if (tag.event !== null) {
243
+ events.push({
244
+ event: tag.event.event,
245
+ ref: p.ref,
246
+ data: {
247
+ computed: tag.event.computed,
248
+ claimed: tag.event.claimed,
249
+ applied: tag.event.applied,
250
+ },
251
+ });
252
+ }
253
+ if (tag.blind) {
254
+ events.push({
255
+ event: "encode.blind",
256
+ ref: p.ref,
257
+ data: { reason: input.novelty.reason, contextCount: input.novelty.contextCount },
258
+ });
259
+ }
260
+
261
+ const accepted: AcceptedProposal = {
262
+ ref: p.ref,
263
+ accepted: true,
264
+ kind: p.kind,
265
+ content: hedged.text,
266
+ contentHash,
267
+ aliases: aliasResult.kept,
268
+ feeling: emotionResult.feeling,
269
+ salience: tag.salience,
270
+ updates: p.updates ?? null,
271
+ unresolved: p.unresolved ?? false,
272
+ records,
273
+ };
274
+ if (p.title !== undefined) accepted.title = p.title;
275
+ if (p.scope !== undefined) accepted.scope = p.scope;
276
+
277
+ events.push({
278
+ event: "encode.accepted",
279
+ ref: p.ref,
280
+ data: { kind: p.kind, contentHash, blind: tag.blind, aliases: aliasResult.kept.length },
281
+ });
282
+
283
+ return { gated: accepted, events, channels };
284
+ }
@@ -0,0 +1,265 @@
1
+ /**
2
+ * The chunk — the one entrance, and the place "gated means gated" is enforced.
3
+ *
4
+ * A chunk is a unit of experience with proposals attached. `encodeChunk` is the
5
+ * ONLY function in this module that produces `DurableEffect`s, which is what makes
6
+ * scar §7's acceptance criterion enumerable rather than arguable: one chokepoint,
7
+ * and a rejected input moves zero durable state, ASSERTED PER STATE KIND.
8
+ *
9
+ * **A fully-gated chunk moves NO durable state — not strength, not `uses`, not a
10
+ * revision, not an entity mention, and not a prediction check.** That last one is
11
+ * the rider, and it is the whole reason the rule is stated at the chunk level
12
+ * rather than the proposal level: in v1, once gradient reinforcement went live,
13
+ * prediction checks were found to bypass the gate, so *a chunk the gates had
14
+ * rejected could still reinforce schema elements* as an element-level side effect
15
+ * (scar §7b). Ruled strict: "the lost reinforcement signal is affordable; the leak
16
+ * in the non-ablatable wall is not."
17
+ *
18
+ * Deliberately scoped to ALL-REJECTED. A chunk with one survivor was gated in
19
+ * part, not refused (§3 G2) — and then only the survivor's effects exist.
20
+ *
21
+ * Encode writes nothing itself. It returns intents; `remember/` applies them. That
22
+ * is why this file imports `hashText` from the store's prose module and NOTHING
23
+ * from the store's write surface.
24
+ */
25
+
26
+ import { gateProposal } from "./battery.js";
27
+ import type { BatteryOptions } from "./battery.js";
28
+ import { preselectSchemas } from "./preselect.js";
29
+ import type { Preselection, SchemaSlice } from "./preselect.js";
30
+ import { computeNovelty } from "./salience.js";
31
+ import type { NoveltyResult } from "./salience.js";
32
+ import { occursAsWholeWord } from "./words.js";
33
+ import type {
34
+ AcceptedProposal,
35
+ ChannelRecord,
36
+ DurableEffect,
37
+ EncodeEvent,
38
+ GatedProposal,
39
+ PredictionCheck,
40
+ Proposal,
41
+ RefusedProposal,
42
+ } from "./types.js";
43
+
44
+ export interface ChunkInput {
45
+ /** The caller's handle for this chunk — a hash or a span id, never its text. */
46
+ chunkRef: string;
47
+ /** The source span. Used to check claims against; never becomes durable here. */
48
+ span: string;
49
+ proposals: readonly Proposal[];
50
+ /** The schema slice the proposals were encoded against. */
51
+ schemas?: readonly SchemaSlice[];
52
+ /** Supplied by the caller. Absent ⇒ novelty is null and the chunk is blind. */
53
+ chunkVector?: readonly number[] | null;
54
+ /** The lived day (active-day clock, scar E8). Recorded, never derived here. */
55
+ day: number;
56
+ /** Checks the author made against shown schemas. Dropped when fully gated. */
57
+ predictionChecks?: readonly PredictionCheck[];
58
+ /**
59
+ * Observer stance (docs/observer-mode.md, scar E7). An instrument leaves the
60
+ * store as it found it: encode still computes — a read-only instrument may
61
+ * measure the gates — but it emits NO effects, and the stand-down is logged so
62
+ * a stood-down instrument stays distinguishable from a broken hook.
63
+ */
64
+ observer?: boolean;
65
+ }
66
+
67
+ export interface EncodeOptions extends BatteryOptions {
68
+ semanticCap?: number;
69
+ semanticFloor?: number;
70
+ }
71
+
72
+ export interface EncodeResult {
73
+ chunkRef: string;
74
+ day: number;
75
+ accepted: AcceptedProposal[];
76
+ refused: RefusedProposal[];
77
+ /** True iff there were proposals and every one of them was refused. */
78
+ fullyGated: boolean;
79
+ /** EMPTY when `fullyGated` (or under observer). The complete list of ways this
80
+ * chunk may move durable state — there is no second channel. */
81
+ effects: DurableEffect[];
82
+ /** EMPTY when `fullyGated`: the element-level side channel, closed (scar §7b). */
83
+ predictionChecks: PredictionCheck[];
84
+ preselection: Preselection;
85
+ novelty: NoveltyResult;
86
+ channels: ChannelRecord[];
87
+ events: EncodeEvent[];
88
+ observer: boolean;
89
+ }
90
+
91
+ export function encodeChunk(input: ChunkInput, opts: EncodeOptions = {}): EncodeResult {
92
+ const schemas = input.schemas ?? [];
93
+ const events: EncodeEvent[] = [];
94
+
95
+ // ── preselection, ONCE per chunk (§5 G7) ──────────────────────────────────
96
+ const preselectInput: Parameters<typeof preselectSchemas>[0] = {
97
+ chunkRef: input.chunkRef,
98
+ span: input.span,
99
+ schemas,
100
+ };
101
+ if (input.chunkVector !== undefined) preselectInput.chunkVector = input.chunkVector;
102
+ if (opts.semanticCap !== undefined) preselectInput.semanticCap = opts.semanticCap;
103
+ if (opts.semanticFloor !== undefined) preselectInput.semanticFloor = opts.semanticFloor;
104
+ const preselection = preselectSchemas(preselectInput);
105
+ events.push(...preselection.events);
106
+
107
+ // ── novelty as prediction error, against the SHOWN slice ──────────────────
108
+ // Blindness here and blindness in preselection are the same fact seen twice:
109
+ // novelty is error against what the author could see, so a chunk shown nothing
110
+ // has no error to measure — null, recorded, never defaulted.
111
+ const shownIds = new Set(preselection.shown.map((s) => s.id));
112
+ const contextVectors = schemas
113
+ .filter((s) => shownIds.has(s.id))
114
+ .map((s) => s.vector)
115
+ .filter((v): v is readonly number[] => v !== null && v !== undefined && v.length > 0);
116
+ const novelty = computeNovelty(input.chunkVector, contextVectors);
117
+
118
+ // ── the battery, per proposal ─────────────────────────────────────────────
119
+ const gated: GatedProposal[] = [];
120
+ const channels: ChannelRecord[] = [preselection.semantic];
121
+ for (const proposal of input.proposals) {
122
+ const outcome = gateProposal({ proposal, span: input.span, novelty }, opts);
123
+ gated.push(outcome.gated);
124
+ events.push(...outcome.events);
125
+ for (const c of outcome.channels) {
126
+ if (!channels.some((existing) => existing.channel === c.channel)) channels.push(c);
127
+ }
128
+ }
129
+
130
+ const accepted = gated.filter((g): g is AcceptedProposal => g.accepted);
131
+ const refused = gated.filter((g): g is RefusedProposal => !g.accepted);
132
+ const fullyGated = input.proposals.length > 0 && accepted.length === 0;
133
+ const observer = input.observer === true;
134
+
135
+ // ── the effects — and the two ways there are none ─────────────────────────
136
+ let effects: DurableEffect[] = [];
137
+ let predictionChecks: PredictionCheck[] = [];
138
+
139
+ if (fullyGated) {
140
+ events.push({
141
+ event: "encode.fullyGated",
142
+ ref: input.chunkRef,
143
+ data: {
144
+ proposals: input.proposals.length,
145
+ refused: refused.length,
146
+ droppedPredictionChecks: input.predictionChecks?.length ?? 0,
147
+ },
148
+ });
149
+ } else if (observer) {
150
+ events.push({
151
+ event: "encode.observer.standdown",
152
+ ref: input.chunkRef,
153
+ data: { accepted: accepted.length, suppressedEffects: true },
154
+ });
155
+ } else {
156
+ effects = buildEffects(accepted, preselection, schemas, input.predictionChecks ?? []);
157
+ // A prediction check survives only when it names a schema the author was
158
+ // actually SHOWN — the author cannot check a prediction it never saw.
159
+ predictionChecks = (input.predictionChecks ?? []).filter((c) => shownIds.has(c.schemaId));
160
+ }
161
+
162
+ events.push({
163
+ event: "encode.chunk",
164
+ ref: input.chunkRef,
165
+ data: {
166
+ day: input.day,
167
+ proposals: input.proposals.length,
168
+ accepted: accepted.length,
169
+ refused: refused.length,
170
+ fullyGated,
171
+ blind: preselection.blind,
172
+ noveltyReason: novelty.reason,
173
+ effects: effects.length,
174
+ observer,
175
+ },
176
+ });
177
+
178
+ return {
179
+ chunkRef: input.chunkRef,
180
+ day: input.day,
181
+ accepted,
182
+ refused,
183
+ fullyGated,
184
+ effects,
185
+ predictionChecks,
186
+ preselection,
187
+ novelty,
188
+ channels,
189
+ events,
190
+ observer,
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Every durable-state intent an accepted proposal earns, and no others. Entity
196
+ * mentions are computed from the ACCEPTED (redacted, hedged) content by the one
197
+ * whole-word rule — a mention that only existed in redacted text is not a mention.
198
+ */
199
+ function buildEffects(
200
+ accepted: readonly AcceptedProposal[],
201
+ preselection: Preselection,
202
+ schemas: readonly SchemaSlice[],
203
+ checks: readonly PredictionCheck[],
204
+ ): DurableEffect[] {
205
+ const effects: DurableEffect[] = [];
206
+ const shown = new Set(preselection.shown.map((s) => s.id));
207
+ const acceptedRefs = new Set(accepted.map((a) => a.ref));
208
+ const byId = new Map(schemas.map((s) => [s.id, s]));
209
+
210
+ for (const a of accepted) {
211
+ effects.push({
212
+ effect: "memory.create",
213
+ ref: a.ref,
214
+ kind: a.kind,
215
+ contentHash: a.contentHash,
216
+ });
217
+ for (const sel of preselection.shown) {
218
+ const s = byId.get(sel.id);
219
+ if (s === undefined) continue;
220
+ // The lexical channel matched the SPAN. A mention is durable state, so it
221
+ // must survive in what was actually ACCEPTED — the redacted, hedged text —
222
+ // or it is a mention of a credential we just removed.
223
+ const terms = [s.name, ...(s.aliases ?? [])];
224
+ if (terms.some((t) => occursAsWholeWord(a.content, t))) {
225
+ effects.push({ effect: "entity.mention", schemaId: sel.id, ref: a.ref });
226
+ }
227
+ }
228
+ if (a.updates !== null) {
229
+ // `targetId` is the DECLARATION, exactly as the author wrote it — encode
230
+ // resolves nothing and holds no store. The applier is
231
+ // `src/core/revision.ts`, reached once per effect from every mint door,
232
+ // and it is what walks the declaration to a real row (`remember/` matches
233
+ // text to a candidate; the store walks an id through the supersede chain).
234
+ //
235
+ // So the correspondence this list promises is ONE APPLY PER DECLARATION,
236
+ // not one movement per effect: a declaration that resolves to nothing
237
+ // lands as a named `target-unresolvable` refusal, and one that hit an
238
+ // ordinary memory lands as a link. (The applier is reached slightly more
239
+ // often than this list is long: a proposal that declared NOTHING but whose
240
+ // content the engine matched to an existing memory also arrives there, and
241
+ // is a named no-move — a restatement is a confirmation, never a challenge.
242
+ // No effect is missing, because nothing moved.) What the chunk MOVED is
243
+ // the applier's own record. A fully gated chunk accepts nothing, so it
244
+ // emits no effect and applies none — and an observer's emits none either.
245
+ effects.push({ effect: "revision.challenge", targetId: a.updates, ref: a.ref });
246
+ }
247
+ }
248
+
249
+ for (const c of checks) {
250
+ if (!shown.has(c.schemaId)) continue;
251
+ if (c.ref !== null && !acceptedRefs.has(c.ref)) continue;
252
+ effects.push({
253
+ effect: "prediction.check",
254
+ schemaId: c.schemaId,
255
+ ref: c.ref ?? "",
256
+ outcome: c.outcome,
257
+ });
258
+ }
259
+ return effects;
260
+ }
261
+
262
+ /** Re-exported for callers that want the mention rule without the whole chunk. */
263
+ export function mentionsSchema(content: string, term: string): boolean {
264
+ return occursAsWholeWord(content, term);
265
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The emotion gate — STATED-ONLY, and the exemption cannot widen.
3
+ *
4
+ * A typed feeling survives only if the span STATES it: a cited quote the span
5
+ * contains, plus a named subject. The quote is stripped before the feeling
6
+ * becomes durable (§3) — the feeling is what gets kept, not the sentence that
7
+ * evidenced it.
8
+ *
9
+ * THE ONE EXEMPTION (§5 G5, behavioral-spec §3 G5). Exactly one recognized
10
+ * provenance: the author stating its OWN feeling about its OWN span. It is
11
+ * - **set per proposal by the engine that minted it** — `selfAuthoredFeeling` is
12
+ * an INPUT here; encode never infers it from the content, because inferring it
13
+ * is precisely how an exemption widens;
14
+ * - valid only when the subject is the author itself and the feeling is non-empty;
15
+ * - never available to a claim about someone ELSE's interior, which always takes
16
+ * the ordinary path, where a transcript exists to check it against.
17
+ *
18
+ * Absent means NULL, never neutral. And encode never assigns a type to an untyped
19
+ * feeling: retro-typing emotion is forbidden (§3, behavioral-spec §4.2 G5).
20
+ *
21
+ * The emotion CLASSIFIER — the channel that would detect feeling from text — is a
22
+ * different thing entirely and ships DISABLED (TUNABLES). The gate below runs on
23
+ * every proposal regardless; the classifier's stand-down is its own record, so
24
+ * "the channel is off" is never mistaken for "the gate found nothing".
25
+ */
26
+
27
+ import { redactSecrets, scanSecrets } from "./secrets.js";
28
+ import { SELF_SUBJECT } from "./types.js";
29
+ import type { ChannelRecord, DurableFeeling, Feeling, SecretFinding } from "./types.js";
30
+ import { TUNABLES } from "./tunables.js";
31
+
32
+ export type EmotionVerdict =
33
+ | "accepted"
34
+ | "accepted-by-exemption"
35
+ | "no-feeling-declared"
36
+ | "feeling-untyped"
37
+ | "feeling-unattributed"
38
+ | "quote-missing"
39
+ | "quote-not-in-span"
40
+ | "exemption-not-available";
41
+
42
+ export interface EmotionGateResult {
43
+ /** Null whenever the feeling did not survive. NEVER a neutral stand-in. */
44
+ feeling: DurableFeeling | null;
45
+ verdict: EmotionVerdict;
46
+ exemption: boolean;
47
+ quoteStripped: boolean;
48
+ secretFindings: SecretFinding[];
49
+ }
50
+
51
+ export function gateEmotion(
52
+ feeling: Feeling | null | undefined,
53
+ span: string,
54
+ selfAuthored: boolean | undefined,
55
+ ): EmotionGateResult {
56
+ const none = (verdict: EmotionVerdict, exemption = false): EmotionGateResult => ({
57
+ feeling: null,
58
+ verdict,
59
+ exemption,
60
+ quoteStripped: false,
61
+ secretFindings: [],
62
+ });
63
+
64
+ if (feeling === null || feeling === undefined) return none("no-feeling-declared");
65
+
66
+ const type = feeling.type.trim();
67
+ const subject = feeling.subject.trim();
68
+ const quote = feeling.quote.trim();
69
+
70
+ // Untyped is not neutral, and encode will not supply the type.
71
+ if (type.length === 0) return none("feeling-untyped");
72
+ if (subject.length === 0) return none("feeling-unattributed");
73
+
74
+ const claimsExemption = selfAuthored === true;
75
+ const subjectIsAuthor = subject.toLowerCase() === SELF_SUBJECT;
76
+
77
+ if (claimsExemption && !subjectIsAuthor) {
78
+ // The engine set the flag on a claim about someone else's interior. Refused
79
+ // AT THE REFUSAL SITE, structurally — the exemption cannot widen.
80
+ return none("exemption-not-available");
81
+ }
82
+
83
+ const exemption = claimsExemption && subjectIsAuthor;
84
+
85
+ if (!exemption) {
86
+ if (quote.length === 0) return none("quote-missing");
87
+ if (!span.includes(quote)) return none("quote-not-in-span");
88
+ }
89
+
90
+ // The type and subject are the only things that become durable, and both are
91
+ // author-supplied text, so both leave through the gate.
92
+ const scan = scanSecrets(`${type} ${subject}`, "feeling");
93
+ return {
94
+ feeling: { type: redactSecrets(type), subject: redactSecrets(subject) },
95
+ verdict: exemption ? "accepted-by-exemption" : "accepted",
96
+ exemption,
97
+ quoteStripped: quote.length > 0,
98
+ secretFindings: scan.findings,
99
+ };
100
+ }
101
+
102
+ /**
103
+ * The classifier channel's record. It ships off (§4: "do not enable a channel on
104
+ * a rewrite's promise"), and OFF IS SILENCE, not a skip — a distinct record from
105
+ * a failure, and a distinct record from "the gate ran and found nothing".
106
+ */
107
+ export function emotionClassifierRecord(enabled?: boolean): ChannelRecord {
108
+ const on = enabled ?? TUNABLES.EMOTION_CLASSIFIER_ENABLED;
109
+ // No classifier is implemented in v2 yet, so "on" cannot honestly report "ran".
110
+ // Asking for a channel that is not there is a SKIP (loud); leaving it off is
111
+ // silence. Conflating the two is the exact confusion §5 G8 forbids.
112
+ return {
113
+ channel: "emotion-classifier",
114
+ state: on ? "skipped" : "off",
115
+ reason: on
116
+ ? "enabled-but-no-classifier-shipped"
117
+ : `ships-disabled-until-it-re-earns-${TUNABLES.EMOTION_CLASSIFIER_PRECISION_BAR}-fired-cue-precision`,
118
+ };
119
+ }