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,285 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bounded injection.
|
|
3
|
+
*
|
|
4
|
+
* Scar §2.3, in one sentence: *a budget on a sub-lane is not a budget, and "we
|
|
5
|
+
* rendered it" is not "they received it."* v1 byte-capped its index lane at 8,192
|
|
6
|
+
* and left the composed bundle unbounded; every session for eleven days received
|
|
7
|
+
* about 3 of 16 elements, and nothing said so. So:
|
|
8
|
+
*
|
|
9
|
+
* - the budget governs the **composed total**, sentinel included;
|
|
10
|
+
* - the **trim order is explicit** (`TRIM_ORDER`) and tested, not emergent;
|
|
11
|
+
* - every render ends with a **self-describing tail sentinel** (counts + bytes)
|
|
12
|
+
* so the consumer can verify arrival from the last line alone;
|
|
13
|
+
* - there is a **delivery-side** event, not only a render-side one
|
|
14
|
+
* (`Recall.noteDelivered`).
|
|
15
|
+
*
|
|
16
|
+
* **Ids resolve to text HERE**, at render time, through the `Resolve` seam — never
|
|
17
|
+
* baked into the decision record or the telemetry. An erased memory stops
|
|
18
|
+
* resolving the instant it leaves the store, where baked-in text would outlive
|
|
19
|
+
* erasure for a whole retention window.
|
|
20
|
+
*
|
|
21
|
+
* **A quiet turn renders the empty string**, not an empty block and not a bare
|
|
22
|
+
* sentinel (§9 OUTPUTS).
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* THE OQ4 PROBE, STEP 0 → STEP 1. The "quietly available / ignorable" header
|
|
27
|
+
* was v1's deliberate, never-measured probe of whether footnotes are actually
|
|
28
|
+
* ignorable to a model (contract §7 OQ4). On 2026-09-14 the model, asked "what
|
|
29
|
+
* do you remember?", asserted counts and characterizations of five footnoted
|
|
30
|
+
* memories from their 80-byte titles without expanding one (IMPROVEMENTS U5):
|
|
31
|
+
* "ignorable" read as "not obligated", which is right for the ambient design
|
|
32
|
+
* and says nothing about what to do before RELYING on one. Step 1 keeps the
|
|
33
|
+
* word and adds the one instruction the failure lacked. The step-0 string is
|
|
34
|
+
* kept beside it so the owner can reverse the step with a one-line ruling; the
|
|
35
|
+
* measurement is `probe.ts` (`counterparts probe-oq4`), from rows the store
|
|
36
|
+
* already keeps, so the before/after reads off the same table.
|
|
37
|
+
*/
|
|
38
|
+
export const FOOTNOTE_HEADER_STEP_0 = "Quietly available (ignorable):";
|
|
39
|
+
export const FOOTNOTE_HEADER_STEP_1 =
|
|
40
|
+
"Quietly available (ignorable; expand an id with recall before citing one):";
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Framing is load-bearing and part of the spec (§9 G17). The footnote header
|
|
44
|
+
* is the OQ4 probe's one string (above); everything else here is v1's.
|
|
45
|
+
*/
|
|
46
|
+
export const FRAMING = {
|
|
47
|
+
/** Content-free by construction: no ids, no bodies, no feeling named. */
|
|
48
|
+
affect: "Something here carries weight.",
|
|
49
|
+
surfacedHeader: "Came to mind:",
|
|
50
|
+
footnoteHeader: FOOTNOTE_HEADER_STEP_1,
|
|
51
|
+
/**
|
|
52
|
+
* ONE WORD, IN FRONT OF A CHAPTER (owner ruling, 2026-09-04 — LAUNCH-STATUS
|
|
53
|
+
* §I14). A journal entry is the first-person ACCOUNT a memory was made from,
|
|
54
|
+
* not a memory: it sits outside every sleep phase (`sleep/types.ts#isJournal`)
|
|
55
|
+
* and the dashboard has said so in prose since #33, while recall delivered
|
|
56
|
+
* `epi_` rows unmarked in both tiers. The ruling keeps them recallable — a
|
|
57
|
+
* chapter about the lighthouse conversation may rightly come to mind — and
|
|
58
|
+
* makes them say what they are.
|
|
59
|
+
*
|
|
60
|
+
* It is a LABEL, never a filter: nothing about what is recallable, ranked or
|
|
61
|
+
* gated moves. And it goes in front of the text rather than after it, for the
|
|
62
|
+
* same reason the wake's date does (`self/briefing.ts#datePrefix`): what
|
|
63
|
+
* qualifies a claim has to be read before the claim, not after it has landed.
|
|
64
|
+
*/
|
|
65
|
+
journal: "Journal:",
|
|
66
|
+
} as const;
|
|
67
|
+
|
|
68
|
+
export type Lane = "footnote" | "surfaced" | "affect";
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The explicit trim order: cheapest-to-lose first. Footnotes are pointers and go
|
|
72
|
+
* weakest-first; surfaced gists are rare and expensive to have earned; the affect
|
|
73
|
+
* flag is one content-free line and is the last thing standing.
|
|
74
|
+
*/
|
|
75
|
+
export const TRIM_ORDER: readonly Lane[] = ["footnote", "surfaced", "affect"];
|
|
76
|
+
|
|
77
|
+
export interface Resolved {
|
|
78
|
+
readonly title: string;
|
|
79
|
+
readonly gist: string;
|
|
80
|
+
/** True when the row is a journal entry (`ProseDoc.type === "episode"`), which
|
|
81
|
+
* renders with `FRAMING.journal` in front of it. Absent reads as false, so a
|
|
82
|
+
* resolver that predates the label marks nothing. */
|
|
83
|
+
readonly journal?: boolean;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Id -> text, at render time. */
|
|
87
|
+
export type Resolve = (id: string) => Resolved;
|
|
88
|
+
|
|
89
|
+
export interface RenderInput {
|
|
90
|
+
readonly turn: number;
|
|
91
|
+
readonly affectFlag: boolean;
|
|
92
|
+
/** Ids, strongest first. */
|
|
93
|
+
readonly surfaced: readonly string[];
|
|
94
|
+
readonly footnotes: readonly string[];
|
|
95
|
+
readonly budgetBytes: number;
|
|
96
|
+
readonly gistBytes: number;
|
|
97
|
+
readonly titleBytes: number;
|
|
98
|
+
readonly pressureRatio: number;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface TrimEvent {
|
|
102
|
+
readonly lane: Lane;
|
|
103
|
+
readonly id: string | null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface RenderResult {
|
|
107
|
+
readonly text: string;
|
|
108
|
+
readonly bytes: number;
|
|
109
|
+
readonly budgetBytes: number;
|
|
110
|
+
readonly surfaced: string[];
|
|
111
|
+
readonly footnotes: string[];
|
|
112
|
+
readonly affectFlag: boolean;
|
|
113
|
+
readonly trimmed: TrimEvent[];
|
|
114
|
+
/** The tail line, or null on a quiet turn. */
|
|
115
|
+
readonly sentinel: string | null;
|
|
116
|
+
/** True when the composed render crossed the pressure ratio — the tripwire
|
|
117
|
+
* that fires when a budget is APPROACHED, not only when it blows (scar §2.4). */
|
|
118
|
+
readonly pressure: boolean;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const encoder = new TextEncoder();
|
|
122
|
+
|
|
123
|
+
export function byteLength(s: string): number {
|
|
124
|
+
return encoder.encode(s).length;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Truncate to a byte budget on a character boundary, marking the elision. */
|
|
128
|
+
export function clip(text: string, maxBytes: number): string {
|
|
129
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
130
|
+
if (byteLength(flat) <= maxBytes) return flat;
|
|
131
|
+
const ell = "...";
|
|
132
|
+
const room = Math.max(0, maxBytes - byteLength(ell));
|
|
133
|
+
let out = "";
|
|
134
|
+
for (const ch of flat) {
|
|
135
|
+
if (byteLength(out + ch) > room) break;
|
|
136
|
+
out += ch;
|
|
137
|
+
}
|
|
138
|
+
return `${out.trimEnd()}${ell}`;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The one-word prefix, OUTSIDE the clip. The label is what tells a reader the
|
|
143
|
+
* line is not a memory, so it can never be the part that the byte budget eats:
|
|
144
|
+
* clipping runs on the content and the label is added afterwards. A line that
|
|
145
|
+
* did not fit is dropped whole by the trim order, which is where that decision
|
|
146
|
+
* belongs.
|
|
147
|
+
*/
|
|
148
|
+
function label(r: Resolved): string {
|
|
149
|
+
return r.journal === true ? `${FRAMING.journal} ` : "";
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function openMarker(turn: number): string {
|
|
153
|
+
return `<!-- counterparts:recall t=${turn} -->`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function sentinelLine(
|
|
157
|
+
surfaced: number,
|
|
158
|
+
footnotes: number,
|
|
159
|
+
affect: boolean,
|
|
160
|
+
bytes: number,
|
|
161
|
+
): string {
|
|
162
|
+
return `<!-- counterparts:recall/end surfaced=${surfaced} footnotes=${footnotes} affect=${affect ? 1 : 0} bytes=${bytes} -->`;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
interface Composition {
|
|
166
|
+
text: string;
|
|
167
|
+
bytes: number;
|
|
168
|
+
sentinel: string;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function compose(
|
|
172
|
+
input: RenderInput,
|
|
173
|
+
resolve: Resolve,
|
|
174
|
+
surfaced: readonly string[],
|
|
175
|
+
footnotes: readonly string[],
|
|
176
|
+
affect: boolean,
|
|
177
|
+
): Composition {
|
|
178
|
+
const lines: string[] = [openMarker(input.turn)];
|
|
179
|
+
if (affect) lines.push(FRAMING.affect);
|
|
180
|
+
if (surfaced.length > 0) {
|
|
181
|
+
lines.push("", FRAMING.surfacedHeader);
|
|
182
|
+
for (const id of surfaced) {
|
|
183
|
+
const r = resolve(id);
|
|
184
|
+
lines.push(`- ${label(r)}${clip(r.gist, input.gistBytes)}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (footnotes.length > 0) {
|
|
188
|
+
lines.push("", FRAMING.footnoteHeader);
|
|
189
|
+
// Pointers with short titles, NEVER bodies (§9 OUTPUTS).
|
|
190
|
+
for (const id of footnotes) {
|
|
191
|
+
const r = resolve(id);
|
|
192
|
+
lines.push(`- ${label(r)}${clip(r.title, input.titleBytes)} [${id}]`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const body = lines.join("\n");
|
|
196
|
+
// Fixed point: the sentinel states the total byte count, and stating it changes
|
|
197
|
+
// it. Two or three passes settle once the digit count stops moving.
|
|
198
|
+
let total = byteLength(body) + 1;
|
|
199
|
+
let sentinel = sentinelLine(surfaced.length, footnotes.length, affect, total);
|
|
200
|
+
for (let i = 0; i < 5; i++) {
|
|
201
|
+
const next = byteLength(body) + 1 + byteLength(sentinel);
|
|
202
|
+
if (next === total) break;
|
|
203
|
+
total = next;
|
|
204
|
+
sentinel = sentinelLine(surfaced.length, footnotes.length, affect, total);
|
|
205
|
+
}
|
|
206
|
+
const text = `${body}\n${sentinel}`;
|
|
207
|
+
return { text, bytes: byteLength(text), sentinel };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Compose within the budget, trimming in `TRIM_ORDER` until it fits. If even the
|
|
212
|
+
* smallest render does not fit, the turn goes quiet — an over-budget injection is
|
|
213
|
+
* never emitted, and a truncated one is not a smaller injection but a corrupted
|
|
214
|
+
* one.
|
|
215
|
+
*/
|
|
216
|
+
export function render(input: RenderInput, resolve: Resolve): RenderResult {
|
|
217
|
+
const surfaced = [...input.surfaced];
|
|
218
|
+
const footnotes = [...input.footnotes];
|
|
219
|
+
let affect = input.affectFlag;
|
|
220
|
+
const trimmed: TrimEvent[] = [];
|
|
221
|
+
|
|
222
|
+
if (surfaced.length === 0 && footnotes.length === 0 && !affect) {
|
|
223
|
+
return {
|
|
224
|
+
text: "",
|
|
225
|
+
bytes: 0,
|
|
226
|
+
budgetBytes: input.budgetBytes,
|
|
227
|
+
surfaced: [],
|
|
228
|
+
footnotes: [],
|
|
229
|
+
affectFlag: false,
|
|
230
|
+
trimmed,
|
|
231
|
+
sentinel: null,
|
|
232
|
+
pressure: false,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
for (;;) {
|
|
237
|
+
const c = compose(input, resolve, surfaced, footnotes, affect);
|
|
238
|
+
if (c.bytes <= input.budgetBytes) {
|
|
239
|
+
return {
|
|
240
|
+
text: c.text,
|
|
241
|
+
bytes: c.bytes,
|
|
242
|
+
budgetBytes: input.budgetBytes,
|
|
243
|
+
surfaced,
|
|
244
|
+
footnotes,
|
|
245
|
+
affectFlag: affect,
|
|
246
|
+
trimmed,
|
|
247
|
+
sentinel: c.sentinel,
|
|
248
|
+
pressure: c.bytes >= input.budgetBytes * input.pressureRatio,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
let cut = false;
|
|
252
|
+
for (const lane of TRIM_ORDER) {
|
|
253
|
+
if (lane === "footnote" && footnotes.length > 0) {
|
|
254
|
+
trimmed.push({ lane, id: footnotes.pop() ?? null });
|
|
255
|
+
cut = true;
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
if (lane === "surfaced" && surfaced.length > 0) {
|
|
259
|
+
trimmed.push({ lane, id: surfaced.pop() ?? null });
|
|
260
|
+
cut = true;
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
if (lane === "affect" && affect) {
|
|
264
|
+
trimmed.push({ lane, id: null });
|
|
265
|
+
affect = false;
|
|
266
|
+
cut = true;
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (!cut) {
|
|
271
|
+
// Nothing left to give: go quiet rather than emit an over-budget render.
|
|
272
|
+
return {
|
|
273
|
+
text: "",
|
|
274
|
+
bytes: 0,
|
|
275
|
+
budgetBytes: input.budgetBytes,
|
|
276
|
+
surfaced: [],
|
|
277
|
+
footnotes: [],
|
|
278
|
+
affectFlag: false,
|
|
279
|
+
trimmed,
|
|
280
|
+
sentinel: null,
|
|
281
|
+
pressure: true,
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-session gate state — PERSISTED (owner ruling, `docs/module-map.md` Rulings §3).
|
|
3
|
+
*
|
|
4
|
+
* This file exists because of the harvest's most consequential single finding:
|
|
5
|
+
* in v1 the object holding "what surfaced this session", the refractory countdown
|
|
6
|
+
* and the carried cues was constructed fresh every turn and thrown away, because
|
|
7
|
+
* the turn path is a new process per turn and nothing serialized it. Session
|
|
8
|
+
* dedup, the emotional refractory, refractory suppression of arrival cues and
|
|
9
|
+
* cue carry-over were therefore **specified, implemented, tested, and inert on
|
|
10
|
+
* the live path** — exercised only by an in-process replay loop.
|
|
11
|
+
*
|
|
12
|
+
* The generalized lesson, and the reason this module is a file rather than a
|
|
13
|
+
* parameter: **a pure function over caller-owned state is only as real as its
|
|
14
|
+
* caller.** So the state lives in box 2 (canonical operational SQLite, the store's
|
|
15
|
+
* `meta` seam), keyed by session id, and `test/recall.test.ts` asserts that two
|
|
16
|
+
* separate `Recall` instances over two separate `Store` handles — a fresh process,
|
|
17
|
+
* for all this module can tell — share it.
|
|
18
|
+
*
|
|
19
|
+
* **Store:** the `gate_session` TABLE in box 2 — ONE ROW PER RECORD, keyed
|
|
20
|
+
* `(session_id, kind, ref)`. It replaced the single JSON `meta` row at
|
|
21
|
+
* `recall.gate.<sessionId>` on 2026-08-25 (SEAMS item B), which was the fix
|
|
22
|
+
* INTERFACE-GAPS.md #1 asked for and the reason it asked:
|
|
23
|
+
*
|
|
24
|
+
* > `setMeta` is transactional per call, but `load → mutate → save` is not, so
|
|
25
|
+
* > two writers on one session — a turn's `recall()` and a late `resolveUse()`
|
|
26
|
+
* > from the boundary, in different processes — can have the second save drop
|
|
27
|
+
* > the first's records.
|
|
28
|
+
*
|
|
29
|
+
* That is scar §2.1's own sentence arriving inside a transactional database,
|
|
30
|
+
* because the transaction was around the wrong span. With a row per record the
|
|
31
|
+
* late writer inserts ITS record and cannot touch anybody else's. A merge-on-save
|
|
32
|
+
* would have been the sidecar-plus-discipline answer the scar rejects.
|
|
33
|
+
*
|
|
34
|
+
* **Lifetime:** the session, then `Store.pruneGateSessions()` — a real retention
|
|
35
|
+
* sweep beside `pruneSupersededVersions`, which a meta keyspace could never have.
|
|
36
|
+
* `MAX_SESSION_RECORDS` still bounds the per-session record maps, applied on the
|
|
37
|
+
* write AND on the read, so neither direction can exceed it.
|
|
38
|
+
* **Observer:** never written. An instrument deposits nothing, so its gate state
|
|
39
|
+
* lives and dies in the process (`Recall` holds it in memory and stands down at
|
|
40
|
+
* the write).
|
|
41
|
+
*/
|
|
42
|
+
import type { GateRecordInput, Store } from "../store/index.js";
|
|
43
|
+
import type { UseTier } from "../physics/index.js";
|
|
44
|
+
|
|
45
|
+
export const GATE_STATE_VERSION = 1;
|
|
46
|
+
|
|
47
|
+
/** The `gate_session.kind` vocabulary this module owns. `window` is
|
|
48
|
+
* `prospective/`'s (INTERFACE-GAPS.md §3) and is deliberately not read here. */
|
|
49
|
+
export const GATE_KINDS = ["surfaced", "credited", "scalar", "semantic"] as const;
|
|
50
|
+
/** The one `scalar` row: the fields that are not per-memory. */
|
|
51
|
+
export const SCALAR_REF = "state";
|
|
52
|
+
/** The one `semantic` row: last turn's embedding cue, resolved to neighbours. */
|
|
53
|
+
export const SEMANTIC_REF = "lag";
|
|
54
|
+
|
|
55
|
+
/** What a memory got, the turn it got it, and whether it may ever train. */
|
|
56
|
+
export interface SurfaceRecord {
|
|
57
|
+
turn: number;
|
|
58
|
+
tier: "surfaced" | "footnoted";
|
|
59
|
+
/** False when the memory arrived only through ambiguous handles (§9 G5). */
|
|
60
|
+
trains: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface CreditRecord {
|
|
64
|
+
turn: number;
|
|
65
|
+
tier: UseTier;
|
|
66
|
+
/** The lived day the credit landed. Owner ruling 2026-09-14 (R2, review of
|
|
67
|
+
* #99): the never-downgrade check is per (session, memory, LIVED DAY), so a
|
|
68
|
+
* session that spans days and uses the same memory each day credits it once
|
|
69
|
+
* per day — physics' own occasion rule (§5.5) — not once ever. */
|
|
70
|
+
day: number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface GateState {
|
|
74
|
+
v: number;
|
|
75
|
+
sessionId: string;
|
|
76
|
+
/** Turns this session has SERVED (incremented in the record step, never the build). */
|
|
77
|
+
turn: number;
|
|
78
|
+
/** Lived day of the last recorded turn — the handle a future meta sweep needs. */
|
|
79
|
+
lastDay: number;
|
|
80
|
+
/** Session dedup: what this session already saw, and must not see again. */
|
|
81
|
+
surfaced: Record<string, SurfaceRecord>;
|
|
82
|
+
/** Reference credit already granted, so credit never downgrades (§5 G10). */
|
|
83
|
+
credited: Record<string, CreditRecord>;
|
|
84
|
+
/** Emotional refractory: the turn the affect flag last fired. */
|
|
85
|
+
affectFiredTurn: number | null;
|
|
86
|
+
/** Cue carry-over: last turn's cue tokens, re-entering once at CARRY_DECAY. */
|
|
87
|
+
carriedCues: string[];
|
|
88
|
+
/** The turn `carriedCues` came from; they expire after exactly one turn. */
|
|
89
|
+
carriedFromTurn: number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function freshGateState(sessionId: string): GateState {
|
|
93
|
+
return {
|
|
94
|
+
v: GATE_STATE_VERSION,
|
|
95
|
+
sessionId,
|
|
96
|
+
turn: 0,
|
|
97
|
+
lastDay: 0,
|
|
98
|
+
surfaced: {},
|
|
99
|
+
credited: {},
|
|
100
|
+
affectFiredTurn: null,
|
|
101
|
+
carriedCues: [],
|
|
102
|
+
carriedFromTurn: -1,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface LoadResult {
|
|
107
|
+
state: GateState;
|
|
108
|
+
/** "loaded" | "absent" | "unreadable" — a reset is a countable event, never a
|
|
109
|
+
* silent fresh start (scar §2.4: "did not fire" and "was never asked" differ). */
|
|
110
|
+
status: "loaded" | "absent" | "unreadable";
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface ScalarPayload {
|
|
114
|
+
v: number;
|
|
115
|
+
affectFiredTurn: number | null;
|
|
116
|
+
carriedCues: string[];
|
|
117
|
+
carriedFromTurn: number;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function loadGateState(store: Store, sessionId: string, max = Infinity): LoadResult {
|
|
121
|
+
const rows = store.gateRecords(sessionId);
|
|
122
|
+
if (rows.length === 0) return { state: freshGateState(sessionId), status: "absent" };
|
|
123
|
+
|
|
124
|
+
const scalarRow = rows.find((r) => r.kind === "scalar" && r.ref === SCALAR_REF);
|
|
125
|
+
if (scalarRow === undefined) return { state: freshGateState(sessionId), status: "unreadable" };
|
|
126
|
+
let scalar: ScalarPayload;
|
|
127
|
+
try {
|
|
128
|
+
const parsed = JSON.parse(scalarRow.value ?? "") as Partial<ScalarPayload>;
|
|
129
|
+
if (parsed === null || typeof parsed !== "object" || parsed.v !== GATE_STATE_VERSION) {
|
|
130
|
+
return { state: freshGateState(sessionId), status: "unreadable" };
|
|
131
|
+
}
|
|
132
|
+
scalar = {
|
|
133
|
+
v: GATE_STATE_VERSION,
|
|
134
|
+
affectFiredTurn: parsed.affectFiredTurn ?? null,
|
|
135
|
+
carriedCues: parsed.carriedCues ?? [],
|
|
136
|
+
carriedFromTurn: parsed.carriedFromTurn ?? -1,
|
|
137
|
+
};
|
|
138
|
+
} catch {
|
|
139
|
+
return { state: freshGateState(sessionId), status: "unreadable" };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const surfaced: Record<string, SurfaceRecord> = {};
|
|
143
|
+
const credited: Record<string, CreditRecord> = {};
|
|
144
|
+
for (const row of rows) {
|
|
145
|
+
if (row.kind === "surfaced") {
|
|
146
|
+
surfaced[row.ref] = {
|
|
147
|
+
turn: row.turn,
|
|
148
|
+
tier: row.tier === "footnoted" ? "footnoted" : "surfaced",
|
|
149
|
+
trains: row.trains !== 0,
|
|
150
|
+
};
|
|
151
|
+
} else if (row.kind === "credited") {
|
|
152
|
+
credited[row.ref] = { turn: row.turn, tier: (row.tier ?? "referenced") as UseTier, day: row.last_day };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
state: {
|
|
158
|
+
v: GATE_STATE_VERSION,
|
|
159
|
+
sessionId,
|
|
160
|
+
turn: scalarRow.turn,
|
|
161
|
+
lastDay: scalarRow.last_day,
|
|
162
|
+
surfaced: bound(surfaced, max),
|
|
163
|
+
credited: bound(credited, max),
|
|
164
|
+
affectFiredTurn: scalar.affectFiredTurn,
|
|
165
|
+
carriedCues: scalar.carriedCues,
|
|
166
|
+
carriedFromTurn: scalar.carriedFromTurn,
|
|
167
|
+
},
|
|
168
|
+
status: "loaded",
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Keep the newest `max` records by turn — the row bounds itself (see header). */
|
|
173
|
+
function bound<T extends { turn: number }>(rows: Record<string, T>, max: number): Record<string, T> {
|
|
174
|
+
const entries = Object.entries(rows);
|
|
175
|
+
if (entries.length <= max) return rows;
|
|
176
|
+
entries.sort((a, b) => b[1].turn - a[1].turn);
|
|
177
|
+
return Object.fromEntries(entries.slice(0, max));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* The RECORD half of the build/record split (contract §5 G3). It writes through
|
|
182
|
+
* the store seam, so under observer it refuses there — `Recall` never calls it in
|
|
183
|
+
* that case, and if a future caller does, the refusal is inherited rather than
|
|
184
|
+
* remembered.
|
|
185
|
+
*/
|
|
186
|
+
export function saveGateState(store: Store, state: GateState, max: number): void {
|
|
187
|
+
const rows: GateRecordInput[] = [
|
|
188
|
+
{
|
|
189
|
+
sessionId: state.sessionId,
|
|
190
|
+
kind: "scalar",
|
|
191
|
+
ref: SCALAR_REF,
|
|
192
|
+
turn: state.turn,
|
|
193
|
+
lastDay: state.lastDay,
|
|
194
|
+
value: JSON.stringify({
|
|
195
|
+
v: GATE_STATE_VERSION,
|
|
196
|
+
affectFiredTurn: state.affectFiredTurn,
|
|
197
|
+
carriedCues: state.carriedCues,
|
|
198
|
+
carriedFromTurn: state.carriedFromTurn,
|
|
199
|
+
} satisfies ScalarPayload),
|
|
200
|
+
},
|
|
201
|
+
];
|
|
202
|
+
for (const [id, rec] of Object.entries(bound(state.surfaced, max))) {
|
|
203
|
+
rows.push({
|
|
204
|
+
sessionId: state.sessionId,
|
|
205
|
+
kind: "surfaced",
|
|
206
|
+
ref: id,
|
|
207
|
+
turn: rec.turn,
|
|
208
|
+
lastDay: state.lastDay,
|
|
209
|
+
tier: rec.tier,
|
|
210
|
+
trains: rec.trains,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
for (const [id, rec] of Object.entries(bound(state.credited, max))) {
|
|
214
|
+
rows.push({
|
|
215
|
+
sessionId: state.sessionId,
|
|
216
|
+
kind: "credited",
|
|
217
|
+
ref: id,
|
|
218
|
+
turn: rec.turn,
|
|
219
|
+
// The credit's OWN day, not the state's: this is what keys the gate.
|
|
220
|
+
lastDay: rec.day,
|
|
221
|
+
tier: rec.tier,
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
store.setGateRecords(rows);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
228
|
+
// The LAGGED SEMANTIC CUE — per-session, one turn old, on the same table
|
|
229
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Why this exists, and why it holds NEIGHBOURS rather than a vector.
|
|
233
|
+
*
|
|
234
|
+
* `Turn.vector` has been an input since this module was written and NEITHER live
|
|
235
|
+
* path ever set it: the hook built its turn without one and the deliberate tool
|
|
236
|
+
* built its own. Measured on the live store 2026-09-04 — 13,862 embeddings that
|
|
237
|
+
* nothing live consulted, and a semantic channel that existed only in tests and
|
|
238
|
+
* in the sweep's card preselection.
|
|
239
|
+
*
|
|
240
|
+
* The obvious fix — embed the prompt on the way in — is the one v1 shipped
|
|
241
|
+
* (`~/bansai/hooks/surface.ts:82-88`: "a cold cache calls Voyage and the latency
|
|
242
|
+
* race covers it"), and it is how "no second LLM call" quietly became untrue
|
|
243
|
+
* there. It is also unaffordable here: every hook is a fresh process that
|
|
244
|
+
* already spends 700-1000 ms cold against a 1200 ms budget, and `recall.build`
|
|
245
|
+
* is a synchronous pass with checkpoints, not a race — an overrun does not
|
|
246
|
+
* degrade the channel, it aborts the turn.
|
|
247
|
+
*
|
|
248
|
+
* **OWNER RULING (2026-09-04): do not embed on the hot path.** Compute the cue
|
|
249
|
+
* after the turn, in the detached worker, and use it on the NEXT turn — exactly
|
|
250
|
+
* the one-turn lag `carriedCues` already runs on.
|
|
251
|
+
*
|
|
252
|
+
* **And resolve it in the worker too.** Measured here, hermetically, at the live
|
|
253
|
+
* store's size: `Store.nearestTo` over 13,862 stored vectors costs 590-1040 ms,
|
|
254
|
+
* because `cache.nearest` reads and `JSON.parse`s every row. Carrying the raw
|
|
255
|
+
* 1024-float vector across the lag would have moved the embedding call off the
|
|
256
|
+
* hot path and left the SCAN on it — the same abort, one layer down. So the
|
|
257
|
+
* worker embeds AND ranks, and what crosses the lag is the top-M `{id, score}`
|
|
258
|
+
* slice the activation pass would have computed: ~200 bytes, already the shape
|
|
259
|
+
* `activate()` consumes. (A deliberate deviation from "carry the vector": the
|
|
260
|
+
* vector is not kept, because nothing on the hot path could afford to use it —
|
|
261
|
+
* constitution line 15.)
|
|
262
|
+
*
|
|
263
|
+
* **Expiry: exactly one turn**, the same rule and for the same reason as
|
|
264
|
+
* `carriedCues`. The row stamps the session's SERVED turn count at the moment it
|
|
265
|
+
* was written; it is usable only while that number is still the served count,
|
|
266
|
+
* i.e. on the very next turn. A second turn without a fresh row reads `stale`.
|
|
267
|
+
* Retention beyond that is `Store.pruneGateSessions()`, which sweeps this row
|
|
268
|
+
* with the rest of the session's.
|
|
269
|
+
*
|
|
270
|
+
* **A failure is a NAMED STATE, never silence** (scar §2.4). The worker writes
|
|
271
|
+
* this row on every run, including the runs where it could not embed, so "the
|
|
272
|
+
* embedder has no credential" is a word in the decision record rather than an
|
|
273
|
+
* absence indistinguishable from "nothing was near".
|
|
274
|
+
*/
|
|
275
|
+
export const SEMANTIC_STATE_VERSION = 1;
|
|
276
|
+
|
|
277
|
+
/** One neighbour, as `Store.nearestTo` returns it. Ids and scores; no bodies. */
|
|
278
|
+
export interface SemanticHit {
|
|
279
|
+
id: string;
|
|
280
|
+
score: number;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** What the WORKER managed. `ok` is the only one that yields a usable cue. */
|
|
284
|
+
export type SemanticReason =
|
|
285
|
+
| "ok"
|
|
286
|
+
| "embedder-off"
|
|
287
|
+
| "no-credentials"
|
|
288
|
+
| "no-text"
|
|
289
|
+
| "embed-failed";
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* How this turn's semantic channel got its input — a closed vocabulary, so
|
|
293
|
+
* "the channel was dark" always says WHY.
|
|
294
|
+
*
|
|
295
|
+
* `none` nothing was offered and no lag row exists (a core caller, or
|
|
296
|
+
* the first turn of a session).
|
|
297
|
+
* `lagged` a fresh row from the immediately preceding turn was used.
|
|
298
|
+
* `in-line` the caller embedded THIS text now (the deliberate ask, which
|
|
299
|
+
* has no latency budget and is allowed to pay for a round trip).
|
|
300
|
+
* `stale` a row exists but is older than one turn.
|
|
301
|
+
* `unreadable` a row exists and did not parse (a reset is countable).
|
|
302
|
+
* the four `SemanticReason` failures — what the worker said it could not do.
|
|
303
|
+
*/
|
|
304
|
+
export type SemanticSource =
|
|
305
|
+
| "none"
|
|
306
|
+
| "lagged"
|
|
307
|
+
| "in-line"
|
|
308
|
+
| "stale"
|
|
309
|
+
| "unreadable"
|
|
310
|
+
| Exclude<SemanticReason, "ok">;
|
|
311
|
+
|
|
312
|
+
interface SemanticPayload {
|
|
313
|
+
v: number;
|
|
314
|
+
turn: number;
|
|
315
|
+
reason: SemanticReason;
|
|
316
|
+
/** The embedding generation these hits were ranked under. Never a credential. */
|
|
317
|
+
model: string | null;
|
|
318
|
+
dim: number;
|
|
319
|
+
hits: SemanticHit[];
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export interface SemanticInput {
|
|
323
|
+
sessionId: string;
|
|
324
|
+
/** The session's SERVED turn count when this cue was computed. */
|
|
325
|
+
turn: number;
|
|
326
|
+
lastDay: number;
|
|
327
|
+
reason: SemanticReason;
|
|
328
|
+
model?: string | null;
|
|
329
|
+
dim?: number;
|
|
330
|
+
hits?: readonly SemanticHit[];
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export interface SemanticLoad {
|
|
334
|
+
source: SemanticSource;
|
|
335
|
+
/** Present only when `source === "lagged"`. Empty is a real answer: the
|
|
336
|
+
* worker embedded fine and the index held nothing near (degraded). */
|
|
337
|
+
hits: readonly SemanticHit[] | null;
|
|
338
|
+
/** The turn the cue was computed from, when there was a row at all. */
|
|
339
|
+
fromTurn: number | null;
|
|
340
|
+
model: string | null;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Write the lag row. Refuses under observer at the store seam, like every
|
|
344
|
+
* other gate write — an instrument leaves the world as it found it. */
|
|
345
|
+
export function saveSessionSemantic(store: Store, input: SemanticInput): void {
|
|
346
|
+
const payload: SemanticPayload = {
|
|
347
|
+
v: SEMANTIC_STATE_VERSION,
|
|
348
|
+
turn: input.turn,
|
|
349
|
+
reason: input.reason,
|
|
350
|
+
model: input.model ?? null,
|
|
351
|
+
dim: input.dim ?? 0,
|
|
352
|
+
hits: [...(input.hits ?? [])],
|
|
353
|
+
};
|
|
354
|
+
store.setGateRecords([
|
|
355
|
+
{
|
|
356
|
+
sessionId: input.sessionId,
|
|
357
|
+
kind: "semantic",
|
|
358
|
+
ref: SEMANTIC_REF,
|
|
359
|
+
turn: input.turn,
|
|
360
|
+
lastDay: input.lastDay,
|
|
361
|
+
value: JSON.stringify(payload),
|
|
362
|
+
},
|
|
363
|
+
]);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Read the lag row and judge it against the session's own served-turn count —
|
|
368
|
+
* both come out of ONE `gateRecords` read, so freshness is decided against the
|
|
369
|
+
* same snapshot the row was found in.
|
|
370
|
+
*/
|
|
371
|
+
export function loadSessionSemantic(store: Store, sessionId: string): SemanticLoad {
|
|
372
|
+
const rows = store.gateRecords(sessionId);
|
|
373
|
+
const row = rows.find((r) => r.kind === "semantic" && r.ref === SEMANTIC_REF);
|
|
374
|
+
if (row === undefined) return { source: "none", hits: null, fromTurn: null, model: null };
|
|
375
|
+
const served = rows.find((r) => r.kind === "scalar" && r.ref === SCALAR_REF)?.turn ?? 0;
|
|
376
|
+
|
|
377
|
+
let payload: SemanticPayload;
|
|
378
|
+
try {
|
|
379
|
+
const parsed = JSON.parse(row.value ?? "") as Partial<SemanticPayload>;
|
|
380
|
+
if (parsed === null || typeof parsed !== "object" || parsed.v !== SEMANTIC_STATE_VERSION) {
|
|
381
|
+
return { source: "unreadable", hits: null, fromTurn: null, model: null };
|
|
382
|
+
}
|
|
383
|
+
payload = {
|
|
384
|
+
v: SEMANTIC_STATE_VERSION,
|
|
385
|
+
turn: typeof parsed.turn === "number" ? parsed.turn : row.turn,
|
|
386
|
+
reason: (parsed.reason ?? "embed-failed") as SemanticReason,
|
|
387
|
+
model: parsed.model ?? null,
|
|
388
|
+
dim: parsed.dim ?? 0,
|
|
389
|
+
hits: Array.isArray(parsed.hits) ? parsed.hits : [],
|
|
390
|
+
};
|
|
391
|
+
} catch {
|
|
392
|
+
return { source: "unreadable", hits: null, fromTurn: null, model: null };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const base = { fromTurn: payload.turn, model: payload.model };
|
|
396
|
+
// The worker's own refusal outranks staleness: "there was no credential" is
|
|
397
|
+
// the more useful sentence, and it is true whatever turn it happened on.
|
|
398
|
+
if (payload.reason !== "ok") return { source: payload.reason, hits: null, ...base };
|
|
399
|
+
// ONE TURN, exactly as `carriedCues` expires: the cue must have been computed
|
|
400
|
+
// after the last turn this session served.
|
|
401
|
+
if (payload.turn !== served) return { source: "stale", hits: null, ...base };
|
|
402
|
+
return { source: "lagged", hits: payload.hits, ...base };
|
|
403
|
+
}
|