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.
- package/CONSTITUTION.md +68 -0
- package/LICENSE +21 -0
- package/README.md +348 -0
- package/docs/ELI5.md +84 -0
- package/docs/QUICKSTART.md +1258 -0
- package/docs/module-map.md +81 -0
- package/package.json +63 -0
- package/src/adapters/claude-code/CONTRACT.md +606 -0
- package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
- package/src/adapters/claude-code/NOTES.md +1055 -0
- package/src/adapters/claude-code/bin/hook.ts +820 -0
- package/src/adapters/claude-code/bin/runner.ts +522 -0
- package/src/adapters/claude-code/config.ts +778 -0
- package/src/adapters/claude-code/credentials.ts +199 -0
- package/src/adapters/claude-code/doctor.ts +2557 -0
- package/src/adapters/claude-code/embed-client.ts +617 -0
- package/src/adapters/claude-code/hooks.ts +2240 -0
- package/src/adapters/claude-code/index.ts +224 -0
- package/src/adapters/claude-code/interpret-client.ts +395 -0
- package/src/adapters/claude-code/page-writer.ts +462 -0
- package/src/adapters/claude-code/primacy.ts +162 -0
- package/src/adapters/claude-code/spawn.ts +241 -0
- package/src/adapters/claude-code/standdown.ts +536 -0
- package/src/adapters/claude-code/transcript.ts +661 -0
- package/src/adapters/claude-code/vectors.ts +415 -0
- package/src/adapters/cli/CONTRACT.md +255 -0
- package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
- package/src/adapters/cli/NOTES.md +936 -0
- package/src/adapters/cli/bin/counterparts.ts +74 -0
- package/src/adapters/cli/commands.ts +6095 -0
- package/src/adapters/cli/export.ts +766 -0
- package/src/adapters/cli/index.ts +103 -0
- package/src/adapters/cli/install.ts +670 -0
- package/src/adapters/cli/removal.ts +1186 -0
- package/src/adapters/cli/repair-dates.ts +659 -0
- package/src/adapters/cli/self-page.ts +229 -0
- package/src/adapters/cli/snapshot.ts +279 -0
- package/src/adapters/cli/start-fresh.ts +1228 -0
- package/src/adapters/config-path.ts +342 -0
- package/src/adapters/dashboard/CONTRACT.md +67 -0
- package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
- package/src/adapters/dashboard/NOTES.md +474 -0
- package/src/adapters/dashboard/activity.ts +121 -0
- package/src/adapters/dashboard/ansi.ts +82 -0
- package/src/adapters/dashboard/bin/dashboard.ts +479 -0
- package/src/adapters/dashboard/browse.ts +298 -0
- package/src/adapters/dashboard/identity.ts +182 -0
- package/src/adapters/dashboard/index.ts +183 -0
- package/src/adapters/dashboard/layout.ts +149 -0
- package/src/adapters/dashboard/registries.ts +291 -0
- package/src/adapters/dashboard/resolve.ts +206 -0
- package/src/adapters/dashboard/source.ts +48 -0
- package/src/adapters/dashboard/status.ts +327 -0
- package/src/adapters/dashboard/stories.ts +194 -0
- package/src/adapters/dashboard/web/app.html +1731 -0
- package/src/adapters/dashboard/web/brain.html +463 -0
- package/src/adapters/dashboard/web/fired.ts +31 -0
- package/src/adapters/dashboard/web/flow.ts +457 -0
- package/src/adapters/dashboard/web/narrate.ts +1042 -0
- package/src/adapters/dashboard/web/reveal.ts +135 -0
- package/src/adapters/dashboard/web/server.ts +287 -0
- package/src/adapters/dashboard/web/views.ts +1744 -0
- package/src/adapters/expansions.ts +569 -0
- package/src/adapters/fired.ts +1580 -0
- package/src/adapters/mcp/CONTRACT.md +240 -0
- package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
- package/src/adapters/mcp/NOTES.md +205 -0
- package/src/adapters/mcp/bin/serve.ts +349 -0
- package/src/adapters/mcp/deliberate.ts +619 -0
- package/src/adapters/mcp/index.ts +101 -0
- package/src/adapters/mcp/protocol.ts +170 -0
- package/src/adapters/mcp/server.ts +1740 -0
- package/src/adapters/mcp/stdio.ts +56 -0
- package/src/adapters/mcp/tools.ts +779 -0
- package/src/adapters/scopes.ts +657 -0
- package/src/adapters/sessions.ts +402 -0
- package/src/adapters/snapshots.ts +1069 -0
- package/src/adapters/stance-env.ts +137 -0
- package/src/core/associate/CONTRACT.md +118 -0
- package/src/core/associate/INTERFACE-GAPS.md +173 -0
- package/src/core/associate/NOTES.md +194 -0
- package/src/core/associate/buffer.ts +66 -0
- package/src/core/associate/edges.ts +188 -0
- package/src/core/associate/index.ts +570 -0
- package/src/core/associate/pending.ts +383 -0
- package/src/core/associate/spread.ts +149 -0
- package/src/core/associate/tunables.ts +123 -0
- package/src/core/bridge.ts +272 -0
- package/src/core/briefing.ts +67 -0
- package/src/core/counterpart.ts +3855 -0
- package/src/core/encode/CONTRACT.md +151 -0
- package/src/core/encode/INTERFACE-GAPS.md +135 -0
- package/src/core/encode/NOTES.md +146 -0
- package/src/core/encode/aliases.ts +71 -0
- package/src/core/encode/battery.ts +284 -0
- package/src/core/encode/chunk.ts +265 -0
- package/src/core/encode/emotion.ts +119 -0
- package/src/core/encode/floor.ts +76 -0
- package/src/core/encode/index.ts +100 -0
- package/src/core/encode/precision.ts +162 -0
- package/src/core/encode/preselect.ts +269 -0
- package/src/core/encode/salience.ts +108 -0
- package/src/core/encode/secrets.ts +265 -0
- package/src/core/encode/tunables.ts +99 -0
- package/src/core/encode/types.ts +286 -0
- package/src/core/encode/words.ts +75 -0
- package/src/core/handoff/CONTRACT.md +199 -0
- package/src/core/handoff/INTERFACE-GAPS.md +166 -0
- package/src/core/handoff/NOTES.md +206 -0
- package/src/core/handoff/index.ts +957 -0
- package/src/core/mint.ts +279 -0
- package/src/core/observer.ts +28 -0
- package/src/core/physics/CONTRACT.md +341 -0
- package/src/core/physics/NOTES.md +155 -0
- package/src/core/physics/clock.ts +51 -0
- package/src/core/physics/index.ts +1054 -0
- package/src/core/prospective/CONTRACT.md +137 -0
- package/src/core/prospective/INTERFACE-GAPS.md +112 -0
- package/src/core/prospective/NOTES.md +160 -0
- package/src/core/prospective/derive.ts +188 -0
- package/src/core/prospective/index.ts +1030 -0
- package/src/core/prospective/tunables.ts +72 -0
- package/src/core/prospective/windows.ts +187 -0
- package/src/core/recall/CONTRACT.md +326 -0
- package/src/core/recall/INTERFACE-GAPS.md +163 -0
- package/src/core/recall/NOTES.md +472 -0
- package/src/core/recall/activate.ts +521 -0
- package/src/core/recall/cues.ts +275 -0
- package/src/core/recall/gate.ts +441 -0
- package/src/core/recall/index.ts +692 -0
- package/src/core/recall/probe.ts +239 -0
- package/src/core/recall/reference.ts +201 -0
- package/src/core/recall/render.ts +285 -0
- package/src/core/recall/session.ts +403 -0
- package/src/core/recall/tunables.ts +329 -0
- package/src/core/remember/CONTRACT.md +293 -0
- package/src/core/remember/INTERFACE-GAPS.md +189 -0
- package/src/core/remember/NOTES.md +373 -0
- package/src/core/remember/fallback.ts +452 -0
- package/src/core/remember/index.ts +103 -0
- package/src/core/remember/owner-strike-seam.ts +479 -0
- package/src/core/remember/proposals.ts +609 -0
- package/src/core/remember/spans.ts +1310 -0
- package/src/core/remember/tunables.ts +111 -0
- package/src/core/remember/updates.ts +198 -0
- package/src/core/retrieval.ts +96 -0
- package/src/core/revision.ts +441 -0
- package/src/core/schemas/CONTRACT.md +190 -0
- package/src/core/schemas/INTERFACE-GAPS.md +172 -0
- package/src/core/schemas/NOTES.md +260 -0
- package/src/core/schemas/aliases.ts +160 -0
- package/src/core/schemas/index.ts +1459 -0
- package/src/core/schemas/tunables.ts +44 -0
- package/src/core/schemas/types.ts +387 -0
- package/src/core/self/CONTRACT.md +459 -0
- package/src/core/self/INTERFACE-GAPS.md +284 -0
- package/src/core/self/NOTES.md +1057 -0
- package/src/core/self/briefing.ts +980 -0
- package/src/core/self/episodes.ts +483 -0
- package/src/core/self/freeze.ts +103 -0
- package/src/core/self/identity.ts +604 -0
- package/src/core/self/index.ts +2130 -0
- package/src/core/self/journal-file.ts +760 -0
- package/src/core/self/page.ts +404 -0
- package/src/core/self/tunables.ts +244 -0
- package/src/core/self/writer.ts +714 -0
- package/src/core/sleep/CONTRACT.md +298 -0
- package/src/core/sleep/INTERFACE-GAPS.md +262 -0
- package/src/core/sleep/NOTES.md +770 -0
- package/src/core/sleep/briefing.ts +86 -0
- package/src/core/sleep/consolidate.ts +241 -0
- package/src/core/sleep/cycle.ts +598 -0
- package/src/core/sleep/decay.ts +237 -0
- package/src/core/sleep/dedup.ts +373 -0
- package/src/core/sleep/index.ts +112 -0
- package/src/core/sleep/log.ts +116 -0
- package/src/core/sleep/markers.ts +164 -0
- package/src/core/sleep/prune.ts +170 -0
- package/src/core/sleep/strength-cache.ts +176 -0
- package/src/core/sleep/tunables.ts +135 -0
- package/src/core/sleep/types.ts +542 -0
- package/src/core/store/CONTRACT.md +446 -0
- package/src/core/store/NOTES.md +1068 -0
- package/src/core/store/cache.ts +709 -0
- package/src/core/store/db.ts +275 -0
- package/src/core/store/errors.ts +134 -0
- package/src/core/store/index.ts +2450 -0
- package/src/core/store/operational.ts +610 -0
- package/src/core/store/owner-op-seam.ts +428 -0
- package/src/core/store/paths.ts +494 -0
- package/src/core/store/prose.ts +165 -0
- package/src/core/store/render.ts +87 -0
- package/src/core/store/walk-seam.ts +78 -0
- package/src/core/types.ts +68 -0
- package/tools/install-loop/run.sh +1063 -0
|
@@ -0,0 +1,1310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The span buffer — durable holding for lived experience, written at microsecond
|
|
3
|
+
* speed so no host ever waits on judgment (contract §5 G1).
|
|
4
|
+
*
|
|
5
|
+
* Everything durable lives under `<dataDir>/spans/`, one directory per scope:
|
|
6
|
+
*
|
|
7
|
+
* spans/
|
|
8
|
+
* scopes.json the key -> scope legend (keys are hashes, see NOTES §2)
|
|
9
|
+
* cursors/<scope>.<session>.json ONE file per (scope, session) — disjoint by
|
|
10
|
+
* construction, and scoped so one session id under
|
|
11
|
+
* two scopes cannot starve either (PR-1 review)
|
|
12
|
+
* <key>/buffer.jsonl the live conversational buffer (append-only)
|
|
13
|
+
* <key>/assistant.jsonl the assistant's own turns, kept separately
|
|
14
|
+
* <key>/boundaries.jsonl every session-ending boundary, and its ask
|
|
15
|
+
* <key>/coverage.jsonl spanHash -> proposalId (the engine's claims)
|
|
16
|
+
* <key>/proposals.jsonl minted proposals (also the content-idempotency ledger)
|
|
17
|
+
* <key>/consumed.jsonl bounded hash ledger — dedup layer 2 after a claim dies
|
|
18
|
+
* <key>/failures.jsonl bounded {hash, at, code} ledger — the retry bound
|
|
19
|
+
* <key>/quarantine.jsonl spans that failed MAX_SPAN_FAILURES times, in full
|
|
20
|
+
* <key>/claims/<id>.jsonl a claim, renamed ASIDE from the buffer
|
|
21
|
+
*
|
|
22
|
+
* Four structural properties, each load-bearing (contract §5 G3):
|
|
23
|
+
*
|
|
24
|
+
* advance-after-success the cursor moves only after the append landed;
|
|
25
|
+
* two dedup layers a per-session cursor for a GROWING transcript, a content
|
|
26
|
+
* hash for exact repeats — neither catches the other's case;
|
|
27
|
+
* rename choreography a claim is `rename(2)`d aside, so a concurrent append
|
|
28
|
+
* lands in a fresh buffer and cannot be destroyed;
|
|
29
|
+
* restore-before-consume a failed restore keeps the claim, so a failed arc is
|
|
30
|
+
* never in neither place.
|
|
31
|
+
*
|
|
32
|
+
* Nothing here calls a model, and nothing here throws into the host (G2): every
|
|
33
|
+
* public capture path is synchronous, wrapped, and returns a REASON.
|
|
34
|
+
*/
|
|
35
|
+
import {
|
|
36
|
+
appendFileSync,
|
|
37
|
+
existsSync,
|
|
38
|
+
mkdirSync,
|
|
39
|
+
readFileSync,
|
|
40
|
+
readdirSync,
|
|
41
|
+
renameSync,
|
|
42
|
+
rmSync,
|
|
43
|
+
statSync,
|
|
44
|
+
writeFileSync,
|
|
45
|
+
} from "node:fs";
|
|
46
|
+
import { randomBytes } from "node:crypto";
|
|
47
|
+
import { basename, join } from "node:path";
|
|
48
|
+
|
|
49
|
+
import { grantSpanStrike } from "./owner-strike-seam.js";
|
|
50
|
+
import { hashText } from "../store/prose.js";
|
|
51
|
+
import { dataDir } from "../store/paths.js";
|
|
52
|
+
import { isObserver } from "../observer.js";
|
|
53
|
+
import type { Stance } from "../observer.js";
|
|
54
|
+
import { TUNABLES } from "./tunables.js";
|
|
55
|
+
|
|
56
|
+
// ── vocabulary ───────────────────────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
/** Provenance of a turn. Only conversational text (and host-injected context)
|
|
59
|
+
* enters capture; tool output, file contents and images never do. This is a
|
|
60
|
+
* DECLARED blind spot, not an oversight (§3, behavioral-spec §2 G10/G11).
|
|
61
|
+
*
|
|
62
|
+
* `foreign` is the parallel run's addition: material ANOTHER memory system's
|
|
63
|
+
* hooks put into this host's context. It is not the host speaking (`injected`)
|
|
64
|
+
* and it is certainly not the user, so it enters nothing — see `enters()`.
|
|
65
|
+
*
|
|
66
|
+
* `ritual` is THIS system's own asks, read back off the transcript. A host that
|
|
67
|
+
* returns hook output into the context (Claude Code's `Stop hook feedback:`)
|
|
68
|
+
* hands us our own words as though the user had said them; encoding those is
|
|
69
|
+
* the self-referential half of the same mistake `foreign` names. It enters
|
|
70
|
+
* nothing either, and — because it is refused rather than dropped silently —
|
|
71
|
+
* it is COUNTED in `CaptureResult.excluded`, so the exclusion is a number the
|
|
72
|
+
* boundary record carries rather than an absence nobody can see. */
|
|
73
|
+
export type TurnSource =
|
|
74
|
+
| "conversation"
|
|
75
|
+
| "injected"
|
|
76
|
+
| "tool"
|
|
77
|
+
| "file"
|
|
78
|
+
| "image"
|
|
79
|
+
| "foreign"
|
|
80
|
+
| "ritual";
|
|
81
|
+
|
|
82
|
+
export interface Turn {
|
|
83
|
+
role: "user" | "assistant";
|
|
84
|
+
text: string;
|
|
85
|
+
/** Absent reads as "conversation". */
|
|
86
|
+
source?: TurnSource;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export type SpanKind = "conversation" | "assistant" | "jot";
|
|
90
|
+
|
|
91
|
+
/** One appended span. `text` is the only content; everything else is reference. */
|
|
92
|
+
export interface Span {
|
|
93
|
+
hash: string;
|
|
94
|
+
session: string;
|
|
95
|
+
scope: string;
|
|
96
|
+
kind: SpanKind;
|
|
97
|
+
text: string;
|
|
98
|
+
at: number;
|
|
99
|
+
day: number;
|
|
100
|
+
/** Cursor positions this span covers — [from, to) in the session's turn list. */
|
|
101
|
+
from: number;
|
|
102
|
+
to: number;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Every session-ending path is a boundary (contract §3, spec §2 G5). All three
|
|
106
|
+
* route through `boundary()`, and all three raise the ask. */
|
|
107
|
+
export type BoundaryKind = "stop" | "session-end" | "pre-compaction";
|
|
108
|
+
export const BOUNDARY_KINDS: readonly BoundaryKind[] = [
|
|
109
|
+
"stop",
|
|
110
|
+
"session-end",
|
|
111
|
+
"pre-compaction",
|
|
112
|
+
];
|
|
113
|
+
|
|
114
|
+
export interface BoundaryRecord {
|
|
115
|
+
session: string;
|
|
116
|
+
scope: string;
|
|
117
|
+
kind: BoundaryKind;
|
|
118
|
+
at: number;
|
|
119
|
+
day: number;
|
|
120
|
+
/** G11's mechanized half: an ask exists at every session-ending path. */
|
|
121
|
+
askRaised: boolean;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface RememberEvent {
|
|
125
|
+
at: number;
|
|
126
|
+
name: string;
|
|
127
|
+
ref?: string;
|
|
128
|
+
data?: Record<string, string | number | boolean | null>;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Every site that can change durable state under `spans/`. The totality test
|
|
133
|
+
* asserts this list equals the set of sites that consult the observer predicate,
|
|
134
|
+
* and that each one refuses under observer (contract §5 G8 — checked at the seam,
|
|
135
|
+
* not only at the entry point).
|
|
136
|
+
*/
|
|
137
|
+
export const WRITE_SITES = [
|
|
138
|
+
"capture",
|
|
139
|
+
"jot",
|
|
140
|
+
"boundary",
|
|
141
|
+
"claim",
|
|
142
|
+
"consume",
|
|
143
|
+
"restore",
|
|
144
|
+
"coverage",
|
|
145
|
+
"proposal",
|
|
146
|
+
"sweep",
|
|
147
|
+
"failure",
|
|
148
|
+
// The OWNER's strike. It is a write site like any other — an instrument that
|
|
149
|
+
// has stood down may not destroy a span any more than it may append one
|
|
150
|
+
// (observer-mode G3) — and it is reachable only by importing
|
|
151
|
+
// `owner-strike-seam.ts`, never by holding a `SpanBuffer` (§5 G2's shape,
|
|
152
|
+
// borrowed from `store/owner-op-seam.ts`).
|
|
153
|
+
"strike",
|
|
154
|
+
] as const;
|
|
155
|
+
export type WriteSite = (typeof WRITE_SITES)[number];
|
|
156
|
+
|
|
157
|
+
export type CaptureReason =
|
|
158
|
+
| "APPENDED"
|
|
159
|
+
| "OBSERVER"
|
|
160
|
+
| "NOTHING_NEW"
|
|
161
|
+
| "ALL_EXCLUDED"
|
|
162
|
+
| "DEDUPED"
|
|
163
|
+
| "IO_FAILED";
|
|
164
|
+
|
|
165
|
+
export interface CaptureResult {
|
|
166
|
+
captured: boolean;
|
|
167
|
+
reason: CaptureReason;
|
|
168
|
+
spans: Span[];
|
|
169
|
+
/** Layer-2 hits: content already held. Bounded duplication is acceptable; loss is not. */
|
|
170
|
+
deduped: number;
|
|
171
|
+
/** Turns dropped as non-conversational (the declared blind spot). */
|
|
172
|
+
excluded: number;
|
|
173
|
+
cursorBefore: number;
|
|
174
|
+
cursorAfter: number;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export interface Claim {
|
|
178
|
+
id: string;
|
|
179
|
+
scope: string;
|
|
180
|
+
path: string;
|
|
181
|
+
spans: Span[];
|
|
182
|
+
bytes: number;
|
|
183
|
+
/** Claim files from crashed runs that merged into this one (spec §2 G6). */
|
|
184
|
+
mergedOrphans: string[];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export type ClaimRefusal =
|
|
188
|
+
| "OBSERVER"
|
|
189
|
+
| "EMPTY"
|
|
190
|
+
| "BELOW_MIN_CLAIM"
|
|
191
|
+
| "IO_FAILED";
|
|
192
|
+
|
|
193
|
+
export type ClaimOutcome =
|
|
194
|
+
| { claimed: true; claim: Claim }
|
|
195
|
+
| { claimed: false; reason: ClaimRefusal; bytes: number };
|
|
196
|
+
|
|
197
|
+
export interface CoverageMark {
|
|
198
|
+
spanHash: string;
|
|
199
|
+
proposalId: string;
|
|
200
|
+
session: string;
|
|
201
|
+
at: number;
|
|
202
|
+
/** True for the proposal's OWN span, which is withheld from the sweep outright
|
|
203
|
+
* (§4.1 G4) rather than merely marked. */
|
|
204
|
+
own: boolean;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** One recorded interpretation failure. The hash is the buffer's own span hash —
|
|
208
|
+
* the identifier that already lives in `consumed.jsonl` — and never the text. */
|
|
209
|
+
export interface FailureRecord {
|
|
210
|
+
hash: string;
|
|
211
|
+
at: number;
|
|
212
|
+
/** The LIVED day of the failure (scar E8). The bound counts distinct days, not
|
|
213
|
+
* attempts: three Stop hooks inside one API outage are one day's failure. */
|
|
214
|
+
day: number;
|
|
215
|
+
/** The chunk's failure code, or its `ChunkReason` when it carried none. */
|
|
216
|
+
code: string;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** What `noteFailures()` decided about a batch of failed spans. */
|
|
220
|
+
export interface FailureOutcome {
|
|
221
|
+
/** Still under the bound: these go back to the buffer and are retried. */
|
|
222
|
+
retry: Span[];
|
|
223
|
+
/** At the bound: written to `quarantine.jsonl` IN FULL and never restored. */
|
|
224
|
+
quarantined: Span[];
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export interface CoverageReport {
|
|
228
|
+
scope: string;
|
|
229
|
+
spans: number;
|
|
230
|
+
covered: number;
|
|
231
|
+
uncovered: number;
|
|
232
|
+
/** Spans captured after the last session-ending boundary — the stretch nobody
|
|
233
|
+
* can be asked about. Bounded and reported, never pretended away (G12). */
|
|
234
|
+
unaskableSpans: number;
|
|
235
|
+
unaskableBytes: number;
|
|
236
|
+
lastBoundaryAt: number | null;
|
|
237
|
+
/** Spans that left the buffer at the retry bound. They are NOT in `spans`, and
|
|
238
|
+
* counting them here is the point: a span the sweep gave up on is a number the
|
|
239
|
+
* owner can see, never a silent absence (scar §2.4). The text is in
|
|
240
|
+
* `quarantine.jsonl`. */
|
|
241
|
+
quarantined: number;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export interface BufferOptions extends Stance {
|
|
245
|
+
/** Defaults to `dataDir()` — resolved at call time, so tests redirect via env. */
|
|
246
|
+
dir?: string;
|
|
247
|
+
now?: () => number;
|
|
248
|
+
/** The lived day (active-day clock, scar E8). Days, never calendar timestamps. */
|
|
249
|
+
day?: () => number;
|
|
250
|
+
minClaimBytes?: number;
|
|
251
|
+
staleClaimMs?: number;
|
|
252
|
+
/** How long a session must be silent before the fallback may call it crashed
|
|
253
|
+
* (TUNABLES.CRASH_STALE_MS). Nothing to do with `staleClaimMs`. */
|
|
254
|
+
crashStaleMs?: number;
|
|
255
|
+
consumedLedgerMax?: number;
|
|
256
|
+
maxSpanFailures?: number;
|
|
257
|
+
onEvent?: (event: RememberEvent) => void;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const EVENT_RING = 500;
|
|
261
|
+
|
|
262
|
+
// ── the buffer ───────────────────────────────────────────────────────────────
|
|
263
|
+
|
|
264
|
+
export class SpanBuffer {
|
|
265
|
+
readonly dir: string;
|
|
266
|
+
readonly root: string;
|
|
267
|
+
readonly observer: boolean;
|
|
268
|
+
readonly minClaimBytes: number;
|
|
269
|
+
readonly staleClaimMs: number;
|
|
270
|
+
readonly crashStaleMs: number;
|
|
271
|
+
readonly consumedLedgerMax: number;
|
|
272
|
+
readonly maxSpanFailures: number;
|
|
273
|
+
private readonly nowFn: () => number;
|
|
274
|
+
private readonly dayFn: () => number;
|
|
275
|
+
private readonly onEvent: ((e: RememberEvent) => void) | undefined;
|
|
276
|
+
private readonly ring: RememberEvent[] = [];
|
|
277
|
+
|
|
278
|
+
constructor(opts: BufferOptions = {}) {
|
|
279
|
+
this.dir = opts.dir ?? dataDir();
|
|
280
|
+
this.root = join(this.dir, "spans");
|
|
281
|
+
this.observer = isObserver(opts);
|
|
282
|
+
this.minClaimBytes = opts.minClaimBytes ?? TUNABLES.MIN_CLAIM_BYTES;
|
|
283
|
+
this.staleClaimMs = opts.staleClaimMs ?? TUNABLES.STALE_CLAIM_MS;
|
|
284
|
+
this.crashStaleMs = opts.crashStaleMs ?? TUNABLES.CRASH_STALE_MS;
|
|
285
|
+
this.consumedLedgerMax = opts.consumedLedgerMax ?? TUNABLES.CONSUMED_LEDGER_MAX;
|
|
286
|
+
this.maxSpanFailures = opts.maxSpanFailures ?? TUNABLES.MAX_SPAN_FAILURES;
|
|
287
|
+
this.nowFn = opts.now ?? (() => Date.now());
|
|
288
|
+
this.dayFn = opts.day ?? (() => 0);
|
|
289
|
+
this.onEvent = opts.onEvent;
|
|
290
|
+
// The destruction capability, handed over at construction the way `Store`
|
|
291
|
+
// hands `owner-op-seam.ts` its own: holding a buffer does not let you strike
|
|
292
|
+
// a span; importing the seam does, and a test pins who may import it.
|
|
293
|
+
grantSpanStrike(this, {
|
|
294
|
+
observer: this.observer,
|
|
295
|
+
scopes: () => this.scopes(),
|
|
296
|
+
scopeDir: (scope) => this.scopeDir(scope),
|
|
297
|
+
path: (scope, name) => this.path(scope, name),
|
|
298
|
+
claimFiles: (scope) => this.claimFiles(scope),
|
|
299
|
+
streamPath: (scope, kind) => this.streamPath(scope, kind),
|
|
300
|
+
ensureScope: (scope) => this.ensureScope(scope),
|
|
301
|
+
readLines: (file) => this.readLines(file),
|
|
302
|
+
mutate: (site, fn) => this.mutate(site, fn),
|
|
303
|
+
emit: (name, ref, data) => this.emit(name, ref, data),
|
|
304
|
+
now: () => this.nowFn(),
|
|
305
|
+
day: () => this.dayFn(),
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
now(): number {
|
|
310
|
+
return this.nowFn();
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
day(): number {
|
|
314
|
+
return this.dayFn();
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// ── the seam ───────────────────────────────────────────────────────────────
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* The one place a span-side write happens. Stance first, work second — the same
|
|
321
|
+
* ordering the store seam uses, for the same reason: an instrument refuses before
|
|
322
|
+
* it has staged a byte, and a future caller inherits the refusal (§5 G8).
|
|
323
|
+
*
|
|
324
|
+
* It returns a discriminated result rather than throwing, because every caller
|
|
325
|
+
* on the capture path is forbidden to throw into the host (§5 G2).
|
|
326
|
+
*/
|
|
327
|
+
private mutate<T>(site: WriteSite, fn: () => T): { ok: true; value: T } | { ok: false; reason: "OBSERVER" | "IO_FAILED"; code: string } {
|
|
328
|
+
if (this.observer) {
|
|
329
|
+
this.emit("remember.observer.standdown", undefined, { site });
|
|
330
|
+
return { ok: false, reason: "OBSERVER", code: "OBSERVER" };
|
|
331
|
+
}
|
|
332
|
+
try {
|
|
333
|
+
return { ok: true, value: fn() };
|
|
334
|
+
} catch (err) {
|
|
335
|
+
const code = errCode(err);
|
|
336
|
+
this.emit("remember.write.failed", undefined, { site, code });
|
|
337
|
+
return { ok: false, reason: "IO_FAILED", code };
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
emit(
|
|
342
|
+
name: string,
|
|
343
|
+
ref?: string,
|
|
344
|
+
data?: Record<string, string | number | boolean | null>,
|
|
345
|
+
): void {
|
|
346
|
+
const event: RememberEvent = { at: this.nowFn(), name };
|
|
347
|
+
if (ref !== undefined) event.ref = ref;
|
|
348
|
+
if (data !== undefined) event.data = data;
|
|
349
|
+
this.ring.push(event);
|
|
350
|
+
if (this.ring.length > EVENT_RING) this.ring.shift();
|
|
351
|
+
this.onEvent?.(event);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
events(name?: string): RememberEvent[] {
|
|
355
|
+
return this.ring.filter((e) => name === undefined || e.name === name).map((e) => ({ ...e }));
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// ── capture ────────────────────────────────────────────────────────────────
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* A turn boundary: append what is new since this session's cursor, then advance.
|
|
362
|
+
*
|
|
363
|
+
* Synchronous by construction — a boundary is an appender, not a thinker, and a
|
|
364
|
+
* `Promise` return type here would be the first crack in that (G1). Failures are
|
|
365
|
+
* logged and swallowed; the cursor stays put so the next boundary re-reads (G2).
|
|
366
|
+
*/
|
|
367
|
+
capture(input: { session: string; scope: string; turns: readonly Turn[] }): CaptureResult {
|
|
368
|
+
try {
|
|
369
|
+
return this.captureInner(input);
|
|
370
|
+
} catch (err) {
|
|
371
|
+
// The outermost swallow. Nothing below is allowed to reach the host (G2).
|
|
372
|
+
const code = errCode(err);
|
|
373
|
+
this.emit("remember.capture.failed", undefined, { code });
|
|
374
|
+
return {
|
|
375
|
+
captured: false,
|
|
376
|
+
reason: "IO_FAILED",
|
|
377
|
+
spans: [],
|
|
378
|
+
deduped: 0,
|
|
379
|
+
excluded: 0,
|
|
380
|
+
cursorBefore: 0,
|
|
381
|
+
cursorAfter: 0,
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
private captureInner(input: {
|
|
387
|
+
session: string;
|
|
388
|
+
scope: string;
|
|
389
|
+
turns: readonly Turn[];
|
|
390
|
+
}): CaptureResult {
|
|
391
|
+
const cursorBefore = this.cursor(input.scope, input.session);
|
|
392
|
+
const empty = (reason: CaptureReason, cursorAfter = cursorBefore): CaptureResult => ({
|
|
393
|
+
captured: false,
|
|
394
|
+
reason,
|
|
395
|
+
spans: [],
|
|
396
|
+
deduped: 0,
|
|
397
|
+
excluded: 0,
|
|
398
|
+
cursorBefore,
|
|
399
|
+
cursorAfter,
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
if (this.observer) {
|
|
403
|
+
this.emit("remember.observer.standdown", undefined, { site: "capture" });
|
|
404
|
+
return empty("OBSERVER");
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const slice = input.turns.slice(cursorBefore);
|
|
408
|
+
if (slice.length === 0) return empty("NOTHING_NEW");
|
|
409
|
+
|
|
410
|
+
const kept = slice.filter((t) => enters(t));
|
|
411
|
+
const excluded = slice.length - kept.length;
|
|
412
|
+
if (kept.length === 0) {
|
|
413
|
+
// Nothing conversational happened: still advance, or the same tool output is
|
|
414
|
+
// re-scanned forever. Nothing durable was skipped — it was never eligible.
|
|
415
|
+
const advanced = this.mutate("capture", () =>
|
|
416
|
+
this.writeCursor(input.scope, input.session, input.turns.length),
|
|
417
|
+
);
|
|
418
|
+
const out = empty(advanced.ok ? "ALL_EXCLUDED" : "IO_FAILED", advanced.ok ? input.turns.length : cursorBefore);
|
|
419
|
+
out.excluded = excluded;
|
|
420
|
+
return out;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const at = this.nowFn();
|
|
424
|
+
const day = this.dayFn();
|
|
425
|
+
const drafts: Span[] = [];
|
|
426
|
+
for (const kind of ["conversation", "assistant"] as const) {
|
|
427
|
+
const text = kept
|
|
428
|
+
.filter((t) => (kind === "assistant" ? t.role === "assistant" : t.role !== "assistant"))
|
|
429
|
+
.map((t) => t.text)
|
|
430
|
+
.join("\n\n");
|
|
431
|
+
if (text.trim().length === 0) continue;
|
|
432
|
+
drafts.push({
|
|
433
|
+
hash: hashText(text),
|
|
434
|
+
session: input.session,
|
|
435
|
+
scope: input.scope,
|
|
436
|
+
kind,
|
|
437
|
+
text,
|
|
438
|
+
at,
|
|
439
|
+
day,
|
|
440
|
+
from: cursorBefore,
|
|
441
|
+
to: input.turns.length,
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const seen = this.seenHashes(input.scope);
|
|
446
|
+
const fresh = drafts.filter((s) => !seen.has(s.hash));
|
|
447
|
+
const deduped = drafts.length - fresh.length;
|
|
448
|
+
|
|
449
|
+
const written = this.mutate("capture", () => {
|
|
450
|
+
this.ensureScope(input.scope);
|
|
451
|
+
// Append FIRST. If the cursor write then fails, the hash is already in the
|
|
452
|
+
// buffer, so the next boundary's layer-2 catches the repeat (G3's pairing).
|
|
453
|
+
for (const span of fresh) {
|
|
454
|
+
appendFileSync(this.streamPath(span.scope, span.kind), `${JSON.stringify(span)}\n`, "utf8");
|
|
455
|
+
}
|
|
456
|
+
this.writeCursor(input.scope, input.session, input.turns.length);
|
|
457
|
+
return fresh;
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
if (!written.ok) {
|
|
461
|
+
const out = empty("IO_FAILED");
|
|
462
|
+
out.excluded = excluded;
|
|
463
|
+
out.deduped = deduped;
|
|
464
|
+
return out;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
for (const span of fresh) {
|
|
468
|
+
this.emit("remember.span.appended", span.hash, {
|
|
469
|
+
session: span.session,
|
|
470
|
+
kind: span.kind,
|
|
471
|
+
bytes: span.text.length,
|
|
472
|
+
day: span.day,
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
if (deduped > 0) {
|
|
476
|
+
this.emit("remember.span.deduped", undefined, { scope: keyFor(input.scope), count: deduped });
|
|
477
|
+
}
|
|
478
|
+
return {
|
|
479
|
+
captured: fresh.length > 0,
|
|
480
|
+
reason: fresh.length > 0 ? "APPENDED" : "DEDUPED",
|
|
481
|
+
spans: fresh,
|
|
482
|
+
deduped,
|
|
483
|
+
excluded,
|
|
484
|
+
cursorBefore,
|
|
485
|
+
cursorAfter: input.turns.length,
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* An in-the-moment jot. It rides in the buffer with ordinary spans (uniform
|
|
491
|
+
* ordering, claim and dedup semantics — CONTRACT open question 3, answered the
|
|
492
|
+
* simple way in NOTES §4) and carries no cursor movement of its own.
|
|
493
|
+
*/
|
|
494
|
+
jot(input: { session: string; scope: string; text: string }): CaptureResult {
|
|
495
|
+
const cursorBefore = this.cursor(input.scope, input.session);
|
|
496
|
+
const base: CaptureResult = {
|
|
497
|
+
captured: false,
|
|
498
|
+
reason: "APPENDED",
|
|
499
|
+
spans: [],
|
|
500
|
+
deduped: 0,
|
|
501
|
+
excluded: 0,
|
|
502
|
+
cursorBefore,
|
|
503
|
+
cursorAfter: cursorBefore,
|
|
504
|
+
};
|
|
505
|
+
if (this.observer) {
|
|
506
|
+
this.emit("remember.observer.standdown", undefined, { site: "jot" });
|
|
507
|
+
return { ...base, reason: "OBSERVER" };
|
|
508
|
+
}
|
|
509
|
+
if (input.text.trim().length === 0) return { ...base, reason: "NOTHING_NEW" };
|
|
510
|
+
|
|
511
|
+
const span: Span = {
|
|
512
|
+
hash: hashText(input.text),
|
|
513
|
+
session: input.session,
|
|
514
|
+
scope: input.scope,
|
|
515
|
+
kind: "jot",
|
|
516
|
+
text: input.text,
|
|
517
|
+
at: this.nowFn(),
|
|
518
|
+
day: this.dayFn(),
|
|
519
|
+
from: cursorBefore,
|
|
520
|
+
to: cursorBefore,
|
|
521
|
+
};
|
|
522
|
+
if (this.seenHashes(input.scope).has(span.hash)) {
|
|
523
|
+
this.emit("remember.span.deduped", span.hash, { scope: keyFor(input.scope), count: 1 });
|
|
524
|
+
return { ...base, reason: "DEDUPED", deduped: 1 };
|
|
525
|
+
}
|
|
526
|
+
const written = this.mutate("jot", () => {
|
|
527
|
+
this.ensureScope(span.scope);
|
|
528
|
+
appendFileSync(this.streamPath(span.scope, "jot"), `${JSON.stringify(span)}\n`, "utf8");
|
|
529
|
+
});
|
|
530
|
+
if (!written.ok) return { ...base, reason: "IO_FAILED" };
|
|
531
|
+
this.emit("remember.span.appended", span.hash, {
|
|
532
|
+
session: span.session,
|
|
533
|
+
kind: "jot",
|
|
534
|
+
bytes: span.text.length,
|
|
535
|
+
day: span.day,
|
|
536
|
+
});
|
|
537
|
+
return { ...base, captured: true, reason: "APPENDED", spans: [span] };
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* A session-ending boundary. All three kinds route through here, and all three
|
|
542
|
+
* raise the ask — compaction destroying the transcript must not destroy the day
|
|
543
|
+
* (§3, spec §2 G5). The ask's WORDING is advisory (G11 [A]); that an ask exists
|
|
544
|
+
* at every one of these paths is what is mechanized.
|
|
545
|
+
*/
|
|
546
|
+
boundary(input: { session: string; scope: string; kind: BoundaryKind }): BoundaryRecord {
|
|
547
|
+
const record: BoundaryRecord = {
|
|
548
|
+
session: input.session,
|
|
549
|
+
scope: input.scope,
|
|
550
|
+
kind: input.kind,
|
|
551
|
+
at: this.nowFn(),
|
|
552
|
+
day: this.dayFn(),
|
|
553
|
+
askRaised: !this.observer,
|
|
554
|
+
};
|
|
555
|
+
const written = this.mutate("boundary", () => {
|
|
556
|
+
this.ensureScope(input.scope);
|
|
557
|
+
appendFileSync(
|
|
558
|
+
this.path(input.scope, "boundaries.jsonl"),
|
|
559
|
+
`${JSON.stringify(record)}\n`,
|
|
560
|
+
"utf8",
|
|
561
|
+
);
|
|
562
|
+
});
|
|
563
|
+
if (written.ok) {
|
|
564
|
+
this.emit("remember.boundary", input.session, { kind: input.kind, ask: record.askRaised });
|
|
565
|
+
}
|
|
566
|
+
return record;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// ── reads ──────────────────────────────────────────────────────────────────
|
|
570
|
+
|
|
571
|
+
/** Turns already captured for this session IN THIS SCOPE. Per-(scope, session)
|
|
572
|
+
* file: two concurrent boundaries cannot drop each other's advance (spec §2
|
|
573
|
+
* G4 — v1's shared map), and the same session id running under two scopes
|
|
574
|
+
* cannot starve one of them (the PR-1 review's blocker 2: a session-only
|
|
575
|
+
* cursor made scope B read scope A's advance as NOTHING_NEW — 11 real-corpus
|
|
576
|
+
* session ids appear under more than one scope). */
|
|
577
|
+
cursor(scope: string, session: string): number {
|
|
578
|
+
const file = join(this.root, "cursors", `${keyFor(scope)}.${keyFor(session)}.json`);
|
|
579
|
+
if (!existsSync(file)) return 0;
|
|
580
|
+
try {
|
|
581
|
+
const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
|
|
582
|
+
const value = (parsed as { turns?: unknown }).turns;
|
|
583
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
|
|
584
|
+
} catch {
|
|
585
|
+
// An unreadable cursor reads as 0: re-capture (deduped by hash) beats loss.
|
|
586
|
+
this.emit("remember.cursor.unreadable", undefined, {
|
|
587
|
+
scope: keyFor(scope),
|
|
588
|
+
session: keyFor(session),
|
|
589
|
+
});
|
|
590
|
+
return 0;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** Live spans awaiting a claim: conversational plus jots, in append order. */
|
|
595
|
+
spans(scope: string): Span[] {
|
|
596
|
+
return [
|
|
597
|
+
...this.readSpans(this.streamPath(scope, "conversation")),
|
|
598
|
+
...this.readSpans(this.streamPath(scope, "jot")),
|
|
599
|
+
// Stable sort on `at` alone: within one millisecond, APPEND ORDER is the
|
|
600
|
+
// truth, and a hash tiebreak would shuffle a session's own sequence.
|
|
601
|
+
].sort((a, b) => a.at - b.at);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** The assistant's own turns, kept SEPARATELY — the substrate for "was a
|
|
605
|
+
* surfaced memory actually used?" They are never claimed and never swept. */
|
|
606
|
+
assistantSpans(scope: string): Span[] {
|
|
607
|
+
return this.readSpans(this.streamPath(scope, "assistant"));
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
boundaries(scope: string): BoundaryRecord[] {
|
|
611
|
+
return this.readLines<BoundaryRecord>(this.path(scope, "boundaries.jsonl"));
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* THE MECHANICAL DEFINITION OF "CRASHED" (owner ruling 2026-09-04, adapter
|
|
616
|
+
* CONTRACT open question 3). A session is crashed when all three hold:
|
|
617
|
+
*
|
|
618
|
+
* 1. it has recorded NO `session-end` boundary — an author who reached the
|
|
619
|
+
* host's own end-of-session path got the pen, and what it chose not to
|
|
620
|
+
* write is forgotten by design (constitution 3);
|
|
621
|
+
* 2. it has had NO boundary activity for `crashStaleMs` — silence is the
|
|
622
|
+
* only crash signal this host offers, since an abrupt exit looks exactly
|
|
623
|
+
* like an ordinary one at the hook seam;
|
|
624
|
+
* 3. it holds uncovered spans — the third clause, checked by
|
|
625
|
+
* `crashedPending()` below, because a session that crashed months ago
|
|
626
|
+
* and was already swept must not keep the sweep claiming forever.
|
|
627
|
+
*
|
|
628
|
+
* A session with no boundary at all is not here either: nothing has ended, and
|
|
629
|
+
* its author may still get the pen. Note what falls out of (1): a
|
|
630
|
+
* `pre-compaction` boundary is NOT a session end, so a session that compacted
|
|
631
|
+
* and then went silent past the window IS crashed — the compaction-amnesia
|
|
632
|
+
* case is recovered by the silence, never by the compaction event itself.
|
|
633
|
+
*/
|
|
634
|
+
crashedSessions(scope: string, opts: { staleMs?: number } = {}): Set<string> {
|
|
635
|
+
const staleMs = opts.staleMs ?? this.crashStaleMs;
|
|
636
|
+
const now = this.nowFn();
|
|
637
|
+
const lastAt = new Map<string, number>();
|
|
638
|
+
const endedNormally = new Set<string>();
|
|
639
|
+
for (const b of this.boundaries(scope)) {
|
|
640
|
+
if (typeof b.session !== "string") continue;
|
|
641
|
+
const at = typeof b.at === "number" ? b.at : 0;
|
|
642
|
+
lastAt.set(b.session, Math.max(lastAt.get(b.session) ?? 0, at));
|
|
643
|
+
if (b.kind === "session-end") endedNormally.add(b.session);
|
|
644
|
+
}
|
|
645
|
+
const crashed = new Set<string>();
|
|
646
|
+
for (const [session, at] of lastAt) {
|
|
647
|
+
if (endedNormally.has(session)) continue;
|
|
648
|
+
if (now - at >= staleMs) crashed.add(session);
|
|
649
|
+
}
|
|
650
|
+
return crashed;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* The sweep's eligibility test, answered BEFORE any claim: which sessions are
|
|
655
|
+
* crashed, how many spans they left behind, and how many of those nobody
|
|
656
|
+
* authored.
|
|
657
|
+
*
|
|
658
|
+
* Pre-claim on purpose. A scope with nothing crashed must cost no rename, no
|
|
659
|
+
* restore and no consume — and, more importantly, its record must read
|
|
660
|
+
* "nothing crashed" rather than "claimed and found nothing already authored",
|
|
661
|
+
* or the daily cannot tell a quiet sweep from a broken one (constitution 16).
|
|
662
|
+
*
|
|
663
|
+
* TWO NUMBERS, because they gate two different things. `spans` decides whether
|
|
664
|
+
* the sweep looks at this scope at all; `uncovered` is what a model call would
|
|
665
|
+
* ever be spent on. A crashed session whose spans were ALL authored is still
|
|
666
|
+
* worth claiming — it retires them without a call (the `NOTHING_UNCLAIMED`
|
|
667
|
+
* path) — and if it were not claimed, its spans would sit in the buffer for
|
|
668
|
+
* good.
|
|
669
|
+
*
|
|
670
|
+
* Spans held in CLAIM FILES count: a worker that died mid-arc left its spans
|
|
671
|
+
* there, and `claim()` merges those back in past the staleness window. Without
|
|
672
|
+
* them, a crashed run's orphans could be stranded by this very gate.
|
|
673
|
+
*/
|
|
674
|
+
crashedPending(scope: string, opts: { staleMs?: number } = {}): {
|
|
675
|
+
sessions: Set<string>;
|
|
676
|
+
spans: number;
|
|
677
|
+
uncovered: number;
|
|
678
|
+
} {
|
|
679
|
+
const sessions = this.crashedSessions(scope, opts);
|
|
680
|
+
if (sessions.size === 0) return { sessions, spans: 0, uncovered: 0 };
|
|
681
|
+
const covered = this.coveredHashes(scope);
|
|
682
|
+
const seen = new Set<string>();
|
|
683
|
+
let spans = 0;
|
|
684
|
+
let uncovered = 0;
|
|
685
|
+
const consider = (span: Span): void => {
|
|
686
|
+
if (!sessions.has(span.session)) return;
|
|
687
|
+
if (seen.has(span.hash)) return;
|
|
688
|
+
seen.add(span.hash);
|
|
689
|
+
spans += 1;
|
|
690
|
+
if (!covered.has(span.hash)) uncovered += 1;
|
|
691
|
+
};
|
|
692
|
+
for (const span of this.spans(scope)) consider(span);
|
|
693
|
+
for (const file of this.claimFiles(scope)) {
|
|
694
|
+
for (const span of this.readSpans(file)) consider(span);
|
|
695
|
+
}
|
|
696
|
+
return { sessions, spans, uncovered };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
coverage(scope: string): CoverageMark[] {
|
|
700
|
+
return this.readLines<CoverageMark>(this.path(scope, "coverage.jsonl"));
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
coveredHashes(scope: string): Set<string> {
|
|
704
|
+
return new Set(this.coverage(scope).map((c) => c.spanHash));
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/** Hashes withheld from the sweep OUTRIGHT: a proposal's own span, whose
|
|
708
|
+
* re-encoding is guaranteed duplication (§4.1 G4). */
|
|
709
|
+
withheldHashes(scope: string): Set<string> {
|
|
710
|
+
return new Set(this.coverage(scope).filter((c) => c.own).map((c) => c.spanHash));
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Dedup layer 2's full extent: everything this scope currently holds, everything
|
|
715
|
+
* a live claim holds, and the bounded tail of what was already consumed. The
|
|
716
|
+
* consumed ledger is what closes the crash window between "hashes recorded" and
|
|
717
|
+
* "claim file removed" — a replayed orphan dedups away instead of re-entering.
|
|
718
|
+
*/
|
|
719
|
+
seenHashes(scope: string): Set<string> {
|
|
720
|
+
const seen = new Set<string>();
|
|
721
|
+
for (const s of this.spans(scope)) seen.add(s.hash);
|
|
722
|
+
for (const s of this.assistantSpans(scope)) seen.add(s.hash);
|
|
723
|
+
for (const file of this.claimFiles(scope)) {
|
|
724
|
+
for (const s of this.readSpans(file)) seen.add(s.hash);
|
|
725
|
+
}
|
|
726
|
+
for (const line of this.readLines<{ hash: string }>(this.path(scope, "consumed.jsonl"))) {
|
|
727
|
+
seen.add(line.hash);
|
|
728
|
+
}
|
|
729
|
+
return seen;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** Every scope holding experience — the all-scopes sweep's input (spec §2 G9):
|
|
733
|
+
* a project never revisited would otherwise keep captured spans forever. */
|
|
734
|
+
scopes(): string[] {
|
|
735
|
+
const legend = this.legend();
|
|
736
|
+
return [...legend.values()].sort();
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* Coverage measured, not assumed (G12). The unaskable stretch — spans captured
|
|
741
|
+
* after the last session-ending boundary, which nobody can be asked about — is
|
|
742
|
+
* bounded and reported rather than pretended away.
|
|
743
|
+
*/
|
|
744
|
+
coverageReport(scope: string): CoverageReport {
|
|
745
|
+
const spans = this.spans(scope);
|
|
746
|
+
const covered = this.coveredHashes(scope);
|
|
747
|
+
const bounds = this.boundaries(scope);
|
|
748
|
+
const last = bounds.length > 0 ? Math.max(...bounds.map((b) => b.at)) : null;
|
|
749
|
+
const tail = last === null ? spans : spans.filter((s) => s.at > last);
|
|
750
|
+
const report: CoverageReport = {
|
|
751
|
+
scope,
|
|
752
|
+
spans: spans.length,
|
|
753
|
+
covered: spans.filter((s) => covered.has(s.hash)).length,
|
|
754
|
+
uncovered: spans.filter((s) => !covered.has(s.hash)).length,
|
|
755
|
+
unaskableSpans: tail.length,
|
|
756
|
+
unaskableBytes: tail.reduce((n, s) => n + s.text.length, 0),
|
|
757
|
+
lastBoundaryAt: last,
|
|
758
|
+
quarantined: this.quarantined(scope).length,
|
|
759
|
+
};
|
|
760
|
+
this.emit("remember.coverage.measured", keyFor(scope), {
|
|
761
|
+
spans: report.spans,
|
|
762
|
+
covered: report.covered,
|
|
763
|
+
uncovered: report.uncovered,
|
|
764
|
+
unaskableSpans: report.unaskableSpans,
|
|
765
|
+
unaskableBytes: report.unaskableBytes,
|
|
766
|
+
quarantined: report.quarantined,
|
|
767
|
+
});
|
|
768
|
+
return report;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// ── the retry bound ────────────────────────────────────────────────────────
|
|
772
|
+
|
|
773
|
+
/** Failures recorded per span hash. History, not state: a span that later
|
|
774
|
+
* succeeds keeps its lines and is consumed normally. */
|
|
775
|
+
/**
|
|
776
|
+
* Failures per span hash, counted as DISTINCT LIVED DAYS (PR-8 review): a
|
|
777
|
+
* poison pill fails every day it is tried; an outage fails every attempt of
|
|
778
|
+
* one day. Only the first shape should ever reach the bound. A line with no
|
|
779
|
+
* day (none exist in production; the field arrived with the cadence rule)
|
|
780
|
+
* counts as its own day, the conservative direction for an old ledger.
|
|
781
|
+
*/
|
|
782
|
+
failureCounts(scope: string): Map<string, number> {
|
|
783
|
+
const days = new Map<string, Set<number>>();
|
|
784
|
+
for (const line of this.readLines<FailureRecord>(this.path(scope, "failures.jsonl"))) {
|
|
785
|
+
if (typeof line.hash !== "string") continue;
|
|
786
|
+
const set = days.get(line.hash) ?? new Set<number>();
|
|
787
|
+
set.add(typeof line.day === "number" ? line.day : -1 - set.size);
|
|
788
|
+
days.set(line.hash, set);
|
|
789
|
+
}
|
|
790
|
+
return new Map([...days.entries()].map(([hash, set]) => [hash, set.size]));
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** Spans the sweep gave up on, in full. Nothing is ever dropped: this file is
|
|
794
|
+
* the owner's copy, readable in any editor (constitution line 16). */
|
|
795
|
+
quarantined(scope: string): Span[] {
|
|
796
|
+
return this.readSpans(this.path(scope, "quarantine.jsonl"));
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* Record one interpretation failure per span, and decide which of them may go
|
|
801
|
+
* back. A span that has now failed `maxSpanFailures` times is QUARANTINED — its
|
|
802
|
+
* full line appended to `quarantine.jsonl`, and never restored — so a
|
|
803
|
+
* permanently-failing span costs a bounded number of model calls instead of one
|
|
804
|
+
* per boundary forever (replay-review 2026-08-26 follow-up; the P0 fix traded
|
|
805
|
+
* silent loss for indefinite retry, and this is the other half of that trade).
|
|
806
|
+
*
|
|
807
|
+
* Only a FAILURE calls this. A restore that is merely a deferral — scraps under
|
|
808
|
+
* `MIN_CLAIM_BYTES` riding to the next boundary, spans of a session still
|
|
809
|
+
* running — touches no ledger and is never a step toward quarantine.
|
|
810
|
+
*
|
|
811
|
+
* Every failure mode here fails toward RETRY: if the ledger or the quarantine
|
|
812
|
+
* write does not land, nothing is quarantined and every span goes back. A
|
|
813
|
+
* retry costs a call; a drop costs the day.
|
|
814
|
+
*/
|
|
815
|
+
noteFailures(scope: string, spans: readonly Span[], code: string): FailureOutcome {
|
|
816
|
+
if (spans.length === 0) return { retry: [], quarantined: [] };
|
|
817
|
+
const counts = this.failureCounts(scope);
|
|
818
|
+
const day = this.dayFn();
|
|
819
|
+
// Today's failures, per hash — a second failure on the SAME lived day does
|
|
820
|
+
// not move the count (the outage rule), so the pre-read set decides.
|
|
821
|
+
const failedToday = new Set(
|
|
822
|
+
this.readLines<FailureRecord>(this.path(scope, "failures.jsonl"))
|
|
823
|
+
.filter((l) => typeof l.hash === "string" && l.day === day)
|
|
824
|
+
.map((l) => l.hash),
|
|
825
|
+
);
|
|
826
|
+
const at = this.nowFn();
|
|
827
|
+
const retry: Span[] = [];
|
|
828
|
+
const quarantined: Span[] = [];
|
|
829
|
+
for (const span of spans) {
|
|
830
|
+
const n = (counts.get(span.hash) ?? 0) + (failedToday.has(span.hash) ? 0 : 1);
|
|
831
|
+
counts.set(span.hash, n);
|
|
832
|
+
if (n >= this.maxSpanFailures) quarantined.push(span);
|
|
833
|
+
else retry.push(span);
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
const out = this.mutate("failure", () => {
|
|
837
|
+
this.ensureScope(scope);
|
|
838
|
+
const file = this.path(scope, "failures.jsonl");
|
|
839
|
+
const lines = spans.map((s) => JSON.stringify({ hash: s.hash, at, day, code } satisfies FailureRecord));
|
|
840
|
+
appendFileSync(file, `${lines.join("\n")}\n`, "utf8");
|
|
841
|
+
// Bounded exactly like the consumed ledger, and for the same reason: this is
|
|
842
|
+
// bookkeeping, not canonical memory. A trim can drop old failures and so
|
|
843
|
+
// reset a count — which spends a few more calls, never loses a span.
|
|
844
|
+
this.trimLedger(file);
|
|
845
|
+
if (quarantined.length > 0) {
|
|
846
|
+
// ONE append: a half-written batch would put a span in quarantine AND
|
|
847
|
+
// back in the buffer. Bounded duplication is the acceptable failure.
|
|
848
|
+
appendFileSync(
|
|
849
|
+
this.path(scope, "quarantine.jsonl"),
|
|
850
|
+
`${quarantined.map((s) => JSON.stringify(s)).join("\n")}\n`,
|
|
851
|
+
"utf8",
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
});
|
|
855
|
+
if (!out.ok) return { retry: [...spans], quarantined: [] };
|
|
856
|
+
|
|
857
|
+
if (quarantined.length > 0) {
|
|
858
|
+
// Counts and a code, never text — and never the hash of text either: hashing
|
|
859
|
+
// low-entropy content leaks it. (The hash inside `failures.jsonl` is the
|
|
860
|
+
// buffer's own span hash, which already lives in `consumed.jsonl`.)
|
|
861
|
+
this.emit("remember.span.quarantined", undefined, {
|
|
862
|
+
scope: keyFor(scope),
|
|
863
|
+
spans: quarantined.length,
|
|
864
|
+
code,
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
return { retry, quarantined };
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// ── claim / consume / restore ──────────────────────────────────────────────
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Rename the live buffer ASIDE. Not a mutex: a concurrent append lands in a
|
|
874
|
+
* fresh `buffer.jsonl` and cannot be destroyed by the claim (spec §2 G6).
|
|
875
|
+
* Leftovers from crashed runs — claim files older than the staleness window —
|
|
876
|
+
* merge in, deduped by hash against this claim AND the consumed ledger.
|
|
877
|
+
*/
|
|
878
|
+
claim(scope: string, opts: { minBytes?: number; staleClaimMs?: number } = {}): ClaimOutcome {
|
|
879
|
+
if (this.observer) {
|
|
880
|
+
this.emit("remember.observer.standdown", undefined, { site: "claim" });
|
|
881
|
+
return { claimed: false, reason: "OBSERVER", bytes: 0 };
|
|
882
|
+
}
|
|
883
|
+
const minBytes = opts.minBytes ?? this.minClaimBytes;
|
|
884
|
+
const staleMs = opts.staleClaimMs ?? this.staleClaimMs;
|
|
885
|
+
const id = `clm_${randomBytes(6).toString("hex")}`;
|
|
886
|
+
const claimPath = join(this.claimsDir(scope), `${id}.jsonl`);
|
|
887
|
+
|
|
888
|
+
const staged = this.mutate("claim", () => {
|
|
889
|
+
this.ensureScope(scope);
|
|
890
|
+
mkdirSync(this.claimsDir(scope), { recursive: true });
|
|
891
|
+
const live = this.streamPath(scope, "conversation");
|
|
892
|
+
const jots = this.streamPath(scope, "jot");
|
|
893
|
+
let any = false;
|
|
894
|
+
if (existsSync(live)) {
|
|
895
|
+
renameSync(live, claimPath);
|
|
896
|
+
any = true;
|
|
897
|
+
}
|
|
898
|
+
if (existsSync(jots)) {
|
|
899
|
+
// Jots ride with the spans; a second rename would clobber the first, so
|
|
900
|
+
// they are appended into the claim and their file renamed aside first.
|
|
901
|
+
// The aside keeps the `.jsonl` suffix and lives in `claims/` ON PURPOSE:
|
|
902
|
+
// a crash between the rename and the rm must leave an ORDINARY orphan
|
|
903
|
+
// that a later claim can merge, or those spans would be in neither
|
|
904
|
+
// claim nor buffer — the one state spec §2 G6 forbids.
|
|
905
|
+
const aside = join(this.claimsDir(scope), `${id}.jots.jsonl`);
|
|
906
|
+
renameSync(jots, aside);
|
|
907
|
+
appendFileSync(claimPath, readFileSync(aside, "utf8"), "utf8");
|
|
908
|
+
rmSync(aside, { force: true });
|
|
909
|
+
any = true;
|
|
910
|
+
}
|
|
911
|
+
return any;
|
|
912
|
+
});
|
|
913
|
+
if (!staged.ok) {
|
|
914
|
+
return { claimed: false, reason: staged.reason === "OBSERVER" ? "OBSERVER" : "IO_FAILED", bytes: 0 };
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
const merged = this.mergeOrphans(scope, claimPath, id, staleMs);
|
|
918
|
+
const spans = this.readSpans(claimPath);
|
|
919
|
+
const bytes = spans.reduce((n, s) => n + s.text.length, 0);
|
|
920
|
+
const claim: Claim = { id, scope, path: claimPath, spans, bytes, mergedOrphans: merged };
|
|
921
|
+
|
|
922
|
+
if (spans.length === 0) {
|
|
923
|
+
rmSync(claimPath, { force: true });
|
|
924
|
+
return { claimed: false, reason: "EMPTY", bytes: 0 };
|
|
925
|
+
}
|
|
926
|
+
if (bytes < minBytes) {
|
|
927
|
+
// Scraps ride to the next boundary (spec §2 G8) — and they ride by being
|
|
928
|
+
// RESTORED, never by being dropped on the floor.
|
|
929
|
+
this.restore(claim);
|
|
930
|
+
this.emit("remember.claim.refused", id, { reason: "BELOW_MIN_CLAIM", bytes, minBytes });
|
|
931
|
+
return { claimed: false, reason: "BELOW_MIN_CLAIM", bytes };
|
|
932
|
+
}
|
|
933
|
+
this.emit("remember.claim", id, {
|
|
934
|
+
scope: keyFor(scope),
|
|
935
|
+
spans: spans.length,
|
|
936
|
+
bytes,
|
|
937
|
+
mergedOrphans: merged.length,
|
|
938
|
+
});
|
|
939
|
+
return { claimed: true, claim };
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/**
|
|
943
|
+
* Truncate the claim — ONLY ever called after results are applied and persisted
|
|
944
|
+
* (spec §2 G6). The hashes go into the bounded consumed ledger FIRST, so a crash
|
|
945
|
+
* between the two leaves a claim whose spans dedup away rather than duplicate.
|
|
946
|
+
*
|
|
947
|
+
* `except` names the spans that were RESTORED rather than applied, and their
|
|
948
|
+
* hashes MUST NOT enter the ledger: `restore()` dedups against it, so a
|
|
949
|
+
* restored span whose hash is recorded here is un-restorable the next time
|
|
950
|
+
* its chunk fails — the second failure of the same content becomes silent
|
|
951
|
+
* loss. Not hypothetical: the 2026-08-26 replay destroyed a live span exactly
|
|
952
|
+
* this way (docs/replay-review-2026-08-26.md, P0), and scar E6 says an outage
|
|
953
|
+
* must never mean "nothing durable". The ledger records what was CONSUMED —
|
|
954
|
+
* never what merely passed through a claim.
|
|
955
|
+
*
|
|
956
|
+
* A QUARANTINED span is the third disposition, and it is NOT excepted: it left
|
|
957
|
+
* the buffer for good, its text is durable in `quarantine.jsonl`, and its hash
|
|
958
|
+
* belongs in the ledger — that is what stops an identical re-capture from
|
|
959
|
+
* restarting the retry loop, and what lets `mergeOrphans()` filter it out of a
|
|
960
|
+
* replayed claim. Terminal, not pass-through: this is not the P0 regression.
|
|
961
|
+
*/
|
|
962
|
+
consume(
|
|
963
|
+
claim: Claim,
|
|
964
|
+
opts: { except?: readonly Span[] } = {},
|
|
965
|
+
): { consumed: boolean; reason: "CONSUMED" | "OBSERVER" | "IO_FAILED" } {
|
|
966
|
+
const skip = new Set((opts.except ?? []).map((s) => s.hash));
|
|
967
|
+
const kept = claim.spans.filter((s) => !skip.has(s.hash));
|
|
968
|
+
const out = this.mutate("consume", () => {
|
|
969
|
+
this.ensureScope(claim.scope);
|
|
970
|
+
if (kept.length > 0) {
|
|
971
|
+
const file = this.path(claim.scope, "consumed.jsonl");
|
|
972
|
+
const lines = kept.map((s) => JSON.stringify({ hash: s.hash, at: s.at }));
|
|
973
|
+
appendFileSync(file, `${lines.join("\n")}\n`, "utf8");
|
|
974
|
+
this.trimLedger(file);
|
|
975
|
+
}
|
|
976
|
+
rmSync(claim.path, { force: true });
|
|
977
|
+
});
|
|
978
|
+
if (!out.ok) {
|
|
979
|
+
return { consumed: false, reason: out.reason === "OBSERVER" ? "OBSERVER" : "IO_FAILED" };
|
|
980
|
+
}
|
|
981
|
+
this.emit("remember.claim.consumed", claim.id, {
|
|
982
|
+
spans: kept.length,
|
|
983
|
+
excepted: claim.spans.length - kept.length,
|
|
984
|
+
// The KEPT spans' bytes — pairing the full claim's bytes with the kept
|
|
985
|
+
// count would make bytes-per-span nonsense (PR-1 review nit).
|
|
986
|
+
bytes: kept.reduce((n, s) => n + s.text.length, 0),
|
|
987
|
+
});
|
|
988
|
+
return { consumed: true, reason: "CONSUMED" };
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/**
|
|
992
|
+
* Put the claim's spans back where the next claim will find them. A failed
|
|
993
|
+
* restore FORBIDS consuming the claim (spec §2 G7): the claim file is kept, so
|
|
994
|
+
* a failed arc never lives in neither place.
|
|
995
|
+
*/
|
|
996
|
+
restore(
|
|
997
|
+
claim: Claim,
|
|
998
|
+
only?: readonly Span[],
|
|
999
|
+
): { restored: boolean; reason: "RESTORED" | "OBSERVER" | "IO_FAILED"; spans: number } {
|
|
1000
|
+
const wanted = only ?? claim.spans;
|
|
1001
|
+
const out = this.mutate("restore", () => {
|
|
1002
|
+
this.ensureScope(claim.scope);
|
|
1003
|
+
const held = this.seenHashesExcludingClaim(claim);
|
|
1004
|
+
const back = wanted.filter((s) => !held.has(s.hash));
|
|
1005
|
+
for (const span of back) {
|
|
1006
|
+
appendFileSync(
|
|
1007
|
+
this.streamPath(claim.scope, span.kind === "jot" ? "jot" : "conversation"),
|
|
1008
|
+
`${JSON.stringify(span)}\n`,
|
|
1009
|
+
"utf8",
|
|
1010
|
+
);
|
|
1011
|
+
}
|
|
1012
|
+
return back.length;
|
|
1013
|
+
});
|
|
1014
|
+
if (!out.ok) {
|
|
1015
|
+
// The claim stays on disk. Its spans are still in claim-or-buffer, and the
|
|
1016
|
+
// next claim past the staleness window merges them back in.
|
|
1017
|
+
this.emit("remember.claim.restore.failed", claim.id, { spans: wanted.length });
|
|
1018
|
+
return { restored: false, reason: out.reason === "OBSERVER" ? "OBSERVER" : "IO_FAILED", spans: 0 };
|
|
1019
|
+
}
|
|
1020
|
+
if (only === undefined) rmSync(claim.path, { force: true });
|
|
1021
|
+
this.emit("remember.claim.restored", claim.id, { spans: out.value, partial: only !== undefined });
|
|
1022
|
+
return { restored: true, reason: "RESTORED", spans: out.value };
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
/**
|
|
1026
|
+
* The arc: commit the output or restore the input (§5 G4). A throw means the arc
|
|
1027
|
+
* is RETRIED, not lost — and "returned nothing" and "failed" are distinct records
|
|
1028
|
+
* (scar §2.4), which is why the empty case logs its own event and does not throw.
|
|
1029
|
+
*/
|
|
1030
|
+
async arc<T>(
|
|
1031
|
+
claim: Claim,
|
|
1032
|
+
work: (spans: readonly Span[]) => Promise<T>,
|
|
1033
|
+
commit: (value: T) => void | Promise<void>,
|
|
1034
|
+
): Promise<{ ok: true; value: T } | { ok: false; reason: "RESTORED" | "RESTORE_FAILED"; code: string }> {
|
|
1035
|
+
let value: T;
|
|
1036
|
+
try {
|
|
1037
|
+
value = await work(claim.spans);
|
|
1038
|
+
await commit(value);
|
|
1039
|
+
} catch (err) {
|
|
1040
|
+
const code = errCode(err);
|
|
1041
|
+
const restored = this.restore(claim);
|
|
1042
|
+
this.emit("remember.arc.failed", claim.id, { code, restored: restored.restored });
|
|
1043
|
+
return {
|
|
1044
|
+
ok: false,
|
|
1045
|
+
reason: restored.restored ? "RESTORED" : "RESTORE_FAILED",
|
|
1046
|
+
code,
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
this.consume(claim);
|
|
1050
|
+
this.emit("remember.arc.done", claim.id, { spans: claim.spans.length });
|
|
1051
|
+
return { ok: true, value };
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// ── coverage (engine-side only) ────────────────────────────────────────────
|
|
1055
|
+
|
|
1056
|
+
/**
|
|
1057
|
+
* The ENGINE claims coverage, never the author — the author cannot see the
|
|
1058
|
+
* buffer (§5 G5). Claims are sequential: each accepted proposal takes the spans
|
|
1059
|
+
* still uncovered in its session, so successive proposals PARTITION a session
|
|
1060
|
+
* instead of each claiming the backlog (§4.1 G4).
|
|
1061
|
+
*/
|
|
1062
|
+
claimCoverage(input: {
|
|
1063
|
+
scope: string;
|
|
1064
|
+
session: string;
|
|
1065
|
+
proposalId: string;
|
|
1066
|
+
ownSpanHash?: string | null;
|
|
1067
|
+
}): CoverageMark[] {
|
|
1068
|
+
if (this.observer) {
|
|
1069
|
+
// Checked before the scan, not only at the append: an instrument does not
|
|
1070
|
+
// get to compute a claim it would then be refused (observer-mode.md G6).
|
|
1071
|
+
this.emit("remember.observer.standdown", undefined, { site: "coverage" });
|
|
1072
|
+
return [];
|
|
1073
|
+
}
|
|
1074
|
+
const covered = this.coveredHashes(input.scope);
|
|
1075
|
+
const at = this.nowFn();
|
|
1076
|
+
const marks: CoverageMark[] = this.spans(input.scope)
|
|
1077
|
+
.filter((s) => s.session === input.session && !covered.has(s.hash))
|
|
1078
|
+
.map((s) => ({
|
|
1079
|
+
spanHash: s.hash,
|
|
1080
|
+
proposalId: input.proposalId,
|
|
1081
|
+
session: input.session,
|
|
1082
|
+
at,
|
|
1083
|
+
own: input.ownSpanHash !== undefined && input.ownSpanHash !== null && s.hash === input.ownSpanHash,
|
|
1084
|
+
}));
|
|
1085
|
+
if (marks.length === 0) return [];
|
|
1086
|
+
const out = this.mutate("coverage", () => {
|
|
1087
|
+
this.ensureScope(input.scope);
|
|
1088
|
+
appendFileSync(
|
|
1089
|
+
this.path(input.scope, "coverage.jsonl"),
|
|
1090
|
+
`${marks.map((m) => JSON.stringify(m)).join("\n")}\n`,
|
|
1091
|
+
"utf8",
|
|
1092
|
+
);
|
|
1093
|
+
});
|
|
1094
|
+
if (!out.ok) return [];
|
|
1095
|
+
this.emit("remember.coverage.claimed", input.proposalId, {
|
|
1096
|
+
spans: marks.length,
|
|
1097
|
+
withheld: marks.filter((m) => m.own).length,
|
|
1098
|
+
});
|
|
1099
|
+
return marks;
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
/** Append one proposal record (also the content-idempotency ledger, §4.1 G9). */
|
|
1103
|
+
recordProposal(scope: string, record: unknown): boolean {
|
|
1104
|
+
const out = this.mutate("proposal", () => {
|
|
1105
|
+
this.ensureScope(scope);
|
|
1106
|
+
appendFileSync(this.path(scope, "proposals.jsonl"), `${JSON.stringify(record)}\n`, "utf8");
|
|
1107
|
+
});
|
|
1108
|
+
return out.ok;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
proposalRecords<T>(scope: string): T[] {
|
|
1112
|
+
return this.readLines<T>(this.path(scope, "proposals.jsonl"));
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
// ── paths + internals ──────────────────────────────────────────────────────
|
|
1116
|
+
|
|
1117
|
+
/** Scope keys are HASHES, not the scope string: a scope is a project path, and
|
|
1118
|
+
* a path pasted into `join()` escapes the data dir (NOTES §2). */
|
|
1119
|
+
scopeDir(scope: string): string {
|
|
1120
|
+
return join(this.root, keyFor(scope));
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
/** Pure: creates nothing. Every directory is made by `ensureScope()`, which runs
|
|
1124
|
+
* only on write paths, INSIDE the seam — so a read can never throw into a host
|
|
1125
|
+
* and an observer can never create a directory by looking at one. */
|
|
1126
|
+
path(scope: string, name: string): string {
|
|
1127
|
+
return join(this.scopeDir(scope), name);
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
private streamPath(scope: string, kind: SpanKind): string {
|
|
1131
|
+
const name =
|
|
1132
|
+
kind === "assistant" ? "assistant.jsonl" : kind === "jot" ? "jots.jsonl" : "buffer.jsonl";
|
|
1133
|
+
return this.path(scope, name);
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
private claimsDir(scope: string): string {
|
|
1137
|
+
return this.path(scope, "claims");
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
private claimFiles(scope: string): string[] {
|
|
1141
|
+
const dir = join(this.scopeDir(scope), "claims");
|
|
1142
|
+
if (!existsSync(dir)) return [];
|
|
1143
|
+
return readdirSync(dir)
|
|
1144
|
+
.filter((f) => f.endsWith(".jsonl"))
|
|
1145
|
+
.map((f) => join(dir, f))
|
|
1146
|
+
.sort();
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
private ensureScope(scope: string): void {
|
|
1150
|
+
const dir = this.scopeDir(scope);
|
|
1151
|
+
if (existsSync(dir)) return;
|
|
1152
|
+
mkdirSync(dir, { recursive: true });
|
|
1153
|
+
mkdirSync(join(this.root, "cursors"), { recursive: true });
|
|
1154
|
+
const legend = this.legend();
|
|
1155
|
+
legend.set(keyFor(scope), scope);
|
|
1156
|
+
const file = join(this.root, "scopes.json");
|
|
1157
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
1158
|
+
writeFileSync(tmp, JSON.stringify(Object.fromEntries(legend), null, 2), "utf8");
|
|
1159
|
+
renameSync(tmp, file);
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
private legend(): Map<string, string> {
|
|
1163
|
+
const file = join(this.root, "scopes.json");
|
|
1164
|
+
if (!existsSync(file)) return new Map();
|
|
1165
|
+
try {
|
|
1166
|
+
const parsed = JSON.parse(readFileSync(file, "utf8")) as Record<string, string>;
|
|
1167
|
+
return new Map(Object.entries(parsed));
|
|
1168
|
+
} catch {
|
|
1169
|
+
this.emit("remember.legend.unreadable", undefined, {});
|
|
1170
|
+
return new Map();
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
private writeCursor(scope: string, session: string, turns: number): void {
|
|
1175
|
+
const dir = join(this.root, "cursors");
|
|
1176
|
+
mkdirSync(dir, { recursive: true });
|
|
1177
|
+
const file = join(dir, `${keyFor(scope)}.${keyFor(session)}.json`);
|
|
1178
|
+
const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`;
|
|
1179
|
+
writeFileSync(tmp, JSON.stringify({ scope, session, turns }), "utf8");
|
|
1180
|
+
renameSync(tmp, file);
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
private mergeOrphans(scope: string, claimPath: string, id: string, staleMs: number): string[] {
|
|
1184
|
+
const merged: string[] = [];
|
|
1185
|
+
const now = this.nowFn();
|
|
1186
|
+
const held = new Set(this.readSpans(claimPath).map((s) => s.hash));
|
|
1187
|
+
for (const line of this.readLines<{ hash: string }>(this.path(scope, "consumed.jsonl"))) {
|
|
1188
|
+
held.add(line.hash);
|
|
1189
|
+
}
|
|
1190
|
+
for (const file of this.claimFiles(scope)) {
|
|
1191
|
+
if (file === claimPath) continue;
|
|
1192
|
+
let age = Infinity;
|
|
1193
|
+
try {
|
|
1194
|
+
age = now - statSync(file).mtimeMs;
|
|
1195
|
+
} catch {
|
|
1196
|
+
continue;
|
|
1197
|
+
}
|
|
1198
|
+
if (age < staleMs) continue;
|
|
1199
|
+
const spans = this.readSpans(file).filter((s) => !held.has(s.hash));
|
|
1200
|
+
try {
|
|
1201
|
+
if (spans.length > 0) {
|
|
1202
|
+
appendFileSync(claimPath, `${spans.map((s) => JSON.stringify(s)).join("\n")}\n`, "utf8");
|
|
1203
|
+
for (const s of spans) held.add(s.hash);
|
|
1204
|
+
}
|
|
1205
|
+
rmSync(file, { force: true });
|
|
1206
|
+
merged.push(file);
|
|
1207
|
+
this.emit("remember.claim.orphan.merged", id, { spans: spans.length, ageMs: Math.round(age) });
|
|
1208
|
+
} catch (err) {
|
|
1209
|
+
this.emit("remember.claim.orphan.failed", id, { code: errCode(err) });
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
return merged;
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
private seenHashesExcludingClaim(claim: Claim): Set<string> {
|
|
1216
|
+
const held = new Set<string>();
|
|
1217
|
+
for (const s of this.spans(claim.scope)) held.add(s.hash);
|
|
1218
|
+
for (const file of this.claimFiles(claim.scope)) {
|
|
1219
|
+
if (file === claim.path) continue;
|
|
1220
|
+
for (const s of this.readSpans(file)) held.add(s.hash);
|
|
1221
|
+
}
|
|
1222
|
+
for (const line of this.readLines<{ hash: string }>(this.path(claim.scope, "consumed.jsonl"))) {
|
|
1223
|
+
held.add(line.hash);
|
|
1224
|
+
}
|
|
1225
|
+
return held;
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
private trimLedger(file: string): void {
|
|
1229
|
+
const lines = readFileSync(file, "utf8").split("\n").filter((l) => l.length > 0);
|
|
1230
|
+
if (lines.length <= this.consumedLedgerMax) return;
|
|
1231
|
+
const keep = lines.slice(lines.length - this.consumedLedgerMax);
|
|
1232
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
1233
|
+
writeFileSync(tmp, `${keep.join("\n")}\n`, "utf8");
|
|
1234
|
+
renameSync(tmp, file);
|
|
1235
|
+
this.emit("remember.ledger.trimmed", undefined, {
|
|
1236
|
+
// WHICH ledger: two of them trim now (consumed and failures), and a count
|
|
1237
|
+
// with no name is a number nobody can act on.
|
|
1238
|
+
ledger: basename(file),
|
|
1239
|
+
dropped: lines.length - keep.length,
|
|
1240
|
+
kept: keep.length,
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
private readSpans(file: string): Span[] {
|
|
1245
|
+
return this.readLines<Span>(file).filter(
|
|
1246
|
+
(s) => typeof s.hash === "string" && typeof s.text === "string",
|
|
1247
|
+
);
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
private readLines<T>(file: string): T[] {
|
|
1251
|
+
if (!existsSync(file)) return [];
|
|
1252
|
+
let raw = "";
|
|
1253
|
+
try {
|
|
1254
|
+
raw = readFileSync(file, "utf8");
|
|
1255
|
+
} catch (err) {
|
|
1256
|
+
this.emit("remember.read.failed", undefined, { code: errCode(err) });
|
|
1257
|
+
return [];
|
|
1258
|
+
}
|
|
1259
|
+
const out: T[] = [];
|
|
1260
|
+
let corrupt = 0;
|
|
1261
|
+
for (const line of raw.split("\n")) {
|
|
1262
|
+
if (line.trim().length === 0) continue;
|
|
1263
|
+
try {
|
|
1264
|
+
out.push(JSON.parse(line) as T);
|
|
1265
|
+
} catch {
|
|
1266
|
+
// A half-written line from a crash is skipped and COUNTED — never
|
|
1267
|
+
// silently, and never fatally (scar §2.4).
|
|
1268
|
+
corrupt += 1;
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
if (corrupt > 0) this.emit("remember.line.corrupt", undefined, { count: corrupt });
|
|
1272
|
+
return out;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// ── helpers ──────────────────────────────────────────────────────────────────
|
|
1277
|
+
|
|
1278
|
+
/** Tool output, file contents and images never enter capture; host-injected
|
|
1279
|
+
* context does (it is conversational material the model actually saw). */
|
|
1280
|
+
export function enters(turn: Turn): boolean {
|
|
1281
|
+
const source = turn.source ?? "conversation";
|
|
1282
|
+
// THE FOREIGN EXCLUSION, named rather than left to fall through the clause
|
|
1283
|
+
// below: another memory system's injection is text this store would otherwise
|
|
1284
|
+
// read as lived experience and encode as its own — v1's briefing coming back
|
|
1285
|
+
// to v2 as a memory of having thought it. `injected` is kept and merely
|
|
1286
|
+
// unpaced; `foreign` is refused outright.
|
|
1287
|
+
if (source === "foreign") return false;
|
|
1288
|
+
// THE RITUAL EXCLUSION, named for the same reason: this system's OWN ask,
|
|
1289
|
+
// handed back by a host that returns hook output into the context, is not
|
|
1290
|
+
// something that happened to us — it is us. Capturing it would let the ask's
|
|
1291
|
+
// wording become a memory of having thought it, and the ask already has a
|
|
1292
|
+
// durable record of its own (`adapter.authorship.ask`). Refused, and counted.
|
|
1293
|
+
if (source === "ritual") return false;
|
|
1294
|
+
return source === "conversation" || source === "injected";
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
/** A stable, path-safe directory key for an arbitrary scope or session string. */
|
|
1298
|
+
export function keyFor(value: string): string {
|
|
1299
|
+
return hashText(value).slice(0, 12);
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
export function errCode(err: unknown): string {
|
|
1303
|
+
if (err !== null && typeof err === "object") {
|
|
1304
|
+
const code = (err as { code?: unknown }).code;
|
|
1305
|
+
if (typeof code === "string") return code;
|
|
1306
|
+
const name = (err as { name?: unknown }).name;
|
|
1307
|
+
if (typeof name === "string") return name;
|
|
1308
|
+
}
|
|
1309
|
+
return "UNKNOWN";
|
|
1310
|
+
}
|