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,609 @@
1
+ /**
2
+ * Proposal intake — the authorship contract's front door.
3
+ *
4
+ * Two deposits, one shape: the experiencer's end-of-session dump and its
5
+ * in-the-moment jots both arrive as a `ProposalDraft` and leave as a `Proposal`
6
+ * MINTED BY THE ENGINE (§3, §4.1 G2 — routing an author's own words through an
7
+ * interpreter would return them as someone else's paraphrase).
8
+ *
9
+ * The four mechanized properties that live here:
10
+ *
11
+ * G5 the ENGINE claims coverage, never the author — the author cannot see the
12
+ * buffer, so `covers` is filled in on this side of the seam;
13
+ * G6 a rejected proposal claims NO coverage — its spans stay in the sweep's input;
14
+ * G7 coverage marks never enter gated text — the mark rides in a separate field
15
+ * and `renderForSweep()` is the only thing that ever joins the two;
16
+ * G9 (§4.1) deliberate deposits are idempotent by CONTENT, not by span text.
17
+ *
18
+ * Privilege caps are structural (§4.1 G7): a `Proposal` has no operation fields to
19
+ * carry. `protect`, `promote`, `schema.create` and friends are not "rejected" — the
20
+ * minting function has nowhere to put them, and it counts what it dropped.
21
+ */
22
+ import type { Kind, Salience } from "../types.js";
23
+ import { hashText } from "../store/prose.js";
24
+ import { randomBytes } from "node:crypto";
25
+
26
+ // TYPE-ONLY, and the only edge this module has to `encode/`. The gate itself
27
+ // stays INJECTED (INTERFACE-GAPS #2) — nothing here calls the battery. What
28
+ // crosses is the SHAPE of the battery's own per-gate records, so a verdict can
29
+ // relay them to a caller that writes telemetry instead of flattening them to a
30
+ // first reason and a gate name (replay INTERFACE-GAPS §2a). The import is erased
31
+ // at runtime, so the module graph is unchanged; restating the shape here instead
32
+ // would be a second copy that drifts, which is the failure the `satisfies`
33
+ // discipline in this repo exists to stop.
34
+ import type { ChannelRecord, GateRecord } from "../encode/index.js";
35
+
36
+ import type { CoverageMark, Span, SpanBuffer } from "./spans.js";
37
+ import type { UpdatesResolution } from "./updates.js";
38
+
39
+ // ── the shape the author writes ──────────────────────────────────────────────
40
+
41
+ export interface Feeling {
42
+ /** The typed feeling. Absent means null — never "neutral" (encode §3). */
43
+ feeling: string;
44
+ /** A quote the span must contain; the gate strips it before anything is durable. */
45
+ quote: string;
46
+ /** Who felt it. The emotion exemption applies only when this is the author. */
47
+ subject: string;
48
+ }
49
+
50
+ export interface ProposalDraft {
51
+ content: string;
52
+ kind?: Kind;
53
+ title?: string;
54
+ /** The author's claimed aggregate salience: a FLOOR, clamped in `physics/`. */
55
+ claimed?: number | null;
56
+ /** Optional per-dimension hints. Passed through untouched — scoring is encode's. */
57
+ salience?: Partial<Salience>;
58
+ feeling?: Feeling;
59
+ aliases?: string[];
60
+ /** The declared address of the memory this one revises. Validated, never trusted. */
61
+ updates?: string;
62
+ /** An open loop is an ordinary memory with a flag, not a special structure (§4). */
63
+ unresolved?: boolean;
64
+ }
65
+
66
+ export type ProposalSource = "session-end" | "jot";
67
+
68
+ /** What the engine mints. Memory objects only — no operations, by construction. */
69
+ export interface Proposal {
70
+ id: string;
71
+ source: ProposalSource;
72
+ session: string;
73
+ scope: string;
74
+ content: string;
75
+ kind: Kind;
76
+ title: string | null;
77
+ salience: Partial<Salience> & { claimed: number | null };
78
+ feeling: Feeling | null;
79
+ aliases: string[];
80
+ updates: UpdatesResolution | null;
81
+ unresolved: boolean;
82
+ at: number;
83
+ day: number;
84
+ /** Identity for idempotency: CONTENT, not span text (§4.1 G9). */
85
+ contentHash: string;
86
+ /** Span hashes this proposal covers. Engine-set, always (§5 G5). */
87
+ covers: string[];
88
+ /** The proposal's own span, withheld from the sweep outright. */
89
+ ownSpanHash: string | null;
90
+ }
91
+
92
+ // ── intake ───────────────────────────────────────────────────────────────────
93
+
94
+ export type MalformedReason =
95
+ | "NOT_AN_OBJECT"
96
+ | "CONTENT_MISSING"
97
+ | "CONTENT_EMPTY"
98
+ | "CLAIMED_NOT_NUMERIC"
99
+ | "CLAIMED_OUT_OF_RANGE"
100
+ | "DIMENSION_OUT_OF_RANGE"
101
+ | "KIND_UNKNOWN"
102
+ | "TITLE_NOT_STRING"
103
+ | "UPDATES_NOT_STRING"
104
+ | "ALIASES_NOT_STRINGS"
105
+ | "FEELING_MALFORMED";
106
+
107
+ const KIND_SET: Record<Kind, true> = {
108
+ self: true,
109
+ person: true,
110
+ entity: true,
111
+ skill: true,
112
+ place: true,
113
+ fact: true,
114
+ };
115
+
116
+ /** The three dimensions an author may claim. `novelty` is absent by design:
117
+ * prediction error is computed at encoding, never claimed (§2.9). */
118
+ export const AUTHOR_DIMENSIONS = ["relevance", "emotional", "predictive"] as const;
119
+
120
+ /** Fields a draft may carry. Anything else is dropped and counted — the privilege
121
+ * cap is "there is nowhere to put it", not a rule someone must remember. */
122
+ export const DRAFT_FIELDS = [
123
+ "content",
124
+ "kind",
125
+ "title",
126
+ "claimed",
127
+ "salience",
128
+ "feeling",
129
+ "aliases",
130
+ "updates",
131
+ "unresolved",
132
+ ] as const;
133
+
134
+ export type IntakeResult =
135
+ | { ok: true; draft: Required<Pick<ProposalDraft, "content">> & ProposalDraft; dropped: string[] }
136
+ | { ok: false; reason: MalformedReason; text: string | null; dropped: string[] };
137
+
138
+ /**
139
+ * Validate a raw deposit. A malformed proposal is NOT an error — it degrades to an
140
+ * ordinary span, read by the fallback (§3, §4.1 G8), so this returns the salvaged
141
+ * text alongside the reason.
142
+ */
143
+ export function intake(raw: unknown): IntakeResult {
144
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
145
+ return { ok: false, reason: "NOT_AN_OBJECT", text: typeof raw === "string" ? raw : null, dropped: [] };
146
+ }
147
+ const rec = raw as Record<string, unknown>;
148
+ const dropped = Object.keys(rec).filter(
149
+ (k) => !(DRAFT_FIELDS as readonly string[]).includes(k),
150
+ );
151
+ const text = typeof rec["content"] === "string" ? (rec["content"] as string) : null;
152
+ const bad = (reason: MalformedReason): IntakeResult => ({ ok: false, reason, text, dropped });
153
+
154
+ if (rec["content"] === undefined) return bad("CONTENT_MISSING");
155
+ if (typeof rec["content"] !== "string") return bad("CONTENT_MISSING");
156
+ if (rec["content"].trim().length === 0) return bad("CONTENT_EMPTY");
157
+
158
+ if (rec["kind"] !== undefined) {
159
+ if (typeof rec["kind"] !== "string" || !(rec["kind"] in KIND_SET)) return bad("KIND_UNKNOWN");
160
+ }
161
+ if (rec["title"] !== undefined && typeof rec["title"] !== "string") return bad("TITLE_NOT_STRING");
162
+ if (rec["claimed"] !== undefined && rec["claimed"] !== null) {
163
+ if (typeof rec["claimed"] !== "number" || !Number.isFinite(rec["claimed"])) {
164
+ return bad("CLAIMED_NOT_NUMERIC");
165
+ }
166
+ if (rec["claimed"] < 0 || rec["claimed"] > 1) return bad("CLAIMED_OUT_OF_RANGE");
167
+ }
168
+ if (rec["updates"] !== undefined && typeof rec["updates"] !== "string") {
169
+ return bad("UPDATES_NOT_STRING");
170
+ }
171
+ // The author's three dimensions are validated HERE, at the one front door,
172
+ // rather than at each adapter: `sal()` clamps at read time, but `store.put`
173
+ // writes whatever number arrives into the row, so an unvalidated 7 or a NaN
174
+ // would sit in box 2 forever, honest-looking and wrong. `novelty` is not in
175
+ // this list on purpose — it is stripped below, computed and never claimed.
176
+ if (rec["salience"] !== undefined && rec["salience"] !== null) {
177
+ const s = rec["salience"];
178
+ if (typeof s !== "object" || Array.isArray(s)) return bad("DIMENSION_OUT_OF_RANGE");
179
+ for (const dim of AUTHOR_DIMENSIONS) {
180
+ const v = (s as Record<string, unknown>)[dim];
181
+ if (v === undefined) continue;
182
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > 1) {
183
+ return bad("DIMENSION_OUT_OF_RANGE");
184
+ }
185
+ }
186
+ }
187
+ if (rec["aliases"] !== undefined) {
188
+ const a = rec["aliases"];
189
+ if (!Array.isArray(a) || a.some((x) => typeof x !== "string" || x.trim().length === 0)) {
190
+ return bad("ALIASES_NOT_STRINGS");
191
+ }
192
+ }
193
+ if (rec["feeling"] !== undefined) {
194
+ const f = rec["feeling"];
195
+ if (f === null || typeof f !== "object") return bad("FEELING_MALFORMED");
196
+ const g = f as Record<string, unknown>;
197
+ if (
198
+ typeof g["feeling"] !== "string" ||
199
+ typeof g["quote"] !== "string" ||
200
+ typeof g["subject"] !== "string" ||
201
+ g["feeling"].trim().length === 0
202
+ ) {
203
+ return bad("FEELING_MALFORMED");
204
+ }
205
+ }
206
+
207
+ const draft: ProposalDraft = { content: rec["content"] as string };
208
+ if (rec["kind"] !== undefined) draft.kind = rec["kind"] as Kind;
209
+ if (typeof rec["title"] === "string") draft.title = rec["title"];
210
+ if (rec["claimed"] !== undefined) draft.claimed = rec["claimed"] as number | null;
211
+ if (rec["salience"] !== undefined && typeof rec["salience"] === "object" && rec["salience"] !== null) {
212
+ draft.salience = rec["salience"] as Partial<Salience>;
213
+ }
214
+ if (rec["feeling"] !== undefined) draft.feeling = rec["feeling"] as Feeling;
215
+ if (rec["aliases"] !== undefined) draft.aliases = rec["aliases"] as string[];
216
+ if (typeof rec["updates"] === "string") draft.updates = rec["updates"];
217
+ draft.unresolved = rec["unresolved"] === true;
218
+ return { ok: true, draft: draft as Required<Pick<ProposalDraft, "content">> & ProposalDraft, dropped };
219
+ }
220
+
221
+ // ── the gate seam (INJECTED — see INTERFACE-GAPS.md #2) ──────────────────────
222
+
223
+ export interface GateInput {
224
+ content: string;
225
+ kind: Kind;
226
+ aliases: readonly string[];
227
+ feeling: Feeling | null;
228
+ /** The author's title, when given. The bridge treats it as a handle (the ops
229
+ * rule: a secret in a name rejects the operation). SEAMS item 3. */
230
+ title: string | null;
231
+ /** The author's claimed AGGREGATE salience — carried, never re-judged here. */
232
+ claimed: number | null;
233
+ /** The author's claimed dimensions (novelty always absent: computed, never
234
+ * claimed). SEAMS item 3 — without these the physics floor is unreachable. */
235
+ salience: Partial<Salience>;
236
+ /** The proposal's OWN span, when it has one. The emotion exemption is evaluated
237
+ * against this span by the engine that minted the proposal (encode §5 G5). */
238
+ span: { hash: string; text: string } | null;
239
+ source: ProposalSource;
240
+ day: number;
241
+ }
242
+
243
+ export type GateVerdict =
244
+ | {
245
+ ok: true;
246
+ /** Possibly redacted / hedged. This — never the draft — becomes the memory. */
247
+ content: string;
248
+ aliases?: readonly string[];
249
+ feeling?: Feeling | null;
250
+ /**
251
+ * The COMPUTED salience dimension, from the gate that computed it.
252
+ *
253
+ * The other three dimensions are the author's and arrive on the draft;
254
+ * novelty is prediction error, which no author may claim (`encode/`'s §3).
255
+ * It travels back on the verdict because the gate is the only place that
256
+ * holds a vector — and without this field the number was computed, used
257
+ * for the gate decision, and then DROPPED before mint, which is how the
258
+ * store came to record `novelty: null` on every memory it holds.
259
+ *
260
+ * Optional and null-able, both on purpose: a gate with no vector source
261
+ * omits it, and a gate that tried and could not measure sends `null` —
262
+ * "never asked" and "asked, no answer" stay different records (scar §2.4).
263
+ */
264
+ novelty?: number | null;
265
+ /**
266
+ * THE BATTERY'S OWN PER-GATE RECORDS, relayed rather than summarized.
267
+ *
268
+ * On BOTH arms on purpose. Until this field existed a refusal crossed this
269
+ * seam as `{gate, reason}` — one blocking reason and a joined name — and
270
+ * everything the battery had actually measured (per-gate statuses, hedge
271
+ * counts, alias verdicts, secret FAMILIES) died here. That is why the
272
+ * authored door had no durable gate record to write at all, and why
273
+ * `gate.refusalMix` could be computed over the sweep path only
274
+ * (`tools/replay/INTERFACE-GAPS.md` §2a).
275
+ *
276
+ * `remember/` reads nothing out of them: they are carried to
277
+ * `SubmitResult` and handed to whoever writes telemetry. OPTIONAL because
278
+ * a gate that is not the battery — the `NO_GATE` default, a test double —
279
+ * has none, and "no battery ran" must stay distinguishable from "a battery
280
+ * ran and found nothing" (scar §2.4).
281
+ */
282
+ records?: readonly GateRecord[];
283
+ /** The battery's channel records, same relay, same reason. */
284
+ channels?: readonly ChannelRecord[];
285
+ }
286
+ | {
287
+ ok: false;
288
+ gate: string;
289
+ reason: string;
290
+ /** True when the refusal is the battery working as designed (a gate
291
+ * fired), false/absent when the gate itself failed. SEAMS item 3. */
292
+ refusedByDesign?: boolean;
293
+ /** The refusal arm's half of the relay above — the `records` field replay
294
+ * INTERFACE-GAPS §2a names as what would close it. */
295
+ records?: readonly GateRecord[];
296
+ channels?: readonly ChannelRecord[];
297
+ /**
298
+ * EVERY blocking reason, as a list. `reason` above is the same list joined
299
+ * with `+` for a human line; a telemetry reader that has to split a string
300
+ * back apart is a reader one delimiter away from a wrong count.
301
+ */
302
+ blockedBy?: readonly string[];
303
+ };
304
+
305
+ export type GateFn = (input: GateInput) => GateVerdict | Promise<GateVerdict>;
306
+
307
+ /** The default when no gate is injected: refuse. `encode/` owns the battery, and a
308
+ * missing battery must not read as "everything passes" (fail toward not-authoring). */
309
+ export const NO_GATE: GateFn = () => ({ ok: false, gate: "none", reason: "NO_GATE_INJECTED" });
310
+
311
+ // ── submit ───────────────────────────────────────────────────────────────────
312
+
313
+ export type SubmitReason =
314
+ | "ACCEPTED"
315
+ | "OBSERVER"
316
+ | "MALFORMED"
317
+ | "DUPLICATE_CONTENT"
318
+ | "GATE_REJECTED"
319
+ | "GATE_FAILED"
320
+ | "IO_FAILED";
321
+
322
+ export interface SubmitResult {
323
+ accepted: boolean;
324
+ reason: SubmitReason;
325
+ proposal: Proposal | null;
326
+ /** Empty whenever `accepted` is false — a rejected proposal claims no coverage. */
327
+ coverage: CoverageMark[];
328
+ gate: string | null;
329
+ malformed: MalformedReason | null;
330
+ degradedToSpan: boolean;
331
+ droppedFields: string[];
332
+ /**
333
+ * The battery's per-gate records, when a battery ran.
334
+ *
335
+ * EMPTY IS A FACT, not a default. An observer stand-down, a malformed draft
336
+ * and a content duplicate are all decided BEFORE the gate is called (NOTES
337
+ * §7's rejection ordering), so those three outcomes genuinely have no gate
338
+ * record — and the caller must not write a durable one claiming they do.
339
+ */
340
+ records: readonly GateRecord[];
341
+ /** The battery's channel records, on the same terms. */
342
+ channels: readonly ChannelRecord[];
343
+ /**
344
+ * The kind that was PROPOSED, which survives a refusal where `proposal` does
345
+ * not. Null before intake has parsed one — a malformed draft has no kind, and
346
+ * defaulting it to `fact` would put a made-up axis into telemetry.
347
+ */
348
+ kind: Kind | null;
349
+ /** Every reason the gate blocked on, unjoined. Empty on every other outcome. */
350
+ blockedBy: readonly string[];
351
+ }
352
+
353
+ export interface SubmitContext {
354
+ session: string;
355
+ scope: string;
356
+ source: ProposalSource;
357
+ gate?: GateFn;
358
+ /** The span this deposit IS (a jot's own span), withheld from the sweep outright. */
359
+ ownSpanHash?: string | null;
360
+ /** Injected `updates:` resolver — see `updates.ts`. Absent means no resolution
361
+ * is attempted and the declaration rides unresolved. */
362
+ resolveUpdates?: (declared: string, content: string) => Promise<UpdatesResolution> | UpdatesResolution;
363
+ }
364
+
365
+ /** A proposal record as persisted (the content-idempotency ledger). */
366
+ export interface ProposalRecord {
367
+ id: string;
368
+ contentHash: string;
369
+ session: string;
370
+ source: ProposalSource;
371
+ at: number;
372
+ day: number;
373
+ covers: string[];
374
+ accepted: boolean;
375
+ }
376
+
377
+ export async function submitProposal(
378
+ buffer: SpanBuffer,
379
+ raw: unknown,
380
+ ctx: SubmitContext,
381
+ ): Promise<SubmitResult> {
382
+ const base: SubmitResult = {
383
+ accepted: false,
384
+ reason: "OBSERVER",
385
+ proposal: null,
386
+ coverage: [],
387
+ gate: null,
388
+ malformed: null,
389
+ degradedToSpan: false,
390
+ droppedFields: [],
391
+ records: [],
392
+ channels: [],
393
+ kind: null,
394
+ blockedBy: [],
395
+ };
396
+
397
+ if (buffer.observer) {
398
+ buffer.emit("remember.observer.standdown", undefined, { site: "proposal" });
399
+ return base;
400
+ }
401
+
402
+ const parsed = intake(raw);
403
+ if (!parsed.ok) {
404
+ // Degrade to an ordinary span rather than lose the material (§4.1 G8).
405
+ let degraded = false;
406
+ if (parsed.text !== null && parsed.text.trim().length > 0) {
407
+ degraded = buffer.jot({ session: ctx.session, scope: ctx.scope, text: parsed.text }).captured;
408
+ }
409
+ buffer.emit("remember.proposal.malformed", undefined, {
410
+ reason: parsed.reason,
411
+ degraded,
412
+ dropped: parsed.dropped.length,
413
+ });
414
+ return {
415
+ ...base,
416
+ reason: "MALFORMED",
417
+ malformed: parsed.reason,
418
+ degradedToSpan: degraded,
419
+ droppedFields: parsed.dropped,
420
+ };
421
+ }
422
+
423
+ const draft = parsed.draft;
424
+ const contentHash = hashText(normalize(draft.content));
425
+ const priors = buffer.proposalRecords<ProposalRecord>(ctx.scope);
426
+ if (priors.some((p) => p.accepted && p.contentHash === contentHash)) {
427
+ // Two identical deposits cover different spans, so their SPAN hashes differ and
428
+ // span dedup would miss the repeat. Content is the identity (§4.1 G9).
429
+ buffer.emit("remember.proposal.duplicate", contentHash, { session: ctx.session });
430
+ return { ...base, reason: "DUPLICATE_CONTENT", droppedFields: parsed.dropped };
431
+ }
432
+
433
+ const kind: Kind = draft.kind ?? "fact";
434
+ const own =
435
+ ctx.ownSpanHash === undefined || ctx.ownSpanHash === null
436
+ ? null
437
+ : buffer.spans(ctx.scope).find((s) => s.hash === ctx.ownSpanHash) ?? null;
438
+
439
+ const gate = ctx.gate ?? NO_GATE;
440
+ let verdict: GateVerdict;
441
+ try {
442
+ verdict = await gate({
443
+ content: draft.content,
444
+ kind,
445
+ aliases: draft.aliases ?? [],
446
+ feeling: draft.feeling ?? null,
447
+ title: draft.title ?? null,
448
+ claimed: draft.claimed ?? null,
449
+ salience: draft.salience ?? {},
450
+ span: own === null ? null : { hash: own.hash, text: own.text },
451
+ source: ctx.source,
452
+ day: buffer.day(),
453
+ });
454
+ } catch (err) {
455
+ buffer.emit("remember.proposal.gate.failed", undefined, { session: ctx.session });
456
+ // `records` stays EMPTY here on purpose: the gate THREW, so it produced no
457
+ // records, and a telemetry row claiming five clear gates would be a lie in
458
+ // the one direction that matters (SEAMS item 3's failed-vs-refused split).
459
+ return { ...base, reason: "GATE_FAILED", gate: "unknown", droppedFields: parsed.dropped, malformed: null, kind, blockedBy: [] };
460
+ }
461
+
462
+ if (!verdict.ok) {
463
+ // Nothing was authored, so its spans stay in the sweep's input (§5 G6).
464
+ buffer.emit("remember.proposal.rejected", contentHash, {
465
+ gate: verdict.gate,
466
+ reason: verdict.reason,
467
+ });
468
+ return {
469
+ ...base,
470
+ reason: "GATE_REJECTED",
471
+ gate: verdict.gate,
472
+ droppedFields: parsed.dropped,
473
+ // The whole point of §2a: a refusal leaves with everything the battery
474
+ // measured, not with the first reason it hit.
475
+ records: verdict.records ?? [],
476
+ channels: verdict.channels ?? [],
477
+ kind,
478
+ blockedBy: verdict.blockedBy ?? [],
479
+ };
480
+ }
481
+
482
+ let updates: UpdatesResolution | null = null;
483
+ if (draft.updates !== undefined && ctx.resolveUpdates !== undefined) {
484
+ updates = await ctx.resolveUpdates(draft.updates, verdict.content);
485
+ }
486
+
487
+ // Novelty stripped from the author's dimensions BEFORE the gate's computed
488
+ // value applies — see the salience comment below for why the strip must be
489
+ // explicit rather than an override.
490
+ const { novelty: _claimedNovelty, ...authoredDims } = draft.salience ?? {};
491
+
492
+ const proposal: Proposal = {
493
+ id: `prp_${randomBytes(6).toString("hex")}`,
494
+ source: ctx.source,
495
+ session: ctx.session,
496
+ scope: ctx.scope,
497
+ content: verdict.content,
498
+ kind,
499
+ title: draft.title ?? null,
500
+ // The author's three dimensions, with novelty STRIPPED explicitly before
501
+ // the gate's computed value is applied: novelty is prediction error at
502
+ // encoding — computed, never claimed (§2.9) — and relying on the gate's
503
+ // override alone let an author-supplied novelty survive whenever no vector
504
+ // source was wired, which is the DEFAULT config (PR-3 review: a claimed
505
+ // 0.99 reached the stored row and fed salience/banding — F5 through a new
506
+ // door). Stripping first also preserves the omitted-vs-null distinction:
507
+ // no vector source means novelty null ("never asked"), never the claim.
508
+ salience: {
509
+ ...authoredDims,
510
+ ...(verdict.novelty === undefined ? {} : { novelty: verdict.novelty }),
511
+ claimed: draft.claimed ?? null,
512
+ },
513
+ feeling: verdict.feeling !== undefined ? verdict.feeling : draft.feeling ?? null,
514
+ aliases: [...(verdict.aliases ?? draft.aliases ?? [])],
515
+ updates,
516
+ unresolved: draft.unresolved === true,
517
+ at: buffer.now(),
518
+ day: buffer.day(),
519
+ contentHash,
520
+ covers: [],
521
+ ownSpanHash: own?.hash ?? null,
522
+ };
523
+
524
+ const coverage = buffer.claimCoverage({
525
+ scope: ctx.scope,
526
+ session: ctx.session,
527
+ proposalId: proposal.id,
528
+ ownSpanHash: proposal.ownSpanHash,
529
+ });
530
+ proposal.covers = coverage.map((c) => c.spanHash);
531
+
532
+ const record: ProposalRecord = {
533
+ id: proposal.id,
534
+ contentHash,
535
+ session: proposal.session,
536
+ source: proposal.source,
537
+ at: proposal.at,
538
+ day: proposal.day,
539
+ covers: proposal.covers,
540
+ accepted: true,
541
+ };
542
+ if (!buffer.recordProposal(ctx.scope, record)) {
543
+ // The battery DID run before this failure, so its records travel: an IO loss
544
+ // after a clean gate is a different story from a refusal, and the durable
545
+ // row is how the difference survives the process.
546
+ return {
547
+ ...base,
548
+ reason: "IO_FAILED",
549
+ droppedFields: parsed.dropped,
550
+ records: verdict.records ?? [],
551
+ channels: verdict.channels ?? [],
552
+ kind,
553
+ blockedBy: [],
554
+ };
555
+ }
556
+ buffer.emit("remember.proposal.accepted", proposal.id, {
557
+ source: proposal.source,
558
+ kind: proposal.kind,
559
+ claimed: proposal.salience.claimed,
560
+ covers: proposal.covers.length,
561
+ updates: proposal.updates?.method ?? "none",
562
+ });
563
+
564
+ return {
565
+ accepted: true,
566
+ reason: "ACCEPTED",
567
+ proposal,
568
+ coverage,
569
+ gate: null,
570
+ malformed: null,
571
+ degradedToSpan: false,
572
+ droppedFields: parsed.dropped,
573
+ records: verdict.records ?? [],
574
+ channels: verdict.channels ?? [],
575
+ kind,
576
+ blockedBy: [],
577
+ };
578
+ }
579
+
580
+ // ── prompt-side coverage marks (§5 G7) ───────────────────────────────────────
581
+
582
+ export interface MarkedSpan {
583
+ /** The span's text, UNTOUCHED — this is what a gate sees. */
584
+ span: Span;
585
+ /** Prompt-side only. Nothing that reads `span.text` can ever see this. */
586
+ mark: string | null;
587
+ }
588
+
589
+ export const ALREADY_AUTHORED_MARK = "[already authored by the experiencer]";
590
+
591
+ /**
592
+ * Join spans with their coverage marks for a prompt. This function is the ONLY
593
+ * place the two meet, and it returns a rendered string — so no gate can be loosened
594
+ * by a mark the engine wrote (§5 G7). Covered spans still reach the sweep; only a
595
+ * proposal's own span is withheld outright, upstream of here.
596
+ */
597
+ export function markCovered(spans: readonly Span[], covered: ReadonlySet<string>): MarkedSpan[] {
598
+ return spans.map((span) => ({ span, mark: covered.has(span.hash) ? ALREADY_AUTHORED_MARK : null }));
599
+ }
600
+
601
+ export function renderForSweep(marked: readonly MarkedSpan[]): string {
602
+ return marked
603
+ .map((m) => (m.mark === null ? m.span.text : `${m.mark}\n${m.span.text}`))
604
+ .join("\n\n---\n\n");
605
+ }
606
+
607
+ function normalize(text: string): string {
608
+ return text.trim().replace(/\s+/g, " ").toLowerCase();
609
+ }