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,2130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `self/` — the autobiographical self: identity elements, the first-person
|
|
3
|
+
* episode journal, and the wake briefing that restores a continuous self at
|
|
4
|
+
* session start.
|
|
5
|
+
*
|
|
6
|
+
* The module's spine, and where each piece lives:
|
|
7
|
+
*
|
|
8
|
+
* `identity.ts` ranking by strength, the identity/protected enumeration, the
|
|
9
|
+
* standing self-schema byte counter
|
|
10
|
+
* `briefing.ts` the composed budget, the declared trim order, the header and
|
|
11
|
+
* tail sentinel — no model, no network, no prompt
|
|
12
|
+
* `freeze.ts` freeze-but-keep-counting: the lived-salience doctrine as a
|
|
13
|
+
* pure verdict both arms compute
|
|
14
|
+
* `episodes.ts` substance-paced chapters, live append, add-first ingestion
|
|
15
|
+
* `tunables.ts` every knob, in one visible place — and NOT the byte budget
|
|
16
|
+
*
|
|
17
|
+
* Three properties are structural here and worth stating at the top.
|
|
18
|
+
*
|
|
19
|
+
* **RENDER and WAKE are different halves of different sessions.** `boundary()`
|
|
20
|
+
* composes and publishes; `wake()` reads what was published and verifies it. The
|
|
21
|
+
* briefing is the previous boundary's last content write, and wake performs no
|
|
22
|
+
* computation, no model call, and no network access — nor any WRITE, which is the
|
|
23
|
+
* part v1's own design left implicit and then leaned on.
|
|
24
|
+
*
|
|
25
|
+
* **The budget is the caller's.** `budgetBytes` is required on the request
|
|
26
|
+
* because the injection ceiling is a host capability the adapter reports (scar
|
|
27
|
+
* §2.18). v1's 9,000 was 90% of one host's cliff and there is deliberately no
|
|
28
|
+
* such constant in this module.
|
|
29
|
+
*
|
|
30
|
+
* **The freeze withholds movement, never measurement.** `noteSelfConfirmation`
|
|
31
|
+
* runs one walk with one set of guards and emits one event name; `frozen` is a
|
|
32
|
+
* field on that event, not a different code path, so the frozen rate and the live
|
|
33
|
+
* rate share a denominator (§14.2 G4).
|
|
34
|
+
*
|
|
35
|
+
* There is **no tool surface in this module**. v1's self-store tool is superseded
|
|
36
|
+
* by experiencer authorship (contract §4): the doctrine that identity strength
|
|
37
|
+
* comes from lived salience is kept whole, and the end-of-session write *is* the
|
|
38
|
+
* front door it names. Authorship arrives through `remember/`; `self/` is where
|
|
39
|
+
* it lands. *If a doctrine names the only legitimate inputs, those inputs must be
|
|
40
|
+
* reachable by construction, not by a tool description nobody reads.*
|
|
41
|
+
*/
|
|
42
|
+
import type { Band, Kind } from "../types.js";
|
|
43
|
+
import { strength } from "../physics/index.js";
|
|
44
|
+
import type { CreditOutcome, UseTier } from "../physics/index.js";
|
|
45
|
+
import type { ProseDoc, Store } from "../store/index.js";
|
|
46
|
+
import { hashText } from "../store/index.js";
|
|
47
|
+
import {
|
|
48
|
+
IDENTITY_CORE_ROLE,
|
|
49
|
+
byteLength,
|
|
50
|
+
RENDERED_PREFIX,
|
|
51
|
+
enumerate,
|
|
52
|
+
findIdentityCore,
|
|
53
|
+
identityCoreName,
|
|
54
|
+
rankLanes,
|
|
55
|
+
scanActive,
|
|
56
|
+
schemaBytes,
|
|
57
|
+
} from "./identity.js";
|
|
58
|
+
import type {
|
|
59
|
+
Enumeration,
|
|
60
|
+
IdentityCoreSpec,
|
|
61
|
+
LaneName,
|
|
62
|
+
Lanes,
|
|
63
|
+
Ranked,
|
|
64
|
+
Scanned,
|
|
65
|
+
SchemaBytesReport,
|
|
66
|
+
} from "./identity.js";
|
|
67
|
+
import {
|
|
68
|
+
BRIEFING_TRIM_LOG_CAP,
|
|
69
|
+
FRAMING,
|
|
70
|
+
LANE_ORDER,
|
|
71
|
+
TRIM_ORDER,
|
|
72
|
+
WAKE_SYSTEM,
|
|
73
|
+
applyPreface,
|
|
74
|
+
flatten,
|
|
75
|
+
PAGE_FLOOR_RESERVE_BYTES,
|
|
76
|
+
PAGE_MIN_RENDER_BYTES,
|
|
77
|
+
pageDateline,
|
|
78
|
+
pageTooLargeLine,
|
|
79
|
+
prefaceLine,
|
|
80
|
+
readSentinel,
|
|
81
|
+
render,
|
|
82
|
+
} from "./briefing.js";
|
|
83
|
+
import type {
|
|
84
|
+
BriefingRequest,
|
|
85
|
+
BriefingResult,
|
|
86
|
+
PageBlock,
|
|
87
|
+
Resolve,
|
|
88
|
+
Resolved,
|
|
89
|
+
SentinelReading,
|
|
90
|
+
} from "./briefing.js";
|
|
91
|
+
import {
|
|
92
|
+
PAGE_META_BY,
|
|
93
|
+
PAGE_META_REASON,
|
|
94
|
+
PAGE_META_REVISED_DAY,
|
|
95
|
+
PAGE_META_REVISED_ON,
|
|
96
|
+
PAGE_CLEARED_BODY,
|
|
97
|
+
PAGE_META_CLEARED,
|
|
98
|
+
PAGE_TITLE,
|
|
99
|
+
SELF_PAGE_REFUSED_EVENT,
|
|
100
|
+
SELF_PAGE_REVISED_EVENT,
|
|
101
|
+
SELF_PAGE_ROLE,
|
|
102
|
+
findPageRow,
|
|
103
|
+
findSelfPage,
|
|
104
|
+
readSelfPage,
|
|
105
|
+
renderPage,
|
|
106
|
+
} from "./page.js";
|
|
107
|
+
import type { SelfPage, SelfPageAuthor } from "./page.js";
|
|
108
|
+
import {
|
|
109
|
+
SELF_PAGE_WRITER_EVENT,
|
|
110
|
+
dayMemories,
|
|
111
|
+
pageWriterClaimOpen,
|
|
112
|
+
pageWriterDue,
|
|
113
|
+
pageWriterRuns,
|
|
114
|
+
pageWriterStatus,
|
|
115
|
+
} from "./writer.js";
|
|
116
|
+
import type {
|
|
117
|
+
PageWriterDue,
|
|
118
|
+
PageWriterMode,
|
|
119
|
+
PageWriterOutcome,
|
|
120
|
+
PageWriterRun,
|
|
121
|
+
PageWriterStatus,
|
|
122
|
+
WriterInput,
|
|
123
|
+
} from "./writer.js";
|
|
124
|
+
import { COUNTER_PREFIX, FROZEN_KINDS, counterKey, decide } from "./freeze.js";
|
|
125
|
+
import type { ClaimDirection, ClaimSource, FreezeReason, FreezeVerdict } from "./freeze.js";
|
|
126
|
+
import {
|
|
127
|
+
NO_GATE,
|
|
128
|
+
appendChapter,
|
|
129
|
+
askDue,
|
|
130
|
+
askText,
|
|
131
|
+
asksSpentOn,
|
|
132
|
+
findIngested,
|
|
133
|
+
freshEpisodeState,
|
|
134
|
+
ingestKey,
|
|
135
|
+
intakeEpisode,
|
|
136
|
+
loadEpisodeState,
|
|
137
|
+
memoriesForEpisode,
|
|
138
|
+
stateKey,
|
|
139
|
+
} from "./episodes.js";
|
|
140
|
+
import type {
|
|
141
|
+
AskVerdict,
|
|
142
|
+
EpisodeGate,
|
|
143
|
+
EpisodeIntakeReason,
|
|
144
|
+
EpisodeProposal,
|
|
145
|
+
EpisodeState,
|
|
146
|
+
IngestResult,
|
|
147
|
+
Substance,
|
|
148
|
+
} from "./episodes.js";
|
|
149
|
+
import {
|
|
150
|
+
backfillJournalCopies,
|
|
151
|
+
noteJournalCopy,
|
|
152
|
+
syncJournalCopy,
|
|
153
|
+
} from "./journal-file.js";
|
|
154
|
+
import type { JournalCopyOutcome } from "./journal-file.js";
|
|
155
|
+
import { withTunables } from "./tunables.js";
|
|
156
|
+
import type { SelfTunables } from "./tunables.js";
|
|
157
|
+
|
|
158
|
+
export * from "./briefing.js";
|
|
159
|
+
export * from "./journal-file.js";
|
|
160
|
+
export * from "./page.js";
|
|
161
|
+
export * from "./writer.js";
|
|
162
|
+
export * from "./episodes.js";
|
|
163
|
+
export * from "./freeze.js";
|
|
164
|
+
export * from "./identity.js";
|
|
165
|
+
export * from "./tunables.js";
|
|
166
|
+
|
|
167
|
+
/** Telemetry: ids, counts, bytes, reasons, flags. NEVER statement text. */
|
|
168
|
+
export interface SelfEvent {
|
|
169
|
+
at: number;
|
|
170
|
+
name: string;
|
|
171
|
+
ref?: string;
|
|
172
|
+
data?: Record<string, string | number | boolean | null>;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The published briefing lives in box 2, under one key, written by one
|
|
177
|
+
* transactional `setMeta` — so a concurrent read sees the old bundle or the new
|
|
178
|
+
* one and never an empty string. v1's `wake.md` was the one live-read file still
|
|
179
|
+
* written non-atomically, and because an empty string is falsy, an empty
|
|
180
|
+
* concurrent read printed "your persistent memory is initializing" over a full
|
|
181
|
+
* store: identity amnesia disguised as a fresh install (scar §2.3).
|
|
182
|
+
* INTERFACE-GAPS #4 records the store-owned render file this should become.
|
|
183
|
+
*/
|
|
184
|
+
export const BRIEFING_KEY = "self.briefing";
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The honest bootstrap line, and the ONLY case that may be shown in place of a
|
|
188
|
+
* bundle: no bundle has ever been published. A present-but-damaged bundle is an
|
|
189
|
+
* error with its own reason — never this line.
|
|
190
|
+
*/
|
|
191
|
+
export const BOOTSTRAP = "No briefing has been composed yet — this store has not lived a boundary.";
|
|
192
|
+
|
|
193
|
+
export interface SelfOptions {
|
|
194
|
+
store: Store;
|
|
195
|
+
tunables?: Partial<SelfTunables>;
|
|
196
|
+
/** Episode ingestion runs the ordinary gate battery. Absent means REFUSE. */
|
|
197
|
+
gate?: EpisodeGate;
|
|
198
|
+
onEvent?: (e: SelfEvent) => void;
|
|
199
|
+
now?: () => number;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** An arriving occasion. `prospective/` owns the ordering (INTERFACE-GAPS #3). */
|
|
203
|
+
export interface HorizonItem {
|
|
204
|
+
readonly id: string;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export interface BoundaryRequest extends BriefingRequest {
|
|
208
|
+
readonly horizon?: readonly HorizonItem[];
|
|
209
|
+
/** When supplied, the boundary ensures the identity core's home row exists in
|
|
210
|
+
* the shape `schemas/` indexes. Idempotent (schemas/INTERFACE-GAPS #5). */
|
|
211
|
+
readonly identityCore?: IdentityCoreSpec;
|
|
212
|
+
/** Override the id → statement seam (tests, replay, the dashboard). */
|
|
213
|
+
readonly resolve?: Resolve;
|
|
214
|
+
/**
|
|
215
|
+
* Stand an active memory OUT of this composition, before any lane sees it.
|
|
216
|
+
*
|
|
217
|
+
* The owner's own wake never passes one — it is the owner-facing surface and
|
|
218
|
+
* shows everything the store holds (`identity.ts#rankLanes`). It exists for a
|
|
219
|
+
* composition that will LEAVE THE MACHINE: `Counterpart.sweepFallback` wakes
|
|
220
|
+
* the crash-fallback interpreter with the self before it reads a transcript,
|
|
221
|
+
* and that prompt is an egress surface, so confidential and protected rows are
|
|
222
|
+
* omitted there (constitution 6; the same stand-aside `schemas/` makes for the
|
|
223
|
+
* interpreter's cards, §14.1 G2). The predicate lives with the CALLER because
|
|
224
|
+
* the confidentiality class is `recall/`'s to read, not this module's.
|
|
225
|
+
*
|
|
226
|
+
* Filtering here rather than after ranking is deliberate: an omitted row must
|
|
227
|
+
* not occupy a lane slot or a byte of the budget it will never render into.
|
|
228
|
+
*
|
|
229
|
+
* PASSING ONE ALSO SUPPRESSES THE DAY-0 LINE (see `build`): an empty identity
|
|
230
|
+
* lane means "nothing survived the filter" here, not "this store has no self",
|
|
231
|
+
* and the two must not render the same sentence.
|
|
232
|
+
*/
|
|
233
|
+
readonly omit?: (s: Scanned) => boolean;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export type PublishReason = "published" | "observer";
|
|
237
|
+
|
|
238
|
+
export interface BoundaryResult {
|
|
239
|
+
readonly briefing: BriefingResult;
|
|
240
|
+
readonly schema: SchemaBytesReport;
|
|
241
|
+
readonly published: boolean;
|
|
242
|
+
readonly reason: PublishReason;
|
|
243
|
+
/** Content hash of the published text — telemetry that is not the text. */
|
|
244
|
+
readonly hash: string;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export type WakeReason =
|
|
248
|
+
| "delivered"
|
|
249
|
+
| "absent"
|
|
250
|
+
| "empty-read"
|
|
251
|
+
| "sentinel-missing"
|
|
252
|
+
| "sentinel-mismatch";
|
|
253
|
+
|
|
254
|
+
export interface WakeResult {
|
|
255
|
+
/** What to inject. The bootstrap line ONLY when nothing was ever published. */
|
|
256
|
+
readonly text: string;
|
|
257
|
+
/** True when a bundle was read and its sentinel verified against its bytes. */
|
|
258
|
+
readonly ok: boolean;
|
|
259
|
+
readonly reason: WakeReason;
|
|
260
|
+
/** Bytes of what is INJECTED — the preface included, when one was composed. */
|
|
261
|
+
readonly bytes: number;
|
|
262
|
+
/** The sentinel of the injected text: with a preface, the rewritten one. */
|
|
263
|
+
readonly sentinel: string | null;
|
|
264
|
+
/** The integrity reading of the STORED bundle, before any preface. */
|
|
265
|
+
readonly reading: SentinelReading | null;
|
|
266
|
+
/** The delivery-time line, or null when none was asked for or it could not
|
|
267
|
+
* be applied (a damaged bundle is never rewritten). */
|
|
268
|
+
readonly preface: string | null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* What the DELIVERING host knows and the stored bundle cannot: today's date.
|
|
273
|
+
* Passing this object at all is the request for a delivery preface; passing
|
|
274
|
+
* nothing returns the published bundle byte for byte, which is what every
|
|
275
|
+
* non-delivering reader (the dashboard, a test, replay) wants.
|
|
276
|
+
*/
|
|
277
|
+
export interface WakeDelivery {
|
|
278
|
+
/** Today's calendar date as the host reports it. Absent ⇒ no date is stated. */
|
|
279
|
+
readonly date?: string;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export interface ClaimOccasion {
|
|
283
|
+
/** The address the confirmation names. It may be stale; it is resolved. */
|
|
284
|
+
readonly elementId: string;
|
|
285
|
+
readonly source: ClaimSource;
|
|
286
|
+
readonly direction: ClaimDirection;
|
|
287
|
+
readonly tier?: UseTier;
|
|
288
|
+
readonly day?: number;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export type ClaimReason = FreezeReason | "unresolved" | "observer";
|
|
292
|
+
|
|
293
|
+
export interface ClaimOutcome {
|
|
294
|
+
readonly frozen: boolean;
|
|
295
|
+
readonly reason: ClaimReason;
|
|
296
|
+
readonly resolvedId: string | null;
|
|
297
|
+
readonly kind: Kind | null;
|
|
298
|
+
readonly band: Band | null;
|
|
299
|
+
/** Whether physics was asked to move anything. */
|
|
300
|
+
readonly reinforced: boolean;
|
|
301
|
+
readonly credit: CreditOutcome | null;
|
|
302
|
+
/** Strength before and after the walk. Equal is the guarantee, not an aside. */
|
|
303
|
+
readonly strengthBefore: number | null;
|
|
304
|
+
readonly strengthAfter: number | null;
|
|
305
|
+
/** The occasion's counter after this occasion — the measurement that survives
|
|
306
|
+
* the withheld movement (§14.2 G4). */
|
|
307
|
+
readonly count: number;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export interface ChapterAsk {
|
|
311
|
+
readonly asked: boolean;
|
|
312
|
+
readonly verdict: AskVerdict;
|
|
313
|
+
/** The ask text, or null when no ask is due. */
|
|
314
|
+
readonly ask: string | null;
|
|
315
|
+
readonly chapter: number;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export interface ChapterAppend {
|
|
319
|
+
readonly episodeId: string | null;
|
|
320
|
+
readonly chapter: number;
|
|
321
|
+
readonly created: boolean;
|
|
322
|
+
/** True when this append OPENED the chapter (and wrote its heading). A second
|
|
323
|
+
* append inside one chapter continues it — the live-append case (§13 G2). */
|
|
324
|
+
readonly heading: boolean;
|
|
325
|
+
readonly reason: "appended" | "observer" | "anonymous-session" | "gate-refused";
|
|
326
|
+
/**
|
|
327
|
+
* What happened to the markdown copy under `<store>/journal/` (F6). Null when
|
|
328
|
+
* no chapter was written. A `failed` here is NEVER a failed append: the row is
|
|
329
|
+
* canonical and landed before the copy was attempted.
|
|
330
|
+
*/
|
|
331
|
+
readonly copy: JournalCopyOutcome | null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Why a page write did not land. Every one of them is named to the caller.
|
|
336
|
+
*
|
|
337
|
+
* `version-moved` is the optimistic check (adversarial review M4): a caller that
|
|
338
|
+
* passes the version it READ is told when somebody else has written since, and
|
|
339
|
+
* is handed the current page so it can merge rather than revert. A caller that
|
|
340
|
+
* passes nothing behaves exactly as before — it is a courtesy between writers,
|
|
341
|
+
* not a lock, which is what keeps it inside the owner's "no safeguards up front".
|
|
342
|
+
*/
|
|
343
|
+
export type PageRefusal =
|
|
344
|
+
| "empty"
|
|
345
|
+
| "too-large"
|
|
346
|
+
| "gate-refused"
|
|
347
|
+
| "version-moved"
|
|
348
|
+
| "no-page"
|
|
349
|
+
| "page-appeared"
|
|
350
|
+
| "forged-markers"
|
|
351
|
+
| "no-such-version";
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* The `ifVersion` a caller passes to mean "I read NO PAGE". A version is a
|
|
355
|
+
* non-negative integer, so -1 cannot collide with one, and the two ends of the
|
|
356
|
+
* check then speak the same vocabulary: `present: false` on a read carries this
|
|
357
|
+
* number, and passing it back is the claim "nothing was there when I looked".
|
|
358
|
+
*/
|
|
359
|
+
export const NO_PAGE_VERSION = -1;
|
|
360
|
+
|
|
361
|
+
/** `pageBlock`'s third answer: there IS a page and this ceiling has no room for
|
|
362
|
+
* a word about it. Distinct from `null`, which means there is none. */
|
|
363
|
+
export const NO_ROOM = Symbol("self-page-no-room");
|
|
364
|
+
|
|
365
|
+
export interface PageRevision {
|
|
366
|
+
readonly written: boolean;
|
|
367
|
+
/** `created` / `revised` / `cleared` when it landed; the refusal's own name
|
|
368
|
+
* when it did not, with `observer` for a stood-down instrument. */
|
|
369
|
+
readonly reason: "created" | "revised" | "cleared" | PageRefusal | "observer";
|
|
370
|
+
readonly id: string | null;
|
|
371
|
+
/** The version this write produced — 0 for a page written for the first time. */
|
|
372
|
+
readonly version: number | null;
|
|
373
|
+
readonly bytes: number;
|
|
374
|
+
/** Which gate refused, when one did. Null on every other outcome. */
|
|
375
|
+
readonly gate: { readonly gate: string; readonly reason: string } | null;
|
|
376
|
+
/** Accepted, and larger than the wake will show: the page is kept whole and
|
|
377
|
+
* the wake renders a cut of it. Not a refusal — a warning the caller prints. */
|
|
378
|
+
readonly warning: "over-wake-cap" | null;
|
|
379
|
+
/**
|
|
380
|
+
* ACCEPTED, AND CHANGED ON THE WAY IN. The gate battery redacts before
|
|
381
|
+
* anything is stored, and until the adversarial review nothing told the
|
|
382
|
+
* writer: a page carrying an API key was accepted, stored redacted, and the
|
|
383
|
+
* console printed "Wrote the page — 93 bytes". The owner who wrote a file from
|
|
384
|
+
* his editor was not told the file had been altered, on the one row that is
|
|
385
|
+
* then read aloud at the start of every session. Null when the stored text is
|
|
386
|
+
* the text that was sent.
|
|
387
|
+
*/
|
|
388
|
+
readonly redacted: { readonly gate: string; readonly bytesBefore: number } | null;
|
|
389
|
+
/** On `version-moved` only: what is actually there now, so the caller can
|
|
390
|
+
* re-read and merge instead of guessing. */
|
|
391
|
+
readonly current: { readonly version: number; readonly body: string } | null;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** The structural markers a page body may not carry (adversarial review m3). */
|
|
395
|
+
export const WAKE_MARKER = "<!-- counterparts:wake";
|
|
396
|
+
|
|
397
|
+
export interface PageWriteOptions {
|
|
398
|
+
/** One line saying what changed, kept with the version this write produces. */
|
|
399
|
+
readonly reason: string;
|
|
400
|
+
/** Which DOOR this came through. Not claimable from outside the adapter. */
|
|
401
|
+
readonly by: SelfPageAuthor;
|
|
402
|
+
/** WHICH SESSION, when the door knows one. Null/absent is recorded as null —
|
|
403
|
+
* the log says "unknown", never a guess. */
|
|
404
|
+
readonly session?: string | null;
|
|
405
|
+
/**
|
|
406
|
+
* The version the caller believes it is amending. When it does not match, the
|
|
407
|
+
* write is refused as `version-moved` and the answer carries what is actually
|
|
408
|
+
* there. Omit it and the write behaves exactly as it always has.
|
|
409
|
+
*/
|
|
410
|
+
readonly ifVersion?: number;
|
|
411
|
+
readonly day?: number;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export interface PageVersion {
|
|
415
|
+
readonly seq: number;
|
|
416
|
+
readonly day: number;
|
|
417
|
+
readonly body: string | null;
|
|
418
|
+
readonly bytes: number | null;
|
|
419
|
+
/** The reason the write that PRODUCED this body gave. Null when no durable
|
|
420
|
+
* row survives for it. */
|
|
421
|
+
readonly reason: string | null;
|
|
422
|
+
/** Which door produced it, same provenance. Null when unrecorded. */
|
|
423
|
+
readonly by: string | null;
|
|
424
|
+
/** What `store.revise` recorded: the reason the write that REPLACED it gave. */
|
|
425
|
+
readonly replacedBy: string;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** Whole days between two `YYYY-MM-DD` dates, or null when either is unreadable. */
|
|
429
|
+
function daysBetween(from: string, to: string): number | null {
|
|
430
|
+
// The SHAPE is checked, not only the parse: `Date.parse` accepts a great deal
|
|
431
|
+
// that is not a date this store ever wrote, and a page dated by hand is
|
|
432
|
+
// exactly the case this runs on.
|
|
433
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(from) || !/^\d{4}-\d{2}-\d{2}$/.test(to)) return null;
|
|
434
|
+
const a = Date.parse(`${from}T00:00:00Z`);
|
|
435
|
+
const b = Date.parse(`${to}T00:00:00Z`);
|
|
436
|
+
if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
|
|
437
|
+
return Math.round((b - a) / 86_400_000);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
const EVENT_RING = 500;
|
|
441
|
+
|
|
442
|
+
export class Self {
|
|
443
|
+
readonly store: Store;
|
|
444
|
+
readonly tunables: SelfTunables;
|
|
445
|
+
/** One predicate, one definition: the store's. Never re-derived here. */
|
|
446
|
+
readonly observer: boolean;
|
|
447
|
+
|
|
448
|
+
private readonly gate: EpisodeGate;
|
|
449
|
+
private readonly onEvent: ((e: SelfEvent) => void) | undefined;
|
|
450
|
+
private readonly now: () => number;
|
|
451
|
+
private readonly ring: SelfEvent[] = [];
|
|
452
|
+
/** Observer-only state that may never be deposited (observer-mode G3/G6). */
|
|
453
|
+
private readonly volatileState = new Map<string, EpisodeState>();
|
|
454
|
+
private readonly volatileCounts = new Map<string, number>();
|
|
455
|
+
|
|
456
|
+
constructor(opts: SelfOptions) {
|
|
457
|
+
this.store = opts.store;
|
|
458
|
+
this.tunables = withTunables(opts.tunables ?? {});
|
|
459
|
+
this.observer = opts.store.observer;
|
|
460
|
+
this.gate = opts.gate ?? NO_GATE;
|
|
461
|
+
this.onEvent = opts.onEvent;
|
|
462
|
+
this.now = opts.now ?? (() => Date.now());
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// ── the briefing ─────────────────────────────────────────────────────────
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Compose without publishing. Pure with respect to durable state: it reads,
|
|
469
|
+
* ranks and composes, and writes nothing. Exposed because "render and publish
|
|
470
|
+
* are separate steps" is only a real property if the render is separately
|
|
471
|
+
* callable — a private half is a promise, not a seam.
|
|
472
|
+
*/
|
|
473
|
+
build(req: BoundaryRequest): BriefingResult {
|
|
474
|
+
const all = scanActive(this.store, req.day);
|
|
475
|
+
// `omit` (see the field): the owner's wake passes none and this is a no-op;
|
|
476
|
+
// a composition bound for a model call outside this machine passes one.
|
|
477
|
+
const scanned = req.omit === undefined ? all : all.filter((s) => !req.omit?.(s));
|
|
478
|
+
const horizon: Ranked[] = (req.horizon ?? []).map((h) => this.horizonRank(h, req.day));
|
|
479
|
+
const lanes: Lanes = rankLanes(scanned, horizon, this.tunables);
|
|
480
|
+
const docs = new Map<string, ProseDoc>();
|
|
481
|
+
// Provenance rides along from the SAME scan the docs came from: the render
|
|
482
|
+
// dates a migrated element as an upper bound, and a second row read per
|
|
483
|
+
// element to learn that would be a scan the boundary already paid for.
|
|
484
|
+
const sources = new Map<string, string | null>();
|
|
485
|
+
for (const s of scanned) {
|
|
486
|
+
docs.set(s.id, s.doc);
|
|
487
|
+
sources.set(s.id, s.source);
|
|
488
|
+
}
|
|
489
|
+
const resolve: Resolve = req.resolve ?? ((id) => this.resolveStatement(id, docs, sources));
|
|
490
|
+
// THE DAY-0 LANE (NOTES §11). The lookup is guarded by the empty lane and by
|
|
491
|
+
// nothing else: it reads prose, and a store with even one identity element
|
|
492
|
+
// must not pay for it — nor render the line. On a store that has lived
|
|
493
|
+
// boundaries this branch is unreachable, which is also why the change cannot
|
|
494
|
+
// move a byte of the owner's wake.
|
|
495
|
+
//
|
|
496
|
+
// AND BY `omit` (2026-09-17 review). A composition that passes `omit` is by
|
|
497
|
+
// definition not owner-facing, and the identity lane it sees is the
|
|
498
|
+
// POST-OMIT one: a store whose identity band is entirely protected or
|
|
499
|
+
// confidential would otherwise unlock this line and tell a model call — one
|
|
500
|
+
// being asked to write in the first person AS this self — that no identity
|
|
501
|
+
// has formed here. It would also render the core's NAME, which `omit` never
|
|
502
|
+
// saw: the core is a `type: "schema"` row and `scanActive` lists
|
|
503
|
+
// `type: "memory"`. Both by one clause: no day-0 line on a composition that
|
|
504
|
+
// filters.
|
|
505
|
+
const coreName =
|
|
506
|
+
req.omit === undefined && lanes.identity.length === 0 ? identityCoreName(this.store) : null;
|
|
507
|
+
// THE PAGE, cut here rather than in the renderer: the cap is a byte decision
|
|
508
|
+
// that needs the caller's budget AND the page's own prose, and `briefing.ts`
|
|
509
|
+
// composes rather than reads.
|
|
510
|
+
//
|
|
511
|
+
// **DOES IT GO OUT?** A composition that passes `omit` is by definition one
|
|
512
|
+
// that will leave the machine, and the page is born `protected` — the very
|
|
513
|
+
// predicate `sweepFallback` filters on. That flag is the PRUNE's vocabulary
|
|
514
|
+
// and does not decide egress by itself, but the question is too close to it
|
|
515
|
+
// to be answered by an accident, so it is answered by a switch:
|
|
516
|
+
// `PAGE_ON_EGRESS`, default true, the owner's decision of 2026-09-17 (spec
|
|
517
|
+
// §15 item 3). Turn it off and a filtering composition gets no page and
|
|
518
|
+
// falls back to the identity list `omit` left standing, which is what that
|
|
519
|
+
// composition carried before the page existed.
|
|
520
|
+
const block =
|
|
521
|
+
req.omit !== undefined && !this.tunables.PAGE_ON_EGRESS
|
|
522
|
+
? null
|
|
523
|
+
: this.pageBlock(req.budgetBytes);
|
|
524
|
+
// A page that will not FIT is not a page that does not EXIST: the renderer
|
|
525
|
+
// is told `pageExists` so the still-forming line stays off a store that has
|
|
526
|
+
// one, whatever the ceiling did (MINOR-D).
|
|
527
|
+
const page = block === NO_ROOM ? null : block;
|
|
528
|
+
const pageExists = block !== null;
|
|
529
|
+
return render(
|
|
530
|
+
lanes,
|
|
531
|
+
{
|
|
532
|
+
budgetBytes: req.budgetBytes,
|
|
533
|
+
pageExists,
|
|
534
|
+
day: req.day,
|
|
535
|
+
...(coreName === null ? {} : { coreName }),
|
|
536
|
+
...(page === null ? {} : { page }),
|
|
537
|
+
},
|
|
538
|
+
resolve,
|
|
539
|
+
this.tunables,
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// ── the self page ────────────────────────────────────────────────────────
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* THE PAGE, READ. Null when none has been written — never a fabricated one:
|
|
547
|
+
* a store with nothing to say says so (contract §3, and the day-0 lane's own
|
|
548
|
+
* reasoning). Pure: no write, no event.
|
|
549
|
+
*/
|
|
550
|
+
page(): SelfPage | null {
|
|
551
|
+
return readSelfPage(this.store);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* Has the page gone unrevised longer than the tunable allows? CALENDAR days,
|
|
556
|
+
* against the store's own clock — the lived clock has run seven days across
|
|
557
|
+
* fifteen calendar ones on the owner's store, so a lived window would report a
|
|
558
|
+
* fortnight of silence as three days.
|
|
559
|
+
*/
|
|
560
|
+
pageStale(page: SelfPage | null = this.page()): boolean {
|
|
561
|
+
if (page === null) return false;
|
|
562
|
+
// NO READABLE DATE READS AS STALE. A page whose `revisedOn` is blank or
|
|
563
|
+
// unparseable — only reachable on a hand-minted or hand-edited row — used to
|
|
564
|
+
// read as FRESH, which is the direction that says nothing is wrong about a
|
|
565
|
+
// row nobody can date (adversarial review m6). `pageDateline` says the same
|
|
566
|
+
// thing in words rather than printing nothing.
|
|
567
|
+
const days = daysBetween(page.revisedOn.trim(), this.store.today());
|
|
568
|
+
return days === null ? true : days > this.tunables.PAGE_STALE_DAYS;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* How many earlier states the page has — WITHOUT reading a single one of them
|
|
573
|
+
* off disk.
|
|
574
|
+
*
|
|
575
|
+
* Three surfaces wanted only this number and were getting it from
|
|
576
|
+
* `pageVersions().length`, which reads every archived body: on a page revised
|
|
577
|
+
* nightly for a quarter that is ninety file reads of up to 16 KB to print one
|
|
578
|
+
* digit, on every `self_page` read a session makes (adversarial review m9).
|
|
579
|
+
*/
|
|
580
|
+
pageVersionCount(): number {
|
|
581
|
+
const id = this.pageRowId();
|
|
582
|
+
return id === null ? 0 : this.store.versions(id).length;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Every earlier state of the page, newest first.
|
|
587
|
+
*
|
|
588
|
+
* **Each body carries the reason and the author of the write that PRODUCED
|
|
589
|
+
* it**, not of the write that replaced it. `store.revise` stores the
|
|
590
|
+
* REPLACING write's reason on the row it archives, so reading `VersionRow.reason`
|
|
591
|
+
* straight through labelled version 1 — the first page — with the second
|
|
592
|
+
* write's words, while the CURRENT page's own `Last change:` line reads the
|
|
593
|
+
* row's meta and is right. Two surfaces using the same word for opposite
|
|
594
|
+
* things is worse than one surface with no word (adversarial review M3). The
|
|
595
|
+
* durable `self.page.revised` rows carry what is wanted: the write that
|
|
596
|
+
* produced version `seq` is the one whose row says `version: seq - 1`, because
|
|
597
|
+
* a revision archives the body that was standing and numbers it with the
|
|
598
|
+
* revision it is making. `replacedBy` keeps the store's own value, named for
|
|
599
|
+
* what it actually is.
|
|
600
|
+
*
|
|
601
|
+
* `bodies: false` skips the per-version file read.
|
|
602
|
+
*/
|
|
603
|
+
pageVersions(opts: { bodies?: boolean } = {}): PageVersion[] {
|
|
604
|
+
const id = this.pageRowId();
|
|
605
|
+
if (id === null) return [];
|
|
606
|
+
const wrote = new Map<number, { reason: string | null; by: string | null }>();
|
|
607
|
+
try {
|
|
608
|
+
for (const row of this.store.eventLog({ name: SELF_PAGE_REVISED_EVENT, ref: id })) {
|
|
609
|
+
const payload = JSON.parse(row.payload ?? "{}") as Record<string, unknown>;
|
|
610
|
+
const v = payload["version"];
|
|
611
|
+
if (typeof v !== "number") continue;
|
|
612
|
+
wrote.set(v, {
|
|
613
|
+
reason: typeof payload["reason"] === "string" ? payload["reason"] : null,
|
|
614
|
+
by: typeof payload["by"] === "string" ? payload["by"] : null,
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
} catch {
|
|
618
|
+
/* a log that will not read leaves every version unattributed, not wrong */
|
|
619
|
+
}
|
|
620
|
+
return this.store
|
|
621
|
+
.versions(id)
|
|
622
|
+
.slice()
|
|
623
|
+
.sort((a, b) => b.seq - a.seq)
|
|
624
|
+
.map((v) => {
|
|
625
|
+
let body: string | null = null;
|
|
626
|
+
if (opts.bodies !== false) {
|
|
627
|
+
try {
|
|
628
|
+
body = this.store.readVersion(id, v.seq).body;
|
|
629
|
+
} catch {
|
|
630
|
+
body = null;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
const wroteIt = wrote.get(v.seq - 1) ?? { reason: null, by: null };
|
|
634
|
+
return {
|
|
635
|
+
seq: v.seq,
|
|
636
|
+
day: v.version_day,
|
|
637
|
+
body,
|
|
638
|
+
bytes: body === null ? null : byteLength(body),
|
|
639
|
+
reason: wroteIt.reason,
|
|
640
|
+
by: wroteIt.by,
|
|
641
|
+
replacedBy: v.reason,
|
|
642
|
+
};
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* PUT A VERSION BACK, in one command. It is an ordinary revision whose body is
|
|
648
|
+
* that version's, so the restore is itself versioned and itself undoable — the
|
|
649
|
+
* owner never has to hand-edit a file out of `--version <seq>`'s output, which
|
|
650
|
+
* is what he had to do before (the output opens with a header line, so the
|
|
651
|
+
* obvious redirect wrote the header into the page).
|
|
652
|
+
*/
|
|
653
|
+
restorePage(seq: number, opts: { reason?: string; day?: number } = {}): PageRevision {
|
|
654
|
+
const id = this.pageRowId();
|
|
655
|
+
const none = {
|
|
656
|
+
id: null,
|
|
657
|
+
version: null,
|
|
658
|
+
bytes: 0,
|
|
659
|
+
warning: null,
|
|
660
|
+
gate: null,
|
|
661
|
+
redacted: null,
|
|
662
|
+
current: null,
|
|
663
|
+
} as const;
|
|
664
|
+
// Two different absences, named apart: no page has ever been written here,
|
|
665
|
+
// and there is no version by that number. A caller reaching this seam
|
|
666
|
+
// directly (S2) gets the one that is true.
|
|
667
|
+
if (id === null) return { ...none, written: false, reason: "empty" };
|
|
668
|
+
let body: string;
|
|
669
|
+
try {
|
|
670
|
+
body = this.store.readVersion(id, seq).body;
|
|
671
|
+
} catch {
|
|
672
|
+
return { ...none, written: false, reason: "no-such-version" };
|
|
673
|
+
}
|
|
674
|
+
return this.revisePage(body, {
|
|
675
|
+
reason: opts.reason ?? `restored version ${seq}`,
|
|
676
|
+
by: "owner",
|
|
677
|
+
...(opts.day === undefined ? {} : { day: opts.day }),
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* The page's row id INCLUDING a cleared one, for the surfaces that read its
|
|
683
|
+
* history. `findSelfPage` lists live rows only — which is what makes a cleared
|
|
684
|
+
* page read as no page — so the version log needs its own lookup.
|
|
685
|
+
*/
|
|
686
|
+
private pageRowId(): string | null {
|
|
687
|
+
// ONE ROW, cleared or not — so the history is found by the same lookup that
|
|
688
|
+
// finds the page, and nothing here depends on the event log. The first
|
|
689
|
+
// design archived a cleared page and found it again through its
|
|
690
|
+
// `self.page.revised` row; the second review proved that sleep prunes those
|
|
691
|
+
// at 90 lived days and that the fallback scan then picked the WRONG cleared
|
|
692
|
+
// page, whose body `--restore` would have written as the live one. That
|
|
693
|
+
// whole class of question is gone with the row.
|
|
694
|
+
return findPageRow(this.store);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* THE ONE SEAM that writes the page — the MCP tool, the owner's console and
|
|
699
|
+
* (later) the nightly writer all arrive here, so there is one place the row
|
|
700
|
+
* shape, the caps and the durable row are decided.
|
|
701
|
+
*
|
|
702
|
+
* Refusals are NAMED and DURABLE (owner ruling 2's corollary, 2026-09-18: a
|
|
703
|
+
* cap reports what it refused where the owner will see it). There is no silent
|
|
704
|
+
* no-op on this path: every call returns a reason and, unless the store itself
|
|
705
|
+
* is refusing writes, leaves a row saying which it was.
|
|
706
|
+
*
|
|
707
|
+
* `by` is the caller's and is not claimable from the outside by anything but
|
|
708
|
+
* the adapter that opened this seam — the MCP tool writes `session`, the
|
|
709
|
+
* console writes `owner`, and `writer` is S2's.
|
|
710
|
+
*/
|
|
711
|
+
revisePage(body: string, opts: PageWriteOptions): PageRevision {
|
|
712
|
+
const day = opts.day ?? this.store.livedDay();
|
|
713
|
+
const draft = body.replace(/\r\n/g, "\n").trim();
|
|
714
|
+
let bytes = byteLength(draft);
|
|
715
|
+
const session = opts.session ?? null;
|
|
716
|
+
const none = {
|
|
717
|
+
id: null,
|
|
718
|
+
version: null,
|
|
719
|
+
warning: null,
|
|
720
|
+
gate: null,
|
|
721
|
+
redacted: null,
|
|
722
|
+
current: null,
|
|
723
|
+
} as const;
|
|
724
|
+
const refuse = (
|
|
725
|
+
reason: PageRefusal,
|
|
726
|
+
detail: Record<string, string | number | boolean>,
|
|
727
|
+
extra: Partial<PageRevision> = {},
|
|
728
|
+
): PageRevision => {
|
|
729
|
+
this.emit("self.page.refused", undefined, { reason, by: opts.by, ...detail });
|
|
730
|
+
try {
|
|
731
|
+
this.store.appendEvent({
|
|
732
|
+
name: SELF_PAGE_REFUSED_EVENT,
|
|
733
|
+
day,
|
|
734
|
+
// WHICH SESSION, when the door knows one. Null is written rather than
|
|
735
|
+
// a guess: "a session" is what the log said before, and with five or
|
|
736
|
+
// more running at once that answers nothing.
|
|
737
|
+
payload: { reason, by: opts.by, session, ...detail },
|
|
738
|
+
});
|
|
739
|
+
} catch {
|
|
740
|
+
/* a refusal that cannot be recorded is still a refusal (§5 G7) */
|
|
741
|
+
}
|
|
742
|
+
return { ...none, written: false, reason, bytes, ...extra };
|
|
743
|
+
};
|
|
744
|
+
|
|
745
|
+
if (this.observer) {
|
|
746
|
+
// The stand-down comes FIRST and writes nothing at all, the durable row
|
|
747
|
+
// included: an instrument that logged its own refusal would be changing
|
|
748
|
+
// the store it is reading (observer-mode G3).
|
|
749
|
+
this.emit("self.observer.standdown", undefined, { site: "revisePage" });
|
|
750
|
+
return { ...none, written: false, reason: "observer", bytes };
|
|
751
|
+
}
|
|
752
|
+
if (draft.length === 0) return refuse("empty", { bytes: 0 });
|
|
753
|
+
if (bytes > this.tunables.PAGE_MAX_BYTES) {
|
|
754
|
+
// Refused, never cut: what gets cut at write time is the only copy.
|
|
755
|
+
return refuse("too-large", { bytes, limit: this.tunables.PAGE_MAX_BYTES });
|
|
756
|
+
}
|
|
757
|
+
// NO FORGED WAKE STRUCTURE. The page is injected verbatim and FIRST inside
|
|
758
|
+
// the bundle, so a body carrying the wake's own comment markers puts an
|
|
759
|
+
// end-of-memory marker in front of four real lanes for the model reading it,
|
|
760
|
+
// and gives the dashboard's lane splitter a lane the store has no rows for.
|
|
761
|
+
// Nothing downstream breaks — `readSentinel` reads the last line only and
|
|
762
|
+
// the delivery check is already hardened — but the READING is the thing the
|
|
763
|
+
// markers exist for (adversarial review m3). Only the structural markers:
|
|
764
|
+
// the page is meant to carry the session's own prose, headings and all.
|
|
765
|
+
if (draft.includes(WAKE_MARKER)) return refuse("forged-markers", { bytes });
|
|
766
|
+
// THE OPTIMISTIC CHECK, and only when the caller asked for one (M4). Two
|
|
767
|
+
// sessions that both read at 09:00 and both write at 17:00 otherwise leave
|
|
768
|
+
// the second one's page standing and tell the first `stored: true`: not data
|
|
769
|
+
// loss, since every lost body is a version, but silent reversion of a page
|
|
770
|
+
// every session reads, which is the same felt outcome and harder to notice.
|
|
771
|
+
const before = readSelfPage(this.store);
|
|
772
|
+
if (opts.ifVersion !== undefined) {
|
|
773
|
+
// "I READ NO PAGE" HAS A VALUE, and it is `NO_PAGE_VERSION` (-1). With no
|
|
774
|
+
// page, `version` is not a number at all, so every integer mismatched and
|
|
775
|
+
// the first write a careful session made — one that read `present: false`
|
|
776
|
+
// and passed the natural 0 back, as the description tells it to — was
|
|
777
|
+
// refused with a sentence saying somebody else had written the page. That
|
|
778
|
+
// was untrue, and there was nothing handed back to merge against
|
|
779
|
+
// (adversarial review MINOR-C). `no-page` and `page-appeared` name the two
|
|
780
|
+
// directions apart from a genuine race.
|
|
781
|
+
const at = before?.version ?? NO_PAGE_VERSION;
|
|
782
|
+
if (at !== opts.ifVersion) {
|
|
783
|
+
const reason: PageRefusal =
|
|
784
|
+
before === null ? "no-page" : opts.ifVersion === NO_PAGE_VERSION ? "page-appeared" : "version-moved";
|
|
785
|
+
return refuse(
|
|
786
|
+
reason,
|
|
787
|
+
{ bytes, expected: opts.ifVersion, at },
|
|
788
|
+
{
|
|
789
|
+
current:
|
|
790
|
+
before === null ? null : { version: before.version, body: before.body },
|
|
791
|
+
},
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
// THE BATTERY, on the page as on the journal (SEAMS H). The page is prose
|
|
796
|
+
// that will be injected into every session from here on, so a credential
|
|
797
|
+
// written into it would be the most durable place on the machine to leave
|
|
798
|
+
// one. `NO_GATE`'s refusal is the behaviour of a door nobody wired a battery
|
|
799
|
+
// into, and it is loud rather than open.
|
|
800
|
+
const verdict = this.gate({ text: draft, handles: [], sessionId: `page:${opts.by}` });
|
|
801
|
+
if (!verdict.ok) {
|
|
802
|
+
return refuse(
|
|
803
|
+
"gate-refused",
|
|
804
|
+
{ bytes, gate: verdict.gate, gateReason: verdict.reason },
|
|
805
|
+
{ gate: { gate: verdict.gate, reason: verdict.reason } },
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
// The GATE's text, never the draft: the battery may have redacted it.
|
|
809
|
+
const text = verdict.text !== undefined && verdict.text.length > 0 ? verdict.text : draft;
|
|
810
|
+
// ...and the writer is TOLD when that happened (m1).
|
|
811
|
+
// An ACCEPTING verdict carries no gate name — the battery redacts in the
|
|
812
|
+
// secrets gate and says so only when it refuses — so the class is named
|
|
813
|
+
// here, which is the one the redaction can have come from.
|
|
814
|
+
const redacted = text === draft ? null : { gate: "secrets", bytesBefore: bytes };
|
|
815
|
+
bytes = byteLength(text);
|
|
816
|
+
|
|
817
|
+
// THE PAGE'S ROW, cleared or not: a write after a clear revives the SAME row
|
|
818
|
+
// and its whole version chain rather than minting a fresh one beside it.
|
|
819
|
+
// `store.revise` merges meta, so the cleared flag is dropped explicitly.
|
|
820
|
+
const existing = findPageRow(this.store);
|
|
821
|
+
const meta: Record<string, unknown> = {
|
|
822
|
+
role: SELF_PAGE_ROLE,
|
|
823
|
+
[PAGE_META_BY]: opts.by,
|
|
824
|
+
[PAGE_META_REASON]: opts.reason,
|
|
825
|
+
[PAGE_META_REVISED_ON]: this.store.today(),
|
|
826
|
+
[PAGE_META_REVISED_DAY]: day,
|
|
827
|
+
[PAGE_META_CLEARED]: null,
|
|
828
|
+
};
|
|
829
|
+
let id: string;
|
|
830
|
+
let version: number;
|
|
831
|
+
if (existing === null) {
|
|
832
|
+
id = this.store.put({
|
|
833
|
+
type: "schema",
|
|
834
|
+
kind: "self",
|
|
835
|
+
title: PAGE_TITLE,
|
|
836
|
+
body: text,
|
|
837
|
+
meta,
|
|
838
|
+
learnedOn: this.store.today(),
|
|
839
|
+
// PROTECTED AT BIRTH — the one flag that keeps the floor prune off it
|
|
840
|
+
// (`physics#pruneVerdict` blocks on it by name). It is not a
|
|
841
|
+
// confidentiality class and it buys no exemption anywhere else.
|
|
842
|
+
physics: { protected: true },
|
|
843
|
+
});
|
|
844
|
+
version = 0;
|
|
845
|
+
} else {
|
|
846
|
+
id = existing;
|
|
847
|
+
version = this.store.revise(id, { body: text, title: PAGE_TITLE, meta, reason: opts.reason });
|
|
848
|
+
// A page written before this flag existed — or one whose row was minted by
|
|
849
|
+
// hand — is put beyond the prune here rather than at some later repair.
|
|
850
|
+
if (this.store.row(id)?.protected !== 1) this.store.updatePhysics(id, { protected: true });
|
|
851
|
+
}
|
|
852
|
+
const warning = bytes > this.tunables.PAGE_WAKE_BYTES ? ("over-wake-cap" as const) : null;
|
|
853
|
+
this.store.appendEvent({
|
|
854
|
+
name: SELF_PAGE_REVISED_EVENT,
|
|
855
|
+
day,
|
|
856
|
+
ref: id,
|
|
857
|
+
payload: {
|
|
858
|
+
by: opts.by,
|
|
859
|
+
// WHICH SESSION WROTE IT, when the door knows one — `by` says which DOOR
|
|
860
|
+
// and cannot be forged, but with five or more sessions running at once
|
|
861
|
+
// "a session" answers nothing. Null when the door has no id; never a
|
|
862
|
+
// guess (adversarial review M3).
|
|
863
|
+
session,
|
|
864
|
+
reason: opts.reason,
|
|
865
|
+
bytes,
|
|
866
|
+
// What the gate took out on the way in, so the log carries the fact the
|
|
867
|
+
// caller was told (m1).
|
|
868
|
+
...(redacted === null ? {} : { redacted: true, redactedBy: redacted.gate }),
|
|
869
|
+
version,
|
|
870
|
+
created: existing === null,
|
|
871
|
+
wakeCap: this.tunables.PAGE_WAKE_BYTES,
|
|
872
|
+
...(warning === null ? {} : { warning }),
|
|
873
|
+
},
|
|
874
|
+
});
|
|
875
|
+
this.emit("self.page.revised", id, {
|
|
876
|
+
by: opts.by,
|
|
877
|
+
bytes,
|
|
878
|
+
version,
|
|
879
|
+
created: existing === null,
|
|
880
|
+
...(warning === null ? {} : { warning }),
|
|
881
|
+
});
|
|
882
|
+
return {
|
|
883
|
+
written: true,
|
|
884
|
+
reason: existing === null ? "created" : "revised",
|
|
885
|
+
id,
|
|
886
|
+
version,
|
|
887
|
+
bytes,
|
|
888
|
+
warning,
|
|
889
|
+
gate: null,
|
|
890
|
+
redacted,
|
|
891
|
+
current: null,
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// ── the nightly page writer (S2) ───────────────────────────────────────────
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* IS A RUN OWED for the day just gone? Pure — it decides, it does not claim.
|
|
899
|
+
*
|
|
900
|
+
* The caller that acts on `due: true` writes the claim with
|
|
901
|
+
* `recordPageWriterRun({ outcome: "asked" | "started" })`, and from then on
|
|
902
|
+
* this says `already-claimed`.
|
|
903
|
+
*/
|
|
904
|
+
pageWriterDue(opts: { mode: PageWriterMode; today?: string }): PageWriterDue {
|
|
905
|
+
return pageWriterDue(this.store, {
|
|
906
|
+
mode: opts.mode,
|
|
907
|
+
today: opts.today ?? this.store.today(),
|
|
908
|
+
observer: this.observer,
|
|
909
|
+
asksPerDay: this.tunables.PAGE_WRITER_ASKS_PER_DAY,
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* WHAT THE WRITER IS HANDED: the page as it stands, and the day just gone,
|
|
915
|
+
* bounded by `PAGE_WRITER_MEMORY_BYTES` and ordered by salience.
|
|
916
|
+
*
|
|
917
|
+
* `omit` is the CALLER's, exactly as `build`'s is and for the same reason —
|
|
918
|
+
* the confidentiality class is `recall/`'s to read and not this module's. A
|
|
919
|
+
* composition that will leave the machine passes one; what it hides is
|
|
920
|
+
* counted onto the run's row rather than disappearing.
|
|
921
|
+
*
|
|
922
|
+
* Pure: it reads and composes. Nothing here writes.
|
|
923
|
+
*/
|
|
924
|
+
pageWriterInput(opts: {
|
|
925
|
+
about: string;
|
|
926
|
+
today?: string;
|
|
927
|
+
day?: number;
|
|
928
|
+
budgetBytes?: number;
|
|
929
|
+
omit?: (m: { id: string; confidential: boolean; protectedRow: boolean }) => boolean;
|
|
930
|
+
}): WriterInput {
|
|
931
|
+
const day = opts.day ?? this.store.livedDay();
|
|
932
|
+
const picked = dayMemories(this.store, {
|
|
933
|
+
about: opts.about,
|
|
934
|
+
day,
|
|
935
|
+
budgetBytes: opts.budgetBytes ?? this.tunables.PAGE_WRITER_MEMORY_BYTES,
|
|
936
|
+
max: this.tunables.PAGE_WRITER_MEMORY_MAX,
|
|
937
|
+
...(opts.omit === undefined ? {} : { omit: opts.omit }),
|
|
938
|
+
});
|
|
939
|
+
return {
|
|
940
|
+
about: opts.about,
|
|
941
|
+
today: opts.today ?? this.store.today(),
|
|
942
|
+
page: this.page(),
|
|
943
|
+
memories: picked.memories,
|
|
944
|
+
dropped: picked.dropped,
|
|
945
|
+
omitted: picked.omitted,
|
|
946
|
+
bytes: picked.bytes,
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/**
|
|
951
|
+
* THE RUN'S DURABLE ROW — the only thing this mechanism writes besides the
|
|
952
|
+
* page, and the page goes through `revisePage` like every other write.
|
|
953
|
+
*
|
|
954
|
+
* An observer records nothing (observer-mode G3: an instrument that logged
|
|
955
|
+
* its own activity would be changing the store it is reading), and an append
|
|
956
|
+
* that will not land costs the ROW and never the run (§5 G7).
|
|
957
|
+
*/
|
|
958
|
+
recordPageWriterRun(run: {
|
|
959
|
+
about: string;
|
|
960
|
+
mode: PageWriterMode;
|
|
961
|
+
outcome: PageWriterOutcome;
|
|
962
|
+
detail?: string;
|
|
963
|
+
bytesBefore?: number;
|
|
964
|
+
bytesAfter?: number;
|
|
965
|
+
considered?: number;
|
|
966
|
+
omitted?: number;
|
|
967
|
+
day?: number;
|
|
968
|
+
/** One row per key, ever. For the rows that would otherwise repeat at every
|
|
969
|
+
* session start of every day — a deferral has no other bound. */
|
|
970
|
+
dedupKey?: string;
|
|
971
|
+
}): boolean {
|
|
972
|
+
const day = run.day ?? this.store.livedDay();
|
|
973
|
+
const payload = {
|
|
974
|
+
about: run.about,
|
|
975
|
+
// The date the run HAPPENED on, beside the one it is about: a claim is
|
|
976
|
+
// only in flight while the day that made it is still running.
|
|
977
|
+
on: this.store.today(),
|
|
978
|
+
mode: run.mode,
|
|
979
|
+
outcome: run.outcome,
|
|
980
|
+
detail: run.detail ?? "",
|
|
981
|
+
bytesBefore: run.bytesBefore ?? 0,
|
|
982
|
+
bytesAfter: run.bytesAfter ?? 0,
|
|
983
|
+
considered: run.considered ?? 0,
|
|
984
|
+
omitted: run.omitted ?? 0,
|
|
985
|
+
};
|
|
986
|
+
if (this.observer) {
|
|
987
|
+
this.emit("self.observer.standdown", undefined, { site: "recordPageWriterRun" });
|
|
988
|
+
return false;
|
|
989
|
+
}
|
|
990
|
+
try {
|
|
991
|
+
this.store.appendEvent({
|
|
992
|
+
name: SELF_PAGE_WRITER_EVENT,
|
|
993
|
+
day,
|
|
994
|
+
payload,
|
|
995
|
+
...(run.dedupKey === undefined ? {} : { dedupKey: run.dedupKey }),
|
|
996
|
+
});
|
|
997
|
+
} catch {
|
|
998
|
+
this.emit("self.page.writer.unrecorded", undefined, { about: run.about, outcome: run.outcome });
|
|
999
|
+
return false;
|
|
1000
|
+
}
|
|
1001
|
+
this.emit("self.page.writer.ran", undefined, {
|
|
1002
|
+
about: run.about,
|
|
1003
|
+
mode: run.mode,
|
|
1004
|
+
outcome: run.outcome,
|
|
1005
|
+
bytesAfter: payload.bytesAfter,
|
|
1006
|
+
});
|
|
1007
|
+
return true;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/** How a date came out, with the derivation named. Pure. */
|
|
1011
|
+
pageWriterStatus(about: string, today?: string): PageWriterStatus {
|
|
1012
|
+
return pageWriterStatus(this.store, about, today ?? this.store.today());
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
/** Every recorded attempt, newest first. Pure. */
|
|
1016
|
+
pageWriterRuns(opts: { about?: string; limit?: number } = {}): PageWriterRun[] {
|
|
1017
|
+
return pageWriterRuns(this.store, opts);
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/** Is that night's claim still open — the question the page's door asks
|
|
1021
|
+
* before it writes `by: "writer"` on a revision. Pure. */
|
|
1022
|
+
pageWriterClaimOpen(about: string, today?: string): boolean {
|
|
1023
|
+
return pageWriterClaimOpen(this.store, about, today ?? this.store.today());
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
/**
|
|
1027
|
+
* UNWRITE THE PAGE — the owner's door, and only the owner's.
|
|
1028
|
+
*
|
|
1029
|
+
* The adversarial review found the dead end: `revisePage("")` refuses as
|
|
1030
|
+
* `empty`, the dashboard is read-only, and the only affordance an owner had
|
|
1031
|
+
* for "stop leading my wake with this page" was `counterparts remove <id>` —
|
|
1032
|
+
* which tombstones the row and, until the `schemas/` skip lands, leaves a
|
|
1033
|
+
* store that will not open at all. This is the door that removal was standing
|
|
1034
|
+
* in for.
|
|
1035
|
+
*
|
|
1036
|
+
* **How "no page" is represented, and why.** ONE ROW FOR THE LIFE OF THE PAGE:
|
|
1037
|
+
* the clear is an ordinary REVISION — so the body it replaces becomes an
|
|
1038
|
+
* ordinary version, attributed like every other — to a fixed cleared-body line,
|
|
1039
|
+
* with `meta.cleared` set. The row stays live and keeps its whole version
|
|
1040
|
+
* chain. `readSelfPage` returns null for a cleared row, so every reader — the
|
|
1041
|
+
* wake, the doctor, the dashboard, the MCP read, the console — sees a store
|
|
1042
|
+
* with no page and the wake goes back to its empty-page behaviour exactly as
|
|
1043
|
+
* if none had ever been written. The next write or restore revises the SAME
|
|
1044
|
+
* row and drops the flag.
|
|
1045
|
+
*
|
|
1046
|
+
* The first design archived the row instead, and the second review proved what
|
|
1047
|
+
* that cost: `revisePage` finds live rows, so the next write — including the
|
|
1048
|
+
* `--restore <seq>` the clear message itself recommends — minted a fresh row
|
|
1049
|
+
* and orphaned four versions with full attribution on a row no surface could
|
|
1050
|
+
* reach. The undo mechanism closed behind the owner as he walked through it.
|
|
1051
|
+
* Deleting was never available (not a verb `store/` has, on purpose), and
|
|
1052
|
+
* blanking the body would leave a live page whose text is a placeholder, which
|
|
1053
|
+
* is the "empty is a valid state" failure the bootstrap line exists to avoid
|
|
1054
|
+
* (§1 G5): a page that says nothing and a store with no page must not render
|
|
1055
|
+
* the same. The flag is what tells those two apart.
|
|
1056
|
+
*
|
|
1057
|
+
* It is the owner's door alone: no MCP tool reaches it. A session that could
|
|
1058
|
+
* unwrite the page could erase the self between two turns, and nothing about
|
|
1059
|
+
* a session's judgement in the moment earns that.
|
|
1060
|
+
*/
|
|
1061
|
+
clearPage(opts: { reason: string; day?: number }): PageRevision {
|
|
1062
|
+
const day = opts.day ?? this.store.livedDay();
|
|
1063
|
+
const none = {
|
|
1064
|
+
id: null,
|
|
1065
|
+
version: null,
|
|
1066
|
+
bytes: 0,
|
|
1067
|
+
warning: null,
|
|
1068
|
+
gate: null,
|
|
1069
|
+
redacted: null,
|
|
1070
|
+
current: null,
|
|
1071
|
+
} as const;
|
|
1072
|
+
if (this.observer) {
|
|
1073
|
+
this.emit("self.observer.standdown", undefined, { site: "clearPage" });
|
|
1074
|
+
return { ...none, written: false, reason: "observer" };
|
|
1075
|
+
}
|
|
1076
|
+
const page = readSelfPage(this.store);
|
|
1077
|
+
if (page === null) return { ...none, written: false, reason: "empty" };
|
|
1078
|
+
// `revise` archives what was there FIRST, so the page that was cleared is a
|
|
1079
|
+
// version on this same row and `--restore <seq>` reaches it.
|
|
1080
|
+
const version = this.store.revise(page.id, {
|
|
1081
|
+
body: PAGE_CLEARED_BODY,
|
|
1082
|
+
meta: {
|
|
1083
|
+
[PAGE_META_REASON]: opts.reason,
|
|
1084
|
+
[PAGE_META_CLEARED]: { on: this.store.today(), reason: opts.reason },
|
|
1085
|
+
},
|
|
1086
|
+
reason: opts.reason,
|
|
1087
|
+
});
|
|
1088
|
+
this.store.appendEvent({
|
|
1089
|
+
name: SELF_PAGE_REVISED_EVENT,
|
|
1090
|
+
day,
|
|
1091
|
+
ref: page.id,
|
|
1092
|
+
payload: {
|
|
1093
|
+
by: "owner",
|
|
1094
|
+
session: null,
|
|
1095
|
+
reason: opts.reason,
|
|
1096
|
+
cleared: true,
|
|
1097
|
+
bytes: page.bytes,
|
|
1098
|
+
version,
|
|
1099
|
+
created: false,
|
|
1100
|
+
wakeCap: this.tunables.PAGE_WAKE_BYTES,
|
|
1101
|
+
},
|
|
1102
|
+
});
|
|
1103
|
+
this.emit("self.page.revised", page.id, { by: "owner", cleared: true, version });
|
|
1104
|
+
return { ...none, written: true, reason: "cleared", id: page.id, version, bytes: page.bytes };
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/**
|
|
1108
|
+
* The page as the wake will print it, or null. Pure.
|
|
1109
|
+
*
|
|
1110
|
+
* The cap is the caller's ceiling LESS the furniture that wake will wrap the
|
|
1111
|
+
* page in (`PAGE_FLOOR_RESERVE_BYTES`), and not the whole ceiling: the page is
|
|
1112
|
+
* furniture the trim loop cannot pop, so a page sized against the whole budget
|
|
1113
|
+
* puts the composition over it with nothing left to trim (adversarial review
|
|
1114
|
+
* B2). When what is left is too small to be a page at all, the wake says the
|
|
1115
|
+
* page exists and does not fit, in one line — the one thing that is both true
|
|
1116
|
+
* and short enough to say.
|
|
1117
|
+
*/
|
|
1118
|
+
private pageBlock(budgetBytes: number): PageBlock | typeof NO_ROOM | null {
|
|
1119
|
+
const page = this.page();
|
|
1120
|
+
if (page === null) return null;
|
|
1121
|
+
const dateline = pageDateline(
|
|
1122
|
+
page.revisedOn,
|
|
1123
|
+
this.pageStale(page),
|
|
1124
|
+
this.tunables.PAGE_STALE_DAYS,
|
|
1125
|
+
);
|
|
1126
|
+
const room = budgetBytes - PAGE_FLOOR_RESERVE_BYTES;
|
|
1127
|
+
// A ceiling with no room for the wake's OWN furniture has none for a line
|
|
1128
|
+
// about the page either, so "Who I am" carries nothing at all rather than a
|
|
1129
|
+
// sentence that puts the bundle over. At this size every lane is empty too,
|
|
1130
|
+
// and the floor's own over-budget tripwire is left for a host that really is
|
|
1131
|
+
// misconfigured rather than spent on prose about prose.
|
|
1132
|
+
//
|
|
1133
|
+
// `NO_ROOM` and not `null`: a page that does not FIT and a page that does not
|
|
1134
|
+
// EXIST must not reach the renderer as the same thing. With
|
|
1135
|
+
// `PAGE_EMPTY_SHOWS_LIST` off, `null` here made a store that HAS a page print
|
|
1136
|
+
// "no page has been written here yet" — the class of lie PR #71's rule
|
|
1137
|
+
// forbids, moved from identity to the page (adversarial review MINOR-D).
|
|
1138
|
+
if (room <= 0) return NO_ROOM;
|
|
1139
|
+
const cap = Math.min(this.tunables.PAGE_WAKE_BYTES, room);
|
|
1140
|
+
if (cap < PAGE_MIN_RENDER_BYTES && page.bytes > cap) {
|
|
1141
|
+
return {
|
|
1142
|
+
text: pageTooLargeLine(page.bytes),
|
|
1143
|
+
dateline: null,
|
|
1144
|
+
truncated: true,
|
|
1145
|
+
wholeBytes: page.bytes,
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
const rendered = renderPage(page.body, cap);
|
|
1149
|
+
return {
|
|
1150
|
+
text: rendered.text,
|
|
1151
|
+
dateline,
|
|
1152
|
+
truncated: rendered.truncated,
|
|
1153
|
+
wholeBytes: rendered.wholeBytes,
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/**
|
|
1158
|
+
* THE SCHEDULED RECONCILER (contract §5 G12). Every derived surface owes one,
|
|
1159
|
+
* and "a script the owner runs occasionally" is not one: v1's identity index
|
|
1160
|
+
* was seeded once and the routine that would have added newly-formed elements
|
|
1161
|
+
* was never called at a boundary, so elements formed after seed day were
|
|
1162
|
+
* invisible at cold start until a human remembered to run something.
|
|
1163
|
+
*
|
|
1164
|
+
* This is that call. It re-ranks from the live store, re-composes, and
|
|
1165
|
+
* republishes — so a briefing cannot be stale by more than one boundary, by
|
|
1166
|
+
* construction rather than by diligence.
|
|
1167
|
+
*/
|
|
1168
|
+
boundary(req: BoundaryRequest): BoundaryResult {
|
|
1169
|
+
if (req.identityCore !== undefined) this.ensureIdentityCore(req.identityCore);
|
|
1170
|
+
const briefing = this.build(req);
|
|
1171
|
+
const schema = schemaBytes(this.store, req.day, this.tunables);
|
|
1172
|
+
const hash = hashText(briefing.text);
|
|
1173
|
+
|
|
1174
|
+
for (const t of briefing.trimmed) {
|
|
1175
|
+
this.emit("self.briefing.trim", t.id, { lane: t.lane, strength: round(t.strength) });
|
|
1176
|
+
}
|
|
1177
|
+
this.emit("self.briefing.rendered", undefined, {
|
|
1178
|
+
day: req.day,
|
|
1179
|
+
bytes: briefing.bytes,
|
|
1180
|
+
budget: briefing.budgetBytes,
|
|
1181
|
+
elements: briefing.elements,
|
|
1182
|
+
identity: briefing.counts.identity,
|
|
1183
|
+
craft: briefing.counts.craft,
|
|
1184
|
+
threads: briefing.counts.threads,
|
|
1185
|
+
hints: briefing.counts.hints,
|
|
1186
|
+
horizon: briefing.counts.horizon,
|
|
1187
|
+
trimmed: briefing.trimmed.length,
|
|
1188
|
+
// WHETHER THE PAGE RENDERED, AND WHETHER IT WAS CUT. Zero and false mean
|
|
1189
|
+
// "no page in this render", which is what a store with none looks like;
|
|
1190
|
+
// without these a wake led by a 6 KB page and a wake led by nothing are
|
|
1191
|
+
// the same row, and the cut is the thing nobody would otherwise see.
|
|
1192
|
+
page: briefing.page?.bytes ?? 0,
|
|
1193
|
+
pageWhole: briefing.page?.wholeBytes ?? 0,
|
|
1194
|
+
pageTruncated: briefing.page?.truncated ?? false,
|
|
1195
|
+
hash,
|
|
1196
|
+
});
|
|
1197
|
+
// A budget gets an event when APPROACHED and an event when crossed; a number
|
|
1198
|
+
// in a log is not a monitor (scar §2.4).
|
|
1199
|
+
if (briefing.pressure) {
|
|
1200
|
+
this.emit("self.briefing.pressure", undefined, {
|
|
1201
|
+
bytes: briefing.bytes,
|
|
1202
|
+
budget: briefing.budgetBytes,
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
if (briefing.overBudget) {
|
|
1206
|
+
this.emit("self.briefing.overbudget", undefined, {
|
|
1207
|
+
bytes: briefing.bytes,
|
|
1208
|
+
budget: briefing.budgetBytes,
|
|
1209
|
+
floor: true,
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
if (schema.quarantined > 0) {
|
|
1213
|
+
// The F8 quarantine, observable: a stood-aside row is counted, never
|
|
1214
|
+
// silently absent (scar §2.4).
|
|
1215
|
+
this.emit("self.schema.quarantined", undefined, {
|
|
1216
|
+
count: schema.quarantined,
|
|
1217
|
+
bytes: schema.quarantinedBytes,
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
if (schema.pressure) {
|
|
1221
|
+
this.emit("self.schema.pressure", undefined, {
|
|
1222
|
+
bytes: schema.bytes,
|
|
1223
|
+
at: schema.pressureAt,
|
|
1224
|
+
elements: schema.elements,
|
|
1225
|
+
});
|
|
1226
|
+
}
|
|
1227
|
+
if (schema.tripped) {
|
|
1228
|
+
this.emit("self.schema.tripped", undefined, {
|
|
1229
|
+
bytes: schema.bytes,
|
|
1230
|
+
trip: schema.trip,
|
|
1231
|
+
elements: schema.elements,
|
|
1232
|
+
});
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
if (this.observer) {
|
|
1236
|
+
// An instrument composes and reports; it deposits nothing (scar E7).
|
|
1237
|
+
this.emit("self.observer.standdown", undefined, { site: "boundary:publish" });
|
|
1238
|
+
return { briefing, schema, published: false, reason: "observer", hash };
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
this.store.setMeta(BRIEFING_KEY, briefing.text);
|
|
1242
|
+
// The rotation's memory: the identity ids this bundle KEPT, stamped with
|
|
1243
|
+
// the day. Kept, not ranked — an element the budget trimmed did not render
|
|
1244
|
+
// and keeps its place at the front of the next rotation.
|
|
1245
|
+
if (briefing.kept.identity.length > 0) {
|
|
1246
|
+
this.store.setMetaMany(
|
|
1247
|
+
briefing.kept.identity.map((id) => [`${RENDERED_PREFIX}${id}`, String(req.day)] as const),
|
|
1248
|
+
);
|
|
1249
|
+
}
|
|
1250
|
+
this.emit("self.briefing.published", undefined, { bytes: briefing.bytes, hash });
|
|
1251
|
+
// THE JOURNAL'S BACKFILL (F6), and this is the only place it runs.
|
|
1252
|
+
//
|
|
1253
|
+
// A store whose `journal/` was deleted — or one whose episodes predate this
|
|
1254
|
+
// code, which is every store that existed before today — gets its copies
|
|
1255
|
+
// back here, a bounded handful per pass. It is AFTER the publish on purpose:
|
|
1256
|
+
// the briefing is this method's job and a slow disk must not be able to
|
|
1257
|
+
// delay it.
|
|
1258
|
+
//
|
|
1259
|
+
// WHERE THIS RUNS: `Self.boundary` is the consolidation cycle's last content
|
|
1260
|
+
// write, through `core/briefing.ts#selfRenderer` — so this is the DETACHED
|
|
1261
|
+
// WORKER, not the session's Stop hook (that calls `Counterpart.boundary`,
|
|
1262
|
+
// which is a different method). Bounded twice all the same, because the
|
|
1263
|
+
// worker is watchdogged and shares its cycle with decay, dedup and the
|
|
1264
|
+
// prune. The honest consequence is in `journal-file.ts`: a long-standing
|
|
1265
|
+
// store fills over many worker runs, and the chapter door is what keeps a
|
|
1266
|
+
// live one current.
|
|
1267
|
+
this.backfillJournal(req.day);
|
|
1268
|
+
return { briefing, schema, published: true, reason: "published", hash };
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
/**
|
|
1272
|
+
* Fill in missing journal files, a bounded pass. Never throws; an observer
|
|
1273
|
+
* never reaches it (the publish arm above returns first).
|
|
1274
|
+
*/
|
|
1275
|
+
private backfillJournal(day: number): void {
|
|
1276
|
+
try {
|
|
1277
|
+
const report = backfillJournalCopies(this.store);
|
|
1278
|
+
for (const result of report.results) {
|
|
1279
|
+
noteJournalCopy(this.store, result, { day, site: "backfill" });
|
|
1280
|
+
}
|
|
1281
|
+
if (report.written > 0 || report.failed > 0 || report.sweptTemps > 0) {
|
|
1282
|
+
this.emit("self.journal.backfill", undefined, {
|
|
1283
|
+
written: report.written,
|
|
1284
|
+
failed: report.failed,
|
|
1285
|
+
swept: report.sweptTemps,
|
|
1286
|
+
more: report.more,
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
} catch {
|
|
1290
|
+
/* a derived copy never takes a boundary down (§1.5) */
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
/**
|
|
1295
|
+
* WAKE: read what the previous boundary published, and verify it. No model, no
|
|
1296
|
+
* network, no ranking, no write — and observers receive it unchanged (§1 G8).
|
|
1297
|
+
*
|
|
1298
|
+
* Failure is never silence and never a lie: a store that has published nothing
|
|
1299
|
+
* gets the honest bootstrap line, and a store whose bundle is present but
|
|
1300
|
+
* damaged gets the bundle it has, flagged, because printing "initializing" over
|
|
1301
|
+
* a full store is the identity-amnesia failure this guarantee exists for.
|
|
1302
|
+
*
|
|
1303
|
+
* **The one cost, named:** a caller asking for a delivery preface also buys two
|
|
1304
|
+
* meta reads and one `COUNT(*)` — the store's size is a delivery-time fact and
|
|
1305
|
+
* a bundle rendered yesterday cannot state it. Still no ranking, no prose read,
|
|
1306
|
+
* no model and no write; the cost is a single aggregate, not O(store) prose,
|
|
1307
|
+
* and a caller that passes nothing pays exactly the old one meta row
|
|
1308
|
+
* (INTERFACE-GAPS #2).
|
|
1309
|
+
*/
|
|
1310
|
+
wake(delivery?: WakeDelivery): WakeResult {
|
|
1311
|
+
const raw = this.store.getMeta(BRIEFING_KEY);
|
|
1312
|
+
if (raw === undefined) {
|
|
1313
|
+
this.emit("self.wake", undefined, { ok: false, reason: "absent", bytes: 0 });
|
|
1314
|
+
return {
|
|
1315
|
+
text: BOOTSTRAP,
|
|
1316
|
+
ok: false,
|
|
1317
|
+
reason: "absent",
|
|
1318
|
+
bytes: byteLength(BOOTSTRAP),
|
|
1319
|
+
sentinel: null,
|
|
1320
|
+
reading: null,
|
|
1321
|
+
preface: null,
|
|
1322
|
+
};
|
|
1323
|
+
}
|
|
1324
|
+
if (raw.length === 0) {
|
|
1325
|
+
// An empty read is an ERROR, never a silently-valid state (§1 G5).
|
|
1326
|
+
this.emit("self.wake", undefined, { ok: false, reason: "empty-read", bytes: 0 });
|
|
1327
|
+
return {
|
|
1328
|
+
text: BOOTSTRAP,
|
|
1329
|
+
ok: false,
|
|
1330
|
+
reason: "empty-read",
|
|
1331
|
+
bytes: 0,
|
|
1332
|
+
sentinel: null,
|
|
1333
|
+
reading: null,
|
|
1334
|
+
preface: null,
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
const reading = readSentinel(raw);
|
|
1338
|
+
const reason: WakeReason = !reading.present
|
|
1339
|
+
? "sentinel-missing"
|
|
1340
|
+
: reading.intact
|
|
1341
|
+
? "delivered"
|
|
1342
|
+
: "sentinel-mismatch";
|
|
1343
|
+
// THE DELIVERY PREFACE, composed here and never at the boundary: which
|
|
1344
|
+
// system this is, which lived day, today's date, how big the store is now.
|
|
1345
|
+
// A damaged bundle is delivered exactly as found — `applyPreface` refuses to
|
|
1346
|
+
// rewrite a byte count that is already telling the truth about damage.
|
|
1347
|
+
const preface =
|
|
1348
|
+
delivery === undefined || reason !== "delivered"
|
|
1349
|
+
? null
|
|
1350
|
+
: prefaceLine({
|
|
1351
|
+
system: WAKE_SYSTEM,
|
|
1352
|
+
day: this.store.livedDay(),
|
|
1353
|
+
...(delivery.date === undefined ? {} : { date: delivery.date }),
|
|
1354
|
+
memories: this.store.countMemories({ type: "memory", archived: false }),
|
|
1355
|
+
// THE SECOND NUMBER, and it is recall's own denominator (U4): the
|
|
1356
|
+
// same filter minus the type clause, so "live rows" here and
|
|
1357
|
+
// `storeSize` there cannot mean two things.
|
|
1358
|
+
liveRows: this.store.countMemories({ archived: false }),
|
|
1359
|
+
});
|
|
1360
|
+
const delivered = preface === null ? null : applyPreface(raw, preface);
|
|
1361
|
+
this.emit("self.wake", undefined, {
|
|
1362
|
+
ok: reason === "delivered",
|
|
1363
|
+
reason,
|
|
1364
|
+
bytes: delivered?.bytes ?? reading.actualBytes,
|
|
1365
|
+
stated: reading.statedBytes,
|
|
1366
|
+
elements: reading.statedElements,
|
|
1367
|
+
preface: delivered?.applied ?? false,
|
|
1368
|
+
});
|
|
1369
|
+
return {
|
|
1370
|
+
text: delivered?.text ?? raw,
|
|
1371
|
+
ok: reason === "delivered",
|
|
1372
|
+
reason,
|
|
1373
|
+
bytes: delivered?.bytes ?? reading.actualBytes,
|
|
1374
|
+
sentinel: delivered?.sentinel ?? reading.line,
|
|
1375
|
+
reading,
|
|
1376
|
+
preface: delivered?.applied === true ? preface : null,
|
|
1377
|
+
};
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
/**
|
|
1381
|
+
* The DELIVERY-side event, distinct from the render-side one (scar §2.3: "we
|
|
1382
|
+
* rendered it" is not "they received it"). v1 shipped eleven days of truncated
|
|
1383
|
+
* wakes because only the render was instrumented.
|
|
1384
|
+
*
|
|
1385
|
+
* The host calls this with what it saw where the wake's last line should be:
|
|
1386
|
+
* the expectation when that is what stood there, `null` when nothing did, and
|
|
1387
|
+
* some other string when something else did. The adapter that reads a
|
|
1388
|
+
* transcript passes `""` for that third case on purpose — the text around a
|
|
1389
|
+
* sentinel found inside a bundle is the owner's memories, and this seam needs
|
|
1390
|
+
* the verdict, not the line.
|
|
1391
|
+
*/
|
|
1392
|
+
noteDelivered(sentinelSeen: string | null, expected: string | null): boolean {
|
|
1393
|
+
const ok = expected !== null && sentinelSeen === expected;
|
|
1394
|
+
this.emit("self.wake.delivered", undefined, {
|
|
1395
|
+
ok,
|
|
1396
|
+
sawSentinel: sentinelSeen !== null,
|
|
1397
|
+
expected: expected !== null,
|
|
1398
|
+
});
|
|
1399
|
+
return ok;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
// ── identity, enumerated ─────────────────────────────────────────────────
|
|
1403
|
+
|
|
1404
|
+
/**
|
|
1405
|
+
* The identity band and the protected set, side by side (constitution 16, scar
|
|
1406
|
+
* §2.19: everything permanent is enumerable on demand — a list, not a cadence).
|
|
1407
|
+
* Reads are pure: this writes nothing and logs nothing (§14.1 G8).
|
|
1408
|
+
*/
|
|
1409
|
+
enumerate(day?: number): Enumeration {
|
|
1410
|
+
return enumerate(this.store, day ?? this.store.livedDay());
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
/**
|
|
1414
|
+
* Mint the identity core's home row, once, in the shape `schemas/` indexes:
|
|
1415
|
+
* `type: "schema"`, `kind: "self"`, `meta: { role: "entity", name, aliases }`
|
|
1416
|
+
* (schemas/INTERFACE-GAPS #5). Idempotent — a second call returns the existing
|
|
1417
|
+
* row and mints nothing, because a second identity core is a category error no
|
|
1418
|
+
* evidence could justify.
|
|
1419
|
+
*
|
|
1420
|
+
* The NAME is the caller's: this module will not invent one, and there is no
|
|
1421
|
+
* default. `boundary({ identityCore })` is the door that reaches this, so it is
|
|
1422
|
+
* not a method waiting for someone to remember it (scar §2.17).
|
|
1423
|
+
*/
|
|
1424
|
+
ensureIdentityCore(spec: IdentityCoreSpec): { id: string | null; created: boolean; reason: "created" | "exists" | "observer" | "no-name" } {
|
|
1425
|
+
const existing = findIdentityCore(this.store);
|
|
1426
|
+
if (existing !== null) return { id: existing, created: false, reason: "exists" };
|
|
1427
|
+
if (spec.name.trim().length === 0) {
|
|
1428
|
+
this.emit("self.core.skipped", undefined, { reason: "no-name" });
|
|
1429
|
+
return { id: null, created: false, reason: "no-name" };
|
|
1430
|
+
}
|
|
1431
|
+
if (this.observer) {
|
|
1432
|
+
this.emit("self.observer.standdown", undefined, { site: "ensureIdentityCore" });
|
|
1433
|
+
return { id: null, created: false, reason: "observer" };
|
|
1434
|
+
}
|
|
1435
|
+
// Empty except its names: birth creates a PLACE for memories to attach,
|
|
1436
|
+
// never a claim about what is true of the thing.
|
|
1437
|
+
const id = this.store.put({
|
|
1438
|
+
type: "schema",
|
|
1439
|
+
kind: "self",
|
|
1440
|
+
title: spec.name,
|
|
1441
|
+
body: spec.name,
|
|
1442
|
+
meta: {
|
|
1443
|
+
role: IDENTITY_CORE_ROLE,
|
|
1444
|
+
name: spec.name,
|
|
1445
|
+
aliases: [...(spec.aliases ?? [])],
|
|
1446
|
+
},
|
|
1447
|
+
});
|
|
1448
|
+
this.emit("self.core.minted", id, { aliases: (spec.aliases ?? []).length });
|
|
1449
|
+
return { id, created: true, reason: "created" };
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
/** The standing self-schema counter (contract §5 G4). Pure; `boundary()` emits. */
|
|
1453
|
+
schemaBytes(day?: number): SchemaBytesReport {
|
|
1454
|
+
return schemaBytes(this.store, day ?? this.store.livedDay(), this.tunables);
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
// ── freeze, but keep counting ────────────────────────────────────────────
|
|
1458
|
+
|
|
1459
|
+
/**
|
|
1460
|
+
* One walk, one event, one withheld movement.
|
|
1461
|
+
*
|
|
1462
|
+
* Everything before the single `if` is identical in both arms — resolution,
|
|
1463
|
+
* kind lookup, the strength reading, the counter, the event — because a frozen
|
|
1464
|
+
* rate measured on a different denominator would not be comparable to the live
|
|
1465
|
+
* one, and comparability is the whole reason the freeze keeps counting.
|
|
1466
|
+
*/
|
|
1467
|
+
noteSelfConfirmation(occasion: ClaimOccasion): ClaimOutcome {
|
|
1468
|
+
const day = occasion.day ?? this.store.livedDay();
|
|
1469
|
+
const tier: UseTier = occasion.tier ?? "referenced";
|
|
1470
|
+
|
|
1471
|
+
// G8: the freeze is decided on the RESOLVED element, so a confirmation
|
|
1472
|
+
// addressed to a superseded id still freezes.
|
|
1473
|
+
let resolvedId: string;
|
|
1474
|
+
try {
|
|
1475
|
+
resolvedId = this.store.resolve(occasion.elementId);
|
|
1476
|
+
} catch {
|
|
1477
|
+
this.emit("self.claim.unresolved", occasion.elementId, {
|
|
1478
|
+
source: occasion.source,
|
|
1479
|
+
direction: occasion.direction,
|
|
1480
|
+
});
|
|
1481
|
+
return {
|
|
1482
|
+
frozen: false,
|
|
1483
|
+
reason: "unresolved",
|
|
1484
|
+
resolvedId: null,
|
|
1485
|
+
kind: null,
|
|
1486
|
+
band: null,
|
|
1487
|
+
reinforced: false,
|
|
1488
|
+
credit: null,
|
|
1489
|
+
strengthBefore: null,
|
|
1490
|
+
strengthAfter: null,
|
|
1491
|
+
count: 0,
|
|
1492
|
+
};
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
const before = this.store.physicsOf(resolvedId);
|
|
1496
|
+
const row = this.store.row(resolvedId);
|
|
1497
|
+
const band: Band = row?.band ?? "episodic";
|
|
1498
|
+
const kind = before.kind;
|
|
1499
|
+
const verdict: FreezeVerdict = decide(kind, occasion.source, occasion.direction);
|
|
1500
|
+
const strengthBefore = strength(before, day);
|
|
1501
|
+
|
|
1502
|
+
// Softening is untouched on every kind (§14.2 G3, contract §5 G6) — and it
|
|
1503
|
+
// is not reinforcement, so it never moves through here: the verdict says
|
|
1504
|
+
// `live-softening` and the revision path (physics' pressure accumulator) is
|
|
1505
|
+
// the caller's next stop, unimpeded. Freezing both directions would make the
|
|
1506
|
+
// identity model unrevisable in both.
|
|
1507
|
+
const wouldMove = occasion.direction === "confirm";
|
|
1508
|
+
const credit =
|
|
1509
|
+
!verdict.frozen && wouldMove && !this.observer
|
|
1510
|
+
? this.store.reinforce(resolvedId, day, tier)
|
|
1511
|
+
: null;
|
|
1512
|
+
|
|
1513
|
+
const after = this.store.physicsOf(resolvedId);
|
|
1514
|
+
const count = this.bumpCount(kind, verdict.frozen);
|
|
1515
|
+
|
|
1516
|
+
// The SAME event, from both arms, with a frozen marker: the event IS the
|
|
1517
|
+
// measurement; the movement is what is withheld (§14.2 G4, scar §2.4).
|
|
1518
|
+
this.emit("self.claim.repeat", resolvedId, {
|
|
1519
|
+
frozen: verdict.frozen,
|
|
1520
|
+
reason: this.observer ? "observer" : verdict.reason,
|
|
1521
|
+
kind,
|
|
1522
|
+
band,
|
|
1523
|
+
source: occasion.source,
|
|
1524
|
+
direction: occasion.direction,
|
|
1525
|
+
tier,
|
|
1526
|
+
day,
|
|
1527
|
+
addressed: occasion.elementId === resolvedId ? "direct" : "forwarded",
|
|
1528
|
+
reinforced: credit?.credited === true,
|
|
1529
|
+
count,
|
|
1530
|
+
});
|
|
1531
|
+
if (this.observer) {
|
|
1532
|
+
this.emit("self.observer.standdown", resolvedId, { site: "noteSelfConfirmation" });
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
return {
|
|
1536
|
+
frozen: verdict.frozen,
|
|
1537
|
+
reason: this.observer ? "observer" : verdict.reason,
|
|
1538
|
+
resolvedId,
|
|
1539
|
+
kind,
|
|
1540
|
+
band,
|
|
1541
|
+
reinforced: credit?.credited === true,
|
|
1542
|
+
credit,
|
|
1543
|
+
strengthBefore,
|
|
1544
|
+
strengthAfter: strength(after, day),
|
|
1545
|
+
count,
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
/** Every claim counter, frozen and live, by kind. A read: writes nothing. */
|
|
1550
|
+
claimCounts(): Record<string, number> {
|
|
1551
|
+
const out: Record<string, number> = {};
|
|
1552
|
+
for (const kind of ["self", "skill", "person", "entity", "place", "fact"] as const) {
|
|
1553
|
+
for (const frozen of [true, false]) {
|
|
1554
|
+
const key = counterKey(kind, frozen);
|
|
1555
|
+
const value = this.observer
|
|
1556
|
+
? (this.volatileCounts.get(key) ?? 0)
|
|
1557
|
+
: Number(this.store.getMeta(key) ?? "0");
|
|
1558
|
+
if (value > 0) out[key] = value;
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
return out;
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
// ── episodes ─────────────────────────────────────────────────────────────
|
|
1565
|
+
|
|
1566
|
+
episodeState(sessionId: string, day?: number): EpisodeState {
|
|
1567
|
+
const d = day ?? this.store.livedDay();
|
|
1568
|
+
if (this.observer) {
|
|
1569
|
+
return this.volatileState.get(sessionId) ?? freshEpisodeState(sessionId, d);
|
|
1570
|
+
}
|
|
1571
|
+
return loadEpisodeState(this.store, sessionId, d).state;
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
/** Pure: is a chapter due? No state advances, nothing is written. */
|
|
1575
|
+
askDue(sessionId: string, substance: Substance, day?: number): AskVerdict {
|
|
1576
|
+
const d = day ?? this.store.livedDay();
|
|
1577
|
+
return askDue(this.episodeState(sessionId, d), substance, this.tunables, {
|
|
1578
|
+
observer: this.observer,
|
|
1579
|
+
today: this.store.today(),
|
|
1580
|
+
});
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
/**
|
|
1584
|
+
* Ask for a chapter — ONE ask, and **the advance is committed before the ask
|
|
1585
|
+
* blocks** (§13 G3–G4), so a crash cannot re-ask in a loop. The state write
|
|
1586
|
+
* happens here, before the caller ever hands the text to a model.
|
|
1587
|
+
*/
|
|
1588
|
+
openChapter(sessionId: string, substance: Substance, day?: number): ChapterAsk {
|
|
1589
|
+
const d = day ?? this.store.livedDay();
|
|
1590
|
+
// The CALENDAR day the allowance is charged to, read once so the verdict and
|
|
1591
|
+
// the advance cannot straddle midnight (`episodes.ts#asksSpentOn` carries
|
|
1592
|
+
// why it is the calendar date and not the lived one).
|
|
1593
|
+
const today = this.store.today();
|
|
1594
|
+
const state = this.episodeState(sessionId, d);
|
|
1595
|
+
const verdict = askDue(state, substance, this.tunables, {
|
|
1596
|
+
observer: this.observer,
|
|
1597
|
+
today,
|
|
1598
|
+
});
|
|
1599
|
+
if (!verdict.due) {
|
|
1600
|
+
this.emit("self.episode.ask.skipped", sessionId, {
|
|
1601
|
+
reason: verdict.reason,
|
|
1602
|
+
chapter: verdict.chapter,
|
|
1603
|
+
sinceTurns: verdict.sinceTurns,
|
|
1604
|
+
sinceBytes: verdict.sinceBytes,
|
|
1605
|
+
});
|
|
1606
|
+
return { asked: false, verdict, ask: null, chapter: verdict.chapter };
|
|
1607
|
+
}
|
|
1608
|
+
// The ask count advances; the CHAPTER count does not. What the model wrote
|
|
1609
|
+
// is the only thing that may claim to be a chapter (2026-09-04: the hook's
|
|
1610
|
+
// count ran to 7 while the episode held none).
|
|
1611
|
+
const advanced: EpisodeState = {
|
|
1612
|
+
...state,
|
|
1613
|
+
asks: state.asks + 1,
|
|
1614
|
+
asksToday: asksSpentOn(state, today) + 1,
|
|
1615
|
+
asksDay: today,
|
|
1616
|
+
askedAtTurns: substance.turns,
|
|
1617
|
+
askedAtBytes: substance.bytes,
|
|
1618
|
+
lastDay: d,
|
|
1619
|
+
};
|
|
1620
|
+
this.persistState(advanced, "openChapter");
|
|
1621
|
+
this.emit("self.episode.ask", sessionId, {
|
|
1622
|
+
chapter: verdict.chapter,
|
|
1623
|
+
reason: verdict.reason,
|
|
1624
|
+
turns: substance.turns,
|
|
1625
|
+
bytes: substance.bytes,
|
|
1626
|
+
// Asks THIS SESSION has raised in its whole life, and the ones it has
|
|
1627
|
+
// spent TODAY — the second is the one `MAX_ASKS_PER_SESSION` refuses on,
|
|
1628
|
+
// so the distance to the cap is readable in the ring. How many asks a
|
|
1629
|
+
// calendar DATE held ACROSS sessions is a question the durable
|
|
1630
|
+
// `adapter.ask` rows answer, each stamped with its date and outcome; no
|
|
1631
|
+
// second counter is kept for it.
|
|
1632
|
+
asks: advanced.asks,
|
|
1633
|
+
asksToday: advanced.asksToday,
|
|
1634
|
+
asksDay: today,
|
|
1635
|
+
});
|
|
1636
|
+
return { asked: true, verdict, ask: askText(verdict.chapter), chapter: verdict.chapter };
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
/**
|
|
1640
|
+
* Append a chapter in the moment. The episode is created on the first one and
|
|
1641
|
+
* revised thereafter — `store.revise` archives the prior version first, so the
|
|
1642
|
+
* open journal keeps every state it passed through.
|
|
1643
|
+
*/
|
|
1644
|
+
appendChapter(
|
|
1645
|
+
sessionId: string,
|
|
1646
|
+
text: string,
|
|
1647
|
+
opts: { day?: number; title?: string; happenedOn?: string } = {},
|
|
1648
|
+
): ChapterAppend {
|
|
1649
|
+
const d = opts.day ?? this.store.livedDay();
|
|
1650
|
+
if (sessionId.trim().length === 0) {
|
|
1651
|
+
// Identity-safe join (§13 G7): every anonymous session collapses to the
|
|
1652
|
+
// same marker, so one session's account would pool into another's.
|
|
1653
|
+
this.emit("self.episode.skipped", undefined, { reason: "anonymous-session" });
|
|
1654
|
+
return { episodeId: null, chapter: 0, created: false, heading: false, reason: "anonymous-session", copy: null };
|
|
1655
|
+
}
|
|
1656
|
+
if (this.observer) {
|
|
1657
|
+
this.emit("self.observer.standdown", sessionId, { site: "appendChapter" });
|
|
1658
|
+
return { episodeId: null, chapter: 0, created: false, heading: false, reason: "observer", copy: null };
|
|
1659
|
+
}
|
|
1660
|
+
// Every ingestion entrance runs the battery — a chapter is canonical prose,
|
|
1661
|
+
// and a credential in one landed durably before this gate existed (found by
|
|
1662
|
+
// the composition root's caller-universality test, fixed the same day). The
|
|
1663
|
+
// gate's text — possibly redacted — is what gets written, never the draft.
|
|
1664
|
+
const verdict = this.gate({ text, handles: [], sessionId });
|
|
1665
|
+
if (!verdict.ok) {
|
|
1666
|
+
this.emit("self.episode.chapter.refused", sessionId, {
|
|
1667
|
+
gate: verdict.gate,
|
|
1668
|
+
reason: verdict.reason,
|
|
1669
|
+
});
|
|
1670
|
+
return { episodeId: null, chapter: 0, created: false, heading: false, reason: "gate-refused", copy: null };
|
|
1671
|
+
}
|
|
1672
|
+
const gatedText = verdict.text ?? text;
|
|
1673
|
+
const state = this.episodeState(sessionId, d);
|
|
1674
|
+
const append: Parameters<typeof appendChapter>[3] = { day: d };
|
|
1675
|
+
if (opts.title !== undefined) append.title = opts.title;
|
|
1676
|
+
if (opts.happenedOn !== undefined) append.happenedOn = opts.happenedOn;
|
|
1677
|
+
const written = appendChapter(this.store, state, gatedText, append);
|
|
1678
|
+
this.persistState(
|
|
1679
|
+
{
|
|
1680
|
+
...state,
|
|
1681
|
+
episodeId: written.episodeId,
|
|
1682
|
+
chapters: Math.max(state.chapters, written.chapter),
|
|
1683
|
+
// This append ANSWERS the open ask: the next one continues this chapter
|
|
1684
|
+
// rather than opening another (§13 G2's headline case).
|
|
1685
|
+
appendedAtAsk: state.asks,
|
|
1686
|
+
lastDay: d,
|
|
1687
|
+
},
|
|
1688
|
+
"appendChapter",
|
|
1689
|
+
);
|
|
1690
|
+
this.emit("self.episode.chapter", written.episodeId, {
|
|
1691
|
+
session: sessionId,
|
|
1692
|
+
chapter: written.chapter,
|
|
1693
|
+
created: written.created,
|
|
1694
|
+
bytes: byteLength(gatedText),
|
|
1695
|
+
});
|
|
1696
|
+
// THE MARKDOWN COPY, AFTER THE ROW AND NEVER INSTEAD OF IT (F6). The
|
|
1697
|
+
// chapter is committed above; this is a derived file, it cannot throw, and
|
|
1698
|
+
// a failure is a durable row rather than a failed `chapter` call. Written
|
|
1699
|
+
// per append rather than once at session end because the plan's one
|
|
1700
|
+
// undetermined question (§7.6) resolves that way in the code: the episode
|
|
1701
|
+
// row is rewritten per append, so the file is a whole-file rewrite either
|
|
1702
|
+
// way, and per-append is the reading that does not lose a crashed session's
|
|
1703
|
+
// last chapter.
|
|
1704
|
+
const copy = syncJournalCopy(this.store, written.episodeId);
|
|
1705
|
+
noteJournalCopy(this.store, copy, {
|
|
1706
|
+
day: d,
|
|
1707
|
+
chapters: written.chapter,
|
|
1708
|
+
site: "chapter",
|
|
1709
|
+
});
|
|
1710
|
+
this.emit("self.journal.copy", written.episodeId, {
|
|
1711
|
+
outcome: copy.outcome,
|
|
1712
|
+
bytes: copy.bytes,
|
|
1713
|
+
...(copy.reason === null ? {} : { reason: copy.reason }),
|
|
1714
|
+
});
|
|
1715
|
+
return { ...written, reason: "appended", copy: copy.outcome };
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
/**
|
|
1719
|
+
* Ingest the session's episode as an ordinary self-kind memory — context and
|
|
1720
|
+
* source, in that order, ingested ONCE. Idempotent by identity against active
|
|
1721
|
+
* and archived memories; add-first on regrowth; the window closes.
|
|
1722
|
+
*/
|
|
1723
|
+
ingestEpisode(
|
|
1724
|
+
input: EpisodeProposal | { sessionId: string; day?: number; handles?: readonly string[] },
|
|
1725
|
+
): IngestResult {
|
|
1726
|
+
const intake = intakeEpisode({ content: "-", ...input });
|
|
1727
|
+
const none = (
|
|
1728
|
+
reason: IngestResult["reason"],
|
|
1729
|
+
intakeReason: EpisodeIntakeReason | null = null,
|
|
1730
|
+
): IngestResult => ({
|
|
1731
|
+
ingested: false,
|
|
1732
|
+
reason,
|
|
1733
|
+
memoryId: null,
|
|
1734
|
+
episodeId: null,
|
|
1735
|
+
key: null,
|
|
1736
|
+
archived: [],
|
|
1737
|
+
gate: null,
|
|
1738
|
+
intake: intakeReason,
|
|
1739
|
+
});
|
|
1740
|
+
if (!intake.ok) {
|
|
1741
|
+
// The intake's own reason is carried through: an anonymous session and a
|
|
1742
|
+
// malformed handle list are different refusals and must read differently.
|
|
1743
|
+
const reason = intake.reason === "SESSION_MISSING" ? "anonymous-session" : "malformed-input";
|
|
1744
|
+
this.emit("self.episode.skipped", undefined, { reason, intake: intake.reason });
|
|
1745
|
+
return none(reason, intake.reason);
|
|
1746
|
+
}
|
|
1747
|
+
const sessionId = input.sessionId;
|
|
1748
|
+
const d = input.day ?? this.store.livedDay();
|
|
1749
|
+
if (this.observer) {
|
|
1750
|
+
this.emit("self.observer.standdown", sessionId, { site: "ingestEpisode" });
|
|
1751
|
+
return none("observer");
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
const state = this.episodeState(sessionId, d);
|
|
1755
|
+
if (state.episodeId === null) {
|
|
1756
|
+
this.emit("self.episode.ingest.skipped", sessionId, { reason: "no-episode" });
|
|
1757
|
+
return none("no-episode");
|
|
1758
|
+
}
|
|
1759
|
+
const doc = this.store.readProse(state.episodeId);
|
|
1760
|
+
const key = ingestKey(state.episodeId, doc.body);
|
|
1761
|
+
const existing = findIngested(this.store, key);
|
|
1762
|
+
if (existing !== null) {
|
|
1763
|
+
// Idempotent against active AND archived, so consolidation's archival
|
|
1764
|
+
// decisions are not resurrected by a stray touch (§5 G10).
|
|
1765
|
+
this.emit("self.episode.ingest.skipped", state.episodeId, {
|
|
1766
|
+
reason: "already-ingested",
|
|
1767
|
+
memory: existing.id,
|
|
1768
|
+
});
|
|
1769
|
+
return {
|
|
1770
|
+
ingested: false,
|
|
1771
|
+
reason: "already-ingested",
|
|
1772
|
+
memoryId: existing.id,
|
|
1773
|
+
episodeId: state.episodeId,
|
|
1774
|
+
key,
|
|
1775
|
+
archived: [],
|
|
1776
|
+
gate: null,
|
|
1777
|
+
intake: null,
|
|
1778
|
+
};
|
|
1779
|
+
}
|
|
1780
|
+
const regrow = state.firstIngestDay !== null;
|
|
1781
|
+
if (regrow && d - (state.firstIngestDay ?? d) > this.tunables.REGROW_WINDOW_DAYS) {
|
|
1782
|
+
// The window CLOSES — the deliberate deviation from human
|
|
1783
|
+
// reconsolidation, which reopens on every retrieval (§13 G12).
|
|
1784
|
+
this.emit("self.episode.ingest.skipped", state.episodeId, {
|
|
1785
|
+
reason: "window-closed",
|
|
1786
|
+
openedOn: state.firstIngestDay,
|
|
1787
|
+
day: d,
|
|
1788
|
+
window: this.tunables.REGROW_WINDOW_DAYS,
|
|
1789
|
+
});
|
|
1790
|
+
return {
|
|
1791
|
+
ingested: false,
|
|
1792
|
+
reason: "window-closed",
|
|
1793
|
+
memoryId: state.ingestedMemoryId,
|
|
1794
|
+
episodeId: state.episodeId,
|
|
1795
|
+
key,
|
|
1796
|
+
archived: [],
|
|
1797
|
+
gate: null,
|
|
1798
|
+
intake: null,
|
|
1799
|
+
};
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
const handles = [...(input.handles ?? [])];
|
|
1803
|
+
const verdict = this.gate({ text: doc.body, handles, sessionId });
|
|
1804
|
+
if (!verdict.ok) {
|
|
1805
|
+
// A first-person reflection is not exempt from never durably encoding a
|
|
1806
|
+
// credential (§13 G8, scar §2.7).
|
|
1807
|
+
this.emit("self.episode.ingest.refused", state.episodeId, {
|
|
1808
|
+
gate: verdict.gate,
|
|
1809
|
+
reason: verdict.reason,
|
|
1810
|
+
});
|
|
1811
|
+
return {
|
|
1812
|
+
ingested: false,
|
|
1813
|
+
reason: "gate-refused",
|
|
1814
|
+
memoryId: null,
|
|
1815
|
+
episodeId: state.episodeId,
|
|
1816
|
+
key,
|
|
1817
|
+
archived: [],
|
|
1818
|
+
gate: { gate: verdict.gate, reason: verdict.reason },
|
|
1819
|
+
intake: null,
|
|
1820
|
+
};
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
// ADD FIRST, then archive the stale one: a failed add can never leave an
|
|
1824
|
+
// episode with no live memory (§13 G11).
|
|
1825
|
+
const proposal = input as EpisodeProposal;
|
|
1826
|
+
// The GATE's text, never the draft, is what becomes the memory: an episode
|
|
1827
|
+
// is an ordinary ingestion and the battery may have redacted it (SEAMS H).
|
|
1828
|
+
const body = verdict.text !== undefined && verdict.text.length > 0 ? verdict.text : doc.body;
|
|
1829
|
+
const put: Parameters<Store["put"]>[0] = {
|
|
1830
|
+
type: "memory",
|
|
1831
|
+
kind: "self",
|
|
1832
|
+
body,
|
|
1833
|
+
meta: { episodeId: state.episodeId, episodeKey: key, sessionId, handles },
|
|
1834
|
+
// The experiencer's own episode is lived testimony — the "episode"
|
|
1835
|
+
// channel, recorded as provenance like every other mint (F9-light).
|
|
1836
|
+
source: "episode",
|
|
1837
|
+
origin: { session: sessionId, ref: state.episodeId },
|
|
1838
|
+
};
|
|
1839
|
+
if (proposal.title !== undefined) put.title = proposal.title;
|
|
1840
|
+
if (proposal.happenedOn !== undefined) put.happenedOn = proposal.happenedOn;
|
|
1841
|
+
else if (doc.happenedOn !== undefined) put.happenedOn = doc.happenedOn;
|
|
1842
|
+
if (proposal.salience !== undefined || proposal.claimed !== undefined) {
|
|
1843
|
+
put.salience = { ...(proposal.salience ?? {}), claimed: proposal.claimed ?? null };
|
|
1844
|
+
}
|
|
1845
|
+
const memoryId = this.store.put(put);
|
|
1846
|
+
|
|
1847
|
+
const archived: string[] = [];
|
|
1848
|
+
for (const stale of memoriesForEpisode(this.store, state.episodeId)) {
|
|
1849
|
+
if (stale === memoryId) continue;
|
|
1850
|
+
this.store.archive(stale, "episode-regrown");
|
|
1851
|
+
archived.push(stale);
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
this.persistState(
|
|
1855
|
+
{
|
|
1856
|
+
...state,
|
|
1857
|
+
ingestedKey: key,
|
|
1858
|
+
ingestedMemoryId: memoryId,
|
|
1859
|
+
firstIngestDay: state.firstIngestDay ?? d,
|
|
1860
|
+
lastDay: d,
|
|
1861
|
+
},
|
|
1862
|
+
"ingestEpisode",
|
|
1863
|
+
);
|
|
1864
|
+
this.emit("self.episode.ingested", state.episodeId, {
|
|
1865
|
+
memory: memoryId,
|
|
1866
|
+
regrown: regrow,
|
|
1867
|
+
archived: archived.length,
|
|
1868
|
+
handles: handles.length,
|
|
1869
|
+
bytes: byteLength(doc.body),
|
|
1870
|
+
});
|
|
1871
|
+
return {
|
|
1872
|
+
ingested: true,
|
|
1873
|
+
reason: regrow ? "regrown" : "ingested",
|
|
1874
|
+
memoryId,
|
|
1875
|
+
episodeId: state.episodeId,
|
|
1876
|
+
key,
|
|
1877
|
+
archived,
|
|
1878
|
+
gate: null,
|
|
1879
|
+
intake: null,
|
|
1880
|
+
};
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
/**
|
|
1884
|
+
* THE DOOR THAT REACHES INGESTION (contract §3: "every identity surface owes
|
|
1885
|
+
* an answer to *which door reaches this?*", §5 G12: every derived surface owes
|
|
1886
|
+
* a SCHEDULED reconciler, asserted to run at a boundary).
|
|
1887
|
+
*
|
|
1888
|
+
* Measured 2026-09-04: `ingestEpisode` had no caller outside this module and
|
|
1889
|
+
* its own tests. An episode that nobody ingests is a file, not a memory — the
|
|
1890
|
+
* "context and source, in that order" half of §13 G6 was unreachable in
|
|
1891
|
+
* production for the whole run. This is that scheduled pass: every live
|
|
1892
|
+
* episode whose CURRENT text has not been ingested is ingested here, at the
|
|
1893
|
+
* boundary, before the cycle that decays and re-renders around it.
|
|
1894
|
+
*
|
|
1895
|
+
* Cheap by construction: the skip is a state read plus a hash, so an episode
|
|
1896
|
+
* already ingested at its current text costs no scan of the memory table.
|
|
1897
|
+
*/
|
|
1898
|
+
reconcileEpisodes(day?: number): {
|
|
1899
|
+
considered: number;
|
|
1900
|
+
ingested: number;
|
|
1901
|
+
regrown: number;
|
|
1902
|
+
skipped: number;
|
|
1903
|
+
} {
|
|
1904
|
+
const d = day ?? this.store.livedDay();
|
|
1905
|
+
let considered = 0;
|
|
1906
|
+
let ingested = 0;
|
|
1907
|
+
let regrown = 0;
|
|
1908
|
+
let skipped = 0;
|
|
1909
|
+
for (const id of this.store.list({ type: "episode", archived: false })) {
|
|
1910
|
+
let doc: ProseDoc;
|
|
1911
|
+
try {
|
|
1912
|
+
doc = this.store.readProse(id);
|
|
1913
|
+
} catch {
|
|
1914
|
+
continue;
|
|
1915
|
+
}
|
|
1916
|
+
const sessionId = doc.meta["sessionId"];
|
|
1917
|
+
// The identity-safe join again: an episode with no session is skipped
|
|
1918
|
+
// outright rather than pooled into anyone's day (§13 G7).
|
|
1919
|
+
if (typeof sessionId !== "string" || sessionId.trim().length === 0) continue;
|
|
1920
|
+
considered += 1;
|
|
1921
|
+
const state = this.episodeState(sessionId, d);
|
|
1922
|
+
if (state.ingestedKey === ingestKey(id, doc.body)) {
|
|
1923
|
+
skipped += 1;
|
|
1924
|
+
continue;
|
|
1925
|
+
}
|
|
1926
|
+
const out = this.ingestEpisode({ sessionId, day: d });
|
|
1927
|
+
if (out.reason === "ingested") ingested += 1;
|
|
1928
|
+
else if (out.reason === "regrown") regrown += 1;
|
|
1929
|
+
else skipped += 1;
|
|
1930
|
+
}
|
|
1931
|
+
this.emit("self.episode.reconciled", undefined, {
|
|
1932
|
+
considered,
|
|
1933
|
+
ingested,
|
|
1934
|
+
regrown,
|
|
1935
|
+
skipped,
|
|
1936
|
+
day: d,
|
|
1937
|
+
});
|
|
1938
|
+
return { considered, ingested, regrown, skipped };
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
/**
|
|
1942
|
+
* The orphanable tail: substance accumulated after the last ask, which no ask
|
|
1943
|
+
* can cover because only a blocked stop hands the model a pen and nobody knows
|
|
1944
|
+
* which stop is last. It is bounded by the re-ask thresholds and LOGGED, so the
|
|
1945
|
+
* miss is measurable before anyone debates a reconstruction fallback — the
|
|
1946
|
+
* right shape for an unfixable gap: bound it, measure it, don't pretend.
|
|
1947
|
+
*/
|
|
1948
|
+
noteOrphanTail(sessionId: string, substance: Substance, day?: number): AskVerdict {
|
|
1949
|
+
// The SAME verdict the ask would get, from the session's own state: the tail
|
|
1950
|
+
// telemetry and the ask must never disagree about why nothing was asked.
|
|
1951
|
+
const verdict = this.askDue(sessionId, substance, day);
|
|
1952
|
+
this.emit("self.episode.tail", sessionId, {
|
|
1953
|
+
sinceTurns: verdict.sinceTurns,
|
|
1954
|
+
sinceBytes: verdict.sinceBytes,
|
|
1955
|
+
boundTurns: this.tunables.REASK_TURNS,
|
|
1956
|
+
boundBytes: this.tunables.REASK_BYTES,
|
|
1957
|
+
chapters: this.episodeState(sessionId, day).chapters,
|
|
1958
|
+
});
|
|
1959
|
+
return verdict;
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
events(name?: string): SelfEvent[] {
|
|
1963
|
+
return this.ring.filter((e) => name === undefined || e.name === name).map((e) => ({ ...e }));
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
// ── internals ────────────────────────────────────────────────────────────
|
|
1967
|
+
|
|
1968
|
+
private horizonRank(item: HorizonItem, day: number): Ranked {
|
|
1969
|
+
let kind: Kind = "fact";
|
|
1970
|
+
let bornDay = day;
|
|
1971
|
+
let s = 0;
|
|
1972
|
+
try {
|
|
1973
|
+
const physics = this.store.physicsOf(item.id);
|
|
1974
|
+
kind = physics.kind;
|
|
1975
|
+
bornDay = physics.birthDay;
|
|
1976
|
+
s = strength(physics, day);
|
|
1977
|
+
} catch {
|
|
1978
|
+
/* an occasion whose memory has gone is still an occasion; it renders by id */
|
|
1979
|
+
}
|
|
1980
|
+
return {
|
|
1981
|
+
id: item.id,
|
|
1982
|
+
lane: "horizon",
|
|
1983
|
+
kind,
|
|
1984
|
+
band: "episodic",
|
|
1985
|
+
strength: s,
|
|
1986
|
+
protected: false,
|
|
1987
|
+
bornDay,
|
|
1988
|
+
personScoped: false,
|
|
1989
|
+
lastRendered: -1,
|
|
1990
|
+
};
|
|
1991
|
+
}
|
|
1992
|
+
|
|
1993
|
+
/**
|
|
1994
|
+
* Id → statement AND its dates, at render time only. A missing doc renders as
|
|
1995
|
+
* its own id, undated: there is nothing left to date it by, and inventing
|
|
1996
|
+
* today's date for a memory whose prose has gone is the exact lie the dates
|
|
1997
|
+
* exist to prevent. The dates come from the SAME read as the text, so an
|
|
1998
|
+
* element's age can never be one boundary older than its words.
|
|
1999
|
+
*/
|
|
2000
|
+
private resolveStatement(
|
|
2001
|
+
id: string,
|
|
2002
|
+
docs: Map<string, ProseDoc>,
|
|
2003
|
+
sources: Map<string, string | null>,
|
|
2004
|
+
): Resolved {
|
|
2005
|
+
let doc = docs.get(id);
|
|
2006
|
+
if (doc === undefined) {
|
|
2007
|
+
try {
|
|
2008
|
+
doc = this.store.readProse(id);
|
|
2009
|
+
} catch {
|
|
2010
|
+
return { statement: id };
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
// The horizon lane's ids never went through `scanActive`, so their
|
|
2014
|
+
// provenance is read here — the one row read the scan did not already make.
|
|
2015
|
+
const source = sources.has(id) ? sources.get(id) ?? null : this.store.row(id)?.source ?? null;
|
|
2016
|
+
const paragraph = doc.body.split(/\n\s*\n/).find((p) => p.trim().length > 0) ?? doc.body;
|
|
2017
|
+
const statement = flatten(paragraph);
|
|
2018
|
+
const out: {
|
|
2019
|
+
statement: string;
|
|
2020
|
+
learnedOn?: string;
|
|
2021
|
+
happenedOn?: string;
|
|
2022
|
+
boundedDate?: boolean;
|
|
2023
|
+
} = { statement: statement.length > 0 ? statement : id };
|
|
2024
|
+
// Blank is how a chased row reads (`owner-op-seam`), and blank is not a date.
|
|
2025
|
+
if (doc.learnedOn.trim() !== "") out.learnedOn = doc.learnedOn;
|
|
2026
|
+
if (doc.happenedOn !== undefined && doc.happenedOn.trim() !== "") {
|
|
2027
|
+
out.happenedOn = doc.happenedOn;
|
|
2028
|
+
}
|
|
2029
|
+
// A MIGRATED element's encode date is an upper bound, not a claim: the
|
|
2030
|
+
// importer wrote the import date wherever v1 carried none, and the row does
|
|
2031
|
+
// not say which it did (measured live 2026-09-05 — all eleven elements read
|
|
2032
|
+
// the import day, a July incident among them).
|
|
2033
|
+
//
|
|
2034
|
+
// UNLESS THE ROW NOW SAYS WHICH. `counterparts repair-dates --apply` writes
|
|
2035
|
+
// `meta.dateRepaired` when it re-dates a migrated row from the row's own
|
|
2036
|
+
// evidence, and a date recovered at HIGH confidence — the v1 document's own
|
|
2037
|
+
// `created` field, or an engram-era id that is a millisecond timestamp — is a
|
|
2038
|
+
// claim again, not a bound. Only `high`: `medium` and `low` came from the
|
|
2039
|
+
// session, the element's statement or the source path, which are all still
|
|
2040
|
+
// "no later than", and hedging them is the honest render.
|
|
2041
|
+
if (source === "migrated" && !repairedAtHighConfidence(doc)) out.boundedDate = true;
|
|
2042
|
+
return out;
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
/**
|
|
2046
|
+
* The counter. One row per (kind, arm), so the frozen rate and the live rate
|
|
2047
|
+
* share a denominator. It is telemetry, not physics: it moves on every
|
|
2048
|
+
* occasion, frozen or live, and moving it is not moving the memory.
|
|
2049
|
+
*/
|
|
2050
|
+
private bumpCount(kind: Kind, frozen: boolean): number {
|
|
2051
|
+
const key = counterKey(kind, frozen);
|
|
2052
|
+
if (this.observer) {
|
|
2053
|
+
const next = (this.volatileCounts.get(key) ?? 0) + 1;
|
|
2054
|
+
this.volatileCounts.set(key, next);
|
|
2055
|
+
return next;
|
|
2056
|
+
}
|
|
2057
|
+
const next = Number(this.store.getMeta(key) ?? "0") + 1;
|
|
2058
|
+
this.store.setMeta(key, String(next));
|
|
2059
|
+
return next;
|
|
2060
|
+
}
|
|
2061
|
+
|
|
2062
|
+
private persistState(state: EpisodeState, site: string): void {
|
|
2063
|
+
if (this.observer) {
|
|
2064
|
+
this.volatileState.set(state.sessionId, state);
|
|
2065
|
+
this.emit("self.observer.standdown", state.sessionId, { site: `persist:${site}` });
|
|
2066
|
+
return;
|
|
2067
|
+
}
|
|
2068
|
+
this.store.setMeta(stateKey(state.sessionId), JSON.stringify(state));
|
|
2069
|
+
}
|
|
2070
|
+
|
|
2071
|
+
private emit(
|
|
2072
|
+
name: string,
|
|
2073
|
+
ref?: string,
|
|
2074
|
+
data?: Record<string, string | number | boolean | null>,
|
|
2075
|
+
): void {
|
|
2076
|
+
const e: SelfEvent = { at: this.now(), name };
|
|
2077
|
+
if (ref !== undefined) e.ref = ref;
|
|
2078
|
+
if (data !== undefined) e.data = data;
|
|
2079
|
+
this.ring.push(e);
|
|
2080
|
+
if (this.ring.length > EVENT_RING) this.ring.shift();
|
|
2081
|
+
this.onEvent?.(e);
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
|
|
2085
|
+
function round(n: number): number {
|
|
2086
|
+
return Math.round(n * 1000) / 1000;
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
/**
|
|
2090
|
+
* Did `counterparts repair-dates` recover this row's date from the row's OWN
|
|
2091
|
+
* strongest evidence?
|
|
2092
|
+
*
|
|
2093
|
+
* The marker is prose meta, written by the repair beside the corrected date
|
|
2094
|
+
* (`adapters/cli/repair-dates.ts`, `DATE_REPAIRED_META`), so the document stays
|
|
2095
|
+
* self-describing: the claim and the reason to believe it travel together and
|
|
2096
|
+
* survive a copy of the store. Read STRUCTURALLY rather than by importing the
|
|
2097
|
+
* adapter's constant — `self/` may not import an adapter — and a shape check that
|
|
2098
|
+
* fails renders the bound, which is the safe direction.
|
|
2099
|
+
*/
|
|
2100
|
+
function repairedAtHighConfidence(doc: ProseDoc): boolean {
|
|
2101
|
+
const marker = doc.meta["dateRepaired"];
|
|
2102
|
+
if (typeof marker !== "object" || marker === null || Array.isArray(marker)) return false;
|
|
2103
|
+
return (marker as Record<string, unknown>)["confidence"] === "high";
|
|
2104
|
+
}
|
|
2105
|
+
|
|
2106
|
+
export type {
|
|
2107
|
+
AskVerdict,
|
|
2108
|
+
Band,
|
|
2109
|
+
BriefingRequest,
|
|
2110
|
+
BriefingResult,
|
|
2111
|
+
ClaimDirection,
|
|
2112
|
+
ClaimSource,
|
|
2113
|
+
Enumeration,
|
|
2114
|
+
EpisodeGate,
|
|
2115
|
+
EpisodeProposal,
|
|
2116
|
+
EpisodeState,
|
|
2117
|
+
FreezeReason,
|
|
2118
|
+
IngestResult,
|
|
2119
|
+
Kind,
|
|
2120
|
+
LaneName,
|
|
2121
|
+
Lanes,
|
|
2122
|
+
Ranked,
|
|
2123
|
+
Resolve,
|
|
2124
|
+
Resolved,
|
|
2125
|
+
SchemaBytesReport,
|
|
2126
|
+
SentinelReading,
|
|
2127
|
+
Substance,
|
|
2128
|
+
UseTier,
|
|
2129
|
+
};
|
|
2130
|
+
export { BRIEFING_TRIM_LOG_CAP, COUNTER_PREFIX, FRAMING, FROZEN_KINDS, LANE_ORDER, TRIM_ORDER };
|