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,452 @@
1
+ /**
2
+ * The crash fallback — transcript interpretation, demoted from primary path to the
3
+ * thing that runs only when the experiencer never got the pen (contract §4).
4
+ *
5
+ * WHAT "CRASHED" MEANS, mechanically (owner ruling 2026-09-04, adapter CONTRACT
6
+ * open question 3; the predicate itself is `SpanBuffer.crashedSessions`): a
7
+ * session holds uncovered spans, has recorded NO `session-end` boundary, and has
8
+ * had no boundary activity for `TUNABLES.CRASH_STALE_MS`. Nothing else is swept
9
+ * — not an ordinary Stop, not a session that ended normally with trailing turns,
10
+ * not a compaction on its own. A host with no end-of-session event has every
11
+ * session swept once it goes quiet, which is the intended degradation.
12
+ *
13
+ * It runs for spans that are unclaimed and left behind by such a session. A fallback
14
+ * that runs after a crash is exactly the path that must not lose the day, so the
15
+ * machinery shrank with its role but did not disappear — chunking with per-chunk
16
+ * failure isolation (E1), a `stop_reason` guard (E2), restore-on-throw (E6), and an
17
+ * observer that sweeps nothing (E7).
18
+ *
19
+ * Restore-on-failure is BOUNDED: `SpanBuffer.noteFailures()` counts a span's
20
+ * failures and quarantines it at `TUNABLES.MAX_SPAN_FAILURES`, so a permanently
21
+ * failing span cannot bill the owner one model call per boundary forever.
22
+ *
23
+ * **There is no SDK and no network here.** Interpretation is an INJECTED async
24
+ * function; streaming, retries, token budgets and detachment belong to whoever
25
+ * injects it (INTERFACE-GAPS.md #3). This module owns the choreography only.
26
+ */
27
+ import { markCovered, renderForSweep } from "./proposals.js";
28
+ import type { MarkedSpan } from "./proposals.js";
29
+ import { errCode } from "./spans.js";
30
+ import type { Span, SpanBuffer } from "./spans.js";
31
+ import { TUNABLES } from "./tunables.js";
32
+
33
+ export interface SweepChunk {
34
+ index: number;
35
+ spans: Span[];
36
+ /** Covered spans ride ALONG, marked — the sweep loses permission to write the
37
+ * same memory twice, not sight of the material (§4.1 G4). */
38
+ marked: MarkedSpan[];
39
+ /** The prompt-side rendering. Marks live here and nowhere else (§5 G7). */
40
+ prompt: string;
41
+ bytes: number;
42
+ }
43
+
44
+ export interface InterpretResult {
45
+ proposals?: readonly unknown[];
46
+ /** A truncated response is a failure, not data (scar E2). Absent means the
47
+ * injected function does not report one — see NOTES §6. */
48
+ stopReason?: string;
49
+ }
50
+
51
+ export type InterpretFn = (chunk: SweepChunk) => Promise<InterpretResult>;
52
+
53
+ /** Persist one chunk's harvest. Injected: minting is `encode/`'s and `store/`'s. */
54
+ export type ApplyFn = (
55
+ proposals: readonly unknown[],
56
+ chunk: SweepChunk,
57
+ ) => void | Promise<void>;
58
+
59
+ export const OK_STOP_REASONS: readonly string[] = [
60
+ "end_turn",
61
+ "stop",
62
+ "stop_sequence",
63
+ "tool_use",
64
+ ];
65
+
66
+ export type ChunkReason =
67
+ | "APPLIED"
68
+ | "EMPTY"
69
+ | "TRUNCATED"
70
+ | "MALFORMED_RESULT"
71
+ | "THREW"
72
+ | "APPLY_FAILED";
73
+
74
+ export interface ChunkOutcome {
75
+ index: number;
76
+ ok: boolean;
77
+ /** "EMPTY" and the failure reasons are DISTINCT records: returned-nothing is not
78
+ * failed (scar §2.4). */
79
+ reason: ChunkReason;
80
+ spans: number;
81
+ bytes: number;
82
+ proposals: number;
83
+ code: string | null;
84
+ }
85
+
86
+ /**
87
+ * EVERY WAY A SWEEP CAN END, as a runtime list — so a per-reason count can zero
88
+ * every key before it counts anything and an absent reason is distinguishable
89
+ * from one that never fired (scar §2.4, the `DECAY_SKIPS` pattern).
90
+ */
91
+ export const SWEEP_REASONS = [
92
+ "OBSERVER",
93
+ "NO_CRASHED_SESSION",
94
+ "NOTHING_TO_SWEEP",
95
+ "NOTHING_UNCLAIMED",
96
+ "BELOW_MIN_CLAIM",
97
+ "IO_FAILED",
98
+ "SWEPT",
99
+ ] as const;
100
+
101
+ export type SweepReason = (typeof SWEEP_REASONS)[number];
102
+
103
+ /**
104
+ * THE QUIET REASONS — the ones whose ordinary count is "most of them, every day"
105
+ * (G48, 2026-09-14).
106
+ *
107
+ * The sweep is a crash fallback, so its healthy state is refusing, and the
108
+ * refusals divide in THREE, not two — the third division is the correction the
109
+ * first reading of G48 needed (2026-09-14, same day):
110
+ *
111
+ * - **Quiet.** `NO_CRASHED_SESSION` (nothing crashed in this scope),
112
+ * `NOTHING_TO_SWEEP` (a crashed session left nothing behind — which,
113
+ * because `crashedSessions()` never forgets a session, is the permanent
114
+ * answer for every scope that was ever swept and retired), and
115
+ * `NOTHING_UNCLAIMED` (everything eligible was already authored, retired
116
+ * without a model call). All three are the gate working.
117
+ * - **Not quiet, NOW.** `IO_FAILED` is a claim the filesystem refused;
118
+ * `OBSERVER` means the buffer stood down under a root that did not — the two
119
+ * stances are set from one flag (`counterpart.ts`), so a nonzero count is a
120
+ * wiring fault. Neither can be a normal day even once.
121
+ * - **Not quiet IF CHRONIC.** `BELOW_MIN_CLAIM` is fine once and a stuck
122
+ * buffer if it repeats. It is PERMANENT BY CONSTRUCTION: a crashed session's
123
+ * leftover under `MIN_CLAIM_BYTES` is restored to the buffer
124
+ * (`spans.ts#claim`), `crashedSessions()` never forgets the session, so the
125
+ * same scope answers `BELOW_MIN_CLAIM` on every run thereafter. Ambering on
126
+ * the first one made one 200-byte leftover an amber dashboard forever, which
127
+ * is the alarm that trains its reader to ignore it.
128
+ *
129
+ * `SWEPT` is not a refusal at all and is in none of the lists; it is counted
130
+ * beside them so the per-reason map is TOTAL over the run's reports.
131
+ */
132
+ export const QUIET_SWEEP_REASONS: readonly SweepReason[] = [
133
+ "NO_CRASHED_SESSION",
134
+ "NOTHING_TO_SWEEP",
135
+ "NOTHING_UNCLAIMED",
136
+ ];
137
+
138
+ /**
139
+ * WORTH AN ALARM ON THE FIRST ONE. Read by the gate row's `noisyRefusals`, by
140
+ * the dashboard narrator's amber and by the daily's `sweep.gate:refused` split —
141
+ * all three of which are single-row readers, and a single row cannot tell a
142
+ * first time from a thousandth.
143
+ */
144
+ export const NOISY_NOW_SWEEP_REASONS: readonly SweepReason[] = ["IO_FAILED", "OBSERVER"];
145
+
146
+ /**
147
+ * WORTH A LOOK ONLY IF IT REPEATS. Counted onto the gate row as
148
+ * `chronicCandidates` and named neutrally by every one-row reader; whether it is
149
+ * chronic is a question about a RUN OF ROWS, which only a reader holding several
150
+ * days of them can answer (`tools/parallel/` reads the series; the dashboard and
151
+ * the daily do not).
152
+ */
153
+ export const NOISY_IF_CHRONIC_SWEEP_REASONS: readonly SweepReason[] = ["BELOW_MIN_CLAIM"];
154
+
155
+ export interface SweepReport {
156
+ scope: string;
157
+ ran: boolean;
158
+ reason: SweepReason;
159
+ claimId: string | null;
160
+ chunks: ChunkOutcome[];
161
+ spansSwept: number;
162
+ spansRestored: number;
163
+ /** Spans that hit the retry bound this run: written to `quarantine.jsonl`,
164
+ * never restored, never swept again (TUNABLES.MAX_SPAN_FAILURES). */
165
+ spansQuarantined: number;
166
+ proposals: number;
167
+ /** False when a failed restore forbade consuming the claim (spec §2 G7). */
168
+ consumed: boolean;
169
+ }
170
+
171
+ export interface SweepOptions {
172
+ scope: string;
173
+ interpret: InterpretFn;
174
+ apply?: ApplyFn;
175
+ chunkBytes?: number;
176
+ minBytes?: number;
177
+ staleClaimMs?: number;
178
+ /** How long a session must be silent before it counts as crashed
179
+ * (`TUNABLES.CRASH_STALE_MS`). Overridden by the REPLAY harness alone, where
180
+ * "every session in this corpus died months ago" is literally true. */
181
+ crashStaleMs?: number;
182
+ okStopReasons?: readonly string[];
183
+ }
184
+
185
+ export async function sweep(buffer: SpanBuffer, opts: SweepOptions): Promise<SweepReport> {
186
+ const report: SweepReport = {
187
+ scope: opts.scope,
188
+ ran: false,
189
+ reason: "OBSERVER",
190
+ claimId: null,
191
+ chunks: [],
192
+ spansSwept: 0,
193
+ spansRestored: 0,
194
+ spansQuarantined: 0,
195
+ proposals: 0,
196
+ consumed: false,
197
+ };
198
+
199
+ if (buffer.observer) {
200
+ buffer.emit("remember.observer.standdown", undefined, { site: "sweep" });
201
+ return report;
202
+ }
203
+
204
+ // THE GATE (owner ruling 2026-09-04): the sweep is a FALLBACK, never the
205
+ // primary mechanism, and it spends the owner's API budget every time it fires.
206
+ // It may read a transcript only for a session that CRASHED — uncovered spans,
207
+ // no `session-end` boundary ever, and silence past `CRASH_STALE_MS`. A session
208
+ // that ended normally is never swept even when trailing spans are uncovered:
209
+ // the experiencer had the pen, and what it did not write is forgotten by
210
+ // design (constitution 3).
211
+ //
212
+ // Answered BEFORE the claim, so a scope with nothing crashed costs no rename
213
+ // and — the point — records "nothing crashed" rather than "claimed and found
214
+ // nothing already authored". The daily has to tell a quiet sweep from a broken
215
+ // one (constitution 16).
216
+ const staleOpt = opts.crashStaleMs === undefined ? {} : { staleMs: opts.crashStaleMs };
217
+ const pending = buffer.crashedPending(opts.scope, staleOpt);
218
+ if (pending.spans === 0) {
219
+ // TWO DIFFERENT FACTS, kept apart (scar §2.4). "Nothing crashed" is the
220
+ // healthy quiet day the ruling produces; "a crashed session left nothing
221
+ // behind" is the buffer already being empty — the same reason `claim()`
222
+ // reports when it finds no lines.
223
+ const reason: SweepReason = pending.sessions.size === 0 ? "NO_CRASHED_SESSION" : "NOTHING_TO_SWEEP";
224
+ buffer.emit("remember.sweep.skipped", undefined, {
225
+ scope: opts.scope,
226
+ reason,
227
+ crashedSessions: pending.sessions.size,
228
+ uncovered: pending.uncovered,
229
+ });
230
+ return { ...report, reason };
231
+ }
232
+ const crashed = pending.sessions;
233
+
234
+ const claimed = buffer.claim(opts.scope, {
235
+ ...(opts.minBytes !== undefined ? { minBytes: opts.minBytes } : {}),
236
+ ...(opts.staleClaimMs !== undefined ? { staleClaimMs: opts.staleClaimMs } : {}),
237
+ });
238
+ if (!claimed.claimed) {
239
+ const reason: SweepReason =
240
+ claimed.reason === "BELOW_MIN_CLAIM"
241
+ ? "BELOW_MIN_CLAIM"
242
+ : claimed.reason === "EMPTY"
243
+ ? "NOTHING_TO_SWEEP"
244
+ : claimed.reason === "OBSERVER"
245
+ ? "OBSERVER"
246
+ : "IO_FAILED";
247
+ return { ...report, reason };
248
+ }
249
+
250
+ const claim = claimed.claim;
251
+ report.claimId = claim.id;
252
+ const withheld = buffer.withheldHashes(opts.scope);
253
+ const covered = buffer.coveredHashes(opts.scope);
254
+
255
+ // Three piles. Ineligible spans belong to sessions that are still running, or
256
+ // that ended normally, or that have not yet gone quiet past the window — all of
257
+ // them go straight back; withheld spans are a proposal's own words and are
258
+ // dropped from the sweep outright (re-encoding them is guaranteed duplication).
259
+ const eligible: Span[] = [];
260
+ const ineligible: Span[] = [];
261
+ for (const span of claim.spans) {
262
+ if (withheld.has(span.hash)) continue;
263
+ if (crashed.has(span.session)) eligible.push(span);
264
+ else ineligible.push(span);
265
+ }
266
+
267
+ const uncovered = eligible.filter((s) => !covered.has(s.hash));
268
+ if (uncovered.length === 0) {
269
+ // Everything eligible was already authored: retire it without a model call.
270
+ const back = buffer.restore(claim, ineligible);
271
+ // Restored spans stay OUT of the consumed ledger: recording them would make
272
+ // them un-restorable at their next failure (the replay-review P0).
273
+ const consumed = back.restored
274
+ ? buffer.consume(claim, { except: ineligible }).consumed
275
+ : false;
276
+ buffer.emit("remember.sweep.skipped", claim.id, {
277
+ scope: opts.scope,
278
+ reason: "NOTHING_UNCLAIMED",
279
+ retired: eligible.length,
280
+ });
281
+ return {
282
+ ...report,
283
+ reason: "NOTHING_UNCLAIMED",
284
+ spansRestored: back.spans,
285
+ consumed,
286
+ };
287
+ }
288
+
289
+ const chunks = chunkSpans(eligible, covered, opts.chunkBytes ?? TUNABLES.CHUNK_BYTES);
290
+ const okStop = opts.okStopReasons ?? OK_STOP_REASONS;
291
+ const failed: Span[] = [];
292
+
293
+ for (const chunk of chunks) {
294
+ const outcome = await runChunk(buffer, chunk, opts, okStop);
295
+ report.chunks.push(outcome);
296
+ if (outcome.ok) {
297
+ report.spansSwept += chunk.spans.length;
298
+ report.proposals += outcome.proposals;
299
+ } else {
300
+ // Per-chunk failure isolation (scar E1): this chunk's spans go back and are
301
+ // retried at the next boundary; its siblings are unaffected.
302
+ //
303
+ // BOUNDED (replay-review follow-up): the failure is recorded per span, and a
304
+ // span that has now failed MAX_SPAN_FAILURES times is quarantined instead of
305
+ // restored. Named limitation: a chunk failure marks EVERY span in the chunk,
306
+ // so an innocent sibling chunked with a poison pill N times is quarantined
307
+ // with it. That is the simplest rule that bounds the cost; bisecting a chunk
308
+ // is machinery in anticipation of a failure not yet seen (Amendment 15).
309
+ const noted = buffer.noteFailures(opts.scope, chunk.spans, outcome.code ?? outcome.reason);
310
+ failed.push(...noted.retry);
311
+ report.spansQuarantined += noted.quarantined.length;
312
+ }
313
+ }
314
+
315
+ // Quarantined spans are deliberately NOT in this list: they are not restored,
316
+ // and their hashes DO belong in the consumed ledger — see `consume()`.
317
+ const restoredSpans = [...failed, ...ineligible];
318
+ const back = buffer.restore(claim, restoredSpans);
319
+ report.spansRestored = back.spans;
320
+ if (!back.restored) {
321
+ // A failed restore FORBIDS consuming the claim: the spans stay in claim-or-buffer.
322
+ buffer.emit("remember.sweep.restore.failed", claim.id, { spans: failed.length });
323
+ return { ...report, ran: true, reason: "SWEPT", consumed: false };
324
+ }
325
+ // The ledger records what was APPLIED. A restored span's hash must stay out of
326
+ // it, or restore()'s dedup makes the SECOND failure of the same content silent
327
+ // loss — the replay-review P0, fired live on 2026-08-09/10.
328
+ report.consumed = buffer.consume(claim, { except: restoredSpans }).consumed;
329
+ buffer.emit("remember.sweep.done", claim.id, {
330
+ scope: opts.scope,
331
+ chunks: report.chunks.length,
332
+ swept: report.spansSwept,
333
+ restored: report.spansRestored,
334
+ quarantined: report.spansQuarantined,
335
+ proposals: report.proposals,
336
+ });
337
+ return { ...report, ran: true, reason: "SWEPT" };
338
+ }
339
+
340
+ /** Every scope holding experience gets swept, not only the one whose boundary fired
341
+ * (spec §2 G9) — a project never revisited would otherwise hold spans forever. */
342
+ export async function sweepAll(
343
+ buffer: SpanBuffer,
344
+ opts: Omit<SweepOptions, "scope">,
345
+ ): Promise<SweepReport[]> {
346
+ const out: SweepReport[] = [];
347
+ for (const scope of buffer.scopes()) {
348
+ out.push(await sweep(buffer, { ...opts, scope }));
349
+ }
350
+ return out;
351
+ }
352
+
353
+ async function runChunk(
354
+ buffer: SpanBuffer,
355
+ chunk: SweepChunk,
356
+ opts: SweepOptions,
357
+ okStop: readonly string[],
358
+ ): Promise<ChunkOutcome> {
359
+ const base: ChunkOutcome = {
360
+ index: chunk.index,
361
+ ok: false,
362
+ reason: "THREW",
363
+ spans: chunk.spans.length,
364
+ bytes: chunk.bytes,
365
+ proposals: 0,
366
+ code: null,
367
+ };
368
+ let result: InterpretResult;
369
+ try {
370
+ result = await opts.interpret(chunk);
371
+ } catch (err) {
372
+ const code = errCode(err);
373
+ buffer.emit("remember.chunk.failed", undefined, { index: chunk.index, reason: "THREW", code });
374
+ return { ...base, reason: "THREW", code };
375
+ }
376
+
377
+ if (result === null || typeof result !== "object") {
378
+ buffer.emit("remember.chunk.failed", undefined, { index: chunk.index, reason: "MALFORMED_RESULT" });
379
+ return { ...base, reason: "MALFORMED_RESULT" };
380
+ }
381
+ if (result.stopReason !== undefined && !okStop.includes(result.stopReason)) {
382
+ // A truncated JSON response is a failure, not data (scar E2).
383
+ buffer.emit("remember.chunk.failed", undefined, {
384
+ index: chunk.index,
385
+ reason: "TRUNCATED",
386
+ stopReason: result.stopReason,
387
+ });
388
+ return { ...base, reason: "TRUNCATED", code: result.stopReason };
389
+ }
390
+ if (result.proposals !== undefined && !Array.isArray(result.proposals)) {
391
+ buffer.emit("remember.chunk.failed", undefined, { index: chunk.index, reason: "MALFORMED_RESULT" });
392
+ return { ...base, reason: "MALFORMED_RESULT" };
393
+ }
394
+
395
+ const proposals = result.proposals ?? [];
396
+ if (proposals.length === 0) {
397
+ // Returned nothing is NOT failed. The chunk's spans are consumed: they were
398
+ // read, and the sweep's verdict was "nothing here" (scar §2.4).
399
+ buffer.emit("remember.chunk.empty", undefined, { index: chunk.index, spans: chunk.spans.length });
400
+ return { ...base, ok: true, reason: "EMPTY" };
401
+ }
402
+
403
+ if (opts.apply !== undefined) {
404
+ try {
405
+ await opts.apply(proposals, chunk);
406
+ } catch (err) {
407
+ const code = errCode(err);
408
+ buffer.emit("remember.chunk.failed", undefined, {
409
+ index: chunk.index,
410
+ reason: "APPLY_FAILED",
411
+ code,
412
+ });
413
+ return { ...base, reason: "APPLY_FAILED", code, proposals: proposals.length };
414
+ }
415
+ }
416
+ buffer.emit("remember.chunk.applied", undefined, {
417
+ index: chunk.index,
418
+ spans: chunk.spans.length,
419
+ proposals: proposals.length,
420
+ });
421
+ return { ...base, ok: true, reason: "APPLIED", proposals: proposals.length };
422
+ }
423
+
424
+ export function chunkSpans(
425
+ spans: readonly Span[],
426
+ covered: ReadonlySet<string>,
427
+ chunkBytes: number,
428
+ ): SweepChunk[] {
429
+ const chunks: SweepChunk[] = [];
430
+ let current: Span[] = [];
431
+ let bytes = 0;
432
+ const flush = (): void => {
433
+ if (current.length === 0) return;
434
+ const marked = markCovered(current, covered);
435
+ chunks.push({
436
+ index: chunks.length,
437
+ spans: current,
438
+ marked,
439
+ prompt: renderForSweep(marked),
440
+ bytes,
441
+ });
442
+ current = [];
443
+ bytes = 0;
444
+ };
445
+ for (const span of spans) {
446
+ if (current.length > 0 && bytes + span.text.length > chunkBytes) flush();
447
+ current.push(span);
448
+ bytes += span.text.length;
449
+ }
450
+ flush();
451
+ return chunks;
452
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * `remember/` — the authorship pipeline's mechanics.
3
+ *
4
+ * The experiencer writes its own memories at session end, jots in the moment where
5
+ * the host allows, and a transcript sweep exists only as the crash fallback
6
+ * (CONTRACT.md §1). This module owns the *mechanics* of that: durable span capture,
7
+ * proposal intake, coverage by hash, `updates:` resolution, and the fallback's
8
+ * claim/consume choreography.
9
+ *
10
+ * What it deliberately does NOT own:
11
+ * - the gate battery (`encode/`) — injected as a `GateFn`;
12
+ * - the model call (an adapter) — injected as an `InterpretFn`;
13
+ * - who the `updates:` candidates are (`store/`, `schemas/`) — injected as a
14
+ * `CandidateSource` plus an `IdResolver`;
15
+ * - the salience clamp (`physics/`), which governs every memory, not just these.
16
+ *
17
+ * Every one of those seams, and every place another module must meet this one, is
18
+ * listed in INTERFACE-GAPS.md. Implementation choices the CONTRACT left open are in
19
+ * NOTES.md.
20
+ */
21
+ export { SpanBuffer, BOUNDARY_KINDS, WRITE_SITES, enters, keyFor, errCode } from "./spans.js";
22
+ export type {
23
+ BoundaryKind,
24
+ BoundaryRecord,
25
+ BufferOptions,
26
+ CaptureReason,
27
+ CaptureResult,
28
+ Claim,
29
+ ClaimOutcome,
30
+ ClaimRefusal,
31
+ CoverageMark,
32
+ CoverageReport,
33
+ FailureOutcome,
34
+ FailureRecord,
35
+ RememberEvent,
36
+ Span,
37
+ SpanKind,
38
+ Turn,
39
+ TurnSource,
40
+ WriteSite,
41
+ } from "./spans.js";
42
+
43
+ export {
44
+ ALREADY_AUTHORED_MARK,
45
+ AUTHOR_DIMENSIONS,
46
+ DRAFT_FIELDS,
47
+ NO_GATE,
48
+ intake,
49
+ markCovered,
50
+ renderForSweep,
51
+ submitProposal,
52
+ } from "./proposals.js";
53
+ export type {
54
+ Feeling,
55
+ GateFn,
56
+ GateInput,
57
+ GateVerdict,
58
+ IntakeResult,
59
+ MalformedReason,
60
+ MarkedSpan,
61
+ Proposal,
62
+ ProposalDraft,
63
+ ProposalRecord,
64
+ ProposalSource,
65
+ SubmitContext,
66
+ SubmitReason,
67
+ SubmitResult,
68
+ } from "./proposals.js";
69
+
70
+ export { resolveUpdates, similarity } from "./updates.js";
71
+ export type {
72
+ Candidate,
73
+ CandidateSource,
74
+ IdResolver,
75
+ UpdatesContext,
76
+ UpdatesMethod,
77
+ UpdatesReason,
78
+ UpdatesResolution,
79
+ } from "./updates.js";
80
+
81
+ export {
82
+ NOISY_IF_CHRONIC_SWEEP_REASONS,
83
+ NOISY_NOW_SWEEP_REASONS,
84
+ OK_STOP_REASONS,
85
+ QUIET_SWEEP_REASONS,
86
+ SWEEP_REASONS,
87
+ chunkSpans,
88
+ sweep,
89
+ sweepAll,
90
+ } from "./fallback.js";
91
+ export type {
92
+ ApplyFn,
93
+ ChunkOutcome,
94
+ ChunkReason,
95
+ InterpretFn,
96
+ InterpretResult,
97
+ SweepChunk,
98
+ SweepOptions,
99
+ SweepReason,
100
+ SweepReport,
101
+ } from "./fallback.js";
102
+
103
+ export { TUNABLES, validateWatchdog } from "./tunables.js";