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,1030 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `prospective/` — remembering to act. Know that the remembered future has
|
|
3
|
+
* arrived, and be *inclined* rather than *reminded*.
|
|
4
|
+
*
|
|
5
|
+
* The module's spine:
|
|
6
|
+
*
|
|
7
|
+
* `windows.ts` precision, window bounds, the ramp, the firing KEY
|
|
8
|
+
* `derive.ts` the eligibility predicate — derived, never stored
|
|
9
|
+
* `tunables.ts` every knob, in one visible place
|
|
10
|
+
* `index.ts` arrivals (read) + the firing-state transitions (write)
|
|
11
|
+
*
|
|
12
|
+
* Three properties are structural here and worth stating at the top:
|
|
13
|
+
*
|
|
14
|
+
* **ARRIVAL IS A CUE, NOT A COMMAND. THERE IS NO BYPASS LANE.** The calendar
|
|
15
|
+
* turning to June is treated exactly like the user saying "Portland": one more
|
|
16
|
+
* cue offered into `recall/`'s ordinary activation → gate → tier competition,
|
|
17
|
+
* under the same floors, refractory, dedup and footnote-first tiering as
|
|
18
|
+
* everything else. This module therefore has **no export that produces text** —
|
|
19
|
+
* no render, no injection, no wording, not even a template. It hands out
|
|
20
|
+
* candidates and weights; whether anything is ever said is entirely `recall/`'s
|
|
21
|
+
* decision, made against the same bars as every other memory. A test enumerates
|
|
22
|
+
* this module's exports and asserts the absence (contract §5 G1).
|
|
23
|
+
*
|
|
24
|
+
* **The tact principle IS the spec.** A system that surfaces every stored
|
|
25
|
+
* commitment at first retrievability is a task queue wearing memory's clothes.
|
|
26
|
+
* Hold debts, lose deadlines. Every brake here answers one question: *is this the
|
|
27
|
+
* moment it MEANS something, or merely the first moment it's retrievable?*
|
|
28
|
+
*
|
|
29
|
+
* **Firing state is not canonical memory** (§12 G12). Losing a row risks one
|
|
30
|
+
* extra polite mention, never a memory — so the write budget is small and loud:
|
|
31
|
+
* transitions never stall a host-facing path, and every refusal has a name.
|
|
32
|
+
*/
|
|
33
|
+
import type { Kind } from "../types.js";
|
|
34
|
+
import { strength } from "../physics/index.js";
|
|
35
|
+
import type { UseTier } from "../physics/index.js";
|
|
36
|
+
import type { ProseDoc, ProspectiveInput, ProspectiveRow, Store } from "../store/index.js";
|
|
37
|
+
import { derive } from "./derive.js";
|
|
38
|
+
import type { DerivableMemory, DeriveReason, ExtractedDate, Prospectivity } from "./derive.js";
|
|
39
|
+
import { TEMPORAL_MAX_TIER, withTunables } from "./tunables.js";
|
|
40
|
+
import type { ProspectiveTunables } from "./tunables.js";
|
|
41
|
+
import { parseWindowKey, phaseOf, precisionOf, rampAt, windowFor } from "./windows.js";
|
|
42
|
+
import type { DatePrecision, Phase, Window, WindowPrecision } from "./windows.js";
|
|
43
|
+
|
|
44
|
+
export * from "./derive.js";
|
|
45
|
+
export * from "./tunables.js";
|
|
46
|
+
export * from "./windows.js";
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The durable lifecycle, in the store's own four-value vocabulary:
|
|
50
|
+
*
|
|
51
|
+
* `armed` a derived window with no fires spent
|
|
52
|
+
* `fired` at least one ambient fire spent this window; budget may remain
|
|
53
|
+
* `suppressed` TERMINAL by referenced-stop — the decisive brake (§12 G6)
|
|
54
|
+
* `expired` TERMINAL because the window closed, or a reschedule replaced it
|
|
55
|
+
*
|
|
56
|
+
* `expired` is also the DERIVED reading of a row nobody stamped: a passed window
|
|
57
|
+
* needs no cleanup pass to stop mattering (§12 G2). Nothing here sweeps.
|
|
58
|
+
*/
|
|
59
|
+
export type WindowState = ProspectiveInput["state"];
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* THE TWO DURABLE ROWS (2026-09-20, E2).
|
|
63
|
+
*
|
|
64
|
+
* This module had none. `fires` and `last_fired_day` are columns on a row, so
|
|
65
|
+
* the store could say a window had ever fired and never when, or why one did
|
|
66
|
+
* not — the 2026-09-17 inventory marked the whole mechanism RING-ONLY, "zero
|
|
67
|
+
* `appendEvent` in the module", with fourteen rows whose counters came from a
|
|
68
|
+
* v1 import and `last_fired_day` null on every one of them.
|
|
69
|
+
*
|
|
70
|
+
* TWO NAMES, not one with an `outcome`. A refusal counted as a firing is the
|
|
71
|
+
* bug the fired view exists to catch, and the two names keep them apart in
|
|
72
|
+
* every reader by construction (the `snapshot.taken` / `snapshot.failed` split,
|
|
73
|
+
* for the same reason).
|
|
74
|
+
*
|
|
75
|
+
* The refusal is LATCHED per memory, window, reason and lived day: eligibility
|
|
76
|
+
* is re-derived every turn, so `not-eligible` on a memory whose date has passed
|
|
77
|
+
* would otherwise write a row every turn for the rest of the store's life. A
|
|
78
|
+
* fire needs no latch — `FIRES_PER_WINDOW` already bounds it.
|
|
79
|
+
*
|
|
80
|
+
* Ids, a window key, a reason and a day. Never a date the memory is about and
|
|
81
|
+
* never a word of it.
|
|
82
|
+
*/
|
|
83
|
+
export const PROSPECTIVE_FIRE_EVENT = "prospective.fire";
|
|
84
|
+
export const PROSPECTIVE_REFUSED_EVENT = "prospective.fire.refused";
|
|
85
|
+
|
|
86
|
+
const WINDOW_STATES: readonly WindowState[] = ["armed", "fired", "suppressed", "expired"];
|
|
87
|
+
|
|
88
|
+
/** Box 2 hands back `state` as TEXT. An unrecognized value reads as `armed` — the
|
|
89
|
+
* direction that costs at most one polite mention, never a silent terminal. */
|
|
90
|
+
export function windowStateOf(row: ProspectiveRow | undefined): WindowState {
|
|
91
|
+
const s = row?.state;
|
|
92
|
+
return WINDOW_STATES.find((x) => x === s) ?? "armed";
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Distinct reasons, because a suppressed fire and a fire that never became
|
|
96
|
+
* eligible are different records (scar §2.4). */
|
|
97
|
+
export type SuppressReason =
|
|
98
|
+
/** Crisis deference (§12 G7). A friend doesn't pivot from the ashes to "so, June!". */
|
|
99
|
+
| "refractory"
|
|
100
|
+
/** The window has not opened yet. */
|
|
101
|
+
| "window-not-open"
|
|
102
|
+
/** The window closed, or was terminally retired. The "stale" case. */
|
|
103
|
+
| "stale-window"
|
|
104
|
+
/** Brake 4, the decisive one: the assistant was observed to have USED the
|
|
105
|
+
* memory, so zero further fires this window. Remembering completes by being
|
|
106
|
+
* lived, not by acknowledgment UI. */
|
|
107
|
+
| "already-referenced"
|
|
108
|
+
/** Brake 2: the per-window cap is spent. */
|
|
109
|
+
| "over-fired"
|
|
110
|
+
/** Brake 1: at most one ambient fire per occasion per LIVED day. */
|
|
111
|
+
| "already-fired-today"
|
|
112
|
+
/** Brake 3: already offered in this session. */
|
|
113
|
+
| "session-dedup";
|
|
114
|
+
|
|
115
|
+
export type FireReason =
|
|
116
|
+
| "fired"
|
|
117
|
+
| "observer"
|
|
118
|
+
| "unknown-memory"
|
|
119
|
+
/** The memory no longer derives as prospective at all; `derivation` says why. */
|
|
120
|
+
| "not-eligible"
|
|
121
|
+
/** Eligible, but this key is not one of the memory's derived windows — the
|
|
122
|
+
* shape a stale caller takes after a reschedule. */
|
|
123
|
+
| "window-not-derived"
|
|
124
|
+
| SuppressReason;
|
|
125
|
+
|
|
126
|
+
export type TransitionReason =
|
|
127
|
+
| "recorded"
|
|
128
|
+
| "observer"
|
|
129
|
+
| "unknown-memory"
|
|
130
|
+
| "malformed-window-key";
|
|
131
|
+
|
|
132
|
+
export type RescheduleReason =
|
|
133
|
+
| "rescheduled"
|
|
134
|
+
| "observer"
|
|
135
|
+
| "unknown-memory"
|
|
136
|
+
/** The proposal named a current value that is not the current value. A stale
|
|
137
|
+
* proposal must never clobber a fresher date (§12 G8). */
|
|
138
|
+
| "stale-proposal"
|
|
139
|
+
| "malformed-date"
|
|
140
|
+
| "unchanged";
|
|
141
|
+
|
|
142
|
+
/** Telemetry: ids, window keys, counts, states, reasons. NEVER body text. */
|
|
143
|
+
export interface ProspectiveEvent {
|
|
144
|
+
at: number;
|
|
145
|
+
name: string;
|
|
146
|
+
ref?: string;
|
|
147
|
+
data?: Record<string, string | number | boolean | null>;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface ProspectiveOptions {
|
|
151
|
+
store: Store;
|
|
152
|
+
/** Overrides on the CAL table. Every one is a calibration claim (scar §2.8). */
|
|
153
|
+
tunables?: Partial<ProspectiveTunables>;
|
|
154
|
+
onEvent?: (e: ProspectiveEvent) => void;
|
|
155
|
+
/** Injectable wall clock, for telemetry stamps only. Never a lived day. */
|
|
156
|
+
now?: () => number;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* One arrived window, offered as a CUE. Note what is absent: no text, no
|
|
161
|
+
* phrasing, no "should surface" boolean. `cueWeight` and `maxTier` are inputs to
|
|
162
|
+
* somebody else's competition.
|
|
163
|
+
*/
|
|
164
|
+
export interface Arrival {
|
|
165
|
+
readonly memoryId: string;
|
|
166
|
+
readonly windowKey: string;
|
|
167
|
+
/** As stated. A month stays a month (§12 G4). */
|
|
168
|
+
readonly eventDate: string;
|
|
169
|
+
readonly precision: WindowPrecision;
|
|
170
|
+
readonly opensOn: string;
|
|
171
|
+
readonly peakOn: string;
|
|
172
|
+
readonly closesOn: string;
|
|
173
|
+
/** 0..1 — how loudly the window is arriving today. */
|
|
174
|
+
readonly ramp: number;
|
|
175
|
+
/** The weight this arrival offers `recall/`'s CUE stage: CUE_STRENGTH x ramp.
|
|
176
|
+
* It is one more cue token's worth of activation, not a channel of its own
|
|
177
|
+
* (INTERFACE-GAPS #1 — do NOT confuse it with recall's `ARRIVAL_WEIGHT`,
|
|
178
|
+
* which is base-level recency and something else entirely). */
|
|
179
|
+
readonly cueWeight: number;
|
|
180
|
+
/** §12 G5: a temporal cue alone reaches the footnote tier AT MOST. */
|
|
181
|
+
readonly maxTier: UseTier;
|
|
182
|
+
readonly state: WindowState;
|
|
183
|
+
readonly fires: number;
|
|
184
|
+
readonly lastFiredDay: number | null;
|
|
185
|
+
/** Decayed strength on `day`, for ORDERING only. No decay exemption before
|
|
186
|
+
* arrival (§12 G10): a future-dated memory that faded before its window was
|
|
187
|
+
* an occasion that didn't matter. */
|
|
188
|
+
readonly strength: number;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export interface SuppressionRecord {
|
|
192
|
+
readonly memoryId: string;
|
|
193
|
+
readonly windowKey: string;
|
|
194
|
+
readonly reason: SuppressReason;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export interface ArrivalInput {
|
|
198
|
+
/** The calendar day being asked about, `YYYY-MM-DD`. An ARGUMENT, never a
|
|
199
|
+
* clock read — "was this arriving on July 5th?" is the same code path. */
|
|
200
|
+
readonly at: string;
|
|
201
|
+
/** The LIVED day, for the once-per-day brake. Defaults to the store's clock. */
|
|
202
|
+
readonly day?: number;
|
|
203
|
+
readonly sessionId?: string;
|
|
204
|
+
/** Crisis deference (§12 G7): suppress arrival cues wholesale. */
|
|
205
|
+
readonly refractory?: boolean;
|
|
206
|
+
/** Extra caller-extracted dates by memory id, merged with the memory's own
|
|
207
|
+
* content dates. This module does NO NLP; whoever read the sentence owns it. */
|
|
208
|
+
readonly extraDates?: ReadonlyMap<string, readonly ExtractedDate[]>;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export interface ArrivalResult {
|
|
212
|
+
readonly at: string;
|
|
213
|
+
readonly day: number;
|
|
214
|
+
readonly observer: boolean;
|
|
215
|
+
/** Sorted by ramp x strength, descending. Candidates, not decisions. */
|
|
216
|
+
readonly arrivals: Arrival[];
|
|
217
|
+
/** Windows that would have arrived and did not, each with its own reason. */
|
|
218
|
+
readonly suppressed: SuppressionRecord[];
|
|
219
|
+
/** Live memories examined. */
|
|
220
|
+
readonly considered: number;
|
|
221
|
+
/** Memories whose derivation refused, by name. This is where "a row exists but
|
|
222
|
+
* the memory is no longer prospective" shows up — the row is firing state, it
|
|
223
|
+
* is never evidence of prospectivity (§12 G2). */
|
|
224
|
+
readonly refused: { memoryId: string; reason: DeriveReason }[];
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export type HorizonReason =
|
|
228
|
+
| "selected"
|
|
229
|
+
| "nothing-arrived"
|
|
230
|
+
/** The horizon beat is suppressed WHOLESALE after a high-affect previous
|
|
231
|
+
* session (§12 G7). A window is days wide; deferring costs nothing. */
|
|
232
|
+
| "high-affect-previous-session";
|
|
233
|
+
|
|
234
|
+
export interface HorizonInput extends ArrivalInput {
|
|
235
|
+
readonly previousSessionHighAffect?: boolean;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export interface HorizonResult {
|
|
239
|
+
readonly items: Arrival[];
|
|
240
|
+
readonly reason: HorizonReason;
|
|
241
|
+
readonly suppressedWholesale: boolean;
|
|
242
|
+
readonly considered: ArrivalResult;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export interface FireInput {
|
|
246
|
+
readonly memoryId: string;
|
|
247
|
+
readonly windowKey: string;
|
|
248
|
+
readonly at: string;
|
|
249
|
+
readonly day?: number;
|
|
250
|
+
readonly sessionId?: string;
|
|
251
|
+
readonly refractory?: boolean;
|
|
252
|
+
readonly dates?: readonly ExtractedDate[];
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export interface FireOutcome {
|
|
256
|
+
readonly fired: boolean;
|
|
257
|
+
readonly reason: FireReason;
|
|
258
|
+
/** Why derivation refused, when it did. Null otherwise. */
|
|
259
|
+
readonly derivation: DeriveReason | null;
|
|
260
|
+
readonly fires: number;
|
|
261
|
+
readonly state: WindowState;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export interface TransitionOutcome {
|
|
265
|
+
readonly recorded: boolean;
|
|
266
|
+
readonly reason: TransitionReason;
|
|
267
|
+
readonly state: WindowState;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export interface RescheduleInput {
|
|
271
|
+
readonly memoryId: string;
|
|
272
|
+
/** The compare half of the compare-and-swap: the exact current event date. */
|
|
273
|
+
readonly expectCurrentDate: string;
|
|
274
|
+
readonly nextDate: string;
|
|
275
|
+
readonly at: string;
|
|
276
|
+
readonly reason?: string;
|
|
277
|
+
readonly dates?: readonly ExtractedDate[];
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export interface RescheduleOutcome {
|
|
281
|
+
readonly rescheduled: boolean;
|
|
282
|
+
readonly reason: RescheduleReason;
|
|
283
|
+
/** The retired window's key — kept, in state `expired`, never deleted. */
|
|
284
|
+
readonly retiredKey: string | null;
|
|
285
|
+
/** The fresh key, which owes nothing to the old one's spent budget (§12 G9). */
|
|
286
|
+
readonly armedKey: string | null;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Every dated memory names its exit (§5 G12, scar §2.17). */
|
|
290
|
+
export type ExitKind =
|
|
291
|
+
| "open"
|
|
292
|
+
| "fired"
|
|
293
|
+
| "referenced"
|
|
294
|
+
| "superseded-by-reschedule"
|
|
295
|
+
| "faded"
|
|
296
|
+
| "expired";
|
|
297
|
+
|
|
298
|
+
export interface Exit {
|
|
299
|
+
readonly memoryId: string;
|
|
300
|
+
readonly windowKey: string;
|
|
301
|
+
readonly kind: ExitKind;
|
|
302
|
+
readonly fires: number;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export interface ExitReport {
|
|
306
|
+
readonly at: string;
|
|
307
|
+
readonly day: number;
|
|
308
|
+
readonly counts: Record<ExitKind, number>;
|
|
309
|
+
readonly exits: Exit[];
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Where a memory's own content-dates live on the prose payload. */
|
|
313
|
+
export const EVENT_DATE_META = "eventDate";
|
|
314
|
+
export const EVENT_DATES_META = "eventDates";
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* A memory's content-dates: `happenedOn` (stated precision, never rounded) plus
|
|
318
|
+
* the `eventDate` / `eventDates` meta convention this module declares. SHAPE
|
|
319
|
+
* ONLY — nothing here reads prose for dates. That is the caller's job, and its
|
|
320
|
+
* output arrives through `extraDates` (INTERFACE-GAPS #2).
|
|
321
|
+
*/
|
|
322
|
+
export function contentDates(doc: ProseDoc): ExtractedDate[] {
|
|
323
|
+
const out: ExtractedDate[] = [];
|
|
324
|
+
const push = (v: unknown): void => {
|
|
325
|
+
if (typeof v === "string" && v !== "") out.push({ date: v });
|
|
326
|
+
};
|
|
327
|
+
push(doc.happenedOn);
|
|
328
|
+
push(doc.meta[EVENT_DATE_META]);
|
|
329
|
+
const many = doc.meta[EVENT_DATES_META];
|
|
330
|
+
if (Array.isArray(many)) for (const v of many) push(v);
|
|
331
|
+
const seen = new Set<string>();
|
|
332
|
+
return out.filter((d) => (seen.has(d.date) ? false : (seen.add(d.date), true)));
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
interface Loaded {
|
|
336
|
+
memory: DerivableMemory;
|
|
337
|
+
doc: ProseDoc;
|
|
338
|
+
dates: ExtractedDate[];
|
|
339
|
+
strength: number;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const EXIT_KINDS: readonly ExitKind[] = [
|
|
343
|
+
"open",
|
|
344
|
+
"fired",
|
|
345
|
+
"referenced",
|
|
346
|
+
"superseded-by-reschedule",
|
|
347
|
+
"faded",
|
|
348
|
+
"expired",
|
|
349
|
+
];
|
|
350
|
+
|
|
351
|
+
export class Prospective {
|
|
352
|
+
readonly store: Store;
|
|
353
|
+
readonly tunables: ProspectiveTunables;
|
|
354
|
+
/** One predicate, one definition: the store's. Never re-derived here
|
|
355
|
+
* (observer-mode.md G7, recall INTERFACE-GAPS #4). */
|
|
356
|
+
readonly observer: boolean;
|
|
357
|
+
|
|
358
|
+
private readonly onEvent: ((e: ProspectiveEvent) => void) | undefined;
|
|
359
|
+
private readonly now: () => number;
|
|
360
|
+
private readonly ring: ProspectiveEvent[] = [];
|
|
361
|
+
/** Brake 3. In-process on purpose — see INTERFACE-GAPS #3. */
|
|
362
|
+
private readonly sessionFired = new Map<string, Set<string>>();
|
|
363
|
+
|
|
364
|
+
constructor(opts: ProspectiveOptions) {
|
|
365
|
+
this.store = opts.store;
|
|
366
|
+
this.tunables = withTunables(opts.tunables ?? {});
|
|
367
|
+
this.observer = opts.store.observer;
|
|
368
|
+
this.onEvent = opts.onEvent;
|
|
369
|
+
this.now = opts.now ?? (() => Date.now());
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// ── derivation (pure, read-time, observer-safe) ───────────────────────────
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* The predicate, against a memory the caller already has. Recomputed every
|
|
376
|
+
* time: there is no stored answer to go stale (§12 G2).
|
|
377
|
+
*/
|
|
378
|
+
derive(
|
|
379
|
+
memory: DerivableMemory,
|
|
380
|
+
dates: readonly ExtractedDate[],
|
|
381
|
+
at: string,
|
|
382
|
+
): Prospectivity {
|
|
383
|
+
return derive(memory, dates, at, this.tunables);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** The same predicate, against a memory the STORE has. Reads only. */
|
|
387
|
+
deriveFor(
|
|
388
|
+
memoryId: string,
|
|
389
|
+
at: string,
|
|
390
|
+
extra: readonly ExtractedDate[] = [],
|
|
391
|
+
day?: number,
|
|
392
|
+
): Prospectivity | null {
|
|
393
|
+
const loaded = this.load(memoryId, extra, day ?? this.store.livedDay());
|
|
394
|
+
if (loaded === null) return null;
|
|
395
|
+
return derive(loaded.memory, loaded.dates, at, this.tunables);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// ── arrivals: candidates for recall's cue stage, never an injection ───────
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Which windows have arrived, as CUES. This method writes nothing — not a row,
|
|
402
|
+
* not a fire, not a byte — which is what makes it safe under observer and what
|
|
403
|
+
* makes "arrival is a cue, not a command" a structural property rather than a
|
|
404
|
+
* promise: the caller has to go back through `fire()` to spend anything, and
|
|
405
|
+
* `recall/` gets to refuse in between.
|
|
406
|
+
*/
|
|
407
|
+
arrivals(input: ArrivalInput): ArrivalResult {
|
|
408
|
+
const day = input.day ?? this.store.livedDay();
|
|
409
|
+
const arrivals: Arrival[] = [];
|
|
410
|
+
const suppressed: SuppressionRecord[] = [];
|
|
411
|
+
const refused: { memoryId: string; reason: DeriveReason }[] = [];
|
|
412
|
+
const denied = new Set(this.store.deniedIds());
|
|
413
|
+
const ids = this.store.list({ archived: false });
|
|
414
|
+
let considered = 0;
|
|
415
|
+
|
|
416
|
+
for (const id of ids) {
|
|
417
|
+
if (denied.has(id)) continue;
|
|
418
|
+
const row = this.store.row(id);
|
|
419
|
+
// A superseded head forwards; the successor arrives on its own merits.
|
|
420
|
+
if (row === undefined || row.superseded_by !== null) continue;
|
|
421
|
+
const loaded = this.load(id, input.extraDates?.get(id) ?? [], day);
|
|
422
|
+
if (loaded === null) continue;
|
|
423
|
+
considered += 1;
|
|
424
|
+
|
|
425
|
+
const p = derive(loaded.memory, loaded.dates, input.at, this.tunables);
|
|
426
|
+
if (!p.eligible) {
|
|
427
|
+
// Includes the load-bearing case: a firing-state row may well exist for
|
|
428
|
+
// this memory, and it buys the memory nothing. The rows record what
|
|
429
|
+
// fired; the predicate decides what is prospective.
|
|
430
|
+
refused.push({ memoryId: id, reason: p.reason });
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const rows = this.rowsFor(id);
|
|
435
|
+
for (const w of p.windows) {
|
|
436
|
+
const stateRow = rows.get(w.key);
|
|
437
|
+
const brake = this.brakeFor(w, stateRow, {
|
|
438
|
+
at: input.at,
|
|
439
|
+
day,
|
|
440
|
+
refractory: input.refractory === true,
|
|
441
|
+
sessionId: input.sessionId,
|
|
442
|
+
});
|
|
443
|
+
if (brake !== null) {
|
|
444
|
+
suppressed.push({ memoryId: id, windowKey: w.key, reason: brake });
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
const ramp = rampAt(w, input.at, this.tunables);
|
|
448
|
+
arrivals.push({
|
|
449
|
+
memoryId: id,
|
|
450
|
+
windowKey: w.key,
|
|
451
|
+
eventDate: w.eventDate,
|
|
452
|
+
precision: w.precision,
|
|
453
|
+
opensOn: w.opensOn,
|
|
454
|
+
peakOn: w.peakOn,
|
|
455
|
+
closesOn: w.closesOn,
|
|
456
|
+
ramp,
|
|
457
|
+
cueWeight: this.tunables.CUE_STRENGTH * ramp,
|
|
458
|
+
maxTier: TEMPORAL_MAX_TIER,
|
|
459
|
+
state: windowStateOf(stateRow),
|
|
460
|
+
fires: stateRow?.fires ?? 0,
|
|
461
|
+
lastFiredDay: stateRow?.last_fired_day ?? null,
|
|
462
|
+
strength: loaded.strength,
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
arrivals.sort(
|
|
468
|
+
(a, b) =>
|
|
469
|
+
b.ramp * b.strength - a.ramp * a.strength || (a.windowKey < b.windowKey ? -1 : 1),
|
|
470
|
+
);
|
|
471
|
+
|
|
472
|
+
for (const s of suppressed) {
|
|
473
|
+
// A window that has not opened yet was NEVER ASKED, which is a different
|
|
474
|
+
// record from a fire that was refused (scar §2.4). It stays in the returned
|
|
475
|
+
// list and out of the telemetry.
|
|
476
|
+
if (s.reason === "window-not-open") continue;
|
|
477
|
+
this.emit("prospective.suppressed", s.memoryId, {
|
|
478
|
+
window: s.windowKey,
|
|
479
|
+
reason: s.reason,
|
|
480
|
+
day,
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
this.emit("prospective.arrivals", undefined, {
|
|
484
|
+
day,
|
|
485
|
+
considered,
|
|
486
|
+
arrived: arrivals.length,
|
|
487
|
+
suppressed: suppressed.length,
|
|
488
|
+
refused: refused.length,
|
|
489
|
+
observer: this.observer,
|
|
490
|
+
});
|
|
491
|
+
return { at: input.at, day, observer: this.observer, arrivals, suppressed, considered, refused };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* The wake horizon: at most `HORIZON_ITEMS` arrivals, *remembered, not tasks*.
|
|
496
|
+
* Returns the SAME `Arrival` records the cue path returns — ids and weights.
|
|
497
|
+
* Whatever a host eventually says about them is the host's wording and the
|
|
498
|
+
* host's decision; this module owns neither (open question 1: whether the
|
|
499
|
+
* post-window grace beat is warm or creepy is deliberately unanswered).
|
|
500
|
+
*/
|
|
501
|
+
horizon(input: HorizonInput): HorizonResult {
|
|
502
|
+
const considered = this.arrivals(input);
|
|
503
|
+
if (input.previousSessionHighAffect === true) {
|
|
504
|
+
this.emit("prospective.horizon", undefined, {
|
|
505
|
+
reason: "high-affect-previous-session",
|
|
506
|
+
items: 0,
|
|
507
|
+
arrived: considered.arrivals.length,
|
|
508
|
+
});
|
|
509
|
+
return {
|
|
510
|
+
items: [],
|
|
511
|
+
reason: "high-affect-previous-session",
|
|
512
|
+
suppressedWholesale: true,
|
|
513
|
+
considered,
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
const items = considered.arrivals.slice(0, this.tunables.HORIZON_ITEMS);
|
|
517
|
+
const reason: HorizonReason = items.length === 0 ? "nothing-arrived" : "selected";
|
|
518
|
+
this.emit("prospective.horizon", undefined, {
|
|
519
|
+
reason,
|
|
520
|
+
items: items.length,
|
|
521
|
+
arrived: considered.arrivals.length,
|
|
522
|
+
ids: items.map((i) => i.memoryId).join(","),
|
|
523
|
+
});
|
|
524
|
+
return { items, reason, suppressedWholesale: false, considered };
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// ── firing-state transitions (all refuse under observer) ──────────────────
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Record a derived window as armed. Optional: `fire()` arms lazily, because
|
|
531
|
+
* losing firing state costs one extra polite mention and never a memory
|
|
532
|
+
* (§12 G12). It exists so `armed` is a real state a caller can assert on.
|
|
533
|
+
*
|
|
534
|
+
* It NEVER resurrects a terminal window: arming a spent key keeps the spent
|
|
535
|
+
* state. The firing key is the window, so a clock repair — or a caller replaying
|
|
536
|
+
* an old arm — cannot re-arm what is already done (§12 G9).
|
|
537
|
+
*/
|
|
538
|
+
arm(memoryId: string, windowKey: string): TransitionOutcome {
|
|
539
|
+
return this.write("arm", memoryId, windowKey, (parsed, row) => ({
|
|
540
|
+
state: windowStateOf(row),
|
|
541
|
+
fires: row?.fires ?? 0,
|
|
542
|
+
lastFiredDay: row?.last_fired_day ?? null,
|
|
543
|
+
eventDate: parsed.eventDate,
|
|
544
|
+
precision: parsed.precision,
|
|
545
|
+
}));
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Spend one ambient fire on one window, on one lived day.
|
|
550
|
+
*
|
|
551
|
+
* Eligibility is RE-DERIVED here, from the memory, every time — a row is never
|
|
552
|
+
* permission. So a memory that was archived, faded below the floor, or
|
|
553
|
+
* rescheduled since the row was written cannot fire, and the refusal says
|
|
554
|
+
* which (§12 G2).
|
|
555
|
+
*
|
|
556
|
+
* A fire is a SURFACING THAT HAPPENED, not an offer that was made: the caller
|
|
557
|
+
* records it after `recall/`'s gate admitted the memory. That split is the
|
|
558
|
+
* whole of "arrival is a cue, not a command" — nothing in this module can
|
|
559
|
+
* cause the surfacing whose budget it counts.
|
|
560
|
+
*/
|
|
561
|
+
fire(input: FireInput): FireOutcome {
|
|
562
|
+
const day = input.day ?? this.store.livedDay();
|
|
563
|
+
if (this.observer) {
|
|
564
|
+
// Checked FIRST, before any read or write: an evaluation must not consume
|
|
565
|
+
// the real store's fire budget (scar E7, contract §5 G9).
|
|
566
|
+
this.emit("prospective.observer.standdown", input.memoryId, {
|
|
567
|
+
site: "fire",
|
|
568
|
+
window: input.windowKey,
|
|
569
|
+
});
|
|
570
|
+
return { fired: false, reason: "observer", derivation: null, fires: 0, state: "armed" };
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const loaded = this.load(input.memoryId, input.dates ?? [], day);
|
|
574
|
+
if (loaded === null) {
|
|
575
|
+
return { fired: false, reason: "unknown-memory", derivation: null, fires: 0, state: "armed" };
|
|
576
|
+
}
|
|
577
|
+
const p = derive(loaded.memory, loaded.dates, input.at, this.tunables);
|
|
578
|
+
if (!p.eligible) {
|
|
579
|
+
this.emit("prospective.fire.refused", input.memoryId, {
|
|
580
|
+
window: input.windowKey,
|
|
581
|
+
reason: "not-eligible",
|
|
582
|
+
derivation: p.reason,
|
|
583
|
+
day,
|
|
584
|
+
});
|
|
585
|
+
this.noteRefusal(input.memoryId, input.windowKey, "not-eligible", day, p.reason);
|
|
586
|
+
return { fired: false, reason: "not-eligible", derivation: p.reason, fires: 0, state: "armed" };
|
|
587
|
+
}
|
|
588
|
+
const w = p.windows.find((x) => x.key === input.windowKey);
|
|
589
|
+
const rows = this.rowsFor(input.memoryId);
|
|
590
|
+
const row = rows.get(input.windowKey);
|
|
591
|
+
if (w === undefined) {
|
|
592
|
+
this.emit("prospective.fire.refused", input.memoryId, {
|
|
593
|
+
window: input.windowKey,
|
|
594
|
+
reason: "window-not-derived",
|
|
595
|
+
day,
|
|
596
|
+
});
|
|
597
|
+
this.noteRefusal(input.memoryId, input.windowKey, "window-not-derived", day, null);
|
|
598
|
+
return {
|
|
599
|
+
fired: false,
|
|
600
|
+
reason: "window-not-derived",
|
|
601
|
+
derivation: null,
|
|
602
|
+
fires: row?.fires ?? 0,
|
|
603
|
+
state: windowStateOf(row),
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
const brake = this.brakeFor(w, row, {
|
|
608
|
+
at: input.at,
|
|
609
|
+
day,
|
|
610
|
+
refractory: input.refractory === true,
|
|
611
|
+
sessionId: input.sessionId,
|
|
612
|
+
});
|
|
613
|
+
if (brake !== null) {
|
|
614
|
+
this.emit("prospective.fire.refused", input.memoryId, {
|
|
615
|
+
window: input.windowKey,
|
|
616
|
+
reason: brake,
|
|
617
|
+
day,
|
|
618
|
+
});
|
|
619
|
+
this.noteRefusal(input.memoryId, input.windowKey, brake, day, null);
|
|
620
|
+
return {
|
|
621
|
+
fired: false,
|
|
622
|
+
reason: brake,
|
|
623
|
+
derivation: null,
|
|
624
|
+
fires: row?.fires ?? 0,
|
|
625
|
+
state: windowStateOf(row),
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
const fires = (row?.fires ?? 0) + 1;
|
|
630
|
+
this.store.setProspective({
|
|
631
|
+
memoryId: input.memoryId,
|
|
632
|
+
windowKey: input.windowKey,
|
|
633
|
+
eventDate: w.eventDate,
|
|
634
|
+
precision: w.precision,
|
|
635
|
+
state: "fired",
|
|
636
|
+
fires,
|
|
637
|
+
lastFiredDay: day,
|
|
638
|
+
});
|
|
639
|
+
if (input.sessionId !== undefined) this.markSession(input.sessionId, input.windowKey);
|
|
640
|
+
this.emit("prospective.fired", input.memoryId, {
|
|
641
|
+
window: input.windowKey,
|
|
642
|
+
precision: w.precision,
|
|
643
|
+
fires,
|
|
644
|
+
cap: this.tunables.FIRES_PER_WINDOW,
|
|
645
|
+
ramp: rampAt(w, input.at, this.tunables),
|
|
646
|
+
day,
|
|
647
|
+
});
|
|
648
|
+
this.note(PROSPECTIVE_FIRE_EVENT, input.memoryId, day, {
|
|
649
|
+
window: input.windowKey,
|
|
650
|
+
precision: w.precision,
|
|
651
|
+
fires,
|
|
652
|
+
cap: this.tunables.FIRES_PER_WINDOW,
|
|
653
|
+
});
|
|
654
|
+
return { fired: true, reason: "fired", derivation: null, fires, state: "fired" };
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* One durable refusal row, latched per memory, window, reason and lived day.
|
|
659
|
+
*
|
|
660
|
+
* Eligibility is re-derived on every turn (§12 G2), so an unlatched row here
|
|
661
|
+
* would write once per turn forever for a window whose date has passed. The
|
|
662
|
+
* latch makes it "this window was stopped by this, on this day", which is the
|
|
663
|
+
* fact the fired view needs and the smallest one that answers it.
|
|
664
|
+
*/
|
|
665
|
+
private noteRefusal(
|
|
666
|
+
memoryId: string,
|
|
667
|
+
windowKey: string,
|
|
668
|
+
reason: string,
|
|
669
|
+
day: number,
|
|
670
|
+
derivation: DeriveReason | null,
|
|
671
|
+
): void {
|
|
672
|
+
this.note(
|
|
673
|
+
PROSPECTIVE_REFUSED_EVENT,
|
|
674
|
+
memoryId,
|
|
675
|
+
day,
|
|
676
|
+
{ window: windowKey, reason, derivation },
|
|
677
|
+
`${PROSPECTIVE_REFUSED_EVENT}:${memoryId}:${windowKey}:${reason}:${String(day)}`,
|
|
678
|
+
);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* The module's one durable seam. Observer is checked by the caller before any
|
|
683
|
+
* read (§5 G9), and a telemetry write may never be what stalls a host-facing
|
|
684
|
+
* path (§12 G12) — so this swallows, and the ring emit beside it stands.
|
|
685
|
+
*/
|
|
686
|
+
private note(
|
|
687
|
+
name: string,
|
|
688
|
+
memoryId: string,
|
|
689
|
+
day: number,
|
|
690
|
+
payload: Record<string, unknown>,
|
|
691
|
+
dedupKey?: string,
|
|
692
|
+
): void {
|
|
693
|
+
if (this.observer) return;
|
|
694
|
+
try {
|
|
695
|
+
this.store.appendEvent({
|
|
696
|
+
name,
|
|
697
|
+
day,
|
|
698
|
+
ref: memoryId,
|
|
699
|
+
payload,
|
|
700
|
+
...(dedupKey === undefined ? {} : { dedupKey }),
|
|
701
|
+
});
|
|
702
|
+
} catch {
|
|
703
|
+
/* a lost row costs a line on a diagnostic, never a memory */
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Brake 4, and the decisive one: the assistant was observed to have USED the
|
|
709
|
+
* memory, so this window is done — zero further fires, whatever budget was
|
|
710
|
+
* left. *Remembering completes by being lived, not by acknowledgment UI.*
|
|
711
|
+
* Idempotent, and it does not care whether a fire ever happened: the user may
|
|
712
|
+
* have raised the occasion themselves.
|
|
713
|
+
*/
|
|
714
|
+
reference(memoryId: string, windowKey: string, day?: number): TransitionOutcome {
|
|
715
|
+
const d = day ?? this.store.livedDay();
|
|
716
|
+
return this.write("reference", memoryId, windowKey, (parsed, row) => ({
|
|
717
|
+
state: "suppressed",
|
|
718
|
+
fires: row?.fires ?? 0,
|
|
719
|
+
lastFiredDay: row?.last_fired_day ?? null,
|
|
720
|
+
eventDate: parsed.eventDate,
|
|
721
|
+
precision: parsed.precision,
|
|
722
|
+
extra: { day: d },
|
|
723
|
+
}));
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Retire a window terminally. The row is KEPT in state `expired` — this module
|
|
728
|
+
* destroys nothing, and the exit accounting needs it (§5 G12).
|
|
729
|
+
*/
|
|
730
|
+
expire(memoryId: string, windowKey: string, reason = "window-closed"): TransitionOutcome {
|
|
731
|
+
return this.write("expire", memoryId, windowKey, (parsed, row) => ({
|
|
732
|
+
state: "expired",
|
|
733
|
+
fires: row?.fires ?? 0,
|
|
734
|
+
lastFiredDay: row?.last_fired_day ?? null,
|
|
735
|
+
eventDate: parsed.eventDate,
|
|
736
|
+
precision: parsed.precision,
|
|
737
|
+
extra: { why: reason },
|
|
738
|
+
}));
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* A rescheduled plan, corrected through a GATED COMPARE-AND-SWAP (§12 G8): the
|
|
743
|
+
* proposal names the exact current value, so a stale proposal cannot clobber a
|
|
744
|
+
* fresher date. The old window is retired (kept, state `expired`) and a fresh
|
|
745
|
+
* key is armed — and because **the firing key is the window**, the new window
|
|
746
|
+
* owes nothing to the old one's spent budget (§12 G9).
|
|
747
|
+
*
|
|
748
|
+
* This half is the FIRING state only. Rewriting the memory's own stated date is
|
|
749
|
+
* the caller's `store.revise` — see INTERFACE-GAPS #4.
|
|
750
|
+
*/
|
|
751
|
+
reschedule(input: RescheduleInput): RescheduleOutcome {
|
|
752
|
+
if (this.observer) {
|
|
753
|
+
this.emit("prospective.observer.standdown", input.memoryId, { site: "reschedule" });
|
|
754
|
+
return { rescheduled: false, reason: "observer", retiredKey: null, armedKey: null };
|
|
755
|
+
}
|
|
756
|
+
const loaded = this.load(input.memoryId, input.dates ?? [], this.store.livedDay());
|
|
757
|
+
if (loaded === null) {
|
|
758
|
+
return { rescheduled: false, reason: "unknown-memory", retiredKey: null, armedKey: null };
|
|
759
|
+
}
|
|
760
|
+
const nextPrecision = precisionOf(input.nextDate);
|
|
761
|
+
const nextWindow =
|
|
762
|
+
nextPrecision === null ? null : windowFor(input.nextDate, nextPrecision, this.tunables);
|
|
763
|
+
if (nextWindow === null) {
|
|
764
|
+
this.emit("prospective.reschedule.refused", input.memoryId, { reason: "malformed-date" });
|
|
765
|
+
return { rescheduled: false, reason: "malformed-date", retiredKey: null, armedKey: null };
|
|
766
|
+
}
|
|
767
|
+
if (input.expectCurrentDate === input.nextDate) {
|
|
768
|
+
this.emit("prospective.reschedule.refused", input.memoryId, { reason: "unchanged" });
|
|
769
|
+
return { rescheduled: false, reason: "unchanged", retiredKey: null, armedKey: null };
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
const p = derive(loaded.memory, loaded.dates, input.at, this.tunables);
|
|
773
|
+
const current = p.windows.find((w) => w.eventDate === input.expectCurrentDate);
|
|
774
|
+
if (current === undefined) {
|
|
775
|
+
// The compare half failing IS the guarantee working.
|
|
776
|
+
this.emit("prospective.reschedule.refused", input.memoryId, {
|
|
777
|
+
reason: "stale-proposal",
|
|
778
|
+
expected: input.expectCurrentDate,
|
|
779
|
+
});
|
|
780
|
+
return { rescheduled: false, reason: "stale-proposal", retiredKey: null, armedKey: null };
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
const rows = this.rowsFor(input.memoryId);
|
|
784
|
+
const old = rows.get(current.key);
|
|
785
|
+
this.store.setProspective({
|
|
786
|
+
memoryId: input.memoryId,
|
|
787
|
+
windowKey: current.key,
|
|
788
|
+
eventDate: current.eventDate,
|
|
789
|
+
precision: current.precision,
|
|
790
|
+
state: "expired",
|
|
791
|
+
fires: old?.fires ?? 0,
|
|
792
|
+
lastFiredDay: old?.last_fired_day ?? null,
|
|
793
|
+
});
|
|
794
|
+
this.store.setProspective({
|
|
795
|
+
memoryId: input.memoryId,
|
|
796
|
+
windowKey: nextWindow.key,
|
|
797
|
+
eventDate: nextWindow.eventDate,
|
|
798
|
+
precision: nextWindow.precision,
|
|
799
|
+
state: "armed",
|
|
800
|
+
fires: 0,
|
|
801
|
+
lastFiredDay: null,
|
|
802
|
+
});
|
|
803
|
+
this.emit("prospective.rescheduled", input.memoryId, {
|
|
804
|
+
from: current.key,
|
|
805
|
+
to: nextWindow.key,
|
|
806
|
+
spentFiresRetired: old?.fires ?? 0,
|
|
807
|
+
why: input.reason ?? "reschedule",
|
|
808
|
+
});
|
|
809
|
+
return {
|
|
810
|
+
rescheduled: true,
|
|
811
|
+
reason: "rescheduled",
|
|
812
|
+
retiredKey: current.key,
|
|
813
|
+
armedKey: nextWindow.key,
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// ── exits (§5 G12: every dated memory names its exit) ─────────────────────
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* Every window this store knows about, classified by how it ended, with
|
|
821
|
+
* counts. A pure read: nothing is stamped, nothing is swept. The property
|
|
822
|
+
* expires by itself, so exit accounting is a QUESTION, never a pass (§12 G2).
|
|
823
|
+
*/
|
|
824
|
+
exitReport(at: string, day?: number): ExitReport {
|
|
825
|
+
const d = day ?? this.store.livedDay();
|
|
826
|
+
const exits: Exit[] = [];
|
|
827
|
+
const counts = Object.fromEntries(EXIT_KINDS.map((k) => [k, 0])) as Record<ExitKind, number>;
|
|
828
|
+
|
|
829
|
+
for (const id of this.store.list({})) {
|
|
830
|
+
const loaded = this.load(id, [], d);
|
|
831
|
+
if (loaded === null) continue;
|
|
832
|
+
const p = derive(loaded.memory, loaded.dates, at, this.tunables);
|
|
833
|
+
const byKey = new Map<string, { window: Window | null; phase: Phase | null }>();
|
|
834
|
+
for (const w of p.windows) byKey.set(w.key, { window: w, phase: w.phase });
|
|
835
|
+
const rows = this.rowsFor(id);
|
|
836
|
+
for (const key of rows.keys()) {
|
|
837
|
+
if (byKey.has(key)) continue;
|
|
838
|
+
const parsed = parseWindowKey(key);
|
|
839
|
+
const w = parsed === null ? null : windowFor(parsed.eventDate, parsed.precision, this.tunables);
|
|
840
|
+
byKey.set(key, { window: w, phase: w === null ? null : phaseOf(w, at) });
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
const laterExists = (key: string): boolean => {
|
|
844
|
+
const self = byKey.get(key)?.window;
|
|
845
|
+
if (self === undefined || self === null) return p.windows.length > 0;
|
|
846
|
+
return p.windows.some((w) => w.key !== key && w.opensOn > self.opensOn);
|
|
847
|
+
};
|
|
848
|
+
|
|
849
|
+
for (const [key, info] of byKey) {
|
|
850
|
+
const row = rows.get(key);
|
|
851
|
+
const fires = row?.fires ?? 0;
|
|
852
|
+
let kind: ExitKind;
|
|
853
|
+
if (windowStateOf(row) === "suppressed") kind = "referenced";
|
|
854
|
+
else if (windowStateOf(row) === "expired") {
|
|
855
|
+
kind = laterExists(key) ? "superseded-by-reschedule" : "expired";
|
|
856
|
+
} else if (fires > 0) kind = "fired";
|
|
857
|
+
else if (info.phase === "passed") {
|
|
858
|
+
kind =
|
|
859
|
+
loaded.memory.archived || loaded.strength <= this.tunables.FADED_STRENGTH
|
|
860
|
+
? "faded"
|
|
861
|
+
: "expired";
|
|
862
|
+
} else kind = "open";
|
|
863
|
+
exits.push({ memoryId: id, windowKey: key, kind, fires });
|
|
864
|
+
counts[kind] += 1;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
this.emit("prospective.exits", undefined, { day: d, ...counts });
|
|
869
|
+
return { at, day: d, counts, exits };
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
events(name?: string): ProspectiveEvent[] {
|
|
873
|
+
return this.ring.filter((e) => name === undefined || e.name === name).map((e) => ({ ...e }));
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// ── internals ─────────────────────────────────────────────────────────────
|
|
877
|
+
|
|
878
|
+
/**
|
|
879
|
+
* The four once-ness brakes plus crisis deference plus the window itself, in
|
|
880
|
+
* ONE place, so the read path and the write path can never disagree about what
|
|
881
|
+
* a spent window is. Order is deliberate: crisis deference outranks everything
|
|
882
|
+
* (§12 G7), and referenced-stop outranks the counting brakes (§12 G6).
|
|
883
|
+
*/
|
|
884
|
+
private brakeFor(
|
|
885
|
+
w: Window,
|
|
886
|
+
row: ProspectiveRow | undefined,
|
|
887
|
+
ctx: { at: string; day: number; refractory: boolean; sessionId?: string | undefined },
|
|
888
|
+
): SuppressReason | null {
|
|
889
|
+
if (ctx.refractory) return "refractory";
|
|
890
|
+
const phase = phaseOf(w, ctx.at);
|
|
891
|
+
if (phase === "pending") return "window-not-open";
|
|
892
|
+
if (phase === "passed") return "stale-window";
|
|
893
|
+
if (row !== undefined) {
|
|
894
|
+
const state = windowStateOf(row);
|
|
895
|
+
if (state === "suppressed") return "already-referenced";
|
|
896
|
+
if (state === "expired") return "stale-window";
|
|
897
|
+
if (row.fires >= this.tunables.FIRES_PER_WINDOW) return "over-fired";
|
|
898
|
+
if (row.last_fired_day !== null && row.last_fired_day === ctx.day) {
|
|
899
|
+
return "already-fired-today";
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
if (ctx.sessionId !== undefined && this.sessionFired.get(ctx.sessionId)?.has(w.key) === true) {
|
|
903
|
+
return "session-dedup";
|
|
904
|
+
}
|
|
905
|
+
return null;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/** `day` is the LIVED day the caller is asking about, never a clock read: the
|
|
909
|
+
* strength on the row is only as-of whatever day was asked (NOTES.md §2). */
|
|
910
|
+
private load(memoryId: string, extra: readonly ExtractedDate[], day: number): Loaded | null {
|
|
911
|
+
const row = this.store.row(memoryId);
|
|
912
|
+
if (row === undefined) return null;
|
|
913
|
+
let read;
|
|
914
|
+
try {
|
|
915
|
+
read = this.store.read(memoryId);
|
|
916
|
+
} catch {
|
|
917
|
+
// A removed memory is not an error here; it simply has no future.
|
|
918
|
+
return null;
|
|
919
|
+
}
|
|
920
|
+
const dates = [...contentDates(read.doc), ...extra];
|
|
921
|
+
const seen = new Set<string>();
|
|
922
|
+
return {
|
|
923
|
+
memory: {
|
|
924
|
+
id: memoryId,
|
|
925
|
+
kind: read.physics.kind as Kind,
|
|
926
|
+
salience: read.physics.salience,
|
|
927
|
+
archived: read.archived,
|
|
928
|
+
learnedOn: read.doc.learnedOn === "" ? null : read.doc.learnedOn,
|
|
929
|
+
// The same field `sleep/types.ts#isJournal` reads off the row, taken
|
|
930
|
+
// from the doc already in hand. See `DerivableMemory.journal`.
|
|
931
|
+
journal: read.doc.type === "episode",
|
|
932
|
+
},
|
|
933
|
+
doc: read.doc,
|
|
934
|
+
dates: dates.filter((d) => (seen.has(d.date) ? false : (seen.add(d.date), true))),
|
|
935
|
+
strength: strength(read.physics, day),
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
private rowsFor(memoryId: string): Map<string, ProspectiveRow> {
|
|
940
|
+
const out = new Map<string, ProspectiveRow>();
|
|
941
|
+
for (const r of this.store.prospectiveFor(memoryId)) out.set(r.window_key, r);
|
|
942
|
+
return out;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
private markSession(sessionId: string, key: string): void {
|
|
946
|
+
let set = this.sessionFired.get(sessionId);
|
|
947
|
+
if (set === undefined) {
|
|
948
|
+
set = new Set<string>();
|
|
949
|
+
this.sessionFired.set(sessionId, set);
|
|
950
|
+
}
|
|
951
|
+
if (set.size >= this.tunables.MAX_SESSION_WINDOWS) {
|
|
952
|
+
const oldest = set.values().next();
|
|
953
|
+
if (!oldest.done) set.delete(oldest.value);
|
|
954
|
+
}
|
|
955
|
+
set.add(key);
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
/** The one shape every non-fire transition shares: observer first, then write. */
|
|
959
|
+
private write(
|
|
960
|
+
site: string,
|
|
961
|
+
memoryId: string,
|
|
962
|
+
windowKey: string,
|
|
963
|
+
next: (
|
|
964
|
+
parsed: { eventDate: string; precision: WindowPrecision },
|
|
965
|
+
row: ProspectiveRow | undefined,
|
|
966
|
+
) => {
|
|
967
|
+
state: WindowState;
|
|
968
|
+
fires: number;
|
|
969
|
+
lastFiredDay: number | null;
|
|
970
|
+
eventDate: string;
|
|
971
|
+
precision: DatePrecision;
|
|
972
|
+
extra?: Record<string, string | number | boolean | null>;
|
|
973
|
+
},
|
|
974
|
+
): TransitionOutcome {
|
|
975
|
+
if (this.observer) {
|
|
976
|
+
this.emit("prospective.observer.standdown", memoryId, { site, window: windowKey });
|
|
977
|
+
return { recorded: false, reason: "observer", state: "armed" };
|
|
978
|
+
}
|
|
979
|
+
const parsed = parseWindowKey(windowKey);
|
|
980
|
+
if (parsed === null) {
|
|
981
|
+
this.emit(`prospective.${site}.refused`, memoryId, {
|
|
982
|
+
window: windowKey,
|
|
983
|
+
reason: "malformed-window-key",
|
|
984
|
+
});
|
|
985
|
+
return { recorded: false, reason: "malformed-window-key", state: "armed" };
|
|
986
|
+
}
|
|
987
|
+
if (!this.store.has(memoryId)) {
|
|
988
|
+
this.emit(`prospective.${site}.refused`, memoryId, {
|
|
989
|
+
window: windowKey,
|
|
990
|
+
reason: "unknown-memory",
|
|
991
|
+
});
|
|
992
|
+
return { recorded: false, reason: "unknown-memory", state: "armed" };
|
|
993
|
+
}
|
|
994
|
+
const row = this.rowsFor(memoryId).get(windowKey);
|
|
995
|
+
const v = next(parsed, row);
|
|
996
|
+
this.store.setProspective({
|
|
997
|
+
memoryId,
|
|
998
|
+
windowKey,
|
|
999
|
+
eventDate: v.eventDate,
|
|
1000
|
+
precision: v.precision,
|
|
1001
|
+
state: v.state,
|
|
1002
|
+
fires: v.fires,
|
|
1003
|
+
lastFiredDay: v.lastFiredDay,
|
|
1004
|
+
});
|
|
1005
|
+
this.emit(`prospective.${site === "arm" ? "armed" : site === "reference" ? "referenced" : "expired"}`, memoryId, {
|
|
1006
|
+
window: windowKey,
|
|
1007
|
+
state: v.state,
|
|
1008
|
+
fires: v.fires,
|
|
1009
|
+
...(v.extra ?? {}),
|
|
1010
|
+
});
|
|
1011
|
+
return { recorded: true, reason: "recorded", state: v.state };
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
private emit(
|
|
1015
|
+
name: string,
|
|
1016
|
+
ref?: string,
|
|
1017
|
+
data?: Record<string, string | number | boolean | null>,
|
|
1018
|
+
): void {
|
|
1019
|
+
const e: ProspectiveEvent = { at: this.now(), name };
|
|
1020
|
+
if (ref !== undefined) e.ref = ref;
|
|
1021
|
+
if (data !== undefined) e.data = data;
|
|
1022
|
+
this.ring.push(e);
|
|
1023
|
+
if (this.ring.length > 500) this.ring.shift();
|
|
1024
|
+
this.onEvent?.(e);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
export type { DerivableMemory, DeriveReason, ExtractedDate, Prospectivity };
|
|
1029
|
+
export type { DatePrecision, Phase, Window, WindowPrecision };
|
|
1030
|
+
export type { UseTier };
|