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,1459 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `schemas/` — semantic memory.
|
|
3
|
+
*
|
|
4
|
+
* The entities experience organizes itself around, and the beliefs held about
|
|
5
|
+
* them. Brain analog: schema formation — repeated episodes abstract into a
|
|
6
|
+
* structure new experience is compared against, which is what makes prediction
|
|
7
|
+
* error possible.
|
|
8
|
+
*
|
|
9
|
+
* FOUR PROPERTIES HOLD ACROSS THE WHOLE MODULE, each enforced rather than
|
|
10
|
+
* asserted (test/schemas.test.ts proves every one):
|
|
11
|
+
*
|
|
12
|
+
* 1. **No operation edits a belief.** There is no such verb — `PUBLIC_SURFACE`
|
|
13
|
+
* enumerates every method, and a test asserts the class has exactly those.
|
|
14
|
+
* A belief's text changes only as the result of `physics.applyChallenge`
|
|
15
|
+
* arithmetic on a DECLARED `updates:`, and the prior text is retained by
|
|
16
|
+
* `store.supersede` (§5 G1, and the accommodation guardrail preserved by
|
|
17
|
+
* construction). `replaceCurrentState` is not an exception to that rule: it
|
|
18
|
+
* writes a SUCCESSOR from the challenging memory's own prose, on a row that
|
|
19
|
+
* is a "now" fact rather than a belief, and the prior row is retained the
|
|
20
|
+
* same way. No verb here takes new text for an EXISTING row.
|
|
21
|
+
* 2. **Birth is by mention, death is by decay.** A newly-named entity becomes a
|
|
22
|
+
* stub immediately — an explicit, logged creation event, no gate and no
|
|
23
|
+
* proposal queue (owner decision 2026-08-25). A stub that never accumulates
|
|
24
|
+
* fades by ordinary physics; no model, on any path, can kill an entity
|
|
25
|
+
* (§5 G7).
|
|
26
|
+
* 3. **Status lives on the entity, never in identity.** The ~72 KB lesson,
|
|
27
|
+
* mechanized at this seam as a named refusal (§3, `status-on-identity-refused`).
|
|
28
|
+
* 4. **This module never promotes.** Promotion is physics'/sleep's counted
|
|
29
|
+
* crossing; here `band` is READ and nothing else. There is no `setBand` call
|
|
30
|
+
* and no promotion path in this directory, and a source scan says so.
|
|
31
|
+
*
|
|
32
|
+
* Ambiguities the contract left open are recorded in NOTES.md; what this module
|
|
33
|
+
* needed from a neighbour and could not have is in INTERFACE-GAPS.md.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import {
|
|
37
|
+
applyChallenge,
|
|
38
|
+
band as bandOfPhysics,
|
|
39
|
+
clampSalienceAtSeam,
|
|
40
|
+
pruneVerdict,
|
|
41
|
+
revisionBar,
|
|
42
|
+
strength as strengthOf,
|
|
43
|
+
successorSeed,
|
|
44
|
+
supersedeRecord,
|
|
45
|
+
TUNABLES as PHYSICS_TUNABLES,
|
|
46
|
+
} from "../physics/index.js";
|
|
47
|
+
import type { MemoryPhysics } from "../physics/index.js";
|
|
48
|
+
import { gateAliases } from "../encode/aliases.js";
|
|
49
|
+
import { containsSecret, redactSecrets } from "../encode/secrets.js";
|
|
50
|
+
import { occursAsWholeWord } from "../encode/words.js";
|
|
51
|
+
import { Store, hashText } from "../store/index.js";
|
|
52
|
+
// The WALKING read — not a `Store` method on purpose (`store/walk-seam.ts`): it
|
|
53
|
+
// skips the archived-read telemetry AND the deny-list, and this module is one of
|
|
54
|
+
// the two files `test/cli.test.ts` allows to import it.
|
|
55
|
+
import { readProseWalking } from "../store/walk-seam.js";
|
|
56
|
+
import { rowTombstoned } from "../store/index.js";
|
|
57
|
+
import type { MemoryRow, PutInput } from "../store/index.js";
|
|
58
|
+
import type { Band, Kind, Salience } from "../types.js";
|
|
59
|
+
import { AliasIndex, collision, handleKey } from "./aliases.js";
|
|
60
|
+
import { TUNABLES } from "./tunables.js";
|
|
61
|
+
import {
|
|
62
|
+
BIRTH_KINDS,
|
|
63
|
+
isBirthKind,
|
|
64
|
+
} from "./types.js";
|
|
65
|
+
import type {
|
|
66
|
+
BeliefInput,
|
|
67
|
+
BeliefOutcome,
|
|
68
|
+
BeliefStory,
|
|
69
|
+
BirthKind,
|
|
70
|
+
BirthOutcome,
|
|
71
|
+
BirthReason,
|
|
72
|
+
ChallengeInput,
|
|
73
|
+
CurrentStateInput,
|
|
74
|
+
DimensionsInput,
|
|
75
|
+
ElementView,
|
|
76
|
+
EntityView,
|
|
77
|
+
FadeReason,
|
|
78
|
+
FadeReport,
|
|
79
|
+
FadeVerdict,
|
|
80
|
+
LifecycleRow,
|
|
81
|
+
LineageStep,
|
|
82
|
+
MentionInput,
|
|
83
|
+
PlacementOutcome,
|
|
84
|
+
PlacementReason,
|
|
85
|
+
PressureIncrement,
|
|
86
|
+
ReplacementOutcome,
|
|
87
|
+
ReplacementReason,
|
|
88
|
+
RevisionOutcome,
|
|
89
|
+
RevisionReason,
|
|
90
|
+
SchemaEvent,
|
|
91
|
+
SchemaRole,
|
|
92
|
+
SchemaSliceOut,
|
|
93
|
+
} from "./types.js";
|
|
94
|
+
|
|
95
|
+
export * from "./types.js";
|
|
96
|
+
export { AliasIndex, collision, handleKey, nameTokens } from "./aliases.js";
|
|
97
|
+
export type { AliasHit, CollisionKind } from "./aliases.js";
|
|
98
|
+
export { TUNABLES } from "./tunables.js";
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Every public method, enumerated. The totality test asserts the class exposes
|
|
102
|
+
* EXACTLY this set — so a future `editBelief` / `setBeliefText` / `promote`
|
|
103
|
+
* cannot be added without editing this list, in a module whose first guarantee
|
|
104
|
+
* is that no such verb exists (§5 G1, scar §2.17's "write paths ship, curation
|
|
105
|
+
* paths starve" read in reverse).
|
|
106
|
+
*/
|
|
107
|
+
export const PUBLIC_SURFACE = [
|
|
108
|
+
// writes
|
|
109
|
+
"mention",
|
|
110
|
+
"addAliases",
|
|
111
|
+
"addBelief",
|
|
112
|
+
"addCurrentState",
|
|
113
|
+
"challengeBelief",
|
|
114
|
+
"replaceCurrentState",
|
|
115
|
+
"fadeSweep",
|
|
116
|
+
// reads
|
|
117
|
+
"entity",
|
|
118
|
+
"entities",
|
|
119
|
+
"element",
|
|
120
|
+
"beliefs",
|
|
121
|
+
"currentState",
|
|
122
|
+
"slices",
|
|
123
|
+
"loadSkips",
|
|
124
|
+
"aliasIndex",
|
|
125
|
+
"aliasMap",
|
|
126
|
+
"bandOf",
|
|
127
|
+
"fadeVerdict",
|
|
128
|
+
"story",
|
|
129
|
+
"lifecycle",
|
|
130
|
+
"events",
|
|
131
|
+
] as const;
|
|
132
|
+
|
|
133
|
+
const EVENT_RING = 500;
|
|
134
|
+
|
|
135
|
+
interface MetaRecord {
|
|
136
|
+
role: SchemaRole;
|
|
137
|
+
/** entity rows only */
|
|
138
|
+
name?: string;
|
|
139
|
+
aliases?: string[];
|
|
140
|
+
/** belief / current-state rows only */
|
|
141
|
+
entityId?: string;
|
|
142
|
+
statedOn?: string;
|
|
143
|
+
statedOnDay?: number;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface SchemasOptions {
|
|
147
|
+
store: Store;
|
|
148
|
+
/** Telemetry sink. The ring is in memory only — see INTERFACE-GAPS §1. */
|
|
149
|
+
onEvent?: (event: SchemaEvent) => void;
|
|
150
|
+
/**
|
|
151
|
+
* SEAMS item E — the supersede executor's edge callback, INJECTED because this
|
|
152
|
+
* module must not import `associate/` (and `store.supersede` must not depend on
|
|
153
|
+
* a core module above it). Wired to `Associate.retargetOnSupersede` at the
|
|
154
|
+
* composition root; absent, the successor starts cold, which is scar §2.2
|
|
155
|
+
* itself: *v1's `gist.merge` set `merged_into` and nothing re-pointed the
|
|
156
|
+
* edges.* It is called in the SAME FLOW as the supersede, immediately after the
|
|
157
|
+
* new id exists, so an arc cannot be half-moved by a caller that forgets.
|
|
158
|
+
*/
|
|
159
|
+
retarget?: (oldId: string, newId: string, day: number) => void;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const ZERO_DIMS: DimensionsInput = { relevance: 0, emotional: 0, predictive: 0 };
|
|
163
|
+
|
|
164
|
+
export class Schemas {
|
|
165
|
+
readonly store: Store;
|
|
166
|
+
private readonly index = new AliasIndex();
|
|
167
|
+
private readonly meta = new Map<string, MetaRecord>();
|
|
168
|
+
private readonly byEntity = new Map<string, Set<string>>();
|
|
169
|
+
private readonly birthsPerChunk = new Map<string, number>();
|
|
170
|
+
private readonly increments: PressureIncrement[] = [];
|
|
171
|
+
private readonly ring: SchemaEvent[] = [];
|
|
172
|
+
/** What `load` left out, by whether the store could account for it. */
|
|
173
|
+
private readonly skips = { removed: 0, unaccounted: [] as string[] };
|
|
174
|
+
private readonly onEvent: ((e: SchemaEvent) => void) | undefined;
|
|
175
|
+
private readonly retarget: ((oldId: string, newId: string, day: number) => void) | undefined;
|
|
176
|
+
|
|
177
|
+
private constructor(opts: SchemasOptions) {
|
|
178
|
+
this.store = opts.store;
|
|
179
|
+
this.onEvent = opts.onEvent;
|
|
180
|
+
this.retarget = opts.retarget;
|
|
181
|
+
this.load();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
static open(opts: SchemasOptions): Schemas {
|
|
185
|
+
return new Schemas(opts);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* One scan at open, because box 2 indexes type/kind/band/archived and has no
|
|
190
|
+
* meta query (INTERFACE-GAPS §2). Prose comes through `readProseWalking`
|
|
191
|
+
* rather than `Store.read`, so building an index does not spend the store's
|
|
192
|
+
* archived-read telemetry — that event answers "did anyone look at archived
|
|
193
|
+
* CONTENT", and an index build is not a look.
|
|
194
|
+
*
|
|
195
|
+
* **A REMOVED ROW IS SKIPPED, and that is what keeps the session alive.** The
|
|
196
|
+
* deny-list is fetched once here rather than asked per id: this runs at every
|
|
197
|
+
* open, over every schema row, and a removal must cost the index one query,
|
|
198
|
+
* not one per row.
|
|
199
|
+
*
|
|
200
|
+
* **The two skips are counted apart, because only one of them is explained.**
|
|
201
|
+
* A row the deny-list names was removed by the owner and its absence is the
|
|
202
|
+
* point. A TOMBSTONED row with no removal record is something else — a
|
|
203
|
+
* half-written repair, a disk event — and skipping it buys uptime with data
|
|
204
|
+
* disappearing without a word. Both are skipped (a session that
|
|
205
|
+
* cannot start helps nobody), and `loadSkips()` says which was which, so the
|
|
206
|
+
* difference is a fact rather than a silence. Nothing prints it yet.
|
|
207
|
+
*/
|
|
208
|
+
private load(): void {
|
|
209
|
+
const denied = new Set(this.store.deniedIds());
|
|
210
|
+
for (const id of this.store.list({ type: "schema" })) {
|
|
211
|
+
const row = this.store.row(id);
|
|
212
|
+
if (row === undefined) continue;
|
|
213
|
+
if (denied.has(id)) {
|
|
214
|
+
this.skips.removed += 1;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (rowTombstoned(row)) {
|
|
218
|
+
this.skips.unaccounted.push(id);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const doc = readProseWalking(this.store, id, row);
|
|
222
|
+
const rec = toMetaRecord(doc.meta);
|
|
223
|
+
if (rec === null) continue;
|
|
224
|
+
this.remember(id, rec);
|
|
225
|
+
if (rec.role === "entity" && row.archived === 0) {
|
|
226
|
+
this.index.register(id, rec.name ?? "", rec.aliases ?? []);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private remember(id: string, rec: MetaRecord): void {
|
|
232
|
+
this.meta.set(id, rec);
|
|
233
|
+
if (rec.entityId !== undefined) {
|
|
234
|
+
const set = this.byEntity.get(rec.entityId) ?? new Set<string>();
|
|
235
|
+
set.add(id);
|
|
236
|
+
this.byEntity.set(rec.entityId, set);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private emit(
|
|
241
|
+
event: string,
|
|
242
|
+
ref?: string,
|
|
243
|
+
data?: Record<string, string | number | boolean | null>,
|
|
244
|
+
): void {
|
|
245
|
+
const e: SchemaEvent = { at: Date.now(), event };
|
|
246
|
+
if (ref !== undefined) e.ref = ref;
|
|
247
|
+
if (data !== undefined) e.data = data;
|
|
248
|
+
this.ring.push(e);
|
|
249
|
+
if (this.ring.length > EVENT_RING) this.ring.shift();
|
|
250
|
+
this.onEvent?.(e);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Copies, oldest first, optionally filtered by name. */
|
|
254
|
+
events(name?: string): SchemaEvent[] {
|
|
255
|
+
return this.ring.filter((e) => name === undefined || e.event === name).map((e) => ({ ...e }));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ── birth by mention ───────────────────────────────────────────────────────
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* A newly-named entity becomes a stub schema immediately.
|
|
262
|
+
*
|
|
263
|
+
* There is no approval gate and no proposal queue: v1's autonomous-birth gate
|
|
264
|
+
* recorded zero births AND zero refusals across 89 interpreter runs — "a gate
|
|
265
|
+
* with no knocks is unmeasured" — so what survives is only the MECHANICAL
|
|
266
|
+
* grounds, which are cheap and still true. Every one of them refuses loudly
|
|
267
|
+
* with its own reason, and THE PROPOSAL IS LOGGED WHATEVER HAPPENS (scar
|
|
268
|
+
* §2.4): "refused" and "never proposed to" must never again be the same
|
|
269
|
+
* record.
|
|
270
|
+
*
|
|
271
|
+
* A newborn schema asserts nothing — names and aliases only (§5 G6). Its
|
|
272
|
+
* salience is zero, which is not a slight: it is what makes death-by-decay
|
|
273
|
+
* the default for a name nobody says twice.
|
|
274
|
+
*
|
|
275
|
+
* A name whose previous entity FADED is a new birth, not a resurrection: the
|
|
276
|
+
* old entity died by physics, and the mention is a fresh place for memories
|
|
277
|
+
* to attach. The old id stays resolvable and keeps its exit in the lifecycle
|
|
278
|
+
* counts, and the birth is tagged `schema.birth.after-fade` so churn —
|
|
279
|
+
* born, faded, born again — is a countable fact rather than an argument
|
|
280
|
+
* (NOTES §6).
|
|
281
|
+
*/
|
|
282
|
+
mention(input: MentionInput): BirthOutcome {
|
|
283
|
+
const name = input.name.trim();
|
|
284
|
+
const nameHash = hashText(handleKey(name));
|
|
285
|
+
this.emit("schema.mention", input.chunkRef, {
|
|
286
|
+
nameHash,
|
|
287
|
+
kind: input.kind,
|
|
288
|
+
day: input.day,
|
|
289
|
+
aliasesDeclared: input.aliases?.length ?? 0,
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
const refuse = (reason: BirthReason, collidedWith: string[] = []): BirthOutcome => {
|
|
293
|
+
this.emit("schema.birth.refused", input.chunkRef, {
|
|
294
|
+
nameHash,
|
|
295
|
+
kind: input.kind,
|
|
296
|
+
reason,
|
|
297
|
+
collided: collidedWith.length,
|
|
298
|
+
});
|
|
299
|
+
return {
|
|
300
|
+
ok: false,
|
|
301
|
+
reason,
|
|
302
|
+
id: null,
|
|
303
|
+
born: false,
|
|
304
|
+
collidedWith,
|
|
305
|
+
droppedAliases: [],
|
|
306
|
+
keptAliases: [],
|
|
307
|
+
reinforced: false,
|
|
308
|
+
};
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
// Layer 1 of "never a second self", checked FIRST and independently of every
|
|
312
|
+
// other ground: one identity core, and a second is a category error no
|
|
313
|
+
// evidence could justify (§5 G5).
|
|
314
|
+
if (input.kind === "self") return refuse("second-self-refused");
|
|
315
|
+
if (!isBirthKind(input.kind)) return refuse("kind-not-allowed");
|
|
316
|
+
if (name.length < TUNABLES.NAME_MIN_CHARS) return refuse("name-empty");
|
|
317
|
+
// A credential must never become an entity the store indexes (encode's ops rule).
|
|
318
|
+
if (containsSecret(name)) return refuse("name-is-secret");
|
|
319
|
+
// The ONE whole-word rule, the same call preselection makes (SEAMS §7).
|
|
320
|
+
if (!occursAsWholeWord(input.source, name)) return refuse("name-not-in-source");
|
|
321
|
+
|
|
322
|
+
const exact = this.index.lookup(name).filter((id) => this.meta.get(id)?.role === "entity");
|
|
323
|
+
if (exact.length > 1) return refuse("ambiguous-existing-name", exact);
|
|
324
|
+
const hit = exact[0];
|
|
325
|
+
if (hit !== undefined) {
|
|
326
|
+
const row = this.store.row(hit);
|
|
327
|
+
// Layer 2: a name that resolves to the identity core is not a birth site,
|
|
328
|
+
// whatever kind the mention claimed.
|
|
329
|
+
if (row?.kind === "self") return refuse("second-self-refused", [hit]);
|
|
330
|
+
if (row !== undefined && row.kind !== input.kind) {
|
|
331
|
+
return refuse("collision-exact-different-kind", [hit]);
|
|
332
|
+
}
|
|
333
|
+
return this.reMention(hit, input, nameHash);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const near = this.nearCollisions(name);
|
|
337
|
+
if (near.length > 0) return refuse("collision-near", near);
|
|
338
|
+
|
|
339
|
+
const used = this.birthsPerChunk.get(input.chunkRef) ?? 0;
|
|
340
|
+
if (used >= TUNABLES.MAX_BIRTHS_PER_CHUNK) return refuse("birth-cap-per-chunk");
|
|
341
|
+
|
|
342
|
+
return this.birth(name, input.kind, input, nameHash);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** An archived entity that held this exact name before it faded, if any. */
|
|
346
|
+
private fadedNamed(name: string, except: string): string | undefined {
|
|
347
|
+
const key = handleKey(name);
|
|
348
|
+
for (const [id, rec] of this.meta) {
|
|
349
|
+
if (id === except || rec.role !== "entity") continue;
|
|
350
|
+
if (handleKey(rec.name ?? "") !== key) continue;
|
|
351
|
+
if (this.store.row(id)?.archived === 1) return id;
|
|
352
|
+
}
|
|
353
|
+
return undefined;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
private nearCollisions(name: string): string[] {
|
|
357
|
+
const out: string[] = [];
|
|
358
|
+
for (const [id, rec] of this.meta) {
|
|
359
|
+
if (rec.role !== "entity") continue;
|
|
360
|
+
if (!this.index.has(id)) continue;
|
|
361
|
+
const terms = [rec.name ?? "", ...(rec.aliases ?? [])];
|
|
362
|
+
if (terms.some((t) => collision(name, t) === "near")) out.push(id);
|
|
363
|
+
}
|
|
364
|
+
return out.sort();
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* The same name, twice: ONE entity. Dedup does not consume the chunk's birth
|
|
369
|
+
* budget — the budget guards against a confused chunk inventing five things,
|
|
370
|
+
* not against a span saying one thing twice.
|
|
371
|
+
*
|
|
372
|
+
* A re-mention REINFORCES at the `referenced` tier: a mention is the entity
|
|
373
|
+
* being used, and physics refuses the credit on the birth day and again on any
|
|
374
|
+
* day already credited, so "accumulates" means distinct lived days by
|
|
375
|
+
* construction (NOTES §4).
|
|
376
|
+
*/
|
|
377
|
+
private reMention(id: string, input: MentionInput, nameHash: string): BirthOutcome {
|
|
378
|
+
const credit = this.store.reinforce(id, input.day, TUNABLES.MENTION_TIER);
|
|
379
|
+
this.emit("schema.mention.existing", id, {
|
|
380
|
+
nameHash,
|
|
381
|
+
day: input.day,
|
|
382
|
+
credited: credit.credited,
|
|
383
|
+
creditReason: credit.reason,
|
|
384
|
+
});
|
|
385
|
+
return {
|
|
386
|
+
ok: true,
|
|
387
|
+
reason: "existing",
|
|
388
|
+
id,
|
|
389
|
+
born: false,
|
|
390
|
+
collidedWith: [],
|
|
391
|
+
droppedAliases: [],
|
|
392
|
+
keptAliases: this.index.termsFor(id)?.aliases ?? [],
|
|
393
|
+
reinforced: credit.credited,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
private birth(
|
|
398
|
+
name: string,
|
|
399
|
+
kind: BirthKind,
|
|
400
|
+
input: MentionInput,
|
|
401
|
+
nameHash: string,
|
|
402
|
+
): BirthOutcome {
|
|
403
|
+
const gated = gateAliases(input.aliases, input.source);
|
|
404
|
+
const dropped = gated.dropped.map((d) => ({ index: d.index, reason: d.reason as string }));
|
|
405
|
+
const kept: string[] = [];
|
|
406
|
+
keptIndices(input.aliases, gated.dropped).forEach((declaredIndex, i) => {
|
|
407
|
+
const alias = gated.kept[i];
|
|
408
|
+
if (alias === undefined) return;
|
|
409
|
+
// A key pointing at two things retrieves neither well: an alias already
|
|
410
|
+
// resolving elsewhere is DROPPED, never fatal (§14.3). Reported by the
|
|
411
|
+
// index it was DECLARED at, like every other drop.
|
|
412
|
+
if (this.index.lookup(alias).length > 0) {
|
|
413
|
+
dropped.push({ index: declaredIndex, reason: "alias-resolves-elsewhere" });
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
kept.push(alias);
|
|
417
|
+
});
|
|
418
|
+
for (const d of dropped) {
|
|
419
|
+
this.emit("schema.alias.dropped", input.chunkRef, { index: d.index, reason: d.reason });
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const seam = clampSalienceAtSeam({ novelty: null, ...ZERO_DIMS }, null);
|
|
423
|
+
const id = this.store.put({
|
|
424
|
+
type: "schema",
|
|
425
|
+
kind,
|
|
426
|
+
title: name,
|
|
427
|
+
body: stubBody(name, kept, input.day),
|
|
428
|
+
meta: { role: "entity", name, aliases: kept },
|
|
429
|
+
salience: seam.salience,
|
|
430
|
+
physics: { birthDay: input.day, lastUsedDay: input.day },
|
|
431
|
+
});
|
|
432
|
+
this.remember(id, { role: "entity", name, aliases: kept });
|
|
433
|
+
this.index.register(id, name, kept);
|
|
434
|
+
this.birthsPerChunk.set(input.chunkRef, (this.birthsPerChunk.get(input.chunkRef) ?? 0) + 1);
|
|
435
|
+
const priorlyFaded = this.fadedNamed(name, id);
|
|
436
|
+
if (priorlyFaded !== undefined) {
|
|
437
|
+
this.emit("schema.birth.after-fade", id, { nameHash, priorId: priorlyFaded, day: input.day });
|
|
438
|
+
}
|
|
439
|
+
this.emit("schema.birth", id, {
|
|
440
|
+
nameHash,
|
|
441
|
+
kind,
|
|
442
|
+
day: input.day,
|
|
443
|
+
aliases: kept.length,
|
|
444
|
+
aliasesDropped: dropped.length,
|
|
445
|
+
chunkRef: input.chunkRef,
|
|
446
|
+
});
|
|
447
|
+
return {
|
|
448
|
+
ok: true,
|
|
449
|
+
reason: "born",
|
|
450
|
+
id,
|
|
451
|
+
born: true,
|
|
452
|
+
collidedWith: [],
|
|
453
|
+
droppedAliases: dropped,
|
|
454
|
+
keptAliases: kept,
|
|
455
|
+
reinforced: false,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* The explicit alias operation (§4.2 G4). Aliases change HERE and nowhere
|
|
461
|
+
* else — never as a side effect of editing prose, which is why there is no
|
|
462
|
+
* path that re-reads names out of a body.
|
|
463
|
+
*/
|
|
464
|
+
addAliases(
|
|
465
|
+
id: string,
|
|
466
|
+
aliases: readonly string[],
|
|
467
|
+
source: string,
|
|
468
|
+
day: number,
|
|
469
|
+
): { ok: boolean; reason: string; kept: string[]; dropped: { index: number; reason: string }[] } {
|
|
470
|
+
const rec = this.meta.get(id);
|
|
471
|
+
if (rec === undefined || rec.role !== "entity") {
|
|
472
|
+
this.emit("schema.alias.refused", id, { reason: "entity-unknown" });
|
|
473
|
+
return { ok: false, reason: "entity-unknown", kept: [], dropped: [] };
|
|
474
|
+
}
|
|
475
|
+
const gated = gateAliases(aliases, source);
|
|
476
|
+
const dropped = gated.dropped.map((d) => ({ index: d.index, reason: d.reason as string }));
|
|
477
|
+
const existing = rec.aliases ?? [];
|
|
478
|
+
const kept = [...existing];
|
|
479
|
+
keptIndices(aliases, gated.dropped).forEach((declaredIndex, i) => {
|
|
480
|
+
const alias = gated.kept[i];
|
|
481
|
+
if (alias === undefined) return;
|
|
482
|
+
if (this.index.lookup(alias).filter((o) => o !== id).length > 0) {
|
|
483
|
+
dropped.push({ index: declaredIndex, reason: "alias-resolves-elsewhere" });
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
if (!kept.some((k) => handleKey(k) === handleKey(alias))) kept.push(alias);
|
|
487
|
+
});
|
|
488
|
+
const next: MetaRecord = { role: "entity", name: rec.name ?? "", aliases: kept };
|
|
489
|
+
this.store.revise(id, { meta: { role: "entity", name: next.name, aliases: kept }, reason: "alias-op" });
|
|
490
|
+
this.meta.set(id, next);
|
|
491
|
+
this.index.register(id, next.name ?? "", kept);
|
|
492
|
+
for (const d of dropped) {
|
|
493
|
+
this.emit("schema.alias.dropped", id, { index: d.index, reason: d.reason });
|
|
494
|
+
}
|
|
495
|
+
this.emit("schema.alias.registered", id, { kept: kept.length, dropped: dropped.length, day });
|
|
496
|
+
return { ok: true, reason: "registered", kept, dropped };
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// ── beliefs and current state ──────────────────────────────────────────────
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* Mint a belief on an entity. The row's kind is the ENTITY's kind, which is
|
|
503
|
+
* how "revision bars differ by kind" becomes arithmetic rather than policy:
|
|
504
|
+
* a belief about a person inherits iota 0.8, project state on an entity 0.5 —
|
|
505
|
+
* the loosening chosen out loud (§4.3).
|
|
506
|
+
*/
|
|
507
|
+
addBelief(input: BeliefInput): BeliefOutcome {
|
|
508
|
+
const entity = this.requireEntity(input.entityId);
|
|
509
|
+
if (entity.problem !== null) {
|
|
510
|
+
this.emit("schema.belief.refused", input.entityId, { reason: entity.problem });
|
|
511
|
+
return { ok: false, reason: entity.problem, id: null };
|
|
512
|
+
}
|
|
513
|
+
const statement = input.statement.trim();
|
|
514
|
+
if (statement.length === 0) {
|
|
515
|
+
this.emit("schema.belief.refused", input.entityId, { reason: "statement-empty" });
|
|
516
|
+
return { ok: false, reason: "statement-empty", id: null };
|
|
517
|
+
}
|
|
518
|
+
const put = this.mintElement({
|
|
519
|
+
role: "belief",
|
|
520
|
+
entityId: input.entityId,
|
|
521
|
+
kind: entity.row.kind,
|
|
522
|
+
body: statement,
|
|
523
|
+
day: input.day,
|
|
524
|
+
dimensions: input.dimensions,
|
|
525
|
+
claimedSalience: input.claimedSalience ?? null,
|
|
526
|
+
...(input.channel === undefined ? {} : { channel: input.channel }),
|
|
527
|
+
protectedFlag: input.protected === true,
|
|
528
|
+
meta: { groundedIn: [...(input.groundedIn ?? [])] },
|
|
529
|
+
});
|
|
530
|
+
this.emit("schema.belief.added", put, {
|
|
531
|
+
entityId: input.entityId,
|
|
532
|
+
kind: entity.row.kind,
|
|
533
|
+
day: input.day,
|
|
534
|
+
protected: input.protected === true,
|
|
535
|
+
});
|
|
536
|
+
return { ok: true, reason: "added", id: put };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Timestamped status about an entity — and THE PLACEMENT RULE.
|
|
541
|
+
*
|
|
542
|
+
* v1 measured ~72 KB of dated project status rendered verbatim into every
|
|
543
|
+
* self-keyed prompt, with 14 of self's 19 active beliefs about projects that
|
|
544
|
+
* had no retrieval key of their own. The corrective is not a cleanup pass; it
|
|
545
|
+
* is that this seam refuses, by name, to put status in identity. Status has
|
|
546
|
+
* homes — they are entities — and the refusal says so.
|
|
547
|
+
*/
|
|
548
|
+
addCurrentState(input: CurrentStateInput): PlacementOutcome {
|
|
549
|
+
const entity = this.requireEntity(input.entityId);
|
|
550
|
+
if (entity.problem !== null) {
|
|
551
|
+
this.emit("schema.placement.refused", input.entityId, { reason: entity.problem });
|
|
552
|
+
return { ok: false, reason: entity.problem, id: null, belongsOn: null };
|
|
553
|
+
}
|
|
554
|
+
if (entity.row.kind === "self") {
|
|
555
|
+
const reason: PlacementReason = "status-on-identity-refused";
|
|
556
|
+
this.emit("schema.placement.refused", input.entityId, {
|
|
557
|
+
reason,
|
|
558
|
+
day: input.day,
|
|
559
|
+
statementHash: hashText(input.statement),
|
|
560
|
+
});
|
|
561
|
+
return { ok: false, reason, id: null, belongsOn: [...BIRTH_KINDS] };
|
|
562
|
+
}
|
|
563
|
+
const statement = input.statement.trim();
|
|
564
|
+
if (statement.length === 0) {
|
|
565
|
+
this.emit("schema.placement.refused", input.entityId, { reason: "statement-empty" });
|
|
566
|
+
return { ok: false, reason: "statement-empty", id: null, belongsOn: null };
|
|
567
|
+
}
|
|
568
|
+
// The STORE's clock, not the ambient one (§I7): a current state placed
|
|
569
|
+
// during a seeded or replayed run is stated on that run's date.
|
|
570
|
+
const statedOn = input.statedOn ?? this.store.today();
|
|
571
|
+
const id = this.mintElement({
|
|
572
|
+
role: "current-state",
|
|
573
|
+
entityId: input.entityId,
|
|
574
|
+
kind: entity.row.kind,
|
|
575
|
+
body: statement,
|
|
576
|
+
day: input.day,
|
|
577
|
+
dimensions: input.dimensions,
|
|
578
|
+
claimedSalience: input.claimedSalience ?? null,
|
|
579
|
+
...(input.channel === undefined ? {} : { channel: input.channel }),
|
|
580
|
+
protectedFlag: false,
|
|
581
|
+
happenedOn: statedOn,
|
|
582
|
+
meta: { statedOn, statedOnDay: input.day },
|
|
583
|
+
});
|
|
584
|
+
this.emit("schema.state.placed", id, {
|
|
585
|
+
entityId: input.entityId,
|
|
586
|
+
kind: entity.row.kind,
|
|
587
|
+
day: input.day,
|
|
588
|
+
statedOn,
|
|
589
|
+
});
|
|
590
|
+
return { ok: true, reason: "placed", id, belongsOn: null };
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
private requireEntity(
|
|
594
|
+
id: string,
|
|
595
|
+
): { problem: "entity-unknown" | "entity-archived" | null; row: MemoryRow } {
|
|
596
|
+
const rec = this.meta.get(id);
|
|
597
|
+
const row = this.store.row(id);
|
|
598
|
+
if (rec === undefined || rec.role !== "entity" || row === undefined) {
|
|
599
|
+
return { problem: "entity-unknown", row: row ?? ({} as MemoryRow) };
|
|
600
|
+
}
|
|
601
|
+
if (row.archived === 1) return { problem: "entity-archived", row };
|
|
602
|
+
return { problem: null, row };
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
private mintElement(spec: {
|
|
606
|
+
role: SchemaRole;
|
|
607
|
+
entityId: string;
|
|
608
|
+
kind: Kind;
|
|
609
|
+
body: string;
|
|
610
|
+
day: number;
|
|
611
|
+
dimensions?: DimensionsInput;
|
|
612
|
+
claimedSalience: number | null;
|
|
613
|
+
/** See `BeliefInput.channel`. Default "authored"; the ceiling and the
|
|
614
|
+
* persisted `source` both derive from it — engine-set, never claimable. */
|
|
615
|
+
channel?: "authored" | "fallback" | "episode" | "accommodation" | "migrated";
|
|
616
|
+
protectedFlag: boolean;
|
|
617
|
+
happenedOn?: string;
|
|
618
|
+
meta?: Record<string, unknown>;
|
|
619
|
+
salience?: Salience;
|
|
620
|
+
seed?: Partial<MemoryPhysics>;
|
|
621
|
+
}): string {
|
|
622
|
+
// The CEILING derives from the channel with "authored" as the arithmetic
|
|
623
|
+
// default — but the PERSISTED source is `spec.channel ?? null`: a caller
|
|
624
|
+
// that says nothing records "unrecorded", never a claim of authorship. The
|
|
625
|
+
// PR-2 review's blocker was exactly this conflation: a `?? "authored"`
|
|
626
|
+
// persistence default stamped every migrated belief as authored-in-v2.
|
|
627
|
+
const channel = spec.channel ?? "authored";
|
|
628
|
+
let salience: Salience;
|
|
629
|
+
if (spec.salience !== undefined) {
|
|
630
|
+
salience = spec.salience;
|
|
631
|
+
} else {
|
|
632
|
+
// novelty is null for an engine mint and is RECORDED as null, never
|
|
633
|
+
// defaulted: novelty is prediction error at encoding, and this is not one.
|
|
634
|
+
//
|
|
635
|
+
// The reteller's cap applies HERE TOO (owner ruling 2026-08-29): this was
|
|
636
|
+
// the doctrine's latent second door — a belief placed on behalf of a
|
|
637
|
+
// transcript sweep would have carried the model's uncapped claim. No live
|
|
638
|
+
// caller uses the fallback channel today; when one is built, the cap is
|
|
639
|
+
// already structural.
|
|
640
|
+
const seam = clampSalienceAtSeam(
|
|
641
|
+
{ novelty: null, ...(spec.dimensions ?? ZERO_DIMS) },
|
|
642
|
+
spec.claimedSalience,
|
|
643
|
+
channel === "fallback" ? PHYSICS_TUNABLES.SWEEP_CLAIM_CEILING : 1,
|
|
644
|
+
);
|
|
645
|
+
if (seam.event !== null) {
|
|
646
|
+
this.emit("salience.lifted", spec.entityId, {
|
|
647
|
+
computed: seam.event.computed,
|
|
648
|
+
claimed: seam.event.claimed,
|
|
649
|
+
applied: seam.event.applied,
|
|
650
|
+
ceiling: seam.event.ceiling,
|
|
651
|
+
capped: seam.event.capped,
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
salience = seam.salience;
|
|
655
|
+
}
|
|
656
|
+
const meta: Record<string, unknown> = {
|
|
657
|
+
role: spec.role,
|
|
658
|
+
entityId: spec.entityId,
|
|
659
|
+
...(spec.meta ?? {}),
|
|
660
|
+
};
|
|
661
|
+
const put: PutInput = {
|
|
662
|
+
type: "schema",
|
|
663
|
+
kind: spec.kind,
|
|
664
|
+
// The statement crosses the secrets gate on its way to disk (PR-6 review
|
|
665
|
+
// SF1): the direct addBelief/addCurrentState API gated the entity NAME
|
|
666
|
+
// and the aliases but never the STATEMENT body — so a credential could
|
|
667
|
+
// live in a belief on disk (and reach both the sweep prompt and the
|
|
668
|
+
// embedder, which redact at their own edges, but the store held it raw).
|
|
669
|
+
// Redacting at THE SOURCE closes all three at once, the way migrate's
|
|
670
|
+
// own runGate already treats a statement.
|
|
671
|
+
body: redactSecrets(spec.body),
|
|
672
|
+
meta,
|
|
673
|
+
salience,
|
|
674
|
+
physics: {
|
|
675
|
+
birthDay: spec.day,
|
|
676
|
+
lastUsedDay: spec.day,
|
|
677
|
+
protected: spec.protectedFlag,
|
|
678
|
+
...(spec.seed ?? {}),
|
|
679
|
+
},
|
|
680
|
+
...(spec.channel === undefined ? {} : { source: spec.channel }),
|
|
681
|
+
};
|
|
682
|
+
if (spec.happenedOn !== undefined) put.happenedOn = spec.happenedOn;
|
|
683
|
+
const id = this.store.put(put);
|
|
684
|
+
const rec: MetaRecord = { role: spec.role, entityId: spec.entityId };
|
|
685
|
+
if (spec.meta?.["statedOn"] !== undefined) rec.statedOn = spec.meta["statedOn"] as string;
|
|
686
|
+
if (spec.meta?.["statedOnDay"] !== undefined) {
|
|
687
|
+
rec.statedOnDay = spec.meta["statedOnDay"] as number;
|
|
688
|
+
}
|
|
689
|
+
this.remember(id, rec);
|
|
690
|
+
return id;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// ── revision ───────────────────────────────────────────────────────────────
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* One declared challenge against one belief, on one lived day (§5.6).
|
|
697
|
+
*
|
|
698
|
+
* The declaration is RESOLVED THROUGH THE SUPERSEDE CHAIN before physics sees
|
|
699
|
+
* it — `store.resolve()` is the one retarget site every write path crosses
|
|
700
|
+
* (§5 G10, scar §2.2). Without it, a challenge naming a belief that was
|
|
701
|
+
* revised last week comes back `target-mismatch` and the evidence is lost:
|
|
702
|
+
* v1's dangling-ledger-after-supersede, rebuilt by accident.
|
|
703
|
+
*
|
|
704
|
+
* The pressure field lives ON THE TARGET ROW; there is no second object, so
|
|
705
|
+
* the whole dangling-ledger family cannot recur. Every credited increment is
|
|
706
|
+
* logged with its force, its running pressure and the bar it is climbing
|
|
707
|
+
* toward — the pressure history IS the evidence record, and it is what the
|
|
708
|
+
* dashboard's story view reads.
|
|
709
|
+
*/
|
|
710
|
+
challengeBelief(input: ChallengeInput): RevisionOutcome {
|
|
711
|
+
const refuse = (reason: RevisionReason, targetId: string | null): RevisionOutcome => {
|
|
712
|
+
this.emit("schema.revision.refused", targetId ?? input.updates, {
|
|
713
|
+
reason,
|
|
714
|
+
challengerId: input.challengerId,
|
|
715
|
+
day: input.day,
|
|
716
|
+
});
|
|
717
|
+
return {
|
|
718
|
+
verdict: "hold",
|
|
719
|
+
reason,
|
|
720
|
+
credited: false,
|
|
721
|
+
targetId,
|
|
722
|
+
retargeted: false,
|
|
723
|
+
successorId: null,
|
|
724
|
+
force: 0,
|
|
725
|
+
pressureBefore: 0,
|
|
726
|
+
pressureAfter: 0,
|
|
727
|
+
bar: 0,
|
|
728
|
+
increment: null,
|
|
729
|
+
};
|
|
730
|
+
};
|
|
731
|
+
|
|
732
|
+
if (input.updates.trim().length === 0) return refuse("no-declared-target", null);
|
|
733
|
+
|
|
734
|
+
let targetId: string;
|
|
735
|
+
try {
|
|
736
|
+
targetId = this.store.resolve(input.updates);
|
|
737
|
+
} catch {
|
|
738
|
+
return refuse("target-unresolvable", null);
|
|
739
|
+
}
|
|
740
|
+
const retargeted = targetId !== input.updates;
|
|
741
|
+
if (retargeted) {
|
|
742
|
+
this.emit("schema.revision.retargeted", targetId, {
|
|
743
|
+
declared: input.updates,
|
|
744
|
+
day: input.day,
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
const rec = this.meta.get(targetId);
|
|
749
|
+
if (rec === undefined || rec.role !== "belief") return refuse("target-not-a-belief", targetId);
|
|
750
|
+
const row = this.store.row(targetId);
|
|
751
|
+
if (row === undefined) return refuse("target-unresolvable", targetId);
|
|
752
|
+
// Superseded targets already resolved away above, so an archived row here is
|
|
753
|
+
// archived on purpose — a distinct fact from "not a belief".
|
|
754
|
+
if (row.archived === 1) return refuse("target-archived", targetId);
|
|
755
|
+
|
|
756
|
+
const target = this.store.physicsOf(targetId);
|
|
757
|
+
// Protected elements refuse every revision path, always (§5 G11). Checked
|
|
758
|
+
// BEFORE the arithmetic, so a protected belief accrues no pressure at all:
|
|
759
|
+
// permanence that quietly accumulated a case against itself would be a
|
|
760
|
+
// different, worse guarantee.
|
|
761
|
+
if (target.protected) return refuse("protected-refuses-revision", targetId);
|
|
762
|
+
|
|
763
|
+
const challengerRow = this.store.row(input.challengerId);
|
|
764
|
+
if (challengerRow === undefined) return refuse("challenger-unknown", targetId);
|
|
765
|
+
const challenger = this.store.physicsOf(input.challengerId);
|
|
766
|
+
|
|
767
|
+
const outcome = applyChallenge(
|
|
768
|
+
targetId,
|
|
769
|
+
target,
|
|
770
|
+
// The RESOLVED id is what physics is told, and the raw declaration stays in
|
|
771
|
+
// the retarget event: the model proposes semantics, the engine resolves
|
|
772
|
+
// references (scar §2.5).
|
|
773
|
+
{ id: input.challengerId, declaredUpdates: targetId, physics: challenger },
|
|
774
|
+
input.day,
|
|
775
|
+
);
|
|
776
|
+
|
|
777
|
+
let increment: PressureIncrement | null = null;
|
|
778
|
+
if (outcome.credited) {
|
|
779
|
+
this.store.updatePhysics(targetId, outcome.next);
|
|
780
|
+
const log = outcome.log;
|
|
781
|
+
if (log !== null) {
|
|
782
|
+
increment = {
|
|
783
|
+
event: "revision.pressure",
|
|
784
|
+
targetId,
|
|
785
|
+
day: log.day,
|
|
786
|
+
challengerId: log.challengerId,
|
|
787
|
+
force: log.force,
|
|
788
|
+
pressureAfter: log.pressureAfter,
|
|
789
|
+
bar: log.bar,
|
|
790
|
+
};
|
|
791
|
+
this.increments.push(increment);
|
|
792
|
+
// SEAMS item K — the increment is DURABLE, not just ringed. Restart the
|
|
793
|
+
// process and the pressure number used to survive while the story of how
|
|
794
|
+
// it got there did not (INTERFACE-GAPS.md §1; constitution line 16 says
|
|
795
|
+
// the owner can see what changed and why). One credited challenge per
|
|
796
|
+
// target per day (physics §5.6), so `(target, day, challenger)` is a
|
|
797
|
+
// natural latch and a replayed day appends nothing twice.
|
|
798
|
+
this.store.appendEvent({
|
|
799
|
+
name: "revision.pressure",
|
|
800
|
+
day: log.day,
|
|
801
|
+
ref: targetId,
|
|
802
|
+
dedupKey: `revision.pressure:${targetId}:${log.day}:${log.challengerId}`,
|
|
803
|
+
payload: {
|
|
804
|
+
targetId,
|
|
805
|
+
day: log.day,
|
|
806
|
+
challengerId: log.challengerId,
|
|
807
|
+
force: log.force,
|
|
808
|
+
pressureAfter: log.pressureAfter,
|
|
809
|
+
bar: log.bar,
|
|
810
|
+
},
|
|
811
|
+
});
|
|
812
|
+
this.emit("revision.pressure", targetId, {
|
|
813
|
+
day: log.day,
|
|
814
|
+
challengerId: log.challengerId,
|
|
815
|
+
force: log.force,
|
|
816
|
+
pressureAfter: log.pressureAfter,
|
|
817
|
+
bar: log.bar,
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
let successorId: string | null = null;
|
|
823
|
+
if (outcome.verdict === "revise") {
|
|
824
|
+
successorId = this.supersedeBelief(targetId, rec, row, input, challenger);
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
return {
|
|
828
|
+
verdict: outcome.verdict,
|
|
829
|
+
reason: outcome.reason as RevisionReason,
|
|
830
|
+
credited: outcome.credited,
|
|
831
|
+
targetId,
|
|
832
|
+
retargeted,
|
|
833
|
+
successorId,
|
|
834
|
+
force: outcome.force,
|
|
835
|
+
pressureBefore: outcome.pressureBefore,
|
|
836
|
+
pressureAfter: outcome.pressureAfter,
|
|
837
|
+
bar: outcome.bar,
|
|
838
|
+
increment,
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/**
|
|
843
|
+
* Revision keeps its reason: the old element is retained as superseded with
|
|
844
|
+
* lineage, and stays resolvable (§5 G10, earned live 2026-08-24 when
|
|
845
|
+
* accommodation's forensics needed the retained element).
|
|
846
|
+
*
|
|
847
|
+
* The successor carries the target's `entityId` and `belief` role. Miss that
|
|
848
|
+
* and the revised belief silently detaches from its schema — it stops
|
|
849
|
+
* appearing in slices and in its own story, and nothing else fails.
|
|
850
|
+
*/
|
|
851
|
+
private supersedeBelief(
|
|
852
|
+
targetId: string,
|
|
853
|
+
rec: MetaRecord,
|
|
854
|
+
row: MemoryRow,
|
|
855
|
+
input: ChallengeInput,
|
|
856
|
+
challenger: MemoryPhysics,
|
|
857
|
+
): string {
|
|
858
|
+
const entityId = rec.entityId ?? "";
|
|
859
|
+
const successorId = this.supersedeElement({
|
|
860
|
+
targetId,
|
|
861
|
+
row,
|
|
862
|
+
role: "belief",
|
|
863
|
+
entityId,
|
|
864
|
+
input,
|
|
865
|
+
challenger,
|
|
866
|
+
reason: TUNABLES.REVISED_REASON,
|
|
867
|
+
indexRec: { role: "belief", entityId },
|
|
868
|
+
});
|
|
869
|
+
this.emit("schema.belief.revised", successorId, {
|
|
870
|
+
predecessorId: targetId,
|
|
871
|
+
entityId,
|
|
872
|
+
day: input.day,
|
|
873
|
+
});
|
|
874
|
+
return successorId;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/**
|
|
878
|
+
* A CURRENT-STATE row is a "now" fact, and the owner's ruling (2026-09-04) is
|
|
879
|
+
* that a resolved `updates:` against one REPLACES it, immediately, with
|
|
880
|
+
* lineage — no pressure to accumulate. That is not a second revision rule; it
|
|
881
|
+
* is §4.3's own ("world-state should flip on one clear correction") applied to
|
|
882
|
+
* the row type that IS world state. Pressure on a status already known stale
|
|
883
|
+
* would only keep the stale line rendering into slices while the correction
|
|
884
|
+
* waited for a bar it has no reason to climb.
|
|
885
|
+
*
|
|
886
|
+
* Everything else about the crossing is the belief path's — shared, not
|
|
887
|
+
* copied: the same supersede, the same lineage, the same retarget callback,
|
|
888
|
+
* the same `memory.superseded` record. The successor is stamped with a NEW
|
|
889
|
+
* `statedOn`, because a replaced status is a status as of the day that
|
|
890
|
+
* replaced it.
|
|
891
|
+
*/
|
|
892
|
+
replaceCurrentState(input: ChallengeInput): ReplacementOutcome {
|
|
893
|
+
const refuse = (reason: ReplacementReason, targetId: string | null): ReplacementOutcome => {
|
|
894
|
+
this.emit("schema.state.replace.refused", targetId ?? undefined, {
|
|
895
|
+
reason,
|
|
896
|
+
challengerId: input.challengerId,
|
|
897
|
+
day: input.day,
|
|
898
|
+
});
|
|
899
|
+
return { ok: false, reason, targetId, retargeted: false, successorId: null };
|
|
900
|
+
};
|
|
901
|
+
|
|
902
|
+
if (input.updates.trim().length === 0) return refuse("no-declared-target", null);
|
|
903
|
+
let targetId: string;
|
|
904
|
+
try {
|
|
905
|
+
targetId = this.store.resolve(input.updates);
|
|
906
|
+
} catch {
|
|
907
|
+
return refuse("target-unresolvable", null);
|
|
908
|
+
}
|
|
909
|
+
const retargeted = targetId !== input.updates;
|
|
910
|
+
if (retargeted) {
|
|
911
|
+
this.emit("schema.revision.retargeted", targetId, {
|
|
912
|
+
declared: input.updates,
|
|
913
|
+
day: input.day,
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
const rec = this.meta.get(targetId);
|
|
918
|
+
if (rec === undefined || rec.role !== "current-state") {
|
|
919
|
+
return refuse("target-not-current-state", targetId);
|
|
920
|
+
}
|
|
921
|
+
const row = this.store.row(targetId);
|
|
922
|
+
if (row === undefined) return refuse("target-unresolvable", targetId);
|
|
923
|
+
if (row.archived === 1) return refuse("target-archived", targetId);
|
|
924
|
+
// Protected refuses EVERY revision path, the replace path included (§5 G11).
|
|
925
|
+
if (this.store.physicsOf(targetId).protected) {
|
|
926
|
+
return refuse("protected-refuses-revision", targetId);
|
|
927
|
+
}
|
|
928
|
+
if (this.store.row(input.challengerId) === undefined) {
|
|
929
|
+
return refuse("challenger-unknown", targetId);
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
const challenger = this.store.physicsOf(input.challengerId);
|
|
933
|
+
const entityId = rec.entityId ?? "";
|
|
934
|
+
// The store's clock, not the ambient one (§I7) — same rule as the placement
|
|
935
|
+
// path above, and the two must not disagree about what day it is.
|
|
936
|
+
const statedOn = this.store.today();
|
|
937
|
+
const successorId = this.supersedeElement({
|
|
938
|
+
targetId,
|
|
939
|
+
row,
|
|
940
|
+
role: "current-state",
|
|
941
|
+
entityId,
|
|
942
|
+
input,
|
|
943
|
+
challenger,
|
|
944
|
+
reason: TUNABLES.REPLACED_REASON,
|
|
945
|
+
meta: { statedOn, statedOnDay: input.day },
|
|
946
|
+
happenedOn: statedOn,
|
|
947
|
+
indexRec: { role: "current-state", entityId, statedOn, statedOnDay: input.day },
|
|
948
|
+
});
|
|
949
|
+
this.emit("schema.state.replaced", successorId, {
|
|
950
|
+
predecessorId: targetId,
|
|
951
|
+
entityId,
|
|
952
|
+
day: input.day,
|
|
953
|
+
statedOn,
|
|
954
|
+
});
|
|
955
|
+
return { ok: true, reason: "replaced", targetId, retargeted, successorId };
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
/**
|
|
959
|
+
* The one supersede flow both element paths cross. Written once because the
|
|
960
|
+
* half that is easy to forget is not the `store.supersede` call — it is
|
|
961
|
+
* everything after it: the successor carries the target's `entityId` and its
|
|
962
|
+
* ROLE (miss that and the revised element silently detaches from its schema —
|
|
963
|
+
* it stops appearing in slices and in its own story, and nothing else fails),
|
|
964
|
+
* it is registered in the in-memory index, its edges are retargeted, and the
|
|
965
|
+
* crossing is recorded.
|
|
966
|
+
*/
|
|
967
|
+
private supersedeElement(spec: {
|
|
968
|
+
targetId: string;
|
|
969
|
+
row: MemoryRow;
|
|
970
|
+
role: SchemaRole;
|
|
971
|
+
entityId: string;
|
|
972
|
+
input: ChallengeInput;
|
|
973
|
+
challenger: MemoryPhysics;
|
|
974
|
+
reason: string;
|
|
975
|
+
meta?: Record<string, unknown>;
|
|
976
|
+
happenedOn?: string;
|
|
977
|
+
indexRec: MetaRecord;
|
|
978
|
+
}): string {
|
|
979
|
+
const { targetId, input } = spec;
|
|
980
|
+
const statement = (input.statement ?? this.store.readProse(input.challengerId).body).trim();
|
|
981
|
+
const seed = successorSeed(this.store.physicsOf(targetId));
|
|
982
|
+
const put: PutInput = {
|
|
983
|
+
type: "schema",
|
|
984
|
+
kind: spec.row.kind,
|
|
985
|
+
body: statement,
|
|
986
|
+
meta: {
|
|
987
|
+
role: spec.role,
|
|
988
|
+
entityId: spec.entityId,
|
|
989
|
+
revisedFrom: targetId,
|
|
990
|
+
groundedIn: [input.challengerId],
|
|
991
|
+
...(spec.meta ?? {}),
|
|
992
|
+
},
|
|
993
|
+
// The evidence that carried the revision sets the successor's salience:
|
|
994
|
+
// an element is as strongly held as what made it (NOTES §3).
|
|
995
|
+
salience: spec.challenger.salience,
|
|
996
|
+
physics: { birthDay: input.day, lastUsedDay: input.day, ...seed },
|
|
997
|
+
// The channel vocabulary's fifth member finally has its writer (PR-2
|
|
998
|
+
// review should-fix 1): an accommodation successor is the engine
|
|
999
|
+
// revising under pressure, and its provenance is the challenger.
|
|
1000
|
+
source: "accommodation",
|
|
1001
|
+
origin: { ref: input.challengerId },
|
|
1002
|
+
};
|
|
1003
|
+
if (spec.happenedOn !== undefined) put.happenedOn = spec.happenedOn;
|
|
1004
|
+
const successorId = this.store.supersede(targetId, put, spec.reason);
|
|
1005
|
+
this.remember(successorId, spec.indexRec);
|
|
1006
|
+
// SEAMS item E, in the same flow as the supersede: the successor inherits the
|
|
1007
|
+
// old head's live edges. A retarget that THROWS must not undo a revision that
|
|
1008
|
+
// already landed — the element is superseded either way, and a cold successor
|
|
1009
|
+
// is a recoverable loss where a half-applied revision is not.
|
|
1010
|
+
if (this.retarget !== undefined) {
|
|
1011
|
+
try {
|
|
1012
|
+
this.retarget(targetId, successorId, input.day);
|
|
1013
|
+
this.emit("schema.edges.retargeted", targetId, { successorId, day: input.day });
|
|
1014
|
+
} catch (err) {
|
|
1015
|
+
this.emit("schema.edges.retarget.failed", targetId, {
|
|
1016
|
+
successorId,
|
|
1017
|
+
day: input.day,
|
|
1018
|
+
error: err instanceof Error ? err.name : "UNKNOWN",
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
const record = supersedeRecord(targetId, successorId, input.day);
|
|
1023
|
+
this.emit("memory.superseded", targetId, {
|
|
1024
|
+
successorId,
|
|
1025
|
+
day: record.day,
|
|
1026
|
+
resolvableUntilDay: record.resolvableUntilDay,
|
|
1027
|
+
});
|
|
1028
|
+
return successorId;
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
// ── death by decay ─────────────────────────────────────────────────────────
|
|
1032
|
+
|
|
1033
|
+
/**
|
|
1034
|
+
* Would this entity fade today, and if not, why not — EVERY reason, not the
|
|
1035
|
+
* first (§5 G7). Death is decay: physics decides, and this module adds one
|
|
1036
|
+
* blocker of its own, because an entity with live beliefs or live status is a
|
|
1037
|
+
* place memories are still attached to (open question 1; NOTES §5).
|
|
1038
|
+
*/
|
|
1039
|
+
fadeVerdict(id: string, day: number): FadeVerdict {
|
|
1040
|
+
const row = this.store.row(id);
|
|
1041
|
+
const rec = this.meta.get(id);
|
|
1042
|
+
if (row === undefined || rec === undefined || rec.role !== "entity") {
|
|
1043
|
+
// "there is no such entity" and "it already faded" are different facts,
|
|
1044
|
+
// and a shared reason string would make them one (scar §2.4).
|
|
1045
|
+
return {
|
|
1046
|
+
fade: false,
|
|
1047
|
+
reason: "not-an-entity",
|
|
1048
|
+
blockedBy: ["not-an-entity"],
|
|
1049
|
+
strength: 0,
|
|
1050
|
+
band: "episodic",
|
|
1051
|
+
dwellDays: 0,
|
|
1052
|
+
attached: 0,
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
const p = this.store.physicsOf(id);
|
|
1056
|
+
if (row.archived === 1) {
|
|
1057
|
+
return {
|
|
1058
|
+
fade: false,
|
|
1059
|
+
reason: "already-archived",
|
|
1060
|
+
blockedBy: ["already-archived"],
|
|
1061
|
+
strength: strengthOf(p, day),
|
|
1062
|
+
band: bandOfPhysics(p, day),
|
|
1063
|
+
dwellDays: day - p.lastUsedDay,
|
|
1064
|
+
attached: this.liveElementIds(id).length,
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
const v = pruneVerdict(p, day, { inLiveRevisionChain: false });
|
|
1068
|
+
const attached = this.liveElementIds(id).length;
|
|
1069
|
+
// `prunable` is physics' OK value and never appears among blockers; the
|
|
1070
|
+
// filter is there so the two vocabularies cannot silently diverge.
|
|
1071
|
+
const blockedBy: FadeReason[] = v.blockedBy.filter(
|
|
1072
|
+
(r): r is Exclude<typeof r, "prunable"> => r !== "prunable",
|
|
1073
|
+
);
|
|
1074
|
+
if (attached > 0) blockedBy.push("has-live-attached-elements");
|
|
1075
|
+
return {
|
|
1076
|
+
fade: blockedBy.length === 0,
|
|
1077
|
+
reason: blockedBy[0] ?? "faded",
|
|
1078
|
+
blockedBy,
|
|
1079
|
+
strength: v.strength,
|
|
1080
|
+
band: v.band,
|
|
1081
|
+
dwellDays: v.dwellDays,
|
|
1082
|
+
attached,
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
/**
|
|
1087
|
+
* The sweep. Archive is a STATE, not a deletion: a faded entity keeps its id,
|
|
1088
|
+
* stays resolvable, and simply stops surfacing (§4.2 G3). No model, on any
|
|
1089
|
+
* path, holds this power — it is arithmetic on a lived day.
|
|
1090
|
+
*/
|
|
1091
|
+
fadeSweep(day: number): FadeReport {
|
|
1092
|
+
const faded: string[] = [];
|
|
1093
|
+
let examined = 0;
|
|
1094
|
+
for (const [id, rec] of this.meta) {
|
|
1095
|
+
if (rec.role !== "entity") continue;
|
|
1096
|
+
const row = this.store.row(id);
|
|
1097
|
+
if (row === undefined || row.archived === 1) continue;
|
|
1098
|
+
examined += 1;
|
|
1099
|
+
const v = this.fadeVerdict(id, day);
|
|
1100
|
+
if (!v.fade) continue;
|
|
1101
|
+
this.store.archive(id, TUNABLES.FADE_REASON);
|
|
1102
|
+
this.index.unregister(id);
|
|
1103
|
+
faded.push(id);
|
|
1104
|
+
this.emit("schema.faded", id, {
|
|
1105
|
+
day,
|
|
1106
|
+
kind: row.kind,
|
|
1107
|
+
strength: v.strength,
|
|
1108
|
+
dwellDays: v.dwellDays,
|
|
1109
|
+
birthDay: row.birth_day,
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
1112
|
+
this.emit("schema.fade.sweep", undefined, { day, examined, faded: faded.length });
|
|
1113
|
+
return { day, examined, faded };
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
// ── reads ──────────────────────────────────────────────────────────────────
|
|
1117
|
+
|
|
1118
|
+
/**
|
|
1119
|
+
* A row this index must not hold, because the owner removed it.
|
|
1120
|
+
*
|
|
1121
|
+
* Two states, and the first one is the crash. **Chased:** the row is a
|
|
1122
|
+
* tombstone — body and content hash both blanked (`store/owner-op-seam.ts`)
|
|
1123
|
+
* — so reading it throws `MEMORY_BODY_MISSING` out of `Schemas.open`, out of
|
|
1124
|
+
* `Counterpart.open`, and the hook catches that and exits 0, which is a
|
|
1125
|
+
* session with no wake, no recall and no capture and one line on stderr.
|
|
1126
|
+
* Free to check: the row is already in hand. **Dark:** marked but not yet
|
|
1127
|
+
* chased, so the row and its words are both still there and only the
|
|
1128
|
+
* deny-list knows. `denied` is passed in where the caller has a whole WALK to do, so a
|
|
1129
|
+
* walk costs one query and not one per row.
|
|
1130
|
+
*
|
|
1131
|
+
* `load` does not use this — it counts its two skips apart, which this cannot
|
|
1132
|
+
* (a blanked pointer alone does not say who blanked it).
|
|
1133
|
+
*
|
|
1134
|
+
* Skipping is the honest answer. A removed belief or entity is absent from
|
|
1135
|
+
* this index, so it is absent from everything built on it; what hangs off a
|
|
1136
|
+
* removed entity is orphaned rather than destroyed, and §7b says where that
|
|
1137
|
+
* still shows. The store keeps saying `REMOVED` by name to anyone who asks
|
|
1138
|
+
* for it by id (`Store.read`), which is where "removed" and "never existed"
|
|
1139
|
+
* stay distinguishable.
|
|
1140
|
+
*/
|
|
1141
|
+
private removed(id: string, row: MemoryRow, denied?: ReadonlySet<string>): boolean {
|
|
1142
|
+
if (rowTombstoned(row)) return true;
|
|
1143
|
+
return denied === undefined ? this.store.deniedIds().includes(id) : denied.has(id);
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
/** What `load` left out and whether the store could account for it — see
|
|
1147
|
+
* `load`. Read-only: the caller gets copies, never the counters. */
|
|
1148
|
+
loadSkips(): { readonly removed: number; readonly unaccounted: readonly string[] } {
|
|
1149
|
+
return { removed: this.skips.removed, unaccounted: [...this.skips.unaccounted] };
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
entity(id: string): EntityView | undefined {
|
|
1153
|
+
const rec = this.meta.get(id);
|
|
1154
|
+
const row = this.store.row(id);
|
|
1155
|
+
if (rec === undefined || rec.role !== "entity" || row === undefined) return undefined;
|
|
1156
|
+
// One caller, one id: asking the deny-list live is the right cost here, and
|
|
1157
|
+
// it is what makes a removal visible to a long-lived process before it
|
|
1158
|
+
// reopens. A WALK must not pay it per row — see `entities` below.
|
|
1159
|
+
if (this.removed(id, row)) return undefined;
|
|
1160
|
+
return entityViewOf(id, rec, row);
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
entities(opts: { includeArchived?: boolean } = {}): EntityView[] {
|
|
1164
|
+
const out: EntityView[] = [];
|
|
1165
|
+
// ONE deny-list query for the whole walk. Asking per entity made this
|
|
1166
|
+
// O(entities × removals): at 300 entities it measured 10.4 ms against an
|
|
1167
|
+
// empty deny-list and 111 ms against 1,000 removals, and a deny-list only
|
|
1168
|
+
// ever grows. `slices()` is built on this.
|
|
1169
|
+
const denied = new Set(this.store.deniedIds());
|
|
1170
|
+
for (const [id, rec] of this.meta) {
|
|
1171
|
+
if (rec.role !== "entity") continue;
|
|
1172
|
+
const row = this.store.row(id);
|
|
1173
|
+
if (row === undefined || this.removed(id, row, denied)) continue;
|
|
1174
|
+
const view = entityViewOf(id, rec, row);
|
|
1175
|
+
if (view.archived && opts.includeArchived !== true) continue;
|
|
1176
|
+
out.push(view);
|
|
1177
|
+
}
|
|
1178
|
+
return out.sort((a, b) => a.id.localeCompare(b.id));
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
element(id: string): ElementView | undefined {
|
|
1182
|
+
const rec = this.meta.get(id);
|
|
1183
|
+
const row = this.store.row(id);
|
|
1184
|
+
if (rec === undefined || row === undefined) return undefined;
|
|
1185
|
+
if (rec.role === "entity") return undefined;
|
|
1186
|
+
// ── the removal gate, and it runs BEFORE the prose is read ──────────────
|
|
1187
|
+
//
|
|
1188
|
+
// Chased: the row is a tombstone, so reading it is the
|
|
1189
|
+
// `MEMORY_BODY_MISSING` that used to come out of `Counterpart.open`. Free
|
|
1190
|
+
// to see; the row is in hand.
|
|
1191
|
+
if (rowTombstoned(row)) return undefined;
|
|
1192
|
+
// Dark: marked, not yet chased — the row and its words are both still
|
|
1193
|
+
// there, and only
|
|
1194
|
+
// the deny-list knows. `physicsOf` asks it (`requireRow` → `refuseIfDenied`)
|
|
1195
|
+
// and this call has to happen anyway, so the gate costs nothing; what
|
|
1196
|
+
// changed on 2026-09-18 is that it is a STATEMENT, above the read, instead
|
|
1197
|
+
// of a field evaluated after `statement` in the literal below. That ordering
|
|
1198
|
+
// was luck: reordering two lines lost the gate, and the removed text was
|
|
1199
|
+
// read into memory before the throw discarded it — off disk then, off the
|
|
1200
|
+
// `body` column since the floor, and loaded either way. An in-process
|
|
1201
|
+
// `Schemas` can be older than a removal the owner has since run, which is
|
|
1202
|
+
// why the question is asked here and not trusted from `load`.
|
|
1203
|
+
let salience;
|
|
1204
|
+
try {
|
|
1205
|
+
salience = this.store.physicsOf(id).salience;
|
|
1206
|
+
} catch (err) {
|
|
1207
|
+
// Removed, or the row went while we were looking: no element either way.
|
|
1208
|
+
// Anything else is a real store failure and is not this module's to eat.
|
|
1209
|
+
if (!isAbsence(err)) throw err;
|
|
1210
|
+
return undefined;
|
|
1211
|
+
}
|
|
1212
|
+
const view: ElementView = {
|
|
1213
|
+
id,
|
|
1214
|
+
entityId: rec.entityId ?? "",
|
|
1215
|
+
role: rec.role,
|
|
1216
|
+
statement: readProseWalking(this.store, id, row).body,
|
|
1217
|
+
kind: row.kind,
|
|
1218
|
+
archived: row.archived === 1,
|
|
1219
|
+
supersededBy: row.superseded_by,
|
|
1220
|
+
protected: row.protected === 1,
|
|
1221
|
+
salience,
|
|
1222
|
+
};
|
|
1223
|
+
if (rec.statedOn !== undefined) view.statedOn = rec.statedOn;
|
|
1224
|
+
if (rec.statedOnDay !== undefined) view.statedOnDay = rec.statedOnDay;
|
|
1225
|
+
return view;
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
private liveElementIds(entityId: string, role?: SchemaRole): string[] {
|
|
1229
|
+
const out: string[] = [];
|
|
1230
|
+
for (const id of this.byEntity.get(entityId) ?? []) {
|
|
1231
|
+
const rec = this.meta.get(id);
|
|
1232
|
+
if (rec === undefined) continue;
|
|
1233
|
+
if (role !== undefined && rec.role !== role) continue;
|
|
1234
|
+
const row = this.store.row(id);
|
|
1235
|
+
if (row === undefined || row.archived === 1) continue;
|
|
1236
|
+
out.push(id);
|
|
1237
|
+
}
|
|
1238
|
+
return out.sort();
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
beliefs(entityId: string): ElementView[] {
|
|
1242
|
+
return this.liveElementIds(entityId, "belief")
|
|
1243
|
+
.map((id) => this.element(id))
|
|
1244
|
+
.filter((e): e is ElementView => e !== undefined);
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
currentState(entityId: string): ElementView[] {
|
|
1248
|
+
return this.liveElementIds(entityId, "current-state")
|
|
1249
|
+
.map((id) => this.element(id))
|
|
1250
|
+
.filter((e): e is ElementView => e !== undefined);
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
/**
|
|
1254
|
+
* What the author is shown at encoding (§8 G7). Beliefs and current state are
|
|
1255
|
+
* VERBATIM — a paraphrase of a belief cannot be honestly confirmed or
|
|
1256
|
+
* contradicted, and contradiction detection is the whole reason the slice
|
|
1257
|
+
* exists — and each element carries its ID, the address an `updates:`
|
|
1258
|
+
* declaration names. Faded entities are absent: that is what "fades out of
|
|
1259
|
+
* preselection" means.
|
|
1260
|
+
*
|
|
1261
|
+
* `excludeProtected` is the INTERPRETER's view (§14.1 G2: protected elements
|
|
1262
|
+
* never render into the falsification path — a model must not be handed the
|
|
1263
|
+
* one class of statement it is forbidden to challenge). The filter is
|
|
1264
|
+
* PER-ELEMENT, never per-entity, and every filtered element is COUNTED in
|
|
1265
|
+
* `elided` rather than silently absent (§5 G8). One builder serves both the
|
|
1266
|
+
* prompt cards and the gate slices, so the two surfaces cannot drift.
|
|
1267
|
+
*/
|
|
1268
|
+
slices(opts: { excludeProtected?: boolean } = {}): SchemaSliceOut[] {
|
|
1269
|
+
return this.entities().map((e) => {
|
|
1270
|
+
let elided = 0;
|
|
1271
|
+
const keep = (v: ElementView): boolean => {
|
|
1272
|
+
if (opts.excludeProtected === true && v.protected) {
|
|
1273
|
+
elided += 1;
|
|
1274
|
+
return false;
|
|
1275
|
+
}
|
|
1276
|
+
return true;
|
|
1277
|
+
};
|
|
1278
|
+
const beliefs = this.beliefs(e.id)
|
|
1279
|
+
.filter(keep)
|
|
1280
|
+
.map((b) => ({ id: b.id, statement: b.statement }));
|
|
1281
|
+
const currentState = this.currentState(e.id)
|
|
1282
|
+
.filter(keep)
|
|
1283
|
+
.map((c) => ({ id: c.id, statement: c.statement }));
|
|
1284
|
+
return { id: e.id, name: e.name, aliases: [...e.aliases], beliefs, currentState, elided };
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
/** The index recall borrows (SEAMS §6). Live object; treat it as read-only. */
|
|
1289
|
+
aliasIndex(): AliasIndex {
|
|
1290
|
+
return this.index;
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
/** Handle -> ids, the shape `recall/`'s `Turn.aliases` wants. */
|
|
1294
|
+
aliasMap(): ReadonlyMap<string, readonly string[]> {
|
|
1295
|
+
return this.index.map();
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
/** READ ONLY. Promotion is physics'/sleep's counted crossing, never this
|
|
1299
|
+
* module's — there is no write path to a band in this directory. */
|
|
1300
|
+
bandOf(id: string, day: number): Band {
|
|
1301
|
+
return bandOfPhysics(this.store.physicsOf(id), day);
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
/**
|
|
1305
|
+
* The revision story of one belief, for the dashboard (constitution line 16):
|
|
1306
|
+
* the lineage the store retained, the pressure standing on the live head, the
|
|
1307
|
+
* bar it is climbing toward, and every credited increment this session logged.
|
|
1308
|
+
*/
|
|
1309
|
+
story(beliefId: string): BeliefStory {
|
|
1310
|
+
const chain: string[] = [];
|
|
1311
|
+
let cursor: string | undefined = beliefId;
|
|
1312
|
+
const lineage: LineageStep[] = [];
|
|
1313
|
+
while (cursor !== undefined && !chain.includes(cursor)) {
|
|
1314
|
+
chain.push(cursor);
|
|
1315
|
+
for (const v of this.store.versions(cursor)) {
|
|
1316
|
+
lineage.push({
|
|
1317
|
+
id: cursor,
|
|
1318
|
+
seq: v.seq,
|
|
1319
|
+
reason: v.reason,
|
|
1320
|
+
day: v.version_day,
|
|
1321
|
+
successorId: v.successor_id,
|
|
1322
|
+
});
|
|
1323
|
+
}
|
|
1324
|
+
const row: MemoryRow | undefined = this.store.row(cursor);
|
|
1325
|
+
cursor = row?.superseded_by ?? undefined;
|
|
1326
|
+
}
|
|
1327
|
+
const headId = chain[chain.length - 1] ?? beliefId;
|
|
1328
|
+
const head = this.store.row(headId);
|
|
1329
|
+
const p = head === undefined ? undefined : this.store.physicsOf(headId);
|
|
1330
|
+
return {
|
|
1331
|
+
beliefId,
|
|
1332
|
+
headId,
|
|
1333
|
+
lineage,
|
|
1334
|
+
pressure: p?.pressure ?? 0,
|
|
1335
|
+
lastChallengedDay: p?.lastChallengedDay ?? null,
|
|
1336
|
+
bar: p === undefined ? 0 : revisionBar(p, p.lastChallengedDay ?? p.birthDay),
|
|
1337
|
+
strength: p === undefined ? 0 : strengthOf(p, p.lastChallengedDay ?? p.birthDay),
|
|
1338
|
+
increments: this.storyIncrements(chain),
|
|
1339
|
+
};
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
/**
|
|
1343
|
+
* The durable increments first (box 2's `events` table — they survive a
|
|
1344
|
+
* restart), then anything this session logged that the log does not already
|
|
1345
|
+
* carry. The union is deduped on the same `(target, day, challenger)` latch the
|
|
1346
|
+
* append uses, so a story never shows one challenge twice.
|
|
1347
|
+
*/
|
|
1348
|
+
private storyIncrements(chain: readonly string[]): PressureIncrement[] {
|
|
1349
|
+
const key = (i: { targetId: string; day: number; challengerId: string }): string =>
|
|
1350
|
+
`${i.targetId}:${i.day}:${i.challengerId}`;
|
|
1351
|
+
const out: PressureIncrement[] = [];
|
|
1352
|
+
const seen = new Set<string>();
|
|
1353
|
+
for (const row of this.store.eventLog({ name: "revision.pressure", limit: 1000 })) {
|
|
1354
|
+
if (row.ref === null || !chain.includes(row.ref) || row.payload === null) continue;
|
|
1355
|
+
try {
|
|
1356
|
+
const p = JSON.parse(row.payload) as Omit<PressureIncrement, "event">;
|
|
1357
|
+
const inc: PressureIncrement = { event: "revision.pressure", ...p };
|
|
1358
|
+
out.push(inc);
|
|
1359
|
+
seen.add(key(inc));
|
|
1360
|
+
} catch {
|
|
1361
|
+
// An unparseable payload is a lost line of the story, never a throw in
|
|
1362
|
+
// the dashboard's read path.
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
for (const i of this.increments) {
|
|
1366
|
+
if (chain.includes(i.targetId) && !seen.has(key(i))) out.push(i);
|
|
1367
|
+
}
|
|
1368
|
+
return out;
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
/**
|
|
1372
|
+
* Guarantee 13: created versus exited, per kind. A kind that has minted
|
|
1373
|
+
* entities and never retired one is a defect to investigate, not a base rate
|
|
1374
|
+
* to accept (scar §2.17 — write paths ship, curation paths starve).
|
|
1375
|
+
*/
|
|
1376
|
+
lifecycle(): LifecycleRow[] {
|
|
1377
|
+
const counts = new Map<Kind, { created: number; exited: number }>();
|
|
1378
|
+
for (const [id, rec] of this.meta) {
|
|
1379
|
+
if (rec.role !== "entity") continue;
|
|
1380
|
+
const row = this.store.row(id);
|
|
1381
|
+
if (row === undefined) continue;
|
|
1382
|
+
const c = counts.get(row.kind) ?? { created: 0, exited: 0 };
|
|
1383
|
+
c.created += 1;
|
|
1384
|
+
if (row.archived === 1 && row.archived_reason === TUNABLES.FADE_REASON) c.exited += 1;
|
|
1385
|
+
counts.set(row.kind, c);
|
|
1386
|
+
}
|
|
1387
|
+
return [...counts.entries()]
|
|
1388
|
+
.map(([kind, c]) => ({
|
|
1389
|
+
kind,
|
|
1390
|
+
created: c.created,
|
|
1391
|
+
exited: c.exited,
|
|
1392
|
+
noExitsYet: c.created > 0 && c.exited === 0,
|
|
1393
|
+
}))
|
|
1394
|
+
.sort((a, b) => a.kind.localeCompare(b.kind));
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
/** The entity view, built in one place so `entity` and the `entities` walk —
|
|
1399
|
+
* which ask the deny-list differently — cannot drift into two shapes. */
|
|
1400
|
+
function entityViewOf(id: string, rec: MetaRecord, row: MemoryRow): EntityView {
|
|
1401
|
+
return {
|
|
1402
|
+
id,
|
|
1403
|
+
name: rec.name ?? "",
|
|
1404
|
+
kind: row.kind,
|
|
1405
|
+
aliases: [...(rec.aliases ?? [])],
|
|
1406
|
+
archived: row.archived === 1,
|
|
1407
|
+
archivedReason: row.archived_reason,
|
|
1408
|
+
birthDay: row.birth_day,
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
/**
|
|
1413
|
+
* "There is no memory at this id" — the owner removed it, or the row is gone.
|
|
1414
|
+
* Anything else out of a store read is a real failure, and swallowing it here
|
|
1415
|
+
* would turn a broken database into a quietly empty index.
|
|
1416
|
+
*/
|
|
1417
|
+
function isAbsence(err: unknown): boolean {
|
|
1418
|
+
const code = (err as { code?: unknown } | null)?.code;
|
|
1419
|
+
return code === "REMOVED" || code === "ID_UNKNOWN";
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
/** A newborn schema is empty except its names — a place for memories to attach,
|
|
1423
|
+
* never a claim about what is true of the thing (§14.3, §5 G6). */
|
|
1424
|
+
function stubBody(name: string, aliases: readonly string[], day: number): string {
|
|
1425
|
+
const lines = [`# ${name}`, "", `Born by mention on lived day ${day}. Asserts nothing yet.`];
|
|
1426
|
+
if (aliases.length > 0) lines.push("", `Also called: ${aliases.join(", ")}`);
|
|
1427
|
+
return `${lines.join("\n")}\n`;
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
/**
|
|
1431
|
+
* The DECLARED indices of the aliases the gate kept, in kept order. Drops are
|
|
1432
|
+
* reported by the position the author declared them at, never by their text
|
|
1433
|
+
* (§5 G10) — so a second drop reason downstream can speak the same language.
|
|
1434
|
+
*/
|
|
1435
|
+
function keptIndices(
|
|
1436
|
+
declared: readonly string[] | undefined,
|
|
1437
|
+
dropped: readonly { index: number }[],
|
|
1438
|
+
): number[] {
|
|
1439
|
+
const gone = new Set(dropped.map((d) => d.index));
|
|
1440
|
+
const out: number[] = [];
|
|
1441
|
+
(declared ?? []).forEach((_, i) => {
|
|
1442
|
+
if (!gone.has(i)) out.push(i);
|
|
1443
|
+
});
|
|
1444
|
+
return out;
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
function toMetaRecord(meta: Record<string, unknown>): MetaRecord | null {
|
|
1448
|
+
const role = meta["role"];
|
|
1449
|
+
if (role !== "entity" && role !== "belief" && role !== "current-state") return null;
|
|
1450
|
+
const rec: MetaRecord = { role };
|
|
1451
|
+
if (typeof meta["name"] === "string") rec.name = meta["name"];
|
|
1452
|
+
if (Array.isArray(meta["aliases"])) {
|
|
1453
|
+
rec.aliases = (meta["aliases"] as unknown[]).filter((a): a is string => typeof a === "string");
|
|
1454
|
+
}
|
|
1455
|
+
if (typeof meta["entityId"] === "string") rec.entityId = meta["entityId"];
|
|
1456
|
+
if (typeof meta["statedOn"] === "string") rec.statedOn = meta["statedOn"];
|
|
1457
|
+
if (typeof meta["statedOnDay"] === "number") rec.statedOnDay = meta["statedOnDay"];
|
|
1458
|
+
return rec;
|
|
1459
|
+
}
|