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,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `sleep/` — systems consolidation: pure math on a cycle.
|
|
3
|
+
*
|
|
4
|
+
* The librarian. It advances the lived-day clock, materializes strength into the
|
|
5
|
+
* ranking cache, marks consolidation and executes the identity crossing, prunes
|
|
6
|
+
* at the floor (archivally), dedups, expires superseded-version rows, re-renders
|
|
7
|
+
* the wake briefing (the last CONTENT write), and finally sweeps the durable
|
|
8
|
+
* event log past its retention window — bounded per pass, latched records kept
|
|
9
|
+
* (CONTRACT §5 G16).
|
|
10
|
+
*
|
|
11
|
+
* **Zero generative model calls, asserted by a test over this module's sources**
|
|
12
|
+
* (CONTRACT §5 G1). Embedding lookups are permitted arithmetic and arrive
|
|
13
|
+
* INJECTED, isolated, and degrading to lexical — never as a dependency of this
|
|
14
|
+
* module.
|
|
15
|
+
*
|
|
16
|
+
* What this module deliberately does NOT contain, and why:
|
|
17
|
+
*
|
|
18
|
+
* - **The lock, the watchdog, and detachment** (§3, scars E4/E5). Those belong
|
|
19
|
+
* to the adapter that spawns the cycle; the cross-key configuration
|
|
20
|
+
* invariant that binds them is here, as `validateWatchdog`, because it is
|
|
21
|
+
* arithmetic. INTERFACE-GAPS.md §6.
|
|
22
|
+
* - **The briefing itself.** `self/` owns it. Sleep owns only that it is last.
|
|
23
|
+
* - **Any import from `../self/`.** A test asserts the absence.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export { runCycle, todayDate, census } from "./cycle.js";
|
|
27
|
+
export type { SleepOptions } from "./cycle.js";
|
|
28
|
+
|
|
29
|
+
export {
|
|
30
|
+
CURSOR_PREFIX,
|
|
31
|
+
MARKER_PREFIX,
|
|
32
|
+
MARKER_UNSET,
|
|
33
|
+
MERGE_ARCHIVE_REASON,
|
|
34
|
+
MERGE_RECORD_PREFIX,
|
|
35
|
+
PROMOTION_RECORD_PREFIX,
|
|
36
|
+
PRUNE_ARCHIVE_REASON,
|
|
37
|
+
PRUNE_RECORD_PREFIX,
|
|
38
|
+
TUNABLES,
|
|
39
|
+
shouldSpawn,
|
|
40
|
+
validateWatchdog,
|
|
41
|
+
} from "./tunables.js";
|
|
42
|
+
export type { SpawnReason, WatchdogReason } from "./tunables.js";
|
|
43
|
+
|
|
44
|
+
export {
|
|
45
|
+
advanceMarker,
|
|
46
|
+
budgetFor,
|
|
47
|
+
cadenceFor,
|
|
48
|
+
cursorKey,
|
|
49
|
+
initializeMarkers,
|
|
50
|
+
markerDue,
|
|
51
|
+
markerKey,
|
|
52
|
+
readCursor,
|
|
53
|
+
readMarker,
|
|
54
|
+
resumeIndex,
|
|
55
|
+
writeCursor,
|
|
56
|
+
} from "./markers.js";
|
|
57
|
+
export type { DueVerdict, MarkerHealth, MarkerRead } from "./markers.js";
|
|
58
|
+
|
|
59
|
+
export {
|
|
60
|
+
STRENGTH_CACHE_FILE,
|
|
61
|
+
memoryStrengthCache,
|
|
62
|
+
sqliteStrengthCache,
|
|
63
|
+
storeRankingCache,
|
|
64
|
+
supportsRanking,
|
|
65
|
+
strengthCachePath,
|
|
66
|
+
} from "./strength-cache.js";
|
|
67
|
+
export type { StrengthCache, StrengthRow } from "./strength-cache.js";
|
|
68
|
+
|
|
69
|
+
export { DECAY_SKIPS, runDecay } from "./decay.js";
|
|
70
|
+
export type { DecayResult, DecaySkip } from "./decay.js";
|
|
71
|
+
|
|
72
|
+
export { CONSOLIDATION_SKIPS, promotionRecordKey, runConsolidate } from "./consolidate.js";
|
|
73
|
+
export type { ConsolidateResult, ConsolidationSkip } from "./consolidate.js";
|
|
74
|
+
|
|
75
|
+
export { inLiveRevisionChain, pruneRecordKey, runPrune } from "./prune.js";
|
|
76
|
+
export type { PruneResult } from "./prune.js";
|
|
77
|
+
|
|
78
|
+
export {
|
|
79
|
+
contentHashCandidates,
|
|
80
|
+
declaredUpdates,
|
|
81
|
+
mergeRecordKey,
|
|
82
|
+
revisionSuccessorOf,
|
|
83
|
+
revisionSuccessorPair,
|
|
84
|
+
runDedup,
|
|
85
|
+
} from "./dedup.js";
|
|
86
|
+
export type { DedupCandidateInput, DedupCandidateSource, DedupPair, DedupResult } from "./dedup.js";
|
|
87
|
+
|
|
88
|
+
export { runBriefing } from "./briefing.js";
|
|
89
|
+
export type { BriefingContext, BriefingOutcome, BriefingResult, RenderFn } from "./briefing.js";
|
|
90
|
+
|
|
91
|
+
export { LOG_SWEEP_EVENT, LOG_SWEEP_SKIPS, runLogSweep } from "./log.js";
|
|
92
|
+
export type { LogSweepResult, LogSweepSkip } from "./log.js";
|
|
93
|
+
|
|
94
|
+
export { BAND_TRANSITION_EVENT, BAND_TRANSITION_FIELDS, CycleKilled, PHASES, attachCyclePartial, countSkip, cyclePartial, emptyOutcome, isJournal, isSchemaRow, phaseReport } from "./types.js";
|
|
95
|
+
export type {
|
|
96
|
+
CyclePartial,
|
|
97
|
+
CycleReport,
|
|
98
|
+
CycleStep,
|
|
99
|
+
KindCensus,
|
|
100
|
+
MergeRecord,
|
|
101
|
+
Phase,
|
|
102
|
+
PhaseCtx,
|
|
103
|
+
PhaseOutcome,
|
|
104
|
+
PhaseReason,
|
|
105
|
+
PhaseReport,
|
|
106
|
+
PhaseStatus,
|
|
107
|
+
PromotionRecord,
|
|
108
|
+
PrunedRecord,
|
|
109
|
+
SleepEvent,
|
|
110
|
+
SleepStore,
|
|
111
|
+
StepStage,
|
|
112
|
+
} from "./types.js";
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The log sweep — bounded retention on the durable event log, the cycle's
|
|
3
|
+
* LAST phase (CONTRACT §5 G16).
|
|
4
|
+
*
|
|
5
|
+
* `Store.pruneEvents()` existed, documented a 90-lived-day window, and had no
|
|
6
|
+
* caller anywhere in `src/` (NOTES.md §13): every unlatched row ever written —
|
|
7
|
+
* one `recall.decision` per turn, one `gate.deposit` per authored deposit, the
|
|
8
|
+
* adapter's per-hook rows — was still there, and the dashboard's "I keep events
|
|
9
|
+
* for N lived days; older ones are swept" was a sentence about a sweep that
|
|
10
|
+
* never ran. This phase is the caller.
|
|
11
|
+
*
|
|
12
|
+
* Three decisions, each of which is a test:
|
|
13
|
+
*
|
|
14
|
+
* 1. **It is its own phase, not a line in `prune`.** The floor prune forgets
|
|
15
|
+
* MEMORIES; this drops TELEMETRY. One budget doing half of each would make
|
|
16
|
+
* "what the cycle forgot" and "what the log dropped" one number, and the
|
|
17
|
+
* created-versus-exited census (§5 G13) reads the first.
|
|
18
|
+
* 2. **Bounded per pass, oldest first.** `ctx.budget` (`TUNABLES.BUDGETS.log`)
|
|
19
|
+
* caps the rows one pass deletes. A store swept for the first time takes
|
|
20
|
+
* its backlog a cap's worth a day; the rest is `skippedForBudget`, reported
|
|
21
|
+
* and never owed (§3: a budget is not a debt).
|
|
22
|
+
* 3. **Kept by kind is a NUMBER.** Every record the store latches with a
|
|
23
|
+
* `dedup_key` — prune, promotion, merge, unmerge, pressure, gate-chunk,
|
|
24
|
+
* band-transition — is kept at any age by the store, not by a list here.
|
|
25
|
+
* Rows past the window that the latch kept are counted in `skipped.latched`
|
|
26
|
+
* so the report can say how many, rather than a reader inferring it.
|
|
27
|
+
*
|
|
28
|
+
* Under observer (`ctx.apply === false`) the phase reads the census and reports
|
|
29
|
+
* the count that WOULD go; it never calls `pruneEvents`, so the read-only report
|
|
30
|
+
* produces zero stand-downs — nothing was attempted (observer-mode.md G4).
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import type { PhaseCtx, PhaseOutcome } from "./types.js";
|
|
34
|
+
import { countSkip, emptyOutcome } from "./types.js";
|
|
35
|
+
|
|
36
|
+
/** Emitted once per applied sweep, counts only — never a payload's contents. */
|
|
37
|
+
export const LOG_SWEEP_EVENT = "sleep.log.swept";
|
|
38
|
+
|
|
39
|
+
/** The one named skip: rows past the window kept because a latch holds them. */
|
|
40
|
+
export const LOG_SWEEP_SKIPS = ["latched"] as const;
|
|
41
|
+
export type LogSweepSkip = (typeof LOG_SWEEP_SKIPS)[number];
|
|
42
|
+
|
|
43
|
+
export interface LogSweepResult extends PhaseOutcome {
|
|
44
|
+
/** Unlatched rows past the window when the sweep began. */
|
|
45
|
+
readonly eligible: number;
|
|
46
|
+
/** Rows actually deleted this pass. Zero under observer; `changed` then carries the would-count. */
|
|
47
|
+
readonly deleted: number;
|
|
48
|
+
/** Eligible rows the cap left for the next pass. Zero means the window is clean. */
|
|
49
|
+
readonly remaining: number;
|
|
50
|
+
/** Latched rows past the window — kept by kind, and said so. */
|
|
51
|
+
readonly keptLatched: number;
|
|
52
|
+
readonly cutoffDay: number;
|
|
53
|
+
readonly retentionDays: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function runLogSweep(ctx: PhaseCtx): LogSweepResult {
|
|
57
|
+
const { store } = ctx;
|
|
58
|
+
// `cycle.ts` prechecks both and reports `no-durable-event-log` when either is
|
|
59
|
+
// absent; reaching here without them is a programming error, and a thrown
|
|
60
|
+
// phase (marker unmoved, retried tomorrow) is the honest record of one.
|
|
61
|
+
if (store.pruneEvents === undefined || store.eventLogCensus === undefined) {
|
|
62
|
+
throw Object.assign(new Error("log sweep on a port with no durable event log"), {
|
|
63
|
+
code: "NO_DURABLE_EVENT_LOG",
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const out = emptyOutcome();
|
|
68
|
+
// The census FIRST, on both paths: it is the only source of the kept-by-kind
|
|
69
|
+
// count, and reading it before the delete means `examined` describes the
|
|
70
|
+
// window as the phase found it.
|
|
71
|
+
const census = store.eventLogCensus();
|
|
72
|
+
const keptLatched = census.latchedPastCutoff;
|
|
73
|
+
if (keptLatched > 0) countSkip(out, "latched" satisfies LogSweepSkip, keptLatched);
|
|
74
|
+
|
|
75
|
+
if (!ctx.apply) {
|
|
76
|
+
const would = Math.min(census.eligible, ctx.budget);
|
|
77
|
+
out.examined = census.eligible + keptLatched;
|
|
78
|
+
out.changed = would;
|
|
79
|
+
out.skippedForBudget = census.eligible - would;
|
|
80
|
+
out.budgetExhausted = out.skippedForBudget > 0;
|
|
81
|
+
return {
|
|
82
|
+
...out,
|
|
83
|
+
eligible: census.eligible,
|
|
84
|
+
deleted: 0,
|
|
85
|
+
remaining: census.eligible - would,
|
|
86
|
+
keptLatched,
|
|
87
|
+
cutoffDay: census.cutoffDay,
|
|
88
|
+
retentionDays: census.retentionDays,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const report = store.pruneEvents({ limit: ctx.budget });
|
|
93
|
+
out.examined = report.eligible + keptLatched;
|
|
94
|
+
out.changed = report.pruned;
|
|
95
|
+
out.skippedForBudget = report.remaining;
|
|
96
|
+
out.budgetExhausted = report.remaining > 0;
|
|
97
|
+
ctx.event(LOG_SWEEP_EVENT, undefined, {
|
|
98
|
+
day: ctx.day,
|
|
99
|
+
count: report.pruned,
|
|
100
|
+
eligible: report.eligible,
|
|
101
|
+
remaining: report.remaining,
|
|
102
|
+
keptLatched,
|
|
103
|
+
budget: ctx.budget,
|
|
104
|
+
cutoffDay: report.cutoffDay,
|
|
105
|
+
retentionDays: report.retentionDays,
|
|
106
|
+
});
|
|
107
|
+
return {
|
|
108
|
+
...out,
|
|
109
|
+
eligible: report.eligible,
|
|
110
|
+
deleted: report.pruned,
|
|
111
|
+
remaining: report.remaining,
|
|
112
|
+
keptLatched,
|
|
113
|
+
cutoffDay: report.cutoffDay,
|
|
114
|
+
retentionDays: report.retentionDays,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-concern completion markers — the whole of crash resumption.
|
|
3
|
+
*
|
|
4
|
+
* CONTRACT §3 / §5 G4, v1 §5 G3, scar E8:
|
|
5
|
+
*
|
|
6
|
+
* - A concern gates on **"active day > my marker"**, never on a transient
|
|
7
|
+
* "is this a new day" flag. That is the difference between a crash between
|
|
8
|
+
* the clock ticking and the work finishing replaying its day EXACTLY ONCE,
|
|
9
|
+
* and skipping it forever.
|
|
10
|
+
* - A marker advances only after the work AND its persist both succeed.
|
|
11
|
+
* - Markers only move FORWARD. A torn clock's repair snaps them forward with
|
|
12
|
+
* it, so recovery never retro-runs history.
|
|
13
|
+
*
|
|
14
|
+
* Markers live in box 2 (canonical operational, transactional), one meta row per
|
|
15
|
+
* phase. INTERFACE-GAPS.md §3 asks for a real table; the key/value row is what
|
|
16
|
+
* the seam offers today, and it is transactional, which is the load-bearing part.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { CURSOR_PREFIX, MARKER_PREFIX, MARKER_UNSET, TUNABLES } from "./tunables.js";
|
|
20
|
+
import type { Phase, SleepStore } from "./types.js";
|
|
21
|
+
import { PHASES } from "./types.js";
|
|
22
|
+
|
|
23
|
+
export function markerKey(phase: Phase): string {
|
|
24
|
+
return `${MARKER_PREFIX}${phase}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type MarkerHealth = "unset" | "ok" | "torn";
|
|
28
|
+
|
|
29
|
+
export interface MarkerRead {
|
|
30
|
+
day: number;
|
|
31
|
+
health: MarkerHealth;
|
|
32
|
+
/** The raw stored text when the marker is torn — for the loud event. */
|
|
33
|
+
raw?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A torn marker is LOUD, and repair moves forward only (§3, v1 §11 G9). An
|
|
38
|
+
* unreadable value resolves to `MARKER_UNSET`, which means "due today" — the
|
|
39
|
+
* forward direction. It never resolves to a day in the future, which would
|
|
40
|
+
* silently skip work, and never to a day in the past, which would retro-run it.
|
|
41
|
+
*/
|
|
42
|
+
export function readMarker(store: Pick<SleepStore, "getMeta">, phase: Phase): MarkerRead {
|
|
43
|
+
const raw = store.getMeta(markerKey(phase));
|
|
44
|
+
if (raw === undefined) return { day: MARKER_UNSET, health: "unset" };
|
|
45
|
+
const n = Number(raw);
|
|
46
|
+
if (!Number.isFinite(n) || !Number.isInteger(n) || n < MARKER_UNSET) {
|
|
47
|
+
return { day: MARKER_UNSET, health: "torn", raw };
|
|
48
|
+
}
|
|
49
|
+
return { day: n, health: "ok" };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export type DueVerdict = "due" | "already-done-today" | "not-due-this-cadence";
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The gate. `cadence` lived days must have passed since the marker, and an unset
|
|
56
|
+
* marker is always due — an upgraded store that has never run must run, and a
|
|
57
|
+
* store whose marker is ahead of the clock (a torn clock, repaired forward) must
|
|
58
|
+
* NOT retro-run.
|
|
59
|
+
*/
|
|
60
|
+
export function markerDue(marker: number, day: number, cadence = 1): DueVerdict {
|
|
61
|
+
if (marker === MARKER_UNSET) return "due";
|
|
62
|
+
if (day <= marker) return "already-done-today";
|
|
63
|
+
return day - marker >= cadence ? "due" : "not-due-this-cadence";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Forward-only. An attempt to move a marker backwards is a silent no-op. */
|
|
67
|
+
export function advanceMarker(
|
|
68
|
+
store: Pick<SleepStore, "getMeta" | "setMeta">,
|
|
69
|
+
phase: Phase,
|
|
70
|
+
day: number,
|
|
71
|
+
): number {
|
|
72
|
+
const current = readMarker(store, phase);
|
|
73
|
+
if (current.health === "ok" && day <= current.day) return current.day;
|
|
74
|
+
store.setMeta(markerKey(phase), String(day));
|
|
75
|
+
return day;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* An upgraded store initializes markers to the present (§3, v1 §11 G9): *we
|
|
80
|
+
* record completion, so an upgrade must not retro-run.* Only unset markers are
|
|
81
|
+
* touched; an existing marker is never moved backwards to satisfy this.
|
|
82
|
+
*/
|
|
83
|
+
export function initializeMarkers(
|
|
84
|
+
store: Pick<SleepStore, "getMeta" | "setMeta">,
|
|
85
|
+
day: number,
|
|
86
|
+
): Phase[] {
|
|
87
|
+
const touched: Phase[] = [];
|
|
88
|
+
for (const phase of PHASES) {
|
|
89
|
+
if (readMarker(store, phase).health === "unset") {
|
|
90
|
+
store.setMeta(markerKey(phase), String(day));
|
|
91
|
+
touched.push(phase);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return touched;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ── where a phase stopped, as opposed to when it last ran ───────────────────
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* A phase's RESUME CURSOR: the id of the last row it visited. The marker above
|
|
101
|
+
* says WHEN the phase last ran; this says WHERE it stopped, and the two answer
|
|
102
|
+
* different questions.
|
|
103
|
+
*
|
|
104
|
+
* A budget is still not a debt (§3) — nothing here is owed, and the marker still
|
|
105
|
+
* advances on a truncated phase. What the cursor changes is only the place the
|
|
106
|
+
* next run starts from: without one, a budget smaller than the store means the
|
|
107
|
+
* same head of it is examined every night and the tail never once. Measured on
|
|
108
|
+
* the live store 2026-09-17 (`docs/promotion-diagnosis-2026-09-17.md`): 15,292
|
|
109
|
+
* rows against a consolidate budget of 5,000, and two thirds of the store had
|
|
110
|
+
* never been asked whether it should consolidate or cross into identity.
|
|
111
|
+
*
|
|
112
|
+
* Same seam as the markers — one meta row per phase in box 2, transactional —
|
|
113
|
+
* and the same forward-safety: an unset or unreadable cursor reads as null,
|
|
114
|
+
* which means "start at the head", which is always a legal place to start.
|
|
115
|
+
*/
|
|
116
|
+
export function cursorKey(phase: Phase): string {
|
|
117
|
+
return `${CURSOR_PREFIX}${phase}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function readCursor(store: Pick<SleepStore, "getMeta">, phase: Phase): string | null {
|
|
121
|
+
const raw = store.getMeta(cursorKey(phase));
|
|
122
|
+
return raw === undefined || raw.length === 0 ? null : raw;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function writeCursor(
|
|
126
|
+
store: Pick<SleepStore, "setMeta">,
|
|
127
|
+
phase: Phase,
|
|
128
|
+
id: string,
|
|
129
|
+
): void {
|
|
130
|
+
store.setMeta(cursorKey(phase), id);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The position in an ASCENDING id list to resume at: the first id strictly
|
|
135
|
+
* greater than the cursor.
|
|
136
|
+
*
|
|
137
|
+
* Strictly greater, so no row is re-examined merely because it was the last one
|
|
138
|
+
* of the previous run. The list is `store.list()`'s `ORDER BY id`, which is what
|
|
139
|
+
* makes a cursor mean anything at all. Two cases fall out of the comparison
|
|
140
|
+
* rather than needing their own branch: a cursor whose row has since been
|
|
141
|
+
* deleted, archived out of the filter or renamed lands on the next id that IS
|
|
142
|
+
* still there, and a cursor past the end of the list wraps to the head.
|
|
143
|
+
*/
|
|
144
|
+
export function resumeIndex(ids: readonly string[], cursor: string | null): number {
|
|
145
|
+
if (cursor === null || ids.length === 0) return 0;
|
|
146
|
+
let lo = 0;
|
|
147
|
+
let hi = ids.length;
|
|
148
|
+
while (lo < hi) {
|
|
149
|
+
const mid = (lo + hi) >>> 1;
|
|
150
|
+
if ((ids[mid] as string) <= cursor) lo = mid + 1;
|
|
151
|
+
else hi = mid;
|
|
152
|
+
}
|
|
153
|
+
return lo === ids.length ? 0 : lo;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function cadenceFor(phase: Phase, override?: Partial<Record<Phase, number>>): number {
|
|
157
|
+
const custom = override?.[phase];
|
|
158
|
+
return custom !== undefined && custom > 0 ? custom : TUNABLES.CADENCE[phase];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function budgetFor(phase: Phase, override?: Partial<Record<Phase, number>>): number {
|
|
162
|
+
const custom = override?.[phase];
|
|
163
|
+
return custom !== undefined && custom >= 0 ? custom : TUNABLES.BUDGETS[phase];
|
|
164
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The floor prune — and it is ARCHIVAL, not deletion.
|
|
3
|
+
*
|
|
4
|
+
* `physics.pruneVerdict` alone decides. No model on any path holds this power,
|
|
5
|
+
* and this phase adds no criterion of its own: it supplies the one piece of
|
|
6
|
+
* context physics cannot compute (is this memory in a live revision chain?),
|
|
7
|
+
* applies the verdict absolutely, and records it.
|
|
8
|
+
*
|
|
9
|
+
* **The contract's open question 1, resolved toward archival.** `sleep/CONTRACT.md`
|
|
10
|
+
* §4 called the floor prune "the one place the system deletes" and flagged the
|
|
11
|
+
* question as open; v1's §11 G6 said the opposite in as many words. The answer
|
|
12
|
+
* is archival, and the store settles it structurally: there is no delete, no
|
|
13
|
+
* unlink, no remove anywhere in `store/`, so there is no verb to call. A pruned
|
|
14
|
+
* memory keeps its prose, keeps its id, stays resolvable, and carries
|
|
15
|
+
* `archived_reason = "pruned"`. Fading is not deletion; a strong enough cue can
|
|
16
|
+
* still reach it, and the exit is countable (scar §2.17). See NOTES.md §2.
|
|
17
|
+
*
|
|
18
|
+
* **Record first, move second (§5 G8).** The record is counts, kind, and dates —
|
|
19
|
+
* NEVER a body and NEVER a content hash (scar §2.20; hashing low-entropy content
|
|
20
|
+
* leaks it). A failed record append means NOTHING MOVES for that memory: the
|
|
21
|
+
* archive is skipped, the failure is counted with its reason, and the cycle
|
|
22
|
+
* continues.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { pressureAt, pruneVerdict, supersededResolvable } from "../physics/index.js";
|
|
26
|
+
import type { MemoryPhysics, PruneReason } from "../physics/index.js";
|
|
27
|
+
import { rowToPhysics } from "../store/operational.js";
|
|
28
|
+
import { PRUNE_ARCHIVE_REASON, PRUNE_RECORD_PREFIX } from "./tunables.js";
|
|
29
|
+
import type { MemoryRow, PhaseCtx, PhaseOutcome, PrunedRecord } from "./types.js";
|
|
30
|
+
import { countSkip, emptyOutcome, isJournal } from "./types.js";
|
|
31
|
+
|
|
32
|
+
export interface PruneResult extends PhaseOutcome {
|
|
33
|
+
readonly pruned: readonly PrunedRecord[];
|
|
34
|
+
/** Every blocking gate, counted — physics names all five, not just the first. */
|
|
35
|
+
readonly blocked: Readonly<Record<string, number>>;
|
|
36
|
+
/** Memories left in place because their record could not be written. */
|
|
37
|
+
readonly recordFailures: readonly { id: string; error: string }[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function pruneRecordKey(id: string): string {
|
|
41
|
+
return `${PRUNE_RECORD_PREFIX}${id}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The one input physics cannot see: is this memory load-bearing in a revision
|
|
46
|
+
* that is still live? Three ways to be, all read from canonical state:
|
|
47
|
+
*
|
|
48
|
+
* - it has already been superseded (it has a forwarding address);
|
|
49
|
+
* - a version row still points at a successor within the resolvable horizon H;
|
|
50
|
+
* - challenge pressure is standing against it right now — an argument in
|
|
51
|
+
* progress is not a memory to quietly retire.
|
|
52
|
+
*/
|
|
53
|
+
export function inLiveRevisionChain(
|
|
54
|
+
store: Pick<PhaseCtx["store"], "versions">,
|
|
55
|
+
id: string,
|
|
56
|
+
row: MemoryRow,
|
|
57
|
+
physics: MemoryPhysics,
|
|
58
|
+
day: number,
|
|
59
|
+
): boolean {
|
|
60
|
+
if (row.superseded_by !== null) return true;
|
|
61
|
+
if (pressureAt(physics, day) > 0) return true;
|
|
62
|
+
return store
|
|
63
|
+
.versions(id)
|
|
64
|
+
.some((v) => v.successor_id !== null && supersededResolvable(v.version_day, day));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function runPrune(ctx: PhaseCtx): PruneResult {
|
|
68
|
+
const out = emptyOutcome();
|
|
69
|
+
out.skipped["archived"] = 0;
|
|
70
|
+
out.skipped["removed"] = 0;
|
|
71
|
+
out.skipped["journal"] = 0;
|
|
72
|
+
const blocked: Record<string, number> = {};
|
|
73
|
+
const pruned: PrunedRecord[] = [];
|
|
74
|
+
const recordFailures: { id: string; error: string }[] = [];
|
|
75
|
+
|
|
76
|
+
const { store, day } = ctx;
|
|
77
|
+
const denied = new Set(store.deniedIds());
|
|
78
|
+
const ids = store.list();
|
|
79
|
+
|
|
80
|
+
let index = 0;
|
|
81
|
+
for (const id of ids) {
|
|
82
|
+
if (out.examined >= ctx.budget) {
|
|
83
|
+
out.budgetExhausted = true;
|
|
84
|
+
out.skippedForBudget = ids.length - index;
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
index += 1;
|
|
88
|
+
const row = store.row(id);
|
|
89
|
+
if (row === undefined) continue;
|
|
90
|
+
if (denied.has(id)) {
|
|
91
|
+
countSkip(out, "removed");
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
// Already archived — including anything this cycle's dedup archived. An
|
|
95
|
+
// archived memory has already exited; it is not pruned a second time.
|
|
96
|
+
if (row.archived === 1) {
|
|
97
|
+
countSkip(out, "archived");
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
// THE JOURNAL IS NEVER PRUNED. Measured 2026-09-04: 224 migrated episodes
|
|
101
|
+
// at zero on every dimension would have been archived at the floor, and an
|
|
102
|
+
// archived episode stops reconciling — so the memories it had not yet
|
|
103
|
+
// minted would never exist (`types.ts#isJournal`).
|
|
104
|
+
if (isJournal(row)) {
|
|
105
|
+
countSkip(out, "journal");
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
out.examined += 1;
|
|
109
|
+
|
|
110
|
+
const p = rowToPhysics(row);
|
|
111
|
+
const verdict = pruneVerdict(p, day, {
|
|
112
|
+
inLiveRevisionChain: inLiveRevisionChain(store, id, row, p, day),
|
|
113
|
+
});
|
|
114
|
+
if (!verdict.prune || verdict.record === null) {
|
|
115
|
+
// EVERY failing gate, not just the first — physics names all five, and a
|
|
116
|
+
// memory blocked by two reasons that reports one is a memory nobody can
|
|
117
|
+
// explain. Mirrored into the skip map so the cycle report carries them.
|
|
118
|
+
for (const reason of verdict.blockedBy) {
|
|
119
|
+
blocked[reason] = (blocked[reason] ?? 0) + 1;
|
|
120
|
+
countSkip(out, `blocked:${reason}`);
|
|
121
|
+
}
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (ctx.apply) {
|
|
126
|
+
try {
|
|
127
|
+
store.setMeta(pruneRecordKey(id), JSON.stringify(verdict.record));
|
|
128
|
+
// Beside it, never instead of it: the meta row is what §5 G8 gates the
|
|
129
|
+
// move on; the durable event is what makes the record queryable.
|
|
130
|
+
store.appendEvent?.({
|
|
131
|
+
name: verdict.record.event,
|
|
132
|
+
day,
|
|
133
|
+
ref: id,
|
|
134
|
+
dedupKey: pruneRecordKey(id),
|
|
135
|
+
payload: { ...verdict.record },
|
|
136
|
+
});
|
|
137
|
+
} catch (err) {
|
|
138
|
+
// §5 G8: a failed record append means nothing moves.
|
|
139
|
+
const code = errorCode(err);
|
|
140
|
+
recordFailures.push({ id, error: code });
|
|
141
|
+
countSkip(out, "record-append-failed");
|
|
142
|
+
ctx.event("sleep.prune.record-failed", id, { error: code });
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
store.archive(id, PRUNE_ARCHIVE_REASON);
|
|
146
|
+
}
|
|
147
|
+
pruned.push({ id, record: verdict.record });
|
|
148
|
+
out.changed += 1;
|
|
149
|
+
ctx.event("sleep.pruned", id, {
|
|
150
|
+
kind: verdict.record.kind,
|
|
151
|
+
band: verdict.record.band,
|
|
152
|
+
strength: verdict.record.strength,
|
|
153
|
+
uses: verdict.record.uses,
|
|
154
|
+
dwellDays: verdict.dwellDays,
|
|
155
|
+
day,
|
|
156
|
+
});
|
|
157
|
+
ctx.step("item", { index, id });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return { ...out, pruned, blocked, recordFailures };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function errorCode(err: unknown): string {
|
|
164
|
+
if (err !== null && typeof err === "object" && "code" in err) {
|
|
165
|
+
return String((err as { code: unknown }).code);
|
|
166
|
+
}
|
|
167
|
+
return err instanceof Error ? err.name : "UNKNOWN";
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export type { PruneReason };
|