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,598 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The consolidation cycle — the librarian's whole run.
|
|
3
|
+
*
|
|
4
|
+
* Five properties live in this file, and every one of them is a test:
|
|
5
|
+
*
|
|
6
|
+
* 1. **Phase order is behavior** (§5 G5). `PHASES` is the order; the report
|
|
7
|
+
* echoes the order actually executed so an assertion can compare them.
|
|
8
|
+
* 2. **Completion markers make a crash resumable** (§5 G4). A marker advances
|
|
9
|
+
* only after the work AND its persist succeed, and only forward. A cycle
|
|
10
|
+
* killed mid-phase leaves earlier markers advanced and the killed phase's
|
|
11
|
+
* marker where it was, so the rerun neither redoes nor skips.
|
|
12
|
+
* 3. **A budget is not a debt** (§3, v1 §5 G4). Per-phase budgets cap effort;
|
|
13
|
+
* the marker still advances when a budget truncates a phase, and
|
|
14
|
+
* `skippedForBudget` is reported rather than carried as arrears.
|
|
15
|
+
* 4. **Degrade, don't abort** (§5 G6). A phase that throws is caught, recorded
|
|
16
|
+
* as `failed` with its code, and the cycle continues — with its marker NOT
|
|
17
|
+
* advanced, so the work is retried on the next lived day. The one exception
|
|
18
|
+
* is `CycleKilled`, which is a process kill wearing an exception's clothes
|
|
19
|
+
* and must not be papered over.
|
|
20
|
+
* 5. **An observer runs the whole cycle as a read-only report** (§5 G10, scar
|
|
21
|
+
* E7). Every phase computes; `ctx.apply` is false, so not one `WRITE_METHOD`
|
|
22
|
+
* is called — the report is produced without a single stand-down, because
|
|
23
|
+
* nothing was ever attempted. The spawner's own answer is separate and
|
|
24
|
+
* blunter: `shouldSpawn()` says no.
|
|
25
|
+
*
|
|
26
|
+
* ZERO GENERATIVE MODEL CALLS. There is no client, no fetch, no network import
|
|
27
|
+
* anywhere in this module, and a test scans the source to say so.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import type { Kind } from "../types.js";
|
|
31
|
+
import { TUNABLES as PHYSICS, symmetryCheck } from "../physics/index.js";
|
|
32
|
+
import { runBriefing } from "./briefing.js";
|
|
33
|
+
import type { RenderFn } from "./briefing.js";
|
|
34
|
+
import { runConsolidate } from "./consolidate.js";
|
|
35
|
+
import { runDecay } from "./decay.js";
|
|
36
|
+
import { runDedup } from "./dedup.js";
|
|
37
|
+
import type { DedupCandidateSource } from "./dedup.js";
|
|
38
|
+
import { runLogSweep } from "./log.js";
|
|
39
|
+
import { advanceMarker, budgetFor, cadenceFor, markerDue, readMarker } from "./markers.js";
|
|
40
|
+
import { runPrune } from "./prune.js";
|
|
41
|
+
import { sqliteStrengthCache, storeRankingCache, supportsRanking } from "./strength-cache.js";
|
|
42
|
+
import type { StrengthCache } from "./strength-cache.js";
|
|
43
|
+
import { shouldSpawn } from "./tunables.js";
|
|
44
|
+
import { isJournal } from "./types.js";
|
|
45
|
+
import type {
|
|
46
|
+
BandTransition,
|
|
47
|
+
CycleReport,
|
|
48
|
+
CycleStep,
|
|
49
|
+
KindCensus,
|
|
50
|
+
MergeRecord,
|
|
51
|
+
Phase,
|
|
52
|
+
PhaseCtx,
|
|
53
|
+
PhaseOutcome,
|
|
54
|
+
PhaseReason,
|
|
55
|
+
PhaseReport,
|
|
56
|
+
PromotionRecord,
|
|
57
|
+
PrunedRecord,
|
|
58
|
+
SleepEvent,
|
|
59
|
+
SleepStore,
|
|
60
|
+
StepStage,
|
|
61
|
+
SymmetryCheck,
|
|
62
|
+
} from "./types.js";
|
|
63
|
+
import { BAND_TRANSITION_EVENT, CycleKilled, PHASES, attachCyclePartial, emptyOutcome } from "./types.js";
|
|
64
|
+
|
|
65
|
+
export interface SleepOptions {
|
|
66
|
+
store: SleepStore;
|
|
67
|
+
/** The calendar date this cycle belongs to. Defaults to today, UTC-dated. */
|
|
68
|
+
date?: string;
|
|
69
|
+
/** `self/`'s briefing render. Absent ⇒ the phase reports `no-render-fn`. */
|
|
70
|
+
render?: RenderFn;
|
|
71
|
+
/**
|
|
72
|
+
* The host's reported injection ceiling, passed to the renderer untouched
|
|
73
|
+
* (SEAMS item G). It joins the cycle options rather than being closed over at
|
|
74
|
+
* the call site so that a wrong number is a visible ARGUMENT, not a constant
|
|
75
|
+
* hidden in a lambda between a host's real cliff and the render (scar §2.18).
|
|
76
|
+
*/
|
|
77
|
+
budgetBytes?: number;
|
|
78
|
+
/** Injected ranking cache. Absent ⇒ the box-3 SQLite one, opened lazily. */
|
|
79
|
+
strengthCache?: StrengthCache;
|
|
80
|
+
/** Extra dedup candidates (embeddings). Isolated: a throw degrades to lexical. */
|
|
81
|
+
candidates?: DedupCandidateSource;
|
|
82
|
+
budgets?: Partial<Record<Phase, number>>;
|
|
83
|
+
cadence?: Partial<Record<Phase, number>>;
|
|
84
|
+
onEvent?: (event: SleepEvent) => void;
|
|
85
|
+
/**
|
|
86
|
+
* Per-step telemetry, and the crash seam. Throwing `CycleKilled` from here
|
|
87
|
+
* simulates the watchdog's hard kill at a chosen point in a chosen phase.
|
|
88
|
+
*/
|
|
89
|
+
onStep?: (step: CycleStep) => void;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const EVENT_RING = 500;
|
|
93
|
+
|
|
94
|
+
/** UTC calendar date. The lived-day mapping is the store's, not this module's. */
|
|
95
|
+
export function todayDate(): string {
|
|
96
|
+
return new Date().toISOString().slice(0, 10);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function runCycle(opts: SleepOptions): CycleReport {
|
|
100
|
+
const { store } = opts;
|
|
101
|
+
const observer = store.observer;
|
|
102
|
+
const apply = !observer;
|
|
103
|
+
const date = opts.date ?? todayDate();
|
|
104
|
+
|
|
105
|
+
const events: SleepEvent[] = [];
|
|
106
|
+
const emit = (
|
|
107
|
+
name: string,
|
|
108
|
+
ref?: string,
|
|
109
|
+
data?: Record<string, string | number | boolean | null>,
|
|
110
|
+
): void => {
|
|
111
|
+
const event: SleepEvent = {
|
|
112
|
+
at: Date.now(),
|
|
113
|
+
name,
|
|
114
|
+
...(ref !== undefined ? { ref } : {}),
|
|
115
|
+
...(data !== undefined ? { data } : {}),
|
|
116
|
+
};
|
|
117
|
+
events.push(event);
|
|
118
|
+
if (events.length > EVENT_RING) events.shift();
|
|
119
|
+
opts.onEvent?.(event);
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const step = (phase: Phase, stage: StepStage, detail?: { index?: number; id?: string }): void => {
|
|
123
|
+
opts.onStep?.({ phase, stage, ...detail });
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const reports: PhaseReport[] = [];
|
|
127
|
+
const order: Phase[] = [];
|
|
128
|
+
const promoted: PromotionRecord[] = [];
|
|
129
|
+
const pruned: PrunedRecord[] = [];
|
|
130
|
+
const merged: MergeRecord[] = [];
|
|
131
|
+
const bandTransitions: BandTransition[] = [];
|
|
132
|
+
|
|
133
|
+
// The ranking cache is opened LAZILY by the decay phase, and never at all
|
|
134
|
+
// under observer: a created file is a mutation.
|
|
135
|
+
const injectedCache = opts.strengthCache;
|
|
136
|
+
// SEAMS item J: box 3's own `ranking` table, through the store's connection, is
|
|
137
|
+
// the default wherever the port implements it; the side file remains only for a
|
|
138
|
+
// store-shaped port that does not.
|
|
139
|
+
const cache: StrengthCache | null = observer
|
|
140
|
+
? null
|
|
141
|
+
: (injectedCache ?? (supportsRanking(store) ? storeRankingCache(store) : sqliteStrengthCache(store.dir)));
|
|
142
|
+
|
|
143
|
+
emit("sleep.cycle.start", undefined, { date, observer, spawn: shouldSpawn(store).reason });
|
|
144
|
+
|
|
145
|
+
try {
|
|
146
|
+
// ── phase 1: the clock ────────────────────────────────────────────────
|
|
147
|
+
const day = runClock();
|
|
148
|
+
|
|
149
|
+
const ctxFor = (phase: Phase, budget: number): PhaseCtx => ({
|
|
150
|
+
store,
|
|
151
|
+
day,
|
|
152
|
+
apply,
|
|
153
|
+
budget,
|
|
154
|
+
step: (stage, detail) => step(phase, stage, detail),
|
|
155
|
+
event: emit,
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* One phase, with its marker gate, its budget, its degrade-don't-abort
|
|
160
|
+
* wrapper, and its three-way outcome vocabulary.
|
|
161
|
+
*/
|
|
162
|
+
const runPhase = <T extends PhaseOutcome>(
|
|
163
|
+
phase: Phase,
|
|
164
|
+
body: (ctx: PhaseCtx) => T,
|
|
165
|
+
collect?: (result: T) => void,
|
|
166
|
+
precheck?: () => PhaseReason | null,
|
|
167
|
+
): void => {
|
|
168
|
+
const before = readMarker(store, phase);
|
|
169
|
+
if (before.health === "torn") {
|
|
170
|
+
// A torn marker is LOUD (§3, v1 §11 G9) and repairs forward only.
|
|
171
|
+
emit("sleep.marker.torn", undefined, { phase, raw: before.raw ?? "" });
|
|
172
|
+
}
|
|
173
|
+
const budget = budgetFor(phase, opts.budgets);
|
|
174
|
+
const skeleton = { phase, budget, markerBefore: before.day, markerAfter: before.day };
|
|
175
|
+
const idle = (reason: PhaseReason): PhaseReport => ({
|
|
176
|
+
...skeleton,
|
|
177
|
+
status: "did-not-run",
|
|
178
|
+
reason,
|
|
179
|
+
examined: 0,
|
|
180
|
+
changed: 0,
|
|
181
|
+
skipped: {},
|
|
182
|
+
budgetExhausted: false,
|
|
183
|
+
skippedForBudget: 0,
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
order.push(phase);
|
|
187
|
+
step(phase, "start");
|
|
188
|
+
|
|
189
|
+
const blocked = precheck?.() ?? null;
|
|
190
|
+
if (blocked !== null) {
|
|
191
|
+
reports.push(idle(blocked));
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (!observer) {
|
|
195
|
+
const due = markerDue(before.day, day, cadenceFor(phase, opts.cadence));
|
|
196
|
+
if (due !== "due") {
|
|
197
|
+
reports.push(idle(due));
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
let result: T;
|
|
203
|
+
try {
|
|
204
|
+
result = body(ctxFor(phase, budget));
|
|
205
|
+
} catch (err) {
|
|
206
|
+
if (err instanceof CycleKilled) throw err;
|
|
207
|
+
// Degrade, don't abort. The marker stays put, so the next lived day
|
|
208
|
+
// retries this phase rather than skipping it forever.
|
|
209
|
+
const code = errorCode(err);
|
|
210
|
+
emit("sleep.phase.failed", undefined, { phase, error: code });
|
|
211
|
+
reports.push({
|
|
212
|
+
...skeleton,
|
|
213
|
+
status: "failed",
|
|
214
|
+
reason: "failed",
|
|
215
|
+
examined: 0,
|
|
216
|
+
changed: 0,
|
|
217
|
+
skipped: {},
|
|
218
|
+
budgetExhausted: false,
|
|
219
|
+
skippedForBudget: 0,
|
|
220
|
+
error: code,
|
|
221
|
+
});
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
collect?.(result);
|
|
225
|
+
|
|
226
|
+
const shape = {
|
|
227
|
+
examined: result.examined,
|
|
228
|
+
changed: result.changed,
|
|
229
|
+
skipped: result.skipped,
|
|
230
|
+
budgetExhausted: result.budgetExhausted,
|
|
231
|
+
skippedForBudget: result.skippedForBudget,
|
|
232
|
+
// Present only where the phase set it (the decay pass, U8). Copied like
|
|
233
|
+
// every other number here — this function invents no verdict.
|
|
234
|
+
...(result.reconciled === undefined ? {} : { reconciled: result.reconciled }),
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
if (observer) {
|
|
238
|
+
// Nothing ran and nothing advanced; `changed` is the count that WOULD
|
|
239
|
+
// have changed, and `status` keeps that from being misread as work.
|
|
240
|
+
reports.push({ ...skeleton, status: "did-not-run", reason: "observer-report", ...shape });
|
|
241
|
+
emit("sleep.observer.report", undefined, { phase, would: result.changed });
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
step(phase, "work-done");
|
|
246
|
+
// The marker advances AFTER the work and its persist, both of which are
|
|
247
|
+
// complete by the time `body` returns — every phase persists as it goes.
|
|
248
|
+
// A budget-truncated phase still advances: a budget is not a debt.
|
|
249
|
+
const after = advanceMarker(store, phase, day);
|
|
250
|
+
step(phase, "marked");
|
|
251
|
+
reports.push({
|
|
252
|
+
...skeleton,
|
|
253
|
+
markerAfter: after,
|
|
254
|
+
status: result.changed > 0 ? "ran" : "ran-nothing-found",
|
|
255
|
+
reason: result.changed > 0 ? "completed" : "nothing-to-do",
|
|
256
|
+
...shape,
|
|
257
|
+
});
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
// ── phase 2: the decay tick ───────────────────────────────────────────
|
|
261
|
+
runPhase(
|
|
262
|
+
"decay",
|
|
263
|
+
(ctx) => runDecay(ctx, cache),
|
|
264
|
+
(r) => {
|
|
265
|
+
bandTransitions.push(...r.transitions);
|
|
266
|
+
},
|
|
267
|
+
);
|
|
268
|
+
|
|
269
|
+
// ── phase 3: consolidation marking + the identity crossing ────────────
|
|
270
|
+
runPhase(
|
|
271
|
+
"consolidate",
|
|
272
|
+
(ctx) => runConsolidate(ctx),
|
|
273
|
+
(r) => {
|
|
274
|
+
promoted.push(...r.promoted);
|
|
275
|
+
},
|
|
276
|
+
);
|
|
277
|
+
|
|
278
|
+
// ── phase 4: the floor prune (archival) ───────────────────────────────
|
|
279
|
+
runPhase(
|
|
280
|
+
"prune",
|
|
281
|
+
(ctx) => runPrune(ctx),
|
|
282
|
+
(r) => {
|
|
283
|
+
pruned.push(...r.pruned);
|
|
284
|
+
},
|
|
285
|
+
);
|
|
286
|
+
|
|
287
|
+
// ── phase 5: dedup ────────────────────────────────────────────────────
|
|
288
|
+
runPhase(
|
|
289
|
+
"dedup",
|
|
290
|
+
(ctx) => runDedup(ctx, opts.candidates),
|
|
291
|
+
(r) => {
|
|
292
|
+
merged.push(...r.merged);
|
|
293
|
+
},
|
|
294
|
+
);
|
|
295
|
+
|
|
296
|
+
// ── phase 6: version retention past H ─────────────────────────────────
|
|
297
|
+
runPhase("versions", (ctx) => {
|
|
298
|
+
const out = emptyOutcome();
|
|
299
|
+
if (!ctx.apply) {
|
|
300
|
+
out.skipped["observer-report"] = 1;
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
const report = store.pruneSupersededVersions();
|
|
304
|
+
out.examined = report.pruned;
|
|
305
|
+
out.changed = report.pruned;
|
|
306
|
+
emit("sleep.versions.pruned", undefined, {
|
|
307
|
+
count: report.pruned,
|
|
308
|
+
cutoffDay: report.cutoffDay,
|
|
309
|
+
retentionDays: report.retentionDays,
|
|
310
|
+
});
|
|
311
|
+
return out;
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
// ── phase 7: the wake briefing — the LAST content write ───────────────
|
|
315
|
+
runPhase(
|
|
316
|
+
"briefing",
|
|
317
|
+
(ctx) => runBriefing(ctx, opts.render, opts.budgetBytes),
|
|
318
|
+
undefined,
|
|
319
|
+
() => (opts.render === undefined ? "no-render-fn" : null),
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
// ── phase 8: the log sweep — bounded retention on the durable log ─────
|
|
323
|
+
// LAST, and deliberately after the briefing: it deletes telemetry rows
|
|
324
|
+
// past the store's window and writes no content, so §3's "the briefing is
|
|
325
|
+
// the last content write" holds with it here. `BUDGETS.log` is the per-pass
|
|
326
|
+
// cap — a backlog is taken a cap's worth a day, never all at once. A port
|
|
327
|
+
// with no durable log has nothing to sweep and says so by name.
|
|
328
|
+
runPhase(
|
|
329
|
+
"log",
|
|
330
|
+
(ctx) => runLogSweep(ctx),
|
|
331
|
+
undefined,
|
|
332
|
+
() =>
|
|
333
|
+
store.pruneEvents === undefined || store.eventLogCensus === undefined
|
|
334
|
+
? "no-durable-event-log"
|
|
335
|
+
: null,
|
|
336
|
+
);
|
|
337
|
+
|
|
338
|
+
// ── the tripwire, at cycle end (physics guarantee 12, scar §2.10) ─────
|
|
339
|
+
const symmetry = symmetryVerdicts(store, day, emit);
|
|
340
|
+
|
|
341
|
+
const report: CycleReport = {
|
|
342
|
+
day,
|
|
343
|
+
date,
|
|
344
|
+
observer,
|
|
345
|
+
order,
|
|
346
|
+
phases: reports,
|
|
347
|
+
promoted,
|
|
348
|
+
pruned,
|
|
349
|
+
merged,
|
|
350
|
+
bandTransitions,
|
|
351
|
+
symmetry,
|
|
352
|
+
census: census(store, day, pruned, merged),
|
|
353
|
+
events,
|
|
354
|
+
};
|
|
355
|
+
emit("sleep.cycle.done", undefined, {
|
|
356
|
+
day,
|
|
357
|
+
phases: reports.length,
|
|
358
|
+
promoted: promoted.length,
|
|
359
|
+
pruned: pruned.length,
|
|
360
|
+
merged: merged.length,
|
|
361
|
+
bandUp: bandTransitions.filter((t) => t.direction === "up").length,
|
|
362
|
+
bandDown: bandTransitions.filter((t) => t.direction === "down").length,
|
|
363
|
+
failed: reports.filter((p) => p.status === "failed").length,
|
|
364
|
+
});
|
|
365
|
+
return report;
|
|
366
|
+
} catch (err) {
|
|
367
|
+
// A CYCLE THAT DIES CARRIES ITS WORK OUT WITH IT (see `CyclePartial`).
|
|
368
|
+
// Degrade-don't-abort already covers a phase body that throws; what escapes
|
|
369
|
+
// here threw from OUTSIDE one — a marker advance, the clock, `onStep`'s hard
|
|
370
|
+
// kill — and the caller is left with an exception and no report. Without
|
|
371
|
+
// this, a recorder reading that exception writes a row of zeroes over a
|
|
372
|
+
// night in which seven phases ran, which is a fabricated zero (scar §2.4)
|
|
373
|
+
// arriving through a throw. Attaching cannot itself throw.
|
|
374
|
+
attachCyclePartial(err, {
|
|
375
|
+
phases: [...reports],
|
|
376
|
+
order: [...order],
|
|
377
|
+
...(err instanceof CycleKilled ? { phase: err.phase, stage: err.stage } : {}),
|
|
378
|
+
});
|
|
379
|
+
throw err;
|
|
380
|
+
} finally {
|
|
381
|
+
// Only a cache this cycle created is this cycle's to close.
|
|
382
|
+
if (injectedCache === undefined) cache?.close();
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// ── the clock phase, inline: it produces the day everything else gates on ──
|
|
386
|
+
function runClock(): number {
|
|
387
|
+
const phase: Phase = "clock";
|
|
388
|
+
const before = readMarker(store, phase);
|
|
389
|
+
const budget = budgetFor(phase, opts.budgets);
|
|
390
|
+
const skeleton = { phase, budget, markerBefore: before.day, markerAfter: before.day };
|
|
391
|
+
order.push(phase);
|
|
392
|
+
step(phase, "start");
|
|
393
|
+
|
|
394
|
+
if (observer) {
|
|
395
|
+
reports.push({
|
|
396
|
+
...skeleton,
|
|
397
|
+
status: "did-not-run",
|
|
398
|
+
reason: "observer-report",
|
|
399
|
+
examined: 0,
|
|
400
|
+
changed: 0,
|
|
401
|
+
skipped: { "observer-report": 1 },
|
|
402
|
+
budgetExhausted: false,
|
|
403
|
+
skippedForBudget: 0,
|
|
404
|
+
});
|
|
405
|
+
return store.livedDay();
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const wasDay = store.livedDay();
|
|
409
|
+
let day: number;
|
|
410
|
+
try {
|
|
411
|
+
day = store.advanceClock(date);
|
|
412
|
+
} catch (err) {
|
|
413
|
+
if (err instanceof CycleKilled) throw err;
|
|
414
|
+
// A torn clock is LOUD and repair moves FORWARD ONLY: a backwards date is
|
|
415
|
+
// refused by the store, and the cycle continues on the day the store
|
|
416
|
+
// already believes in rather than retro-running history.
|
|
417
|
+
const code = errorCode(err);
|
|
418
|
+
emit("sleep.clock.failed", undefined, { date, error: code });
|
|
419
|
+
reports.push({
|
|
420
|
+
...skeleton,
|
|
421
|
+
status: "failed",
|
|
422
|
+
reason: "failed",
|
|
423
|
+
examined: 0,
|
|
424
|
+
changed: 0,
|
|
425
|
+
skipped: {},
|
|
426
|
+
budgetExhausted: false,
|
|
427
|
+
skippedForBudget: 0,
|
|
428
|
+
error: code,
|
|
429
|
+
});
|
|
430
|
+
return wasDay;
|
|
431
|
+
}
|
|
432
|
+
step(phase, "work-done");
|
|
433
|
+
const after = advanceMarker(store, phase, day);
|
|
434
|
+
step(phase, "marked");
|
|
435
|
+
const advanced = day > wasDay;
|
|
436
|
+
reports.push({
|
|
437
|
+
...skeleton,
|
|
438
|
+
markerAfter: after,
|
|
439
|
+
status: advanced ? "ran" : "ran-nothing-found",
|
|
440
|
+
reason: advanced ? "completed" : "nothing-to-do",
|
|
441
|
+
examined: 1,
|
|
442
|
+
changed: advanced ? 1 : 0,
|
|
443
|
+
skipped: advanced ? {} : { "same-lived-day": 1 },
|
|
444
|
+
budgetExhausted: false,
|
|
445
|
+
skippedForBudget: 0,
|
|
446
|
+
});
|
|
447
|
+
return day;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* No ceiling worth naming: the WHOLE transition history is the sample. v1's
|
|
453
|
+
* ratchet ran 279:0 across three days and `SYMMETRY_MIN_SAMPLE` is 20 moves, so
|
|
454
|
+
* a one-cycle window would answer `never-asked` forever — which is the shape of
|
|
455
|
+
* failure this tripwire was written to end, not one to reproduce.
|
|
456
|
+
*/
|
|
457
|
+
const TRANSITION_LOG_LIMIT = 1_000_000;
|
|
458
|
+
|
|
459
|
+
type Emit = (
|
|
460
|
+
name: string,
|
|
461
|
+
ref?: string,
|
|
462
|
+
data?: Record<string, string | number | boolean | null>,
|
|
463
|
+
) => void;
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* GUARANTEE 12, FED AND CONSUMED — the ratchet tripwire, at cycle end.
|
|
467
|
+
*
|
|
468
|
+
* Up-moves and down-moves per kind, summed over the durable `band.transition`
|
|
469
|
+
* log, handed to `physics.symmetryCheck`, and emitted as a verdict per kind.
|
|
470
|
+
* Physics owns the arithmetic and the expected ratio; this function owns
|
|
471
|
+
* nothing but the summation and the announcement.
|
|
472
|
+
*
|
|
473
|
+
* TWO THINGS THAT MUST NOT BE SMOOTHED OVER, both scar §2.4:
|
|
474
|
+
*
|
|
475
|
+
* - Below the minimum sample the verdict is `never-asked`, and it carries
|
|
476
|
+
* `ok: true`. Anything reading `ok` alone reads a starved counter as
|
|
477
|
+
* health. Every event below leads with `reason`.
|
|
478
|
+
* - A store with no event log has not asked the question at all, and gets NO
|
|
479
|
+
* verdicts plus a loud `sleep.symmetry.unavailable` — six `never-asked`
|
|
480
|
+
* rows would claim a counter was consulted when none exists.
|
|
481
|
+
*
|
|
482
|
+
* `ratio` is `Infinity` by design when nothing ever moved down (v1's exact
|
|
483
|
+
* shape) and `JSON.stringify` turns that into `null`, so it is reported only
|
|
484
|
+
* when finite: a null that means infinity is a lie in the log.
|
|
485
|
+
*/
|
|
486
|
+
export function symmetryVerdicts(store: SleepStore, day: number, emit: Emit): SymmetryCheck[] {
|
|
487
|
+
const kinds = Object.keys(PHYSICS.KINDS) as Kind[];
|
|
488
|
+
if (store.eventLog === undefined) {
|
|
489
|
+
emit("sleep.symmetry.unavailable", undefined, { day, reason: "no-durable-event-log" });
|
|
490
|
+
return [];
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const up = new Map<string, number>();
|
|
494
|
+
const down = new Map<string, number>();
|
|
495
|
+
let unreadable = 0;
|
|
496
|
+
for (const row of store.eventLog({
|
|
497
|
+
name: BAND_TRANSITION_EVENT,
|
|
498
|
+
limit: TRANSITION_LOG_LIMIT,
|
|
499
|
+
})) {
|
|
500
|
+
let payload: Record<string, unknown>;
|
|
501
|
+
try {
|
|
502
|
+
payload = JSON.parse(row.payload ?? "") as Record<string, unknown>;
|
|
503
|
+
} catch {
|
|
504
|
+
unreadable += 1;
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
const kind = typeof payload["kind"] === "string" ? payload["kind"] : null;
|
|
508
|
+
const direction = payload["direction"];
|
|
509
|
+
if (kind === null) {
|
|
510
|
+
unreadable += 1;
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
if (direction === "up") up.set(kind, (up.get(kind) ?? 0) + 1);
|
|
514
|
+
else if (direction === "down") down.set(kind, (down.get(kind) ?? 0) + 1);
|
|
515
|
+
else unreadable += 1;
|
|
516
|
+
}
|
|
517
|
+
if (unreadable > 0) {
|
|
518
|
+
// A row the counter could not read is a row the counter did not count.
|
|
519
|
+
emit("sleep.symmetry.unreadable", undefined, { day, rows: unreadable });
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const out: SymmetryCheck[] = [];
|
|
523
|
+
for (const kind of kinds) {
|
|
524
|
+
const verdict = symmetryCheck(kind, {
|
|
525
|
+
up: up.get(kind) ?? 0,
|
|
526
|
+
down: down.get(kind) ?? 0,
|
|
527
|
+
});
|
|
528
|
+
out.push(verdict);
|
|
529
|
+
emit("sleep.symmetry", undefined, {
|
|
530
|
+
day,
|
|
531
|
+
kind: verdict.kind,
|
|
532
|
+
reason: verdict.reason,
|
|
533
|
+
ok: verdict.ok,
|
|
534
|
+
up: verdict.up,
|
|
535
|
+
down: verdict.down,
|
|
536
|
+
ratio: Number.isFinite(verdict.ratio) ? verdict.ratio : null,
|
|
537
|
+
expectedMax: verdict.expectedMax,
|
|
538
|
+
});
|
|
539
|
+
if (!verdict.ok) {
|
|
540
|
+
emit("sleep.symmetry.tripped", undefined, {
|
|
541
|
+
day,
|
|
542
|
+
kind: verdict.kind,
|
|
543
|
+
reason: verdict.reason,
|
|
544
|
+
up: verdict.up,
|
|
545
|
+
down: verdict.down,
|
|
546
|
+
expectedMax: verdict.expectedMax,
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return out;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* §5 G13 / scar §2.17 — created versus exited, per kind, every cycle. A kind
|
|
555
|
+
* with a zero exit count after the bake-in window is a defect to investigate:
|
|
556
|
+
* a curation path that never fires is indistinguishable from one that is broken.
|
|
557
|
+
*/
|
|
558
|
+
export function census(
|
|
559
|
+
store: SleepStore,
|
|
560
|
+
day: number,
|
|
561
|
+
pruned: readonly PrunedRecord[],
|
|
562
|
+
merged: readonly MergeRecord[],
|
|
563
|
+
): Record<Kind, KindCensus> {
|
|
564
|
+
const kinds = Object.keys(PHYSICS.KINDS) as Kind[];
|
|
565
|
+
const created = new Map<Kind, number>();
|
|
566
|
+
const exited = new Map<Kind, number>();
|
|
567
|
+
for (const id of store.list()) {
|
|
568
|
+
const row = store.row(id);
|
|
569
|
+
if (row === undefined) continue;
|
|
570
|
+
// MEMORIES. A chapter written today is not a memory born today, and
|
|
571
|
+
// counting it as one would give every journal kind a permanent
|
|
572
|
+
// created-without-exit imbalance — the exact signal G13 exists to raise
|
|
573
|
+
// (`sleep/types.ts#isJournal`).
|
|
574
|
+
if (isJournal(row)) continue;
|
|
575
|
+
if (row.birth_day === day) created.set(row.kind, (created.get(row.kind) ?? 0) + 1);
|
|
576
|
+
}
|
|
577
|
+
for (const p of pruned) exited.set(p.record.kind, (exited.get(p.record.kind) ?? 0) + 1);
|
|
578
|
+
for (const m of merged) {
|
|
579
|
+
const row = store.row(m.candidateId);
|
|
580
|
+
if (row === undefined) continue;
|
|
581
|
+
exited.set(row.kind, (exited.get(row.kind) ?? 0) + 1);
|
|
582
|
+
}
|
|
583
|
+
const out = {} as Record<Kind, KindCensus>;
|
|
584
|
+
for (const kind of kinds) {
|
|
585
|
+
out[kind] = { created: created.get(kind) ?? 0, exited: exited.get(kind) ?? 0 };
|
|
586
|
+
}
|
|
587
|
+
return out;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function errorCode(err: unknown): string {
|
|
591
|
+
if (err !== null && typeof err === "object" && "code" in err) {
|
|
592
|
+
return String((err as { code: unknown }).code);
|
|
593
|
+
}
|
|
594
|
+
return err instanceof Error ? err.name : "UNKNOWN";
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
export { PHASES };
|
|
598
|
+
export type { Phase, PhaseReport, CycleReport };
|