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,2557 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `doctor` — the one reading that says out loud whether the BACKGROUND half is
|
|
3
|
+
* alive.
|
|
4
|
+
*
|
|
5
|
+
* **The incident this answers (I32, 2026-09-11).** For a week the detached
|
|
6
|
+
* worker was refused at every boundary — `~/.counterparts/credentials.env` had
|
|
7
|
+
* been rewritten to the template by a forced install, so `planSpawn` answered
|
|
8
|
+
* `NO_CREDENTIAL` every time. Every VISIBLE surface read healthy: the wake
|
|
9
|
+
* delivered, recall rendered, capture captured, `verify` was clean, the daily
|
|
10
|
+
* graded the day ACTIVE. Meanwhile the lived-day clock was frozen at 185, no
|
|
11
|
+
* sleep cycle had run since 09-04, every ask was `capped` against a day that
|
|
12
|
+
* never rolled over, and nothing had been embedded. The owner learned it from a
|
|
13
|
+
* session that went looking.
|
|
14
|
+
*
|
|
15
|
+
* #95 made the refusals durable and persisted the escalation counter — the
|
|
16
|
+
* evidence exists now. This module is the READER of that evidence, and it exists
|
|
17
|
+
* once so the console and the session-start notice cannot disagree about what
|
|
18
|
+
* "healthy" means (constitution 16: if the owner can't see it, it isn't
|
|
19
|
+
* trustworthy).
|
|
20
|
+
*
|
|
21
|
+
* Three rules shape it:
|
|
22
|
+
*
|
|
23
|
+
* 1. **It reads and never writes.** Every store call below is a read; the
|
|
24
|
+
* caller supplies an OBSERVER store or one that is already open. Nothing
|
|
25
|
+
* here opens a database, mints a directory or touches box 3.
|
|
26
|
+
* 2. **Names and counts, never values.** A credential is reported by NAME and
|
|
27
|
+
* by the mode of the file that holds it. Never a value, never a length,
|
|
28
|
+
* never a prefix. The same rule `credentials.ts` states for itself.
|
|
29
|
+
* 3. **It is on the hot path, so it is bounded.** `sessionNoticeBudgetMs`
|
|
30
|
+
* bounds the whole reading at session start, checked BETWEEN groups; what
|
|
31
|
+
* the budget cut off is reported as a finding rather than silently
|
|
32
|
+
* omitted (scar §2.4 — a door that did not open must not look like a door
|
|
33
|
+
* nobody needed).
|
|
34
|
+
*/
|
|
35
|
+
import { spawnSync } from "node:child_process";
|
|
36
|
+
import { existsSync } from "node:fs";
|
|
37
|
+
import { dirname, join } from "node:path";
|
|
38
|
+
import { fileURLToPath } from "node:url";
|
|
39
|
+
|
|
40
|
+
import {
|
|
41
|
+
ADAPTER_ASK_EVENT,
|
|
42
|
+
BOUNDARY_EVENT,
|
|
43
|
+
EMBED_BACKFILL_EVENT,
|
|
44
|
+
GATE_CHUNK_EVENT,
|
|
45
|
+
GATE_DEPOSIT_EVENT,
|
|
46
|
+
RECALL_CREDIT_EVENT,
|
|
47
|
+
RUNNER_FAILED_EVENT,
|
|
48
|
+
SLEEP_CYCLE_EVENT,
|
|
49
|
+
SNAPSHOT_FAILED_EVENT,
|
|
50
|
+
SNAPSHOT_TAKEN_EVENT,
|
|
51
|
+
SPAWN_FAILED_EVENT,
|
|
52
|
+
SPAWN_REFUSED_EVENT,
|
|
53
|
+
SWEEP_GATE_EVENT,
|
|
54
|
+
} from "../../core/counterpart.js";
|
|
55
|
+
import { Counterpart } from "../../core/counterpart.js";
|
|
56
|
+
import { Store, dateOf, isStoreError, paths } from "../../core/store/index.js";
|
|
57
|
+
import { BUSY_TIMEOUT_MS, journalModeOf } from "../../core/store/db.js";
|
|
58
|
+
import type { EventRow } from "../../core/store/index.js";
|
|
59
|
+
// The ask allowance the amber hint names, read rather than retyped: a number in
|
|
60
|
+
// a diagnostic's prose is a number that goes stale silently.
|
|
61
|
+
import { SELF_TUNABLES } from "../../core/self/tunables.js";
|
|
62
|
+
// The page's own reader, so this line cannot drift from what the wake prints.
|
|
63
|
+
import { clearedMarker, findPageRow, readSelfPage } from "../../core/self/page.js";
|
|
64
|
+
import {
|
|
65
|
+
JOURNAL_COPY_FAILED_EVENT,
|
|
66
|
+
JOURNAL_COPY_WRITTEN_EVENT,
|
|
67
|
+
} from "../../core/self/journal-file.js";
|
|
68
|
+
import {
|
|
69
|
+
hasDayBefore,
|
|
70
|
+
lastPageWriterRun,
|
|
71
|
+
pageWriterAbout,
|
|
72
|
+
pageWriterDue,
|
|
73
|
+
pageWriterStatus,
|
|
74
|
+
} from "../../core/self/writer.js";
|
|
75
|
+
import type { AskReason } from "../../core/self/episodes.js";
|
|
76
|
+
// The what-fired reading, shared with the console's `fired` command and the
|
|
77
|
+
// dashboard's health panel so the three cannot disagree about what "silent"
|
|
78
|
+
// means (constitution 16, the same rule this module already keeps for "healthy").
|
|
79
|
+
import { STATE_MEANING, YOUNG_LIVED_DAYS, daysBetween, firedReport } from "../fired.js";
|
|
80
|
+
// The one name the "no configuration was read" line needs, from the module that
|
|
81
|
+
// owns it — so the sentence here and the refusal it replaced name the same var.
|
|
82
|
+
import { CONFIG_ENV } from "../config-path.js";
|
|
83
|
+
import {
|
|
84
|
+
DEFAULT_KEEP,
|
|
85
|
+
futureNamesIn,
|
|
86
|
+
keepOf,
|
|
87
|
+
readSnapshotsDir,
|
|
88
|
+
resolveSnapshotsDir,
|
|
89
|
+
} from "../snapshots.js";
|
|
90
|
+
import { API_KEY_ENV, EMBED_KEY_ENV, TUNABLES, pageWriterMode } from "./config.js";
|
|
91
|
+
import type { AdapterConfig } from "./config.js";
|
|
92
|
+
import { CREDENTIAL_NAMES } from "./credentials.js";
|
|
93
|
+
import type { CredentialLoad } from "./credentials.js";
|
|
94
|
+
// The same vocabulary the hook's stand-down uses, so the terminal and the
|
|
95
|
+
// console cannot end up with two answers to "why did it not open".
|
|
96
|
+
import { describeFault, faultId, faultPath } from "./standdown.js";
|
|
97
|
+
|
|
98
|
+
/** Worst first. The order of this array IS the report's order. */
|
|
99
|
+
export const SEVERITIES = ["red", "amber", "green"] as const;
|
|
100
|
+
export type Severity = (typeof SEVERITIES)[number];
|
|
101
|
+
|
|
102
|
+
export interface Finding {
|
|
103
|
+
/** Stable machine name — the `--json` key and the notice's identity. */
|
|
104
|
+
readonly key: string;
|
|
105
|
+
readonly severity: Severity;
|
|
106
|
+
/** The column heading a human reads: "Credentials", "Clock". */
|
|
107
|
+
readonly title: string;
|
|
108
|
+
/** One line of FACTS: paths, names, counts, dates. Never memory text. */
|
|
109
|
+
readonly detail: string;
|
|
110
|
+
/** One line naming the fix. Empty only when there is nothing to fix. */
|
|
111
|
+
readonly fix: string;
|
|
112
|
+
/** Ids and counts, for `--json`. Never a credential value, never prose. */
|
|
113
|
+
readonly data: Record<string, string | number | boolean | null>;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* How long the session-start reading may take before it stops and says so.
|
|
118
|
+
*
|
|
119
|
+
* 150 ms is the credit seam's own budget (`CreditReferencesInput.deadline`),
|
|
120
|
+
* chosen for the same reason: this runs inside a foreground hook, and a hook
|
|
121
|
+
* that costs the owner a visible pause has made the cure worse than the disease.
|
|
122
|
+
* The console passes no budget at all — a person who typed `counterparts
|
|
123
|
+
* doctor` is waiting on purpose.
|
|
124
|
+
*/
|
|
125
|
+
export const SESSION_NOTICE_BUDGET_MS = 150;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* How many lived days back the newest-row search widens through.
|
|
129
|
+
*
|
|
130
|
+
* `Store.eventLog` orders ASCENDING and takes a LIMIT, so "the newest row of
|
|
131
|
+
* this name" is not a query it offers (filed as an ask in `cli/INTERFACE-GAPS`).
|
|
132
|
+
* The reading below is exact rather than approximate: a window whose result is
|
|
133
|
+
* SHORTER than the limit was not truncated, so its last row is provably the
|
|
134
|
+
* newest in that window. The ladder starts at today so the common case reads
|
|
135
|
+
* the fewest rows, and widens only when a window is empty.
|
|
136
|
+
*/
|
|
137
|
+
const WINDOWS: readonly (number | null)[] = [0, 2, 7, 30, null];
|
|
138
|
+
const NEWEST_LIMIT = 4000;
|
|
139
|
+
|
|
140
|
+
export interface DoctorInput {
|
|
141
|
+
/** The host configuration file this reading is about. */
|
|
142
|
+
readonly configPath: string;
|
|
143
|
+
/**
|
|
144
|
+
* How `loadConfig` read that file, when the caller knows. The hook resolves
|
|
145
|
+
* and REFUSES a bad one before it gets here (`bin/hook.ts`), so it passes
|
|
146
|
+
* null and the config finding reports only what the file named.
|
|
147
|
+
*/
|
|
148
|
+
/**
|
|
149
|
+
* `not-read` (2026-09-20, finding 6) is `--dir` with no `--config` under the
|
|
150
|
+
* explicit-dir guard: the store was NAMED, so it is read, and the default
|
|
151
|
+
* configuration beside it was not opened at all — because opening it is what
|
|
152
|
+
* would reach the owner's live credentials file. Everything that comes out of
|
|
153
|
+
* a configuration then says so instead of grading a file nobody read.
|
|
154
|
+
*/
|
|
155
|
+
readonly configReason: "loaded" | "absent" | "unreadable" | "not-read" | null;
|
|
156
|
+
readonly config: AdapterConfig;
|
|
157
|
+
/** The store this reading actually read. */
|
|
158
|
+
readonly dir: string;
|
|
159
|
+
/**
|
|
160
|
+
* The credential load to REPORT ON, and the two callers hand in different
|
|
161
|
+
* ones on purpose:
|
|
162
|
+
*
|
|
163
|
+
* - The **console** loads the file against a SCRATCH environment, so what
|
|
164
|
+
* it reports is what the FILE holds. A console that counted its own shell
|
|
165
|
+
* would read green on the owner's machine — his `~/.zshrc` exports both
|
|
166
|
+
* names — while the hook processes, which inherit neither (measured day 0),
|
|
167
|
+
* stayed blind. That is I32 reproduced inside the diagnostic.
|
|
168
|
+
* - The **hook** hands in the load it already performed against its own
|
|
169
|
+
* `process.env` — and that is ALSO a reading of the file, which is what
|
|
170
|
+
* makes the two agree. `loadCredentials` pushes a name onto `loaded` or
|
|
171
|
+
* onto `skippedPresent` only when the FILE holds a line for it
|
|
172
|
+
* (`skippedPresent` means "the file offered this and the environment had
|
|
173
|
+
* already answered it"), so a template file answers nothing whatever the
|
|
174
|
+
* environment carries, and a hook launched from a shell that exports both
|
|
175
|
+
* keys still goes red on a blank file. Asserted in `test/doctor.test.ts`,
|
|
176
|
+
* because the whole PR turns on it.
|
|
177
|
+
*/
|
|
178
|
+
readonly credentials: CredentialLoad;
|
|
179
|
+
readonly credentialsPath: string | undefined;
|
|
180
|
+
/**
|
|
181
|
+
* Names the CALLER's environment answers, when the caller is the console.
|
|
182
|
+
* Reported as one extra clause on the finding for THAT NAME when the file
|
|
183
|
+
* lacks it — "I have that key" and "the hooks have that key" are two different
|
|
184
|
+
* facts, and the gap between them is what made I32 invisible.
|
|
185
|
+
*/
|
|
186
|
+
readonly shellNames?: readonly string[];
|
|
187
|
+
/** Null when there is no store at `dir` — the store findings then say so. */
|
|
188
|
+
readonly store: Store | null;
|
|
189
|
+
/** Today, UTC, `YYYY-MM-DD` — the same spelling every `date` field uses. */
|
|
190
|
+
readonly today: string;
|
|
191
|
+
/**
|
|
192
|
+
* The persisted spawn-refusal counters, `reason -> count`
|
|
193
|
+
* (`adapter.spawn.refusals.<reason>` in box 2's meta).
|
|
194
|
+
*
|
|
195
|
+
* An INPUT rather than a read taken here, because the two callers reach them
|
|
196
|
+
* differently: the adapter has `spawnRefusals()`, which also answers for an
|
|
197
|
+
* observer out of its in-memory map, and the console reads the meta prefix off
|
|
198
|
+
* the store. The THRESHOLD and the wording — the part that could drift — live
|
|
199
|
+
* here and only here.
|
|
200
|
+
*/
|
|
201
|
+
readonly refusals: Record<string, number>;
|
|
202
|
+
/**
|
|
203
|
+
* HOW MANY TIMES THE WORKER STARTED TODAY, and the date that tally is for.
|
|
204
|
+
*
|
|
205
|
+
* An INPUT for the same reason `refusals` is: the counter lives in the
|
|
206
|
+
* adapter's own meta keys, `hooks.ts` already imports this file, and a read
|
|
207
|
+
* taken here would make that a cycle. `adapter.spawn.started` is latched one
|
|
208
|
+
* row per calendar date, so the ROW proves the door opened and this is the
|
|
209
|
+
* only thing that says how often -- which is why the row carries no tally of
|
|
210
|
+
* its own. A date that is not today is ignored rather than printed: a counter
|
|
211
|
+
* stamped with yesterday answers nothing about today.
|
|
212
|
+
*/
|
|
213
|
+
readonly starts?: { date: string | null; count: number };
|
|
214
|
+
/**
|
|
215
|
+
* WHICH CHECKOUT IS RUNNING (see `readCheckout`). Absent: not graded, and no
|
|
216
|
+
* finding is produced at all.
|
|
217
|
+
*/
|
|
218
|
+
readonly checkout?: CheckoutReading;
|
|
219
|
+
/**
|
|
220
|
+
* WHETHER THE STORE OPENS THE WAY A SESSION OPENS IT (see `readCounterpartOpen`).
|
|
221
|
+
* Absent: not read, and no finding is produced at all — which is the hook's
|
|
222
|
+
* case, whose counterpart is already open by the time it asks for a notice.
|
|
223
|
+
*/
|
|
224
|
+
readonly open?: OpenReading;
|
|
225
|
+
/**
|
|
226
|
+
* WHETHER THE TWO STEPS THE USER DOES BY HAND ACTUALLY TOOK (finding 4).
|
|
227
|
+
* Absent: not read, and no finding is produced at all — the hook's case, which
|
|
228
|
+
* is already running BECAUSE the hooks are installed and has no budget for
|
|
229
|
+
* four more file reads.
|
|
230
|
+
*/
|
|
231
|
+
readonly host?: HostReading;
|
|
232
|
+
/** Bound the whole reading. Absent: no bound (the console's case). */
|
|
233
|
+
readonly budgetMs?: number;
|
|
234
|
+
readonly now?: () => number;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ── which checkout is running ───────────────────────────────────────────────
|
|
238
|
+
|
|
239
|
+
export interface CheckoutReading {
|
|
240
|
+
/**
|
|
241
|
+
* WHAT IS DEPLOYED, graded against the LOCAL `refs/remotes/origin/master` as
|
|
242
|
+
* last fetched — never against the local `master` branch, and never by
|
|
243
|
+
* fetching (this runs on a hook's hot path).
|
|
244
|
+
*
|
|
245
|
+
* The case that set the rule, measured 2026-09-14: a merge to origin/master
|
|
246
|
+
* does NOT deploy. The install tree sat DETACHED at an older sha for thirty
|
|
247
|
+
* minutes after a merge, and every hook in that window ran the old code while
|
|
248
|
+
* "it's merged" was true.
|
|
249
|
+
*
|
|
250
|
+
* - `master` — HEAD IS origin/master, on a branch or detached. Detached at
|
|
251
|
+
* origin/master is the intended deploy state, not a fault.
|
|
252
|
+
* - `behind` — HEAD is an ancestor of origin/master: master moved and this
|
|
253
|
+
* tree did not. Amber; the code that runs is old but it is merged code.
|
|
254
|
+
* - `branch` / `detached` — HEAD is NOT an ancestor of origin/master, so
|
|
255
|
+
* unmerged code is live. Red.
|
|
256
|
+
* - `dirty` — tracked modifications, wherever HEAD sits. Red.
|
|
257
|
+
* - `not-a-repo` — an installed package. Nothing to grade.
|
|
258
|
+
* - `unreadable` — git did not answer, or there is no `origin/master` ref to
|
|
259
|
+
* grade against. Neutral, and no durable row.
|
|
260
|
+
*/
|
|
261
|
+
readonly reason: "master" | "behind" | "branch" | "dirty" | "detached" | "not-a-repo" | "unreadable";
|
|
262
|
+
/** The directory graded. Empty when there was nothing to grade. */
|
|
263
|
+
readonly root: string;
|
|
264
|
+
readonly branch: string | null;
|
|
265
|
+
/** Short sha, or null on an empty repository. */
|
|
266
|
+
readonly head: string | null;
|
|
267
|
+
/** TRACKED modifications only. */
|
|
268
|
+
readonly dirty: number;
|
|
269
|
+
/** How many commits origin/master is ahead, when HEAD is an ancestor of it. */
|
|
270
|
+
readonly behindBy: number | null;
|
|
271
|
+
/** The short sha of `refs/remotes/origin/master`, as last fetched. */
|
|
272
|
+
readonly originMaster: string | null;
|
|
273
|
+
/** True when HEAD IS origin/master — the deploy state, branch or not. */
|
|
274
|
+
readonly atMaster: boolean;
|
|
275
|
+
/**
|
|
276
|
+
* True when the reading ran out of `CHECKOUT_BUDGET_MS` (or one call timed
|
|
277
|
+
* out), which forces `reason` to `unreadable`. It is its own field because the
|
|
278
|
+
* ring row distinguishes "git would not answer" from "git was too slow", and
|
|
279
|
+
* only the second one says something about the machine.
|
|
280
|
+
*/
|
|
281
|
+
readonly timedOut: boolean;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* THE PACKAGE ROOT OF THE CODE THAT IS RUNNING — derived from this module's own
|
|
286
|
+
* path and from nothing else.
|
|
287
|
+
*
|
|
288
|
+
* It must not come from a configuration value, and the reason is the whole
|
|
289
|
+
* point of the finding. The host invokes the hook by ABSOLUTE PATH out of
|
|
290
|
+
* `~/.claude/settings.json`, so on the live machine that path resolves to the
|
|
291
|
+
* shared install tree — which is exactly the tree that has to be graded, because
|
|
292
|
+
* whatever is checked out there is what runs against the owner's memory. (It
|
|
293
|
+
* happened: a peer session developed a branch in that checkout and it was live
|
|
294
|
+
* for seven minutes.) A console run from a worktree resolves to the WORKTREE and
|
|
295
|
+
* grades that, which is the right answer for a command somebody typed there.
|
|
296
|
+
*/
|
|
297
|
+
function runningRoot(from: string = dirname(fileURLToPath(import.meta.url))): string | null {
|
|
298
|
+
let dir = from;
|
|
299
|
+
for (let i = 0; i < 8; i += 1) {
|
|
300
|
+
if (existsSync(join(dir, "package.json"))) return dir;
|
|
301
|
+
const up = dirname(dir);
|
|
302
|
+
if (up === dir) return null;
|
|
303
|
+
dir = up;
|
|
304
|
+
}
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** What one bounded `git` call answered. `failed` separates "git said no" from
|
|
309
|
+
* "git never answered", which are different findings. */
|
|
310
|
+
interface GitResult {
|
|
311
|
+
readonly ok: boolean;
|
|
312
|
+
readonly out: string;
|
|
313
|
+
readonly failed: "missing" | "timeout" | "status" | null;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export type GitRunner = (args: readonly string[]) => GitResult;
|
|
317
|
+
|
|
318
|
+
/** The ceiling on ONE `git` call. Never the reading's cost: seven calls at two
|
|
319
|
+
* seconds is fourteen seconds, which is what the reviewer measured against a
|
|
320
|
+
* sleeping git shim (7.81 s) before `CHECKOUT_BUDGET_MS` existed. The budget
|
|
321
|
+
* below is what actually bounds the reading; this is the per-call cap it
|
|
322
|
+
* narrows. */
|
|
323
|
+
export const CHECKOUT_TIMEOUT_MS = 2000;
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* THE WHOLE READING'S BUDGET — one second, and the reason it is not 150 ms.
|
|
327
|
+
*
|
|
328
|
+
* `readCheckout` runs BEFORE `doctorFindings`, whose own deadline starts when it
|
|
329
|
+
* is entered, so the git reads were outside every budget this adapter had: up to
|
|
330
|
+
* seven `spawnSync` calls, each free to take `CHECKOUT_TIMEOUT_MS`. A wedged git
|
|
331
|
+
* — a network filesystem, an index.lock, a fresh cold cache — could hold a
|
|
332
|
+
* foreground session start for fourteen seconds.
|
|
333
|
+
*
|
|
334
|
+
* It is its OWN budget rather than a share of `SESSION_NOTICE_BUDGET_MS`
|
|
335
|
+
* because the two measure different things. 150 ms is right for reading a store
|
|
336
|
+
* that is already open; five process spawns on a cold machine can exceed that on
|
|
337
|
+
* their own, and a checkout reading that timed out every morning would report
|
|
338
|
+
* `unreadable` on exactly the days the tree HAS wandered — the days the finding
|
|
339
|
+
* exists for. One second is the number that is long enough to be read and short
|
|
340
|
+
* enough that nobody notices it. Total worst case at session start:
|
|
341
|
+
* `CHECKOUT_BUDGET_MS` + `SESSION_NOTICE_BUDGET_MS` ≈ 1.15 s.
|
|
342
|
+
*/
|
|
343
|
+
export const CHECKOUT_BUDGET_MS = 1000;
|
|
344
|
+
|
|
345
|
+
function gitIn(root: string, remainingMs: () => number, env: NodeJS.ProcessEnv): GitRunner {
|
|
346
|
+
return (args: readonly string[]): GitResult => {
|
|
347
|
+
const res = spawnSync("git", ["-C", root, ...args], {
|
|
348
|
+
timeout: remainingMs(),
|
|
349
|
+
encoding: "utf8",
|
|
350
|
+
windowsHide: true,
|
|
351
|
+
// The environment is passed rather than inherited by default for one
|
|
352
|
+
// reason: under bun a `spawnSync` with no `env` resolves the binary against
|
|
353
|
+
// the REAL environment, so a test cannot put a slow `git` on `PATH` and
|
|
354
|
+
// prove the budget against a spawn that actually blocks. Passing
|
|
355
|
+
// `process.env` is what inheriting already meant.
|
|
356
|
+
env,
|
|
357
|
+
});
|
|
358
|
+
if (res.error !== undefined && res.error !== null) {
|
|
359
|
+
const code = (res.error as NodeJS.ErrnoException).code ?? "";
|
|
360
|
+
return { ok: false, out: "", failed: code === "ETIMEDOUT" ? "timeout" : "missing" };
|
|
361
|
+
}
|
|
362
|
+
if (res.signal !== null && res.signal !== undefined) return { ok: false, out: "", failed: "timeout" };
|
|
363
|
+
if (res.status !== 0) return { ok: false, out: String(res.stdout ?? ""), failed: "status" };
|
|
364
|
+
return { ok: true, out: String(res.stdout ?? ""), failed: null };
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Which branch the RUNNING code is on, and whether its tree is clean.
|
|
370
|
+
*
|
|
371
|
+
* Read-only, bounded, and it never throws: every git call is `spawnSync` with a
|
|
372
|
+
* timeout, and a git that is missing, slow or angry resolves to `unreadable`
|
|
373
|
+
* rather than to an exception on a hook's hot path.
|
|
374
|
+
*
|
|
375
|
+
* `dirty` counts TRACKED changes only (`--untracked-files=no`), because the
|
|
376
|
+
* shared tree carries untracked files by design — a working `docs/IMPROVEMENTS.md`,
|
|
377
|
+
* `.claude/worktrees/` — and neither changes what runs.
|
|
378
|
+
*/
|
|
379
|
+
export const ORIGIN_MASTER = "refs/remotes/origin/master";
|
|
380
|
+
|
|
381
|
+
export function readCheckout(
|
|
382
|
+
opts: {
|
|
383
|
+
root?: string | null;
|
|
384
|
+
git?: GitRunner;
|
|
385
|
+
timeoutMs?: number;
|
|
386
|
+
budgetMs?: number;
|
|
387
|
+
/** Injectable clock, so the budget is provable without waiting for it. */
|
|
388
|
+
now?: () => number;
|
|
389
|
+
/** The environment the `git` calls run in; injectable so a test can put a
|
|
390
|
+
* slow `git` on `PATH` and measure the real spawn path. */
|
|
391
|
+
env?: NodeJS.ProcessEnv;
|
|
392
|
+
} = {},
|
|
393
|
+
): CheckoutReading {
|
|
394
|
+
const root = opts.root === undefined ? runningRoot() : opts.root;
|
|
395
|
+
const none = {
|
|
396
|
+
branch: null,
|
|
397
|
+
head: null,
|
|
398
|
+
dirty: 0,
|
|
399
|
+
behindBy: null,
|
|
400
|
+
originMaster: null,
|
|
401
|
+
atMaster: false,
|
|
402
|
+
timedOut: false,
|
|
403
|
+
};
|
|
404
|
+
if (root === null) return { reason: "not-a-repo", root: "", ...none };
|
|
405
|
+
// THE BUDGET, spent across every call rather than per call. Each git gets what
|
|
406
|
+
// is LEFT of it (capped at `CHECKOUT_TIMEOUT_MS`), and once it is gone no
|
|
407
|
+
// further call is made at all — a reading that has run out of time is
|
|
408
|
+
// `unreadable`, which is a state this adapter already knows how to say.
|
|
409
|
+
const now = opts.now ?? ((): number => Date.now());
|
|
410
|
+
const ceiling = opts.timeoutMs ?? CHECKOUT_TIMEOUT_MS;
|
|
411
|
+
const deadline = now() + (opts.budgetMs ?? CHECKOUT_BUDGET_MS);
|
|
412
|
+
let timedOut = false;
|
|
413
|
+
const run =
|
|
414
|
+
opts.git ?? gitIn(root, () => Math.max(1, Math.min(ceiling, deadline - now())), opts.env ?? process.env);
|
|
415
|
+
const git: GitRunner = (args) => {
|
|
416
|
+
if (timedOut || now() >= deadline) {
|
|
417
|
+
timedOut = true;
|
|
418
|
+
return { ok: false, out: "", failed: "timeout" };
|
|
419
|
+
}
|
|
420
|
+
const res = run(args);
|
|
421
|
+
if (res.failed === "timeout") timedOut = true;
|
|
422
|
+
return res;
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
const gitDir = git(["rev-parse", "--git-dir"]);
|
|
426
|
+
if (!gitDir.ok) {
|
|
427
|
+
// `status` is git answering "this is not a repository" — an installed
|
|
428
|
+
// package, and nothing to grade. Anything else is git not answering at all.
|
|
429
|
+
return {
|
|
430
|
+
reason: gitDir.failed === "status" ? "not-a-repo" : "unreadable",
|
|
431
|
+
root,
|
|
432
|
+
...none,
|
|
433
|
+
timedOut,
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
const ref = git(["symbolic-ref", "-q", "--short", "HEAD"]);
|
|
437
|
+
const branch = ref.ok && ref.out.trim().length > 0 ? ref.out.trim() : null;
|
|
438
|
+
const headRead = git(["rev-parse", "--short", "HEAD"]);
|
|
439
|
+
const head = headRead.ok && headRead.out.trim().length > 0 ? headRead.out.trim() : null;
|
|
440
|
+
const statusRead = git(["status", "--porcelain", "--untracked-files=no"]);
|
|
441
|
+
const dirty = statusRead.ok
|
|
442
|
+
? statusRead.out.split("\n").filter((l) => l.trim().length > 0).length
|
|
443
|
+
: 0;
|
|
444
|
+
// THE REF THAT DECIDES, read as last fetched. Fetching here would put a
|
|
445
|
+
// network call on a foreground hook, which is the one thing the wake's own
|
|
446
|
+
// contract forbids (§1 G1).
|
|
447
|
+
const originRead = git(["rev-parse", "--short", ORIGIN_MASTER]);
|
|
448
|
+
const originMaster = originRead.ok && originRead.out.trim().length > 0 ? originRead.out.trim() : null;
|
|
449
|
+
if (originMaster === null || head === null) {
|
|
450
|
+
// A repository with no `origin/master` (a clone with no remote, a fresh
|
|
451
|
+
// init) has nothing to grade against, and an empty repository has no HEAD.
|
|
452
|
+
// Neutral, and no durable row: "we could not grade it" is not a state of
|
|
453
|
+
// the checkout.
|
|
454
|
+
return { reason: "unreadable", root, branch, head, dirty, behindBy: null, originMaster, atMaster: false, timedOut };
|
|
455
|
+
}
|
|
456
|
+
const atMaster = head === originMaster;
|
|
457
|
+
const ancestor = atMaster || git(["merge-base", "--is-ancestor", "HEAD", ORIGIN_MASTER]).ok;
|
|
458
|
+
const countRead = ancestor && !atMaster ? git(["rev-list", "--count", `HEAD..${ORIGIN_MASTER}`]) : null;
|
|
459
|
+
const behindBy =
|
|
460
|
+
countRead !== null && countRead.ok ? (Number.parseInt(countRead.out.trim(), 10) || 0) : null;
|
|
461
|
+
|
|
462
|
+
// A reading that ran out of time is not a grade. Half the calls answered and
|
|
463
|
+
// half returned nothing, and "clean at origin/master" assembled out of
|
|
464
|
+
// silence is the one wrong answer this finding may not give.
|
|
465
|
+
if (timedOut) {
|
|
466
|
+
return { reason: "unreadable", root, branch, head, dirty, behindBy, originMaster, atMaster, timedOut };
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// ORDER IS THE GRADE. Tracked modifications are red wherever HEAD sits — they
|
|
470
|
+
// are code that is in no branch at all. Then: at origin/master is the deploy
|
|
471
|
+
// state; an ancestor of it is old-but-merged; anything else is unmerged code
|
|
472
|
+
// running against the owner's memory.
|
|
473
|
+
const reason: CheckoutReading["reason"] =
|
|
474
|
+
dirty > 0
|
|
475
|
+
? "dirty"
|
|
476
|
+
: atMaster
|
|
477
|
+
? "master"
|
|
478
|
+
: ancestor
|
|
479
|
+
? "behind"
|
|
480
|
+
: branch === null
|
|
481
|
+
? "detached"
|
|
482
|
+
: "branch";
|
|
483
|
+
return { reason, root, branch, head, dirty, behindBy, originMaster, atMaster, timedOut };
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** True when this reading is one the adapter records a durable row for. A
|
|
487
|
+
* package that is not a checkout, and a git that would not answer, are not
|
|
488
|
+
* states of the checkout and leave nothing behind. */
|
|
489
|
+
export function checkoutIsGraded(reading: CheckoutReading): boolean {
|
|
490
|
+
return reading.reason !== "not-a-repo" && reading.reason !== "unreadable";
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// ── will it open the way a session opens it ─────────────────────────────────
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* WHETHER `Counterpart.open` SUCCEEDS — which is a different question from the
|
|
497
|
+
* one the `Store` finding above answers, and the difference is the whole of H1.
|
|
498
|
+
*
|
|
499
|
+
* The `Store` finding reads the DIRECTORY: is there a store here, and is it the
|
|
500
|
+
* one the config names. A store can pass that and still throw at every session
|
|
501
|
+
* start, because opening a counterpart does more than open a database —
|
|
502
|
+
* `Schemas.open` scans every `type: "schema"` row and reads each one's prose
|
|
503
|
+
* file. One missing file, or one row a removal left behind, and every hook in
|
|
504
|
+
* every session stands down: no wake, no recall, no capture, and until now
|
|
505
|
+
* nothing said so while `doctor` printed GREEN Store on the line above.
|
|
506
|
+
*
|
|
507
|
+
* READ BY THE CALLER, like `readCheckout` — and for the same reason it is not
|
|
508
|
+
* taken inside `doctorFindings`, which is pure over its input and never opens
|
|
509
|
+
* anything. The session-start reading does not take it at all: a hook that got
|
|
510
|
+
* as far as composing a notice has ALREADY opened its counterpart, so paying for
|
|
511
|
+
* a second open there would buy a fact it has in hand.
|
|
512
|
+
*/
|
|
513
|
+
export interface OpenReading {
|
|
514
|
+
readonly dir: string;
|
|
515
|
+
readonly ok: boolean;
|
|
516
|
+
/** The `StoreErrorCode` (or `HOOK_FAILED`) that came back. Null when it opened. */
|
|
517
|
+
readonly code: string | null;
|
|
518
|
+
/** Plain words for `code` (`standdown.ts`). Empty when it opened. */
|
|
519
|
+
readonly reason: string;
|
|
520
|
+
/**
|
|
521
|
+
* TRUE for the one refusal that is not a fault: `STORE_UNINITIALIZED`, which
|
|
522
|
+
* an OBSERVER gets on a store that does not exist yet or is a schema behind.
|
|
523
|
+
* The hooks run as OWNER and initialize or migrate it, so grading this red
|
|
524
|
+
* would make the console lie for the window between a deploy and the first
|
|
525
|
+
* hook that follows it.
|
|
526
|
+
*/
|
|
527
|
+
readonly migratable: boolean;
|
|
528
|
+
/**
|
|
529
|
+
* TRUE for the other refusal that is not a fault of the store: it was BUSY.
|
|
530
|
+
* Another process held it for the moment this reading wanted it, which says
|
|
531
|
+
* nothing about whether a session could open it a second later. Amber, and the
|
|
532
|
+
* fix is to ask again — the same judgement the hook's transient stand-down
|
|
533
|
+
* makes with the same predicate (`db.ts#isLocked`).
|
|
534
|
+
*/
|
|
535
|
+
readonly busy: boolean;
|
|
536
|
+
/** The path the error named, when it named one. Never memory text (§5 G10). */
|
|
537
|
+
readonly path: string | null;
|
|
538
|
+
/** The ROW the error named, when it named one — an id, never memory text.
|
|
539
|
+
* `MEMORY_BODY_MISSING` carries one and no path, because on this floor the
|
|
540
|
+
* words are the row and there is no file to restore (review B, MAJOR-3). */
|
|
541
|
+
readonly id: string | null;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* "Writes nothing" here means NO STORE CONTENT. It is an observer open, so no
|
|
546
|
+
* row, no prose file and no meta key changes — but any reader of a WAL database
|
|
547
|
+
* touches the `-shm`, and one that finds no `-shm` or `-wal` beside the file
|
|
548
|
+
* CREATES them, exactly as every other reader does (`store/paths.ts#isDatabaseSidecar`
|
|
549
|
+
* is the same exception master's own suites take when they hash a store and mean
|
|
550
|
+
* "nothing wrote"). Anyone comparing store directories should expect that.
|
|
551
|
+
*/
|
|
552
|
+
export function readCounterpartOpen(
|
|
553
|
+
dir: string,
|
|
554
|
+
/** Injectable so the failure branches are provable without a broken fixture;
|
|
555
|
+
* the fixture test is still the one that proves the real path. */
|
|
556
|
+
open: (d: string) => { close: () => void } = (d) => Counterpart.open({ dir: d, observer: true }),
|
|
557
|
+
): OpenReading {
|
|
558
|
+
let opened: { close: () => void } | null = null;
|
|
559
|
+
try {
|
|
560
|
+
// OBSERVER, because `doctor` is an instrument: it reads and never writes,
|
|
561
|
+
// and an owner open of a store that is not there would MINT one.
|
|
562
|
+
opened = open(dir);
|
|
563
|
+
return {
|
|
564
|
+
dir,
|
|
565
|
+
ok: true,
|
|
566
|
+
code: null,
|
|
567
|
+
reason: "",
|
|
568
|
+
migratable: false,
|
|
569
|
+
busy: false,
|
|
570
|
+
path: null,
|
|
571
|
+
id: null,
|
|
572
|
+
};
|
|
573
|
+
} catch (err) {
|
|
574
|
+
const fault = describeFault(err);
|
|
575
|
+
return {
|
|
576
|
+
dir,
|
|
577
|
+
ok: false,
|
|
578
|
+
code: fault.code,
|
|
579
|
+
reason: fault.reason,
|
|
580
|
+
migratable: isStoreError(err, "STORE_UNINITIALIZED"),
|
|
581
|
+
busy: fault.kind === "transient",
|
|
582
|
+
path: faultPath(err),
|
|
583
|
+
id: faultId(err),
|
|
584
|
+
};
|
|
585
|
+
} finally {
|
|
586
|
+
// Closed immediately, so this reading and the store the console opens next
|
|
587
|
+
// never hold the same database at once.
|
|
588
|
+
try {
|
|
589
|
+
opened?.close();
|
|
590
|
+
} catch {
|
|
591
|
+
/* a close that failed is not a state of the store */
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// ── the groups ──────────────────────────────────────────────────────────────
|
|
597
|
+
|
|
598
|
+
/** A finding, with `data` defaulted so each group below stays one expression. */
|
|
599
|
+
function finding(
|
|
600
|
+
key: string,
|
|
601
|
+
severity: Severity,
|
|
602
|
+
title: string,
|
|
603
|
+
detail: string,
|
|
604
|
+
fix: string,
|
|
605
|
+
data: Record<string, string | number | boolean | null> = {},
|
|
606
|
+
): Finding {
|
|
607
|
+
return { key, severity, title, detail, fix, data };
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* The newest rows of one event name, oldest-first, at most `count` of them —
|
|
612
|
+
* or `unknown`, which is a third answer and not a kind of empty.
|
|
613
|
+
*
|
|
614
|
+
* Exact, not approximate: see `WINDOWS`. A window that came back FULL is
|
|
615
|
+
* discarded rather than trusted — its last row is the newest of the first
|
|
616
|
+
* `NEWEST_LIMIT`, which is not the same claim.
|
|
617
|
+
*
|
|
618
|
+
* THE UNBOUNDED WINDOW IS NOT EXEMPT FROM THAT RULE, and the first round of this
|
|
619
|
+
* PR made it so. Once a name held `NEWEST_LIMIT` rows all older than the widest
|
|
620
|
+
* day window, every bounded window came back full and was skipped, the `null`
|
|
621
|
+
* window came back full too — and it alone was trusted, so `rows.slice(-count)`
|
|
622
|
+
* handed back the 4,000th-OLDEST row as "the newest". A store that swept its
|
|
623
|
+
* last 4,000 sleep cycles and ran fine since would have been read off a row from
|
|
624
|
+
* whenever that prefix ended: a confident wrong answer, which is the one thing a
|
|
625
|
+
* diagnostic may never produce. Unknown says so instead.
|
|
626
|
+
*/
|
|
627
|
+
interface NewestRead {
|
|
628
|
+
readonly rows: EventRow[];
|
|
629
|
+
readonly unknown: boolean;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
function newestRows(store: Store, name: string, count: number, livedDay: number): NewestRead {
|
|
633
|
+
for (const back of WINDOWS) {
|
|
634
|
+
const rows = store.eventLog(
|
|
635
|
+
back === null
|
|
636
|
+
? { name, limit: NEWEST_LIMIT }
|
|
637
|
+
: { name, sinceDay: Math.max(0, livedDay - back), limit: NEWEST_LIMIT },
|
|
638
|
+
);
|
|
639
|
+
if (rows.length === 0) continue;
|
|
640
|
+
if (rows.length >= NEWEST_LIMIT) {
|
|
641
|
+
if (back !== null) continue;
|
|
642
|
+
return { rows: [], unknown: true };
|
|
643
|
+
}
|
|
644
|
+
return { rows: rows.slice(-count), unknown: false };
|
|
645
|
+
}
|
|
646
|
+
return { rows: [], unknown: false };
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** The one sentence for a name whose newest row cannot be determined. Neutral:
|
|
650
|
+
* it names what was not read, and claims nothing about the store. */
|
|
651
|
+
function undetermined(name: string): string {
|
|
652
|
+
return (
|
|
653
|
+
`newest ${name} row could not be determined: more than ${NEWEST_LIMIT} rows and no bounded window ` +
|
|
654
|
+
"came back short, so the newest one was not read"
|
|
655
|
+
);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function payloadOf(row: EventRow | undefined): Record<string, unknown> {
|
|
659
|
+
if (row === undefined || row.payload === null) return {};
|
|
660
|
+
try {
|
|
661
|
+
const parsed: unknown = JSON.parse(row.payload);
|
|
662
|
+
return parsed !== null && typeof parsed === "object" ? (parsed as Record<string, unknown>) : {};
|
|
663
|
+
} catch {
|
|
664
|
+
return {};
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** The CALENDAR date a row is about: its own field, else the wall clock it was
|
|
669
|
+
* written at. `day` is the lived-day column and answers a different question. */
|
|
670
|
+
function rowDate(row: EventRow | undefined): string | null {
|
|
671
|
+
if (row === undefined) return null;
|
|
672
|
+
const p = payloadOf(row);
|
|
673
|
+
return typeof p["date"] === "string" && p["date"].length > 0 ? p["date"] : dateOf(row.at);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function num(p: Record<string, unknown>, key: string): number | null {
|
|
677
|
+
const v = p[key];
|
|
678
|
+
return typeof v === "number" ? v : null;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
function str(p: Record<string, unknown>, key: string): string | null {
|
|
682
|
+
const v = p[key];
|
|
683
|
+
return typeof v === "string" ? v : null;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* The phases of one `sleep.cycle` row that stopped at their budget, phrased.
|
|
688
|
+
* Read STRUCTURALLY — an older row carries no `budgetExhausted` at all, and a
|
|
689
|
+
* phase that left nothing behind carries no count, so both read as "nothing to
|
|
690
|
+
* say" rather than as a zero anybody could mistake for a measurement.
|
|
691
|
+
*/
|
|
692
|
+
function budgetTruncatedPhases(p: Record<string, unknown>): string[] {
|
|
693
|
+
const phases = p["phases"];
|
|
694
|
+
if (!Array.isArray(phases)) return [];
|
|
695
|
+
const out: string[] = [];
|
|
696
|
+
for (const entry of phases as unknown[]) {
|
|
697
|
+
if (entry === null || typeof entry !== "object") continue;
|
|
698
|
+
const e = entry as Record<string, unknown>;
|
|
699
|
+
if (e["budgetExhausted"] !== true) continue;
|
|
700
|
+
const name = str(e, "phase") ?? "a phase";
|
|
701
|
+
const left = num(e, "skippedForBudget");
|
|
702
|
+
out.push(
|
|
703
|
+
left === null
|
|
704
|
+
? `${name} ran out of budget`
|
|
705
|
+
: `${name} ran out of budget (${String(left)} rows not reached this run)`,
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
return out;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/** The config file itself: the one the hooks read, and whether it was readable. */
|
|
712
|
+
function configFindings(input: DoctorInput): Finding[] {
|
|
713
|
+
const out: Finding[] = [];
|
|
714
|
+
const reason = input.configReason;
|
|
715
|
+
if (reason === "not-read") {
|
|
716
|
+
// NOT A FAULT AND NOT A GRADE. `--dir` named a store; nothing named a
|
|
717
|
+
// configuration, and reading the default one is what would open somebody's
|
|
718
|
+
// live credentials file. So the store is graded and this line says, in the
|
|
719
|
+
// words the refusal used to use, exactly what to type to grade the rest.
|
|
720
|
+
out.push(
|
|
721
|
+
finding(
|
|
722
|
+
"config",
|
|
723
|
+
"amber",
|
|
724
|
+
"Config",
|
|
725
|
+
`not read — you named a store with --dir and no configuration, so nothing here grades ${input.configPath}: no credentials, no embedder setting, no snapshot policy, no stance`,
|
|
726
|
+
`To grade those too: counterparts doctor --config <absolute path> (or set ${CONFIG_ENV}).`,
|
|
727
|
+
{ path: input.configPath, reason },
|
|
728
|
+
),
|
|
729
|
+
);
|
|
730
|
+
out.push(
|
|
731
|
+
input.store === null
|
|
732
|
+
? finding("store", "red", "Store", `no store at ${input.dir}`, "Check the path you gave --dir.", {
|
|
733
|
+
dir: input.dir,
|
|
734
|
+
exists: false,
|
|
735
|
+
})
|
|
736
|
+
: finding("store", "green", "Store", input.dir, "", { dir: input.dir, exists: true }),
|
|
737
|
+
);
|
|
738
|
+
return out;
|
|
739
|
+
}
|
|
740
|
+
if (reason === "absent" || reason === "unreadable") {
|
|
741
|
+
out.push(
|
|
742
|
+
finding(
|
|
743
|
+
"config",
|
|
744
|
+
"red",
|
|
745
|
+
"Config",
|
|
746
|
+
`${input.configPath} — ${reason === "absent" ? "no such file" : "unreadable, so every entry point stands down to observer"}`,
|
|
747
|
+
reason === "absent"
|
|
748
|
+
? "Run: counterparts install (or point --config at the file you meant)."
|
|
749
|
+
: "Fix the JSON, or restore it from claude-code.json.bak beside it.",
|
|
750
|
+
{ path: input.configPath, reason },
|
|
751
|
+
),
|
|
752
|
+
);
|
|
753
|
+
} else {
|
|
754
|
+
out.push(
|
|
755
|
+
finding(
|
|
756
|
+
"config",
|
|
757
|
+
"green",
|
|
758
|
+
"Config",
|
|
759
|
+
`${input.configPath} — read; dataDir ${input.config.dataDir ?? "(unset: the default store)"}`,
|
|
760
|
+
"",
|
|
761
|
+
{ path: input.configPath, reason: reason ?? "read-by-caller", dataDir: input.config.dataDir ?? null },
|
|
762
|
+
),
|
|
763
|
+
);
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// THE STORE THE HOOKS WOULD OPEN, against the one this reading opened. I31's
|
|
767
|
+
// shape: the hooks and another entry point named different stores and nothing
|
|
768
|
+
// noticed, because each was internally consistent.
|
|
769
|
+
const named = input.config.dataDir;
|
|
770
|
+
if (input.store === null) {
|
|
771
|
+
out.push(
|
|
772
|
+
finding("store", "red", "Store", `no store at ${input.dir}`, "Run: counterparts install, or name the store with --dir.", {
|
|
773
|
+
dir: input.dir,
|
|
774
|
+
exists: false,
|
|
775
|
+
}),
|
|
776
|
+
);
|
|
777
|
+
} else if (named !== undefined && named !== input.dir) {
|
|
778
|
+
out.push(
|
|
779
|
+
finding(
|
|
780
|
+
"store",
|
|
781
|
+
"amber",
|
|
782
|
+
"Store",
|
|
783
|
+
`read ${input.dir}, but ${input.configPath} names ${named} — the hooks read the second one`,
|
|
784
|
+
"Drop --dir (and COUNTERPARTS_DATA_DIR) to read the store the hooks use.",
|
|
785
|
+
{ dir: input.dir, named, exists: true },
|
|
786
|
+
),
|
|
787
|
+
);
|
|
788
|
+
} else {
|
|
789
|
+
out.push(finding("store", "green", "Store", input.dir, "", { dir: input.dir, exists: true }));
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
const embedder = input.config.embedder?.enabled === true;
|
|
793
|
+
out.push(
|
|
794
|
+
embedder
|
|
795
|
+
? finding("embedder", "green", "Embedder", "enabled", "", { enabled: true })
|
|
796
|
+
: finding(
|
|
797
|
+
"embedder",
|
|
798
|
+
"amber",
|
|
799
|
+
"Embedder",
|
|
800
|
+
// SAYS WHAT STILL WORKS (2026-09-20, finding 1). "No vectors, no
|
|
801
|
+
// semantic channel" is true and reads, on day 1, as a broken install.
|
|
802
|
+
// Lexical recall is a whole working channel, not a degraded mode, and
|
|
803
|
+
// the line that tells a new user so is the one that stops them going
|
|
804
|
+
// to buy a key the README says they do not need.
|
|
805
|
+
"off — recall matches on words, not on meaning. That channel works; what a key adds " +
|
|
806
|
+
"is finding a memory that says the same thing in different words",
|
|
807
|
+
`Optional. Add "embedder": { "enabled": true } to ${input.configPath} (read strictly: that exact shape), and set ${EMBED_KEY_ENV}.`,
|
|
808
|
+
{ enabled: false },
|
|
809
|
+
),
|
|
810
|
+
);
|
|
811
|
+
|
|
812
|
+
if (input.config.observer === true) {
|
|
813
|
+
out.push(
|
|
814
|
+
finding("stance", "amber", "Stance", "observer: this host reads memory and never writes it", "Remove \"observer\" from the config to encode again.", {
|
|
815
|
+
observer: true,
|
|
816
|
+
}),
|
|
817
|
+
);
|
|
818
|
+
} else {
|
|
819
|
+
out.push(finding("stance", "green", "Stance", "owner: this host encodes", "", { observer: false }));
|
|
820
|
+
}
|
|
821
|
+
return out;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* HAS THIS STORE EVER HAD A WORKING KEY (2026-09-20, finding 1).
|
|
826
|
+
*
|
|
827
|
+
* README says no API keys are required and QUICKSTART §6 says the worker still
|
|
828
|
+
* runs the day without one — and `doctor` on a brand-new keyless store printed
|
|
829
|
+
* a RED and exited 1. All three cannot be true. A careful reader concludes a
|
|
830
|
+
* fresh install is broken; a trusting one buys a key the docs said they did not
|
|
831
|
+
* need.
|
|
832
|
+
*
|
|
833
|
+
* The red was written for a real and serious case, so it is kept for that case
|
|
834
|
+
* and only that one: a key that was HERE and has gone. The discriminator is the
|
|
835
|
+
* store's own evidence, never a marker file — a marker would have to be written
|
|
836
|
+
* by something, and the thing that would write it is the thing that is missing.
|
|
837
|
+
*
|
|
838
|
+
* - The interpreter ran if anything was ever interpreted. `gate.chunk` is the
|
|
839
|
+
* crash sweep's own row and the sweep is the only interpreted write path,
|
|
840
|
+
* so one such row ever is proof the key worked here.
|
|
841
|
+
* - The embedder ran if any backfill ever embedded anything.
|
|
842
|
+
*
|
|
843
|
+
* Both are ONE bounded read each, over the whole log, and both answer "ever",
|
|
844
|
+
* so neither can be undone by retention sweeping the window.
|
|
845
|
+
*
|
|
846
|
+
* **THE FALSE NEGATIVE, stated.** A key that was present and never EXERCISED —
|
|
847
|
+
* no session ever crashed, so the sweep never ran — leaves no `gate.chunk`, and
|
|
848
|
+
* removing it reads amber where the owner might want red. That is the direction
|
|
849
|
+
* this errs on purpose: the amber still names the key and still says what it
|
|
850
|
+
* would add, so nothing is hidden; the alternative errs towards telling every
|
|
851
|
+
* new user their install is broken. Revisit if a second signal appears that
|
|
852
|
+
* proves the key worked without the sweep having run.
|
|
853
|
+
*/
|
|
854
|
+
interface KeyHistory {
|
|
855
|
+
readonly interpreted: boolean;
|
|
856
|
+
readonly embedded: boolean;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
export function keyHistory(store: Store | null): KeyHistory {
|
|
860
|
+
if (store === null) return { interpreted: false, embedded: false };
|
|
861
|
+
const any = (name: string, limit: number, ok: (p: Record<string, unknown>) => boolean): boolean => {
|
|
862
|
+
try {
|
|
863
|
+
return store.eventLog({ name, limit }).some((r) => ok(payloadOf(r)));
|
|
864
|
+
} catch {
|
|
865
|
+
// A store that will not answer is not a store that says "never had one".
|
|
866
|
+
// Both callers read `false` as "no evidence", and the line that follows
|
|
867
|
+
// says what works without a key rather than accusing anybody.
|
|
868
|
+
return false;
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
return {
|
|
872
|
+
// ONE ROW. `eventLog` orders ascending and `events_name` is an index, so
|
|
873
|
+
// "has there ever been one" is the cheapest question this file asks.
|
|
874
|
+
interpreted: any(GATE_CHUNK_EVENT, 1, () => true),
|
|
875
|
+
// A backfill row exists with or without a key — it records what is still
|
|
876
|
+
// waiting — so this one has to look at the number, over a bounded window of
|
|
877
|
+
// the OLDEST rows, which is where a key that worked and then went would be.
|
|
878
|
+
embedded: any(EMBED_BACKFILL_EVENT, KEY_HISTORY_ROWS, (p) => (num(p, "embedded") ?? 0) > 0),
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/** How many backfill rows the "has a key ever worked here" read looks at. */
|
|
883
|
+
const KEY_HISTORY_ROWS = 200;
|
|
884
|
+
|
|
885
|
+
/** What a store with no key still does, in one sentence a new user can act on. */
|
|
886
|
+
const WITHOUT_A_KEY =
|
|
887
|
+
"everything you and the assistant write by hand still lands — note, session_end, the journal, " +
|
|
888
|
+
"recall, the wake";
|
|
889
|
+
|
|
890
|
+
/**
|
|
891
|
+
* The credentials, BY NAME. The red is I32's own signature: no interpreter key
|
|
892
|
+
* means the worker runs the day and interprets nothing — but see `keyHistory`
|
|
893
|
+
* above: that red is for a key that WENT AWAY, not for a store that never had
|
|
894
|
+
* one, which is a supported way to run.
|
|
895
|
+
*/
|
|
896
|
+
function credentialFindings(input: DoctorInput, history: KeyHistory): Finding[] {
|
|
897
|
+
const load = input.credentials;
|
|
898
|
+
const present = [...load.loaded, ...load.skippedPresent];
|
|
899
|
+
const missing = CREDENTIAL_NAMES.filter((n) => !present.includes(n));
|
|
900
|
+
const path = input.credentialsPath ?? "(no credentialsFile in the config)";
|
|
901
|
+
/**
|
|
902
|
+
* The clause for THE NAME THIS FINDING IS ABOUT, and no other: "your shell
|
|
903
|
+
* exports VOYAGE_API_KEY" hung on a red about `ANTHROPIC_API_KEY` reads as a
|
|
904
|
+
* non-sequitur and teaches the reader to skip the line.
|
|
905
|
+
*
|
|
906
|
+
* It is the sentence that closes I32 on the owner's own machine: his
|
|
907
|
+
* `~/.zshrc` exports both names, hook processes inherit neither (measured day
|
|
908
|
+
* 0), so "I have that key" and "the hooks have that key" are two different
|
|
909
|
+
* facts and this is where they are told apart.
|
|
910
|
+
*/
|
|
911
|
+
const shellClause = (name: string): string =>
|
|
912
|
+
(input.shellNames ?? []).includes(name) && !present.includes(name)
|
|
913
|
+
? ` — your shell exports ${name}, and hook processes do not inherit it`
|
|
914
|
+
: "";
|
|
915
|
+
const where = `${path}${load.mode === null ? "" : ` (mode ${load.mode})`}`;
|
|
916
|
+
const holds = present.length === 0 ? "holds no key" : `holds ${present.join(", ")}`;
|
|
917
|
+
const out: Finding[] = [];
|
|
918
|
+
|
|
919
|
+
const data = {
|
|
920
|
+
path,
|
|
921
|
+
mode: load.mode,
|
|
922
|
+
reason: load.reason,
|
|
923
|
+
present: present.join(","),
|
|
924
|
+
missing: missing.join(","),
|
|
925
|
+
everInterpreted: history.interpreted,
|
|
926
|
+
everEmbedded: history.embedded,
|
|
927
|
+
};
|
|
928
|
+
|
|
929
|
+
if (missing.includes(API_KEY_ENV)) {
|
|
930
|
+
// RED only when the key WORKED here and is now gone — the case this line
|
|
931
|
+
// was written for. Otherwise amber, and the sentence says what a store with
|
|
932
|
+
// no key does and what a key would add, rather than reporting a supported
|
|
933
|
+
// way to run as a fault on the first thing a new user sees.
|
|
934
|
+
out.push(
|
|
935
|
+
history.interpreted
|
|
936
|
+
? finding(
|
|
937
|
+
"credentials",
|
|
938
|
+
"red",
|
|
939
|
+
"Credentials",
|
|
940
|
+
`${where} ${holds}: ${API_KEY_ENV} is missing, and this store HAS interpreted before — so something that was running has stopped; the worker now runs the day and encodes nothing${shellClause(API_KEY_ENV)}`,
|
|
941
|
+
`Run: counterparts credentials set ${API_KEY_ENV} (the value on stdin; it is never echoed).`,
|
|
942
|
+
data,
|
|
943
|
+
)
|
|
944
|
+
: finding(
|
|
945
|
+
"credentials",
|
|
946
|
+
"amber",
|
|
947
|
+
"Credentials",
|
|
948
|
+
`${where} ${holds} — no key has ever been used here, which is a supported way to run: ${WITHOUT_A_KEY}. What ${API_KEY_ENV} would add is the crash sweep, which reads a transcript a session never got to write from and turns it into memories${shellClause(API_KEY_ENV)}`,
|
|
949
|
+
`Optional. Run: counterparts credentials set ${API_KEY_ENV} (the value on stdin; it is never echoed).`,
|
|
950
|
+
data,
|
|
951
|
+
),
|
|
952
|
+
);
|
|
953
|
+
} else if (missing.includes(EMBED_KEY_ENV)) {
|
|
954
|
+
out.push(
|
|
955
|
+
finding(
|
|
956
|
+
"credentials",
|
|
957
|
+
"amber",
|
|
958
|
+
"Credentials",
|
|
959
|
+
`${where} ${holds}: ${EMBED_KEY_ENV} is missing, so nothing is embedded${shellClause(EMBED_KEY_ENV)}`,
|
|
960
|
+
`Run: counterparts credentials set ${EMBED_KEY_ENV} (the value on stdin; it is never echoed).`,
|
|
961
|
+
data,
|
|
962
|
+
),
|
|
963
|
+
);
|
|
964
|
+
} else {
|
|
965
|
+
out.push(
|
|
966
|
+
finding("credentials", "green", "Credentials", `${where} ${holds}`, "", data),
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
// The mode is its own finding: a file that holds both keys and is world
|
|
971
|
+
// readable is a different problem from a file that holds neither, and
|
|
972
|
+
// collapsing them would let one hide the other. Warned, never refused
|
|
973
|
+
// (`permissionWarning` states the rule: the owner's machine, the owner's call).
|
|
974
|
+
if (load.mode !== null && load.mode !== "600") {
|
|
975
|
+
out.push(
|
|
976
|
+
finding(
|
|
977
|
+
"credentials-mode",
|
|
978
|
+
"amber",
|
|
979
|
+
"Cred mode",
|
|
980
|
+
`${path} is mode ${load.mode}${load.permissive ? " — group or other can read it" : ""}`,
|
|
981
|
+
`Run: chmod 600 ${path}`,
|
|
982
|
+
{ path, mode: load.mode, permissive: load.permissive },
|
|
983
|
+
),
|
|
984
|
+
);
|
|
985
|
+
}
|
|
986
|
+
return out;
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/** The two clocks, and the gap that IS I32's signature. */
|
|
990
|
+
function clockFindings(input: DoctorInput, store: Store): Finding[] {
|
|
991
|
+
const livedDay = store.livedDay();
|
|
992
|
+
const raw = store.getMeta("lastActiveDate");
|
|
993
|
+
// A store that has never lived a day carries the key with an EMPTY value, and
|
|
994
|
+
// "" is not the same fact as "2026-09-04": collapsing them here is how a fresh
|
|
995
|
+
// store would read as a frozen one.
|
|
996
|
+
const lastActive = raw === undefined || raw.length === 0 ? null : raw;
|
|
997
|
+
const read = newestRows(store, BOUNDARY_EVENT, 1, livedDay);
|
|
998
|
+
const boundary = rowDate(read.rows[0]);
|
|
999
|
+
const data = { livedDay, lastActiveDate: lastActive, newestBoundary: boundary, today: input.today };
|
|
1000
|
+
// Unknown is not "(none)": an unread newest boundary cannot be compared with
|
|
1001
|
+
// the clock, so the comparison is not made and the line says why.
|
|
1002
|
+
if (read.unknown) {
|
|
1003
|
+
const facts =
|
|
1004
|
+
`lived day ${livedDay}, lastActiveDate ${lastActive ?? "(unset)"}, today ${input.today} (UTC) — ` +
|
|
1005
|
+
undetermined(BOUNDARY_EVENT);
|
|
1006
|
+
return [finding("clock", "green", "Clock", facts, "", data)];
|
|
1007
|
+
}
|
|
1008
|
+
const facts =
|
|
1009
|
+
`lived day ${livedDay}, lastActiveDate ${lastActive ?? "(unset)"}, ` +
|
|
1010
|
+
`newest boundary ${boundary ?? "(none)"}, today ${input.today} (UTC)`;
|
|
1011
|
+
if (boundary !== null && (lastActive === null || lastActive < boundary)) {
|
|
1012
|
+
return [
|
|
1013
|
+
finding(
|
|
1014
|
+
"clock",
|
|
1015
|
+
"amber",
|
|
1016
|
+
"Clock",
|
|
1017
|
+
`${facts} — sessions are reaching boundaries and the clock is not advancing: the worker is not running`,
|
|
1018
|
+
"Read the Spawn line below; a refused spawn is the usual cause.",
|
|
1019
|
+
data,
|
|
1020
|
+
),
|
|
1021
|
+
];
|
|
1022
|
+
}
|
|
1023
|
+
return [finding("clock", "green", "Clock", facts, "", data)];
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
/** The newest row of each family the background half leaves behind. */
|
|
1027
|
+
function rowFindings(input: DoctorInput, store: Store): Finding[] {
|
|
1028
|
+
const livedDay = store.livedDay();
|
|
1029
|
+
const out: Finding[] = [];
|
|
1030
|
+
/**
|
|
1031
|
+
* WAS THERE EVER AN OPPORTUNITY? An absent row is only evidence when a
|
|
1032
|
+
* boundary has been reached: on a store that has never held a session there is
|
|
1033
|
+
* nothing for the worker to have swept, no cycle to have run and nothing to
|
|
1034
|
+
* have embedded, and three ambers on a fresh install teach the owner to read
|
|
1035
|
+
* amber as decoration.
|
|
1036
|
+
*/
|
|
1037
|
+
// `unknown` means the store holds MORE than `NEWEST_LIMIT` boundary rows, so
|
|
1038
|
+
// it has certainly lived — the one thing this flag needs to know.
|
|
1039
|
+
const boundaries = newestRows(store, BOUNDARY_EVENT, 1, livedDay);
|
|
1040
|
+
const lived = boundaries.unknown || boundaries.rows.length > 0;
|
|
1041
|
+
/** The "no row yet" finding: amber once the store has lived, green before. */
|
|
1042
|
+
const absent = (key: string, title: string, what: string, fix: string): Finding =>
|
|
1043
|
+
lived
|
|
1044
|
+
? finding(key, "amber", title, what, fix, { rows: 0 })
|
|
1045
|
+
: finding(key, "green", title, `${what} — and no boundary has been reached here yet`, "", { rows: 0 });
|
|
1046
|
+
/** The "we could not read the newest one" finding: neutral, never a grade. */
|
|
1047
|
+
const unread = (key: string, title: string, name: string): Finding =>
|
|
1048
|
+
finding(key, "green", title, undetermined(name), "", { unknown: true });
|
|
1049
|
+
|
|
1050
|
+
const sweepRead = newestRows(store, SWEEP_GATE_EVENT, 1, livedDay);
|
|
1051
|
+
const sweep = sweepRead.rows[0];
|
|
1052
|
+
if (sweepRead.unknown) {
|
|
1053
|
+
out.push(unread("sweep", "Sweep", SWEEP_GATE_EVENT));
|
|
1054
|
+
} else if (sweep === undefined) {
|
|
1055
|
+
out.push(absent("sweep", "Sweep", "no sweep.gate row — no worker has reached the crash sweep here", "Read the Spawn line below."));
|
|
1056
|
+
} else {
|
|
1057
|
+
const p = payloadOf(sweep);
|
|
1058
|
+
const reason = str(p, "reason") ?? "(none)";
|
|
1059
|
+
const detail = `newest sweep.gate ${rowDate(sweep) ?? "?"}: reason ${reason}, ran ${num(p, "ran") ?? 0} of ${num(p, "scopes") ?? 0} scopes`;
|
|
1060
|
+
out.push(
|
|
1061
|
+
reason === "ran"
|
|
1062
|
+
? finding("sweep", "green", "Sweep", detail, "", { reason, ran: num(p, "ran"), date: rowDate(sweep) })
|
|
1063
|
+
: finding("sweep", "amber", "Sweep", detail, "The sweep stood down; the reason names why.", {
|
|
1064
|
+
reason,
|
|
1065
|
+
ran: num(p, "ran"),
|
|
1066
|
+
date: rowDate(sweep),
|
|
1067
|
+
}),
|
|
1068
|
+
);
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
const cycleRead = newestRows(store, SLEEP_CYCLE_EVENT, 1, livedDay);
|
|
1072
|
+
const cycle = cycleRead.rows[0];
|
|
1073
|
+
if (cycleRead.unknown) {
|
|
1074
|
+
out.push(unread("sleep", "Sleep", SLEEP_CYCLE_EVENT));
|
|
1075
|
+
} else if (cycle === undefined) {
|
|
1076
|
+
out.push(absent("sleep", "Sleep", "no sleep.cycle row — no cycle has run here since the rows existed", "Read the Spawn line below."));
|
|
1077
|
+
} else {
|
|
1078
|
+
const p = payloadOf(cycle);
|
|
1079
|
+
const reason = str(p, "reason") ?? "(none)";
|
|
1080
|
+
const failed = num(p, "failed") ?? 0;
|
|
1081
|
+
// WHICH PHASES RAN OUT OF ROAD, from the row's own phase entries (durable
|
|
1082
|
+
// since 2026-09-18). Not a severity: with a resume cursor a big store is
|
|
1083
|
+
// MEANT to take several nights over a full pass, and grading that amber
|
|
1084
|
+
// would teach the reader to ignore this line. It is here so that "the
|
|
1085
|
+
// consolidate pass reached a third of the store" is readable at all — the
|
|
1086
|
+
// fact that hid for two weeks was not that it happened but that nothing said so.
|
|
1087
|
+
const truncated = budgetTruncatedPhases(p);
|
|
1088
|
+
const detail =
|
|
1089
|
+
`newest sleep.cycle ${rowDate(cycle) ?? "?"}: reason ${reason}, ${failed} failed phase${failed === 1 ? "" : "s"}` +
|
|
1090
|
+
(str(p, "failedPhase") === null ? "" : `, died in ${String(str(p, "failedPhase"))}`) +
|
|
1091
|
+
(truncated.length === 0 ? "" : `; ${truncated.join(", ")}`);
|
|
1092
|
+
// `reason` is "ran" | "clock-failed" | "threw" (`counterpart.ts#recordSleepCycle`),
|
|
1093
|
+
// so anything but "ran" is a night that did not happen, not a cadence.
|
|
1094
|
+
const data = { reason, failed, date: rowDate(cycle), budgetTruncated: truncated.length };
|
|
1095
|
+
out.push(
|
|
1096
|
+
reason !== "ran"
|
|
1097
|
+
? finding("sleep", "red", "Sleep", detail, "The nightly cycle is not completing — decay, prune, dedup and consolidate are not running.", data)
|
|
1098
|
+
: failed > 0
|
|
1099
|
+
? finding("sleep", "amber", "Sleep", detail, "A phase failed; the row names it.", data)
|
|
1100
|
+
: finding("sleep", "green", "Sleep", detail, "", data),
|
|
1101
|
+
);
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
// TWO rows, because one bad backfill is a flaky provider and two in a row is
|
|
1105
|
+
// a poisoned input that will never clear itself (I33's whole shape: the same
|
|
1106
|
+
// head-64 chunk retried for 32 consecutive runs).
|
|
1107
|
+
const backfillRead = newestRows(store, EMBED_BACKFILL_EVENT, 2, livedDay);
|
|
1108
|
+
const backfills = backfillRead.rows;
|
|
1109
|
+
const newest = backfills[backfills.length - 1];
|
|
1110
|
+
if (backfillRead.unknown) {
|
|
1111
|
+
out.push(unread("backfill", "Backfill", EMBED_BACKFILL_EVENT));
|
|
1112
|
+
} else if (newest === undefined) {
|
|
1113
|
+
out.push(
|
|
1114
|
+
absent("backfill", "Backfill", "no adapter.embed.backfill row — nothing has been embedded here", "Read the Embedder and Credentials lines."),
|
|
1115
|
+
);
|
|
1116
|
+
} else {
|
|
1117
|
+
const p = payloadOf(newest);
|
|
1118
|
+
const embedded = num(p, "embedded") ?? 0;
|
|
1119
|
+
const failed = num(p, "failed") ?? 0;
|
|
1120
|
+
const detail =
|
|
1121
|
+
`newest backfill ${rowDate(newest) ?? "?"}: embedded ${embedded}, failed ${failed}, ` +
|
|
1122
|
+
`remaining ${num(p, "remaining") ?? 0}, skipped ${num(p, "skipped") ?? 0}` +
|
|
1123
|
+
(str(p, "codes") === null || str(p, "codes") === "" ? "" : `, codes ${String(str(p, "codes"))}`);
|
|
1124
|
+
const prior = backfills.length > 1 ? payloadOf(backfills[0]) : null;
|
|
1125
|
+
const stalledTwice =
|
|
1126
|
+
embedded === 0 &&
|
|
1127
|
+
failed > 0 &&
|
|
1128
|
+
prior !== null &&
|
|
1129
|
+
(num(prior, "embedded") ?? 0) === 0 &&
|
|
1130
|
+
(num(prior, "failed") ?? 0) > 0;
|
|
1131
|
+
const data = { embedded, failed, remaining: num(p, "remaining"), skipped: num(p, "skipped"), codes: str(p, "codes"), date: rowDate(newest) };
|
|
1132
|
+
out.push(
|
|
1133
|
+
stalledTwice
|
|
1134
|
+
? finding("backfill", "red", "Backfill", `${detail} — and the run before it embedded nothing too`, "The backfill is head-of-line blocked; the codes name the fault (see I33).", data)
|
|
1135
|
+
: failed > 0
|
|
1136
|
+
? finding("backfill", "amber", "Backfill", detail, "Some chunks failed; the codes name why.", data)
|
|
1137
|
+
: finding("backfill", "green", "Backfill", detail, "", data),
|
|
1138
|
+
);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
const creditRead = newestRows(store, RECALL_CREDIT_EVENT, 1, livedDay);
|
|
1142
|
+
const credit = creditRead.rows[0];
|
|
1143
|
+
if (creditRead.unknown) {
|
|
1144
|
+
out.push(unread("credit", "Credit", RECALL_CREDIT_EVENT));
|
|
1145
|
+
} else if (credit !== undefined) {
|
|
1146
|
+
const p = payloadOf(credit);
|
|
1147
|
+
const reason = str(p, "reason") ?? "(none)";
|
|
1148
|
+
const detail = `newest recall.credit ${rowDate(credit) ?? "?"}: reason ${reason}, credited ${num(p, "credited") ?? 0} of ${num(p, "considered") ?? 0} considered`;
|
|
1149
|
+
const data = { reason, credited: num(p, "credited"), considered: num(p, "considered"), date: rowDate(credit) };
|
|
1150
|
+
// `no-candidates` and `nothing-to-credit` are the ORDINARY readings until a
|
|
1151
|
+
// session expands or quotes something (HANDOFF, 2026-09-14); only the seam
|
|
1152
|
+
// itself failing is a finding.
|
|
1153
|
+
out.push(
|
|
1154
|
+
reason === "failed"
|
|
1155
|
+
? finding("credit", "amber", "Credit", detail, "The credit seam threw; the row names the reason.", data)
|
|
1156
|
+
: finding("credit", "green", "Credit", detail, "", data),
|
|
1157
|
+
);
|
|
1158
|
+
}
|
|
1159
|
+
return out;
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
/**
|
|
1163
|
+
* WHO IS DOING THE WRITING — one week of it, in the owner's own words.
|
|
1164
|
+
*
|
|
1165
|
+
* **The finding this answers (finding 12, diagnosed 2026-09-17).** Over the run
|
|
1166
|
+
* the crash fallback out-wrote the session itself 4.5 : 1, and every visible
|
|
1167
|
+
* surface read healthy while it happened: capture captured, deposits were
|
|
1168
|
+
* accepted, nothing was red. The two facts that would have shown it are not
|
|
1169
|
+
* hard to read and were simply never read out — how often the session was
|
|
1170
|
+
* OFFERED the pen, and how much of the week's memory it actually wrote. Both
|
|
1171
|
+
* come out of rows the store already keeps (constitution 11: the system itself
|
|
1172
|
+
* shows what fired).
|
|
1173
|
+
*
|
|
1174
|
+
* Three readings, seven calendar days, nothing computed and nothing guessed:
|
|
1175
|
+
*
|
|
1176
|
+
* - **The asks, by `outcome`** (`adapter.ask`). `asked` is an invitation that
|
|
1177
|
+
* went out; `capped` is one refused because an allowance was spent; `paced`
|
|
1178
|
+
* is one the substance pacer refused.
|
|
1179
|
+
*
|
|
1180
|
+
* The capped ones are SPLIT BY `reason`, because two different rules wear
|
|
1181
|
+
* that one outcome: rows written before 2026-09-17 carry
|
|
1182
|
+
* `day-chapter-cap` — the old ration four sessions of one day shared, whose
|
|
1183
|
+
* clock only the worker advanced — and rows since carry `session-ask-cap`,
|
|
1184
|
+
* this session's own allowance for the day
|
|
1185
|
+
* (`SELF_TUNABLES.MAX_ASKS_PER_SESSION`, which starts over with the calendar
|
|
1186
|
+
* date from 2026-09-18).
|
|
1187
|
+
* Counting them together let the line blame the per-session allowance for
|
|
1188
|
+
* refusals it never made, which is a diagnostic naming the wrong door. The
|
|
1189
|
+
* amber hint therefore keys on the NEW reason alone; the old one is still
|
|
1190
|
+
* counted and named, because the days it recorded are still in the window.
|
|
1191
|
+
* - **The answers** (`gate.deposit`): what the session handed back.
|
|
1192
|
+
* - **The memories** (`memories.source`): how many live memories of the week
|
|
1193
|
+
* the session wrote itself, against how many were written for it later.
|
|
1194
|
+
*
|
|
1195
|
+
* AMBER on either of two comparisons, and never red — this is a balance, not a
|
|
1196
|
+
* fault, and nothing here means the machine is broken.
|
|
1197
|
+
*
|
|
1198
|
+
* The window is CALENDAR days, taken from the payload's own `date` (else the
|
|
1199
|
+
* row's wall clock), never the lived-day column: the lived clock is advanced by
|
|
1200
|
+
* the worker and has run seven lived days across fifteen calendar ones on this
|
|
1201
|
+
* very store. `sinceDay` is used only to keep the SQL cheap, and a lived day is
|
|
1202
|
+
* never longer than a calendar day, so `livedDay - 7` cannot miss a row inside
|
|
1203
|
+
* the window.
|
|
1204
|
+
*/
|
|
1205
|
+
export const AUTHORSHIP_DAYS = 7;
|
|
1206
|
+
|
|
1207
|
+
/** The cap in force. Declared `satisfies AskReason` rather than typed loose, so
|
|
1208
|
+
* a rename in `self/episodes.ts` fails `tsc` here instead of quietly reading
|
|
1209
|
+
* zero one morning. */
|
|
1210
|
+
const SESSION_ASK_CAP = "session-ask-cap" satisfies AskReason;
|
|
1211
|
+
|
|
1212
|
+
/** The cap that WAS in force until 2026-09-17 — one ration shared by every
|
|
1213
|
+
* session of a lived day. Nothing writes it now and it is not in `AskReason`
|
|
1214
|
+
* any more, but the rows it wrote are still inside a seven-day window and a
|
|
1215
|
+
* count that folded them into the new cap would name the wrong door. */
|
|
1216
|
+
const DAY_CHAPTER_CAP = "day-chapter-cap";
|
|
1217
|
+
|
|
1218
|
+
/** The ceiling on one authorship read. A week of the owner's busiest recorded
|
|
1219
|
+
* day (137 ask decisions) is two orders of magnitude inside this; a read that
|
|
1220
|
+
* hits it says so rather than reporting the prefix as the whole. */
|
|
1221
|
+
const AUTHORSHIP_LIMIT = 20000;
|
|
1222
|
+
|
|
1223
|
+
/** `YYYY-MM-DD`, `back` days before `today`. UTC, like every date in this store. */
|
|
1224
|
+
function daysBefore(today: string, back: number): string {
|
|
1225
|
+
const at = Date.parse(`${today}T00:00:00Z`);
|
|
1226
|
+
if (Number.isNaN(at)) return today;
|
|
1227
|
+
return new Date(at - back * 86_400_000).toISOString().slice(0, 10);
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
/** Every row of one name whose CALENDAR date is on or after `from`. */
|
|
1231
|
+
function rowsInWindow(
|
|
1232
|
+
store: Store,
|
|
1233
|
+
name: string,
|
|
1234
|
+
livedDay: number,
|
|
1235
|
+
from: string,
|
|
1236
|
+
): { rows: EventRow[]; truncated: boolean } {
|
|
1237
|
+
const all = store.eventLog({
|
|
1238
|
+
name,
|
|
1239
|
+
sinceDay: Math.max(0, livedDay - AUTHORSHIP_DAYS),
|
|
1240
|
+
limit: AUTHORSHIP_LIMIT,
|
|
1241
|
+
});
|
|
1242
|
+
return {
|
|
1243
|
+
rows: all.filter((r) => {
|
|
1244
|
+
const date = rowDate(r);
|
|
1245
|
+
return date !== null && date >= from;
|
|
1246
|
+
}),
|
|
1247
|
+
// `eventLog` orders ASCENDING, so a full read is the OLDEST rows of the
|
|
1248
|
+
// window and the newest days are the ones missing. The counts are a floor
|
|
1249
|
+
// and the line says so; a confident wrong number is the one thing a
|
|
1250
|
+
// diagnostic may never produce.
|
|
1251
|
+
truncated: all.length >= AUTHORSHIP_LIMIT,
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
/** The oldest calendar date among the rows this line actually read — the second
|
|
1256
|
+
* clock for "too new to grade". Null when it read none at all. */
|
|
1257
|
+
function oldestAuthorshipDate(
|
|
1258
|
+
asks: readonly EventRow[],
|
|
1259
|
+
deposits: readonly EventRow[],
|
|
1260
|
+
): string | null {
|
|
1261
|
+
let oldest: string | null = null;
|
|
1262
|
+
for (const row of [...asks, ...deposits]) {
|
|
1263
|
+
const date = rowDate(row);
|
|
1264
|
+
if (date !== null && (oldest === null || date < oldest)) oldest = date;
|
|
1265
|
+
}
|
|
1266
|
+
return oldest;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
function authorshipFindings(input: DoctorInput, store: Store): Finding[] {
|
|
1270
|
+
const livedDay = store.livedDay();
|
|
1271
|
+
// Inclusive of today: seven calendar days means today and the six before it.
|
|
1272
|
+
const from = daysBefore(input.today, AUTHORSHIP_DAYS - 1);
|
|
1273
|
+
const asks = rowsInWindow(store, ADAPTER_ASK_EVENT, livedDay, from);
|
|
1274
|
+
const deposits = rowsInWindow(store, GATE_DEPOSIT_EVENT, livedDay, from);
|
|
1275
|
+
let asked = 0;
|
|
1276
|
+
let capped = 0;
|
|
1277
|
+
let cappedBySession = 0;
|
|
1278
|
+
let cappedByDay = 0;
|
|
1279
|
+
let paced = 0;
|
|
1280
|
+
let unlabelled = 0;
|
|
1281
|
+
for (const row of asks.rows) {
|
|
1282
|
+
const payload = payloadOf(row);
|
|
1283
|
+
switch (str(payload, "outcome")) {
|
|
1284
|
+
case "asked":
|
|
1285
|
+
asked += 1;
|
|
1286
|
+
break;
|
|
1287
|
+
case "capped": {
|
|
1288
|
+
capped += 1;
|
|
1289
|
+
const reason = str(payload, "reason");
|
|
1290
|
+
if (reason === SESSION_ASK_CAP) cappedBySession += 1;
|
|
1291
|
+
else if (reason === DAY_CHAPTER_CAP) cappedByDay += 1;
|
|
1292
|
+
break;
|
|
1293
|
+
}
|
|
1294
|
+
case "paced":
|
|
1295
|
+
paced += 1;
|
|
1296
|
+
break;
|
|
1297
|
+
default:
|
|
1298
|
+
// Rows from before the single pacer carry no `outcome` at all. Counted
|
|
1299
|
+
// apart rather than folded into one of the three, and named only when
|
|
1300
|
+
// there are any — a bucket that is always zero is noise.
|
|
1301
|
+
unlabelled += 1;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
const authored = store.countMemories({
|
|
1305
|
+
type: "memory",
|
|
1306
|
+
archived: false,
|
|
1307
|
+
source: "authored",
|
|
1308
|
+
learnedOnFrom: from,
|
|
1309
|
+
});
|
|
1310
|
+
const fallback = store.countMemories({
|
|
1311
|
+
type: "memory",
|
|
1312
|
+
archived: false,
|
|
1313
|
+
source: "fallback",
|
|
1314
|
+
learnedOnFrom: from,
|
|
1315
|
+
});
|
|
1316
|
+
// The NEW reason alone decides the hint: the old shared day cap stopped being
|
|
1317
|
+
// written on 2026-09-17 and its rows only age out of the window, so keying on
|
|
1318
|
+
// the total would go on blaming a rule nothing enforces any more.
|
|
1319
|
+
const capBinds = cappedBySession > asked;
|
|
1320
|
+
const sweepWins = fallback > authored;
|
|
1321
|
+
const cappedSplit = [
|
|
1322
|
+
cappedBySession === 0 ? "" : `${String(cappedBySession)} by a session's own allowance for the day`,
|
|
1323
|
+
cappedByDay === 0 ? "" : `${String(cappedByDay)} by the old shared day cap`,
|
|
1324
|
+
capped - cappedBySession - cappedByDay === 0
|
|
1325
|
+
? ""
|
|
1326
|
+
: `${String(capped - cappedBySession - cappedByDay)} naming no cap`,
|
|
1327
|
+
].filter((s) => s.length > 0);
|
|
1328
|
+
const detail =
|
|
1329
|
+
`${from}→${input.today}: the session was invited to write ${String(asked)} ${asked === 1 ? "time" : "times"}, ` +
|
|
1330
|
+
`refused ${String(capped)} on a cap${cappedSplit.length === 0 ? "" : ` (${cappedSplit.join(", ")})`} ` +
|
|
1331
|
+
`and ${String(paced)} for pacing` +
|
|
1332
|
+
`${unlabelled === 0 ? "" : ` (${String(unlabelled)} older rows name no outcome)`}; ` +
|
|
1333
|
+
`it answered with ${String(deposits.rows.length)} ${deposits.rows.length === 1 ? "deposit" : "deposits"}; ` +
|
|
1334
|
+
`${String(authored)} live ${authored === 1 ? "memory" : "memories"} of that week ${authored === 1 ? "is" : "are"} its own, ` +
|
|
1335
|
+
`${String(fallback)} ${fallback === 1 ? "was" : "were"} written for it by the fallback sweep` +
|
|
1336
|
+
`${asks.truncated || deposits.truncated ? " (counts are a floor: the event read hit its limit)" : ""}`;
|
|
1337
|
+
const fixes = [
|
|
1338
|
+
capBinds
|
|
1339
|
+
? `A session's own allowance for the day (${String(SELF_TUNABLES.MAX_ASKS_PER_SESSION)} asks) is refusing the pen more often than it offers it — sessions are running long enough to exhaust it within a day, and that number is worth a look.`
|
|
1340
|
+
: "",
|
|
1341
|
+
sweepWins
|
|
1342
|
+
? "The sweep writes what the session did not: check that sessions reach a session-end boundary in the scope they captured in, and that the Stop ask is reaching the model."
|
|
1343
|
+
: "",
|
|
1344
|
+
].filter((s) => s.length > 0);
|
|
1345
|
+
const data = {
|
|
1346
|
+
from,
|
|
1347
|
+
to: input.today,
|
|
1348
|
+
asked,
|
|
1349
|
+
capped,
|
|
1350
|
+
cappedBySession,
|
|
1351
|
+
cappedByDay,
|
|
1352
|
+
paced,
|
|
1353
|
+
unlabelled,
|
|
1354
|
+
deposits: deposits.rows.length,
|
|
1355
|
+
authored,
|
|
1356
|
+
fallback,
|
|
1357
|
+
truncated: asks.truncated || deposits.truncated,
|
|
1358
|
+
};
|
|
1359
|
+
// TOO NEW TO GRADE (2026-09-20, finding 2). Both ambers here are RATIOS —
|
|
1360
|
+
// "the cap refused more often than it offered", "the sweep wrote more than
|
|
1361
|
+
// the session did" — and a ratio over a handful of rows is not a reading. On
|
|
1362
|
+
// a store that has not lived a day or two, the sentence stands and the colour
|
|
1363
|
+
// does not: there is nothing here to fix that waiting will not answer.
|
|
1364
|
+
//
|
|
1365
|
+
// **TWO CLOCKS, the same rule `FiredReport.young` keeps.** An earlier version
|
|
1366
|
+
// used the lived clock alone, arguing that these ambers are about how a
|
|
1367
|
+
// session behaved and so cannot predate the clock moving. That premise is
|
|
1368
|
+
// false: `store.advanceClock()` has exactly one caller, the sleep cycle, and
|
|
1369
|
+
// sessions ask and deposit at every boundary whether or not the worker ever
|
|
1370
|
+
// runs. So a store whose worker has been dead since day 1 — spawn refused, no
|
|
1371
|
+
// credential, a broken checkout — piles up a fortnight of asks and deposits
|
|
1372
|
+
// with a perfectly meaningful cap/sweep ratio and read GREEN, "too new to
|
|
1373
|
+
// grade", for ever. That is the exact store the two-clock rule exists to
|
|
1374
|
+
// protect, one finding over.
|
|
1375
|
+
const young =
|
|
1376
|
+
livedDay < YOUNG_LIVED_DAYS &&
|
|
1377
|
+
daysBetween(oldestAuthorshipDate(asks.rows, deposits.rows) ?? input.today, input.today) <
|
|
1378
|
+
YOUNG_LIVED_DAYS;
|
|
1379
|
+
return [
|
|
1380
|
+
finding(
|
|
1381
|
+
"authorship",
|
|
1382
|
+
!young && (capBinds || sweepWins) ? "amber" : "green",
|
|
1383
|
+
"Authorship",
|
|
1384
|
+
young && (capBinds || sweepWins)
|
|
1385
|
+
? `${detail} — too new to grade: this store is on lived day ${String(livedDay)}`
|
|
1386
|
+
: detail,
|
|
1387
|
+
young ? "" : fixes.join(" "),
|
|
1388
|
+
{ ...data, young, livedDay },
|
|
1389
|
+
),
|
|
1390
|
+
];
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
/**
|
|
1394
|
+
* WHAT FIRED — the roll-call of mechanisms, read from the rows that exist today.
|
|
1395
|
+
*
|
|
1396
|
+
* Constitution 11: done means seen firing, not merged, and the system itself
|
|
1397
|
+
* shows what fired and what did not. Several mechanisms merged in September ran
|
|
1398
|
+
* zero times on the live store and nothing said so; this is the line that would
|
|
1399
|
+
* have said it.
|
|
1400
|
+
*
|
|
1401
|
+
* AMBER on one comparison and never red in this first version: a mechanism that
|
|
1402
|
+
* fired in the PREVIOUS seven days and not once in this one. That is the only
|
|
1403
|
+
* signal here that says something CHANGED — a count of never-fired mechanisms is
|
|
1404
|
+
* a standing fact about the build, and ambering on it every morning would train
|
|
1405
|
+
* its reader to ignore the line that matters.
|
|
1406
|
+
*
|
|
1407
|
+
* THE SESSION-START READING DOES NOT TAKE IT. This is the only group here whose
|
|
1408
|
+
* SQL is not bounded by a lived day — the roll-call is a question about the
|
|
1409
|
+
* whole log, and the five table probes cost a query per memory on top — and a
|
|
1410
|
+
* hook that paid for it would have made the cure worse than the disease. The
|
|
1411
|
+
* between-groups budget check cannot help: a group that starts inside the budget
|
|
1412
|
+
* then runs as long as it likes. And it would buy nothing there, because the
|
|
1413
|
+
* notice carries reds only and this finding is never red. So the budgeted
|
|
1414
|
+
* reading says where the answer lives instead of half-reading it.
|
|
1415
|
+
*/
|
|
1416
|
+
function firedFindings(input: DoctorInput, store: Store): Finding[] {
|
|
1417
|
+
if (input.budgetMs !== undefined) {
|
|
1418
|
+
return [
|
|
1419
|
+
finding(
|
|
1420
|
+
"fired",
|
|
1421
|
+
"green",
|
|
1422
|
+
"Fired",
|
|
1423
|
+
"the roll-call of mechanisms is not read at session start: it walks the whole event log, " +
|
|
1424
|
+
"and a hook is not the place to pay for that",
|
|
1425
|
+
"",
|
|
1426
|
+
{ read: false },
|
|
1427
|
+
),
|
|
1428
|
+
];
|
|
1429
|
+
}
|
|
1430
|
+
const report = firedReport(store, input.today);
|
|
1431
|
+
const c = report.counts;
|
|
1432
|
+
const blocked =
|
|
1433
|
+
c.blocked === 0
|
|
1434
|
+
? ""
|
|
1435
|
+
: `, ${String(c.blocked)} ${c.blocked === 1 ? "was" : "were"} stopped by something that said so`;
|
|
1436
|
+
const roll =
|
|
1437
|
+
`${report.from}→${report.today}: ${String(c.firing)} of ${String(report.rows.length)} mechanisms fired this week${blocked}, ` +
|
|
1438
|
+
`${String(c.quiet)} ${c.quiet === 1 ? "has" : "have"} gone quiet, ` +
|
|
1439
|
+
`${String(c.never)} ${c.never === 1 ? "has" : "have"} never fired, ` +
|
|
1440
|
+
`${String(c.new)} ${c.new === 1 ? "is" : "are"} too new to grade, ` +
|
|
1441
|
+
`${String(c.blind)} ${c.blind === 1 ? "records" : "record"} nothing durable at all` +
|
|
1442
|
+
`${c.disabled + c.retired === 0 ? "" : ` (${String(c.disabled)} stood down, ${String(c.retired)} retired)`}` +
|
|
1443
|
+
`${report.notRead.length === 0 ? "" : `; ${String(report.notRead.length)} whose evidence is a table were not read on this pass`}` +
|
|
1444
|
+
`${report.truncated ? "; counts are a floor — the event read hit its limit" : ""}`;
|
|
1445
|
+
const data: Record<string, string | number | boolean | null> = {
|
|
1446
|
+
from: report.from,
|
|
1447
|
+
to: report.today,
|
|
1448
|
+
firing: c.firing,
|
|
1449
|
+
blocked: c.blocked,
|
|
1450
|
+
quiet: c.quiet,
|
|
1451
|
+
never: c.never,
|
|
1452
|
+
new: c.new,
|
|
1453
|
+
blind: c.blind,
|
|
1454
|
+
disabled: c.disabled,
|
|
1455
|
+
retired: c.retired,
|
|
1456
|
+
notRead: report.notRead.join(","),
|
|
1457
|
+
truncated: report.truncated,
|
|
1458
|
+
wentQuiet: report.wentQuiet.join("; "),
|
|
1459
|
+
wentBlocked: report.wentBlocked.join("; "),
|
|
1460
|
+
young: report.young,
|
|
1461
|
+
livedDay: report.livedDay,
|
|
1462
|
+
};
|
|
1463
|
+
// TOO NEW TO GRADE (2026-09-20, finding 2). On a store younger than a lived
|
|
1464
|
+
// day or two, "28 have never fired" is a true sentence that reads like a
|
|
1465
|
+
// broken install — nothing has fired because nothing has happened yet. One
|
|
1466
|
+
// line saying so is more use than the roll-call, and the roll-call comes back
|
|
1467
|
+
// on its own. GREEN, because there is nothing here to fix.
|
|
1468
|
+
if (report.young) {
|
|
1469
|
+
return [
|
|
1470
|
+
finding(
|
|
1471
|
+
"fired",
|
|
1472
|
+
"green",
|
|
1473
|
+
"Fired",
|
|
1474
|
+
`this store is on lived day ${String(report.livedDay)} — too new to grade; nothing has fired ` +
|
|
1475
|
+
`because nothing has happened yet` +
|
|
1476
|
+
(c.blocked === 0 ? "" : `, though ${String(c.blocked)} was already stopped by something`),
|
|
1477
|
+
c.blocked === 0 ? "" : "Run: counterparts fired — the blocked rows say by what.",
|
|
1478
|
+
data,
|
|
1479
|
+
),
|
|
1480
|
+
];
|
|
1481
|
+
}
|
|
1482
|
+
// GRADED ON BOTH LISTS. `blocked` outranks `quiet` in the state machine, so a
|
|
1483
|
+
// mechanism that fired last week and was turned away every day this week
|
|
1484
|
+
// leaves `wentQuiet` — and without `wentBlocked` this finding would have gone
|
|
1485
|
+
// GREEN for it. A state that says MORE must never make a diagnostic read
|
|
1486
|
+
// safer than it did before that state existed.
|
|
1487
|
+
if (report.wentQuiet.length === 0 && report.wentBlocked.length === 0) {
|
|
1488
|
+
return [
|
|
1489
|
+
finding(
|
|
1490
|
+
"fired",
|
|
1491
|
+
"green",
|
|
1492
|
+
"Fired",
|
|
1493
|
+
`${roll}. Nothing that fired last week has fallen silent this week.`,
|
|
1494
|
+
"",
|
|
1495
|
+
data,
|
|
1496
|
+
),
|
|
1497
|
+
];
|
|
1498
|
+
}
|
|
1499
|
+
const changed = [
|
|
1500
|
+
report.wentBlocked.length === 0
|
|
1501
|
+
? ""
|
|
1502
|
+
: `Fired last week and STOPPED this week: ${report.wentBlocked.join("; ")}`,
|
|
1503
|
+
report.wentQuiet.length === 0
|
|
1504
|
+
? ""
|
|
1505
|
+
: `Fired last week and not once this week: ${report.wentQuiet.join("; ")}`,
|
|
1506
|
+
].filter((s) => s.length > 0);
|
|
1507
|
+
return [
|
|
1508
|
+
finding(
|
|
1509
|
+
"fired",
|
|
1510
|
+
"amber",
|
|
1511
|
+
"Fired",
|
|
1512
|
+
`${roll}. ${changed.join(". ")}`,
|
|
1513
|
+
report.wentBlocked.length > 0
|
|
1514
|
+
? `Run: counterparts fired — ${STATE_MEANING.blocked}, and the reason on the row names what to fix.`
|
|
1515
|
+
: `Run: counterparts fired — ${STATE_MEANING.quiet}, which is a wiring fault more often than a verdict.`,
|
|
1516
|
+
data,
|
|
1517
|
+
),
|
|
1518
|
+
];
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
/** The spawn seam: the persisted counters and the rows they explain. */
|
|
1522
|
+
function spawnFindings(input: DoctorInput, store: Store): Finding[] {
|
|
1523
|
+
const livedDay = store.livedDay();
|
|
1524
|
+
const entries = Object.entries(input.refusals).filter(([, n]) => n > 0);
|
|
1525
|
+
entries.sort((a, b) => b[1] - a[1]);
|
|
1526
|
+
const worst = entries[0];
|
|
1527
|
+
// The COUNTERS decide this finding; these three rows only explain it. An
|
|
1528
|
+
// unreadable newest row says so in the clause rather than being dropped, which
|
|
1529
|
+
// would read as "there is no such row".
|
|
1530
|
+
const clause = (name: string): string | null => {
|
|
1531
|
+
const read = newestRows(store, name, 1, livedDay);
|
|
1532
|
+
if (read.unknown) return undetermined(name);
|
|
1533
|
+
const row = read.rows[0];
|
|
1534
|
+
return row === undefined ? null : `newest ${name} ${rowDate(row) ?? "?"} (${str(payloadOf(row), "reason") ?? "?"})`;
|
|
1535
|
+
};
|
|
1536
|
+
const rowClause = [clause(SPAWN_REFUSED_EVENT), clause(SPAWN_FAILED_EVENT), clause(RUNNER_FAILED_EVENT)]
|
|
1537
|
+
.filter((s): s is string => s !== null)
|
|
1538
|
+
.join("; ");
|
|
1539
|
+
const counts = entries.map(([reason, n]) => `${reason} ×${n}`).join(", ");
|
|
1540
|
+
// HOW MANY TIMES IT DID START TODAY. `adapter.spawn.started` is latched one
|
|
1541
|
+
// row per calendar date, so the row proves the door opened and this counter
|
|
1542
|
+
// is the only thing that says how often — which is why the row deliberately
|
|
1543
|
+
// carries no tally of its own (it would read `1` forever).
|
|
1544
|
+
const starts =
|
|
1545
|
+
input.starts !== undefined && input.starts.date === input.today && input.starts.count > 0
|
|
1546
|
+
? input.starts.count
|
|
1547
|
+
: null;
|
|
1548
|
+
const startClause =
|
|
1549
|
+
starts === null ? "" : `; started ${String(starts)} ${starts === 1 ? "time" : "times"} today`;
|
|
1550
|
+
const data: Record<string, string | number | boolean | null> = {
|
|
1551
|
+
counters: counts,
|
|
1552
|
+
escalateAfter: TUNABLES.ESCALATE_AFTER,
|
|
1553
|
+
worstReason: worst?.[0] ?? null,
|
|
1554
|
+
worstCount: worst?.[1] ?? 0,
|
|
1555
|
+
};
|
|
1556
|
+
if (worst !== undefined && worst[1] >= TUNABLES.ESCALATE_AFTER) {
|
|
1557
|
+
return [
|
|
1558
|
+
finding(
|
|
1559
|
+
"spawn",
|
|
1560
|
+
"red",
|
|
1561
|
+
"Spawn",
|
|
1562
|
+
`the background worker has been refused ${worst[1]} times in a row (${worst[0]})${rowClause === "" ? "" : ` — ${rowClause}`}`,
|
|
1563
|
+
worst[0] === "NO_CREDENTIAL"
|
|
1564
|
+
? `Run: counterparts credentials set ${API_KEY_ENV}`
|
|
1565
|
+
: "Read the newest adapter.spawn.refused row; its reason names the door.",
|
|
1566
|
+
data,
|
|
1567
|
+
),
|
|
1568
|
+
];
|
|
1569
|
+
}
|
|
1570
|
+
if (entries.length > 0) {
|
|
1571
|
+
return [
|
|
1572
|
+
finding("spawn", "amber", "Spawn", `spawn refusals standing: ${counts}${rowClause === "" ? "" : ` — ${rowClause}`}`, "A spawn that starts clears every counter.", data),
|
|
1573
|
+
];
|
|
1574
|
+
}
|
|
1575
|
+
return [
|
|
1576
|
+
finding(
|
|
1577
|
+
"spawn",
|
|
1578
|
+
"green",
|
|
1579
|
+
"Spawn",
|
|
1580
|
+
`no spawn refusals standing${startClause}${rowClause === "" ? "" : ` (${rowClause})`}`,
|
|
1581
|
+
"",
|
|
1582
|
+
{ ...data, startsToday: starts },
|
|
1583
|
+
),
|
|
1584
|
+
];
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
/**
|
|
1588
|
+
* WHICH CODE IS LIVE. The hooks and the MCP server run whatever the install
|
|
1589
|
+
* tree has checked out, so an unmerged branch sitting in it is not a development
|
|
1590
|
+
* state — it is the memory layer the owner is using today.
|
|
1591
|
+
*/
|
|
1592
|
+
function checkoutFindings(reading: CheckoutReading): Finding[] {
|
|
1593
|
+
const data: Record<string, string | number | boolean | null> = {
|
|
1594
|
+
reason: reading.reason,
|
|
1595
|
+
root: reading.root,
|
|
1596
|
+
branch: reading.branch,
|
|
1597
|
+
head: reading.head,
|
|
1598
|
+
dirty: reading.dirty,
|
|
1599
|
+
behindBy: reading.behindBy,
|
|
1600
|
+
originMaster: reading.originMaster,
|
|
1601
|
+
atMaster: reading.atMaster,
|
|
1602
|
+
timedOut: reading.timedOut,
|
|
1603
|
+
};
|
|
1604
|
+
if (reading.reason === "not-a-repo") {
|
|
1605
|
+
return [finding("checkout", "green", "Checkout", "not a git checkout — an installed package, nothing to grade", "", data)];
|
|
1606
|
+
}
|
|
1607
|
+
if (reading.reason === "unreadable") {
|
|
1608
|
+
return [
|
|
1609
|
+
finding(
|
|
1610
|
+
"checkout",
|
|
1611
|
+
"green",
|
|
1612
|
+
"Checkout",
|
|
1613
|
+
reading.timedOut
|
|
1614
|
+
? `${reading.root} — git did not answer within ${CHECKOUT_BUDGET_MS} ms, so the checkout was not graded`
|
|
1615
|
+
: reading.head === null
|
|
1616
|
+
? `${reading.root} — git did not answer, so the checkout was not graded`
|
|
1617
|
+
: `${reading.root} — no ${ORIGIN_MASTER} as last fetched, so there is nothing to grade against`,
|
|
1618
|
+
"",
|
|
1619
|
+
data,
|
|
1620
|
+
),
|
|
1621
|
+
];
|
|
1622
|
+
}
|
|
1623
|
+
const where = `${reading.branch ?? "detached"}@${reading.head ?? "?"}`;
|
|
1624
|
+
if (reading.reason === "master") {
|
|
1625
|
+
return [
|
|
1626
|
+
finding("checkout", "green", "Checkout", `${reading.root} at origin/master (${where}), clean`, "", data),
|
|
1627
|
+
];
|
|
1628
|
+
}
|
|
1629
|
+
if (reading.reason === "behind") {
|
|
1630
|
+
// AMBER, and deliberately not red: what runs is old, but it is merged code.
|
|
1631
|
+
// A merge to origin/master does not deploy — this tree has to move.
|
|
1632
|
+
return [
|
|
1633
|
+
finding(
|
|
1634
|
+
"checkout",
|
|
1635
|
+
"amber",
|
|
1636
|
+
"Checkout",
|
|
1637
|
+
`${where} is behind origin/master by ${String(reading.behindBy ?? 0)} commit${reading.behindBy === 1 ? "" : "s"} as last fetched — master moved and this checkout did not`,
|
|
1638
|
+
`Move the checkout: git -C ${reading.root} pull --ff-only (the hooks run what is in that tree, not what is on the remote).`,
|
|
1639
|
+
data,
|
|
1640
|
+
),
|
|
1641
|
+
];
|
|
1642
|
+
}
|
|
1643
|
+
const what =
|
|
1644
|
+
reading.reason === "dirty"
|
|
1645
|
+
? `the live hooks are running a modified checkout: ${where}, ${reading.dirty} tracked file${reading.dirty === 1 ? "" : "s"} modified`
|
|
1646
|
+
: `the live hooks are running an unmerged checkout: ${where}, which is not an ancestor of origin/master`;
|
|
1647
|
+
return [
|
|
1648
|
+
finding(
|
|
1649
|
+
"checkout",
|
|
1650
|
+
"red",
|
|
1651
|
+
"Checkout",
|
|
1652
|
+
what,
|
|
1653
|
+
`Return ${reading.root} to origin/master (git -C ${reading.root} checkout master) — what is in that tree is live on the owner's memory.`,
|
|
1654
|
+
data,
|
|
1655
|
+
),
|
|
1656
|
+
];
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1659
|
+
/**
|
|
1660
|
+
* THE OPEN ITSELF — red when a session's own read path would throw here.
|
|
1661
|
+
*
|
|
1662
|
+
* The wording is the hook's: one code and one clause of plain words, so the red
|
|
1663
|
+
* line in the terminal and this line say the same thing about the same morning.
|
|
1664
|
+
*/
|
|
1665
|
+
function openFindings(reading: OpenReading): Finding[] {
|
|
1666
|
+
const data: Record<string, string | number | boolean | null> = {
|
|
1667
|
+
dir: reading.dir,
|
|
1668
|
+
ok: reading.ok,
|
|
1669
|
+
code: reading.code,
|
|
1670
|
+
busy: reading.busy,
|
|
1671
|
+
path: reading.path,
|
|
1672
|
+
};
|
|
1673
|
+
if (reading.ok) {
|
|
1674
|
+
return [
|
|
1675
|
+
finding("store-open", "green", "Store open", `${reading.dir} opens as a session opens it`, "", data),
|
|
1676
|
+
];
|
|
1677
|
+
}
|
|
1678
|
+
const said = `${reading.dir}: will not open — ${reading.code ?? "?"}: ${reading.reason}`;
|
|
1679
|
+
if (reading.busy) {
|
|
1680
|
+
// NOT A STATE OF THE STORE. Another process held it for the moment this
|
|
1681
|
+
// reading wanted it; a second later it may open perfectly. Grading that red
|
|
1682
|
+
// would put an alarm on a race, which is how a diagnostic teaches its reader
|
|
1683
|
+
// to skip a line.
|
|
1684
|
+
return [
|
|
1685
|
+
finding(
|
|
1686
|
+
"store-open",
|
|
1687
|
+
"amber",
|
|
1688
|
+
"Store open",
|
|
1689
|
+
`${reading.dir}: the database was busy right now, so the open was not graded`,
|
|
1690
|
+
"Run: counterparts doctor again. If it stays busy, something is holding the store — read the Journal line.",
|
|
1691
|
+
data,
|
|
1692
|
+
),
|
|
1693
|
+
];
|
|
1694
|
+
}
|
|
1695
|
+
if (reading.migratable) {
|
|
1696
|
+
return [
|
|
1697
|
+
finding(
|
|
1698
|
+
"store-open",
|
|
1699
|
+
"amber",
|
|
1700
|
+
"Store open",
|
|
1701
|
+
`${said} — read as an instrument, which may not write at open`,
|
|
1702
|
+
"The next hook to run as owner initializes or migrates it; run: counterparts install if none does.",
|
|
1703
|
+
data,
|
|
1704
|
+
),
|
|
1705
|
+
];
|
|
1706
|
+
}
|
|
1707
|
+
return [
|
|
1708
|
+
finding(
|
|
1709
|
+
"store-open",
|
|
1710
|
+
"red",
|
|
1711
|
+
"Store open",
|
|
1712
|
+
said,
|
|
1713
|
+
reading.path !== null
|
|
1714
|
+
? `Every session's hooks stand down here. Restore ${reading.path} — a row in this store points at it, and the read path chases it at every open.`
|
|
1715
|
+
: reading.id !== null
|
|
1716
|
+
? // THE ROW, NAMED. On the file floor this said "restore <path>" and the
|
|
1717
|
+
// owner could fetch that one file from a snapshot; the words are the
|
|
1718
|
+
// row now, so the id is the only handle there is — and without it he
|
|
1719
|
+
// cannot tell which of thousands of rows to act on (review B,
|
|
1720
|
+
// MAJOR-3). There is no repair COMMAND for this today, so the two
|
|
1721
|
+
// real exits are named rather than a command invented.
|
|
1722
|
+
`Every session's hooks stand down here: no wake, no recall, no capture. The row the read path ` +
|
|
1723
|
+
`met is ${reading.id} — its words are gone and its content hash still names them, which no write ` +
|
|
1724
|
+
`path in this build produces. THERE MAY BE MORE THAN ONE: this names the row that threw, and ` +
|
|
1725
|
+
`counterparts verify --dir <store> lists every such row. Two ways out, both the owner's call: ` +
|
|
1726
|
+
`restore a snapshot over the store (see the Snapshot line), or remove those rows — ` +
|
|
1727
|
+
`counterparts remove <id> --confirm --dir <store> — which tombstones each one and lets sessions ` +
|
|
1728
|
+
`start again, permanently and without its words.`
|
|
1729
|
+
: "Every session's hooks stand down here: no wake, no recall, no capture. The code names what the read path met.",
|
|
1730
|
+
data,
|
|
1731
|
+
),
|
|
1732
|
+
];
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
/** Coverage of the semantic channel — `verify`'s two census numbers, reused. */
|
|
1736
|
+
/**
|
|
1737
|
+
* Which journal mode box 2 is actually in — the one surface on which a
|
|
1738
|
+
* conversion that did not take becomes visible.
|
|
1739
|
+
*
|
|
1740
|
+
* `openDb` asks for WAL on a writer open and swallows a refusal, because a hook
|
|
1741
|
+
* must not die because the worker happened to be committing (`store/db.ts`).
|
|
1742
|
+
* That is right, and it is silent, so the MODE is the report. Reading it takes
|
|
1743
|
+
* no lock and converts nothing: this is an observer's question, and the console
|
|
1744
|
+
* that asks it is standing down.
|
|
1745
|
+
*/
|
|
1746
|
+
function journalFindings(store: Store): Finding[] {
|
|
1747
|
+
const mode = journalModeOf(paths.operational(store.dir));
|
|
1748
|
+
const data = { mode };
|
|
1749
|
+
if (mode === "wal") {
|
|
1750
|
+
return [
|
|
1751
|
+
finding("journal", "green", "Journal mode", `wal (busy timeout ${BUSY_TIMEOUT_MS} ms)`, "", data),
|
|
1752
|
+
];
|
|
1753
|
+
}
|
|
1754
|
+
return [
|
|
1755
|
+
finding(
|
|
1756
|
+
"journal",
|
|
1757
|
+
"amber",
|
|
1758
|
+
"Journal mode",
|
|
1759
|
+
`${mode}, not wal — several processes hold this store open at once, and only in wal does a reader never wait for the writer`,
|
|
1760
|
+
"Open one session, or run any command that writes: the next writer open converts it. If it keeps reading this, something on an older build is opening the store and setting it back.",
|
|
1761
|
+
data,
|
|
1762
|
+
),
|
|
1763
|
+
];
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
function vectorFindings(store: Store): Finding[] {
|
|
1767
|
+
const unembedded = store.unembeddedCount();
|
|
1768
|
+
const skipped = store.skippedVectorIds().length;
|
|
1769
|
+
const detail = `${unembedded} live memories with no vector, ${skipped} skipped after repeated embed failures`;
|
|
1770
|
+
const data = { unembedded, skipped };
|
|
1771
|
+
if (skipped > 0) {
|
|
1772
|
+
return [finding("vectors", "amber", "Vectors", detail, "counterparts verify --dir <store> --retry-skipped puts the skipped ids back in the rotation.", data)];
|
|
1773
|
+
}
|
|
1774
|
+
if (unembedded > 0) {
|
|
1775
|
+
return [finding("vectors", "amber", "Vectors", detail, "The backfill embeds up to 64 per boundary; this number must fall run over run.", data)];
|
|
1776
|
+
}
|
|
1777
|
+
return [finding("vectors", "green", "Vectors", detail, "", data)];
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
/**
|
|
1781
|
+
* THE JOURNAL'S MARKDOWN COPY (2026-09-20, F6) — A LINE ONLY WHEN ONE IS OWED.
|
|
1782
|
+
*
|
|
1783
|
+
* This group returns NOTHING in the ordinary case, which is the deliberate part.
|
|
1784
|
+
* The copy is derived: it is rewritten on every chapter and refilled at every
|
|
1785
|
+
* boundary, so "how many files are there" is a number nobody needs and a
|
|
1786
|
+
* permanently green line here would be one more row the owner learns to skip
|
|
1787
|
+
* (the same argument `snapshotFindings` makes about a permanently amber one).
|
|
1788
|
+
*
|
|
1789
|
+
* The one reading worth a line is a STANDING failure: the newest
|
|
1790
|
+
* `journal.copy.failed` row is newer than the newest `journal.copy.written`,
|
|
1791
|
+
* which means the last attempt did not land and the next one has not fixed it.
|
|
1792
|
+
* Amber, never red — the chapter itself is a row in the database and is not at
|
|
1793
|
+
* risk, which is exactly what the detail says.
|
|
1794
|
+
*/
|
|
1795
|
+
export function journalCopyFindings(store: Store): Finding[] {
|
|
1796
|
+
const day = store.livedDay();
|
|
1797
|
+
const failed = newestRows(store, JOURNAL_COPY_FAILED_EVENT, 1, day);
|
|
1798
|
+
if (failed.unknown || failed.rows.length === 0) return [];
|
|
1799
|
+
const newestFailed = failed.rows[failed.rows.length - 1] as EventRow;
|
|
1800
|
+
const written = newestRows(store, JOURNAL_COPY_WRITTEN_EVENT, 1, day);
|
|
1801
|
+
const newestWritten = written.rows[written.rows.length - 1];
|
|
1802
|
+
// A later success is the fix, and a fixed fault is not a line.
|
|
1803
|
+
if (newestWritten !== undefined && newestWritten.seq > newestFailed.seq) return [];
|
|
1804
|
+
const payload = payloadOf(newestFailed);
|
|
1805
|
+
const reason = typeof payload["reason"] === "string" ? payload["reason"] : "no reason recorded";
|
|
1806
|
+
const on = typeof payload["date"] === "string" ? payload["date"] : "(date unrecorded)";
|
|
1807
|
+
const episode = newestFailed.ref ?? "(unrecorded)";
|
|
1808
|
+
return [
|
|
1809
|
+
finding(
|
|
1810
|
+
"journal-copy",
|
|
1811
|
+
"amber",
|
|
1812
|
+
"Journal copy",
|
|
1813
|
+
`the readable copy of the journal could not be written on ${on} (${episode}: ${reason}), and nothing has written one since. The chapters themselves are rows in the database and are unharmed.`,
|
|
1814
|
+
"Check that the store directory is writable; the next chapter or the next session boundary writes it again, and deleting journal/ loses nothing.",
|
|
1815
|
+
{ episode, reason, on },
|
|
1816
|
+
),
|
|
1817
|
+
];
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
/**
|
|
1821
|
+
* THE SELF PAGE (2026-09-18, S1) — one line: is there one, how big, how old.
|
|
1822
|
+
*
|
|
1823
|
+
* GREEN when absent, amber when stale, and never red. A store with no page has
|
|
1824
|
+
* not written one yet, which is the correct state of a fresh install and on the
|
|
1825
|
+
* first day after this ships — absence is a fact, not a fault, and a line that
|
|
1826
|
+
* nags from the moment it lands is a line people learn to read past (the same
|
|
1827
|
+
* rule `fired.ts` states for its `blind` rows). Staleness is the reading worth
|
|
1828
|
+
* an amber: a page that exists and has stopped being revised means something
|
|
1829
|
+
* that was running has stopped.
|
|
1830
|
+
*
|
|
1831
|
+
* The reading is two row reads and a date comparison, so it sits with the cheap
|
|
1832
|
+
* groups rather than with `fired`.
|
|
1833
|
+
*/
|
|
1834
|
+
export function selfPageFindings(store: Store): Finding[] {
|
|
1835
|
+
const page = readSelfPage(store);
|
|
1836
|
+
if (page === null) {
|
|
1837
|
+
// CLEARED is not NEVER WRITTEN. The wake says the same thing either way — it
|
|
1838
|
+
// has no page — but a line telling the owner nothing was ever written, about
|
|
1839
|
+
// a page he cleared last week, is the diagnostic getting it wrong in the one
|
|
1840
|
+
// place he would look to check (adversarial review MINOR-F).
|
|
1841
|
+
const cleared = clearedPage(store);
|
|
1842
|
+
if (cleared !== null) {
|
|
1843
|
+
return [
|
|
1844
|
+
finding(
|
|
1845
|
+
"self-page",
|
|
1846
|
+
"green",
|
|
1847
|
+
"Self page",
|
|
1848
|
+
`cleared ${cleared.on === "" ? "(date unrecorded)" : `on ${cleared.on}`}` +
|
|
1849
|
+
`${cleared.reason === "" ? "" : ` — ${cleared.reason}`}; ${cleared.versions} version${cleared.versions === 1 ? "" : "s"} kept`,
|
|
1850
|
+
cleared.versions > 0
|
|
1851
|
+
? `Put one back with: counterparts self-page --restore ${cleared.newest}.`
|
|
1852
|
+
: "",
|
|
1853
|
+
{ present: false, cleared: true, on: cleared.on, versions: cleared.versions },
|
|
1854
|
+
),
|
|
1855
|
+
];
|
|
1856
|
+
}
|
|
1857
|
+
return [
|
|
1858
|
+
finding(
|
|
1859
|
+
"self-page",
|
|
1860
|
+
"green",
|
|
1861
|
+
"Self page",
|
|
1862
|
+
"no page written yet — the wake says it is still forming",
|
|
1863
|
+
"",
|
|
1864
|
+
{ present: false, cleared: false },
|
|
1865
|
+
),
|
|
1866
|
+
];
|
|
1867
|
+
}
|
|
1868
|
+
const stale = pageStaleOn(page.revisedOn, dateOf(store.now()), SELF_TUNABLES.PAGE_STALE_DAYS);
|
|
1869
|
+
const detail =
|
|
1870
|
+
`${page.bytes} bytes, version ${page.version}, last revised ${page.revisedOn === "" ? "(unrecorded)" : page.revisedOn}` +
|
|
1871
|
+
`${page.by === null ? "" : ` by ${page.by}`}`;
|
|
1872
|
+
const data = { present: true, bytes: page.bytes, version: page.version, revisedOn: page.revisedOn, stale };
|
|
1873
|
+
return [
|
|
1874
|
+
stale
|
|
1875
|
+
? finding(
|
|
1876
|
+
"self-page",
|
|
1877
|
+
"amber",
|
|
1878
|
+
"Self page",
|
|
1879
|
+
`${detail} — stale (over ${SELF_TUNABLES.PAGE_STALE_DAYS} days)`,
|
|
1880
|
+
"Nothing has revised it lately: check the page writer, or amend it yourself with counterparts self-page --write.",
|
|
1881
|
+
data,
|
|
1882
|
+
)
|
|
1883
|
+
: finding("self-page", "green", "Self page", detail, "", data),
|
|
1884
|
+
];
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
/**
|
|
1888
|
+
* THE NIGHTLY PAGE WRITER (2026-09-20, S2) — one line: has last night happened,
|
|
1889
|
+
* and what did it come to.
|
|
1890
|
+
*
|
|
1891
|
+
* **GREEN when it has never run on a store younger than a day**, and that is
|
|
1892
|
+
* the whole design of this line rather than a leniency. A mechanism that fires
|
|
1893
|
+
* once a night cannot have fired on a store installed this morning, and a line
|
|
1894
|
+
* that says something is wrong from the moment it lands is a line people learn
|
|
1895
|
+
* to read past — the same rule `fired.ts` states for its `blind` rows and the
|
|
1896
|
+
* same one `selfPageFindings` follows for an absent page.
|
|
1897
|
+
*
|
|
1898
|
+
* Green also for a night that read the day and had nothing to say: that is the
|
|
1899
|
+
* mechanism working, and it is stated in words rather than left as a silence.
|
|
1900
|
+
*
|
|
1901
|
+
* AMBER, with a fix, on the two readings that mean something has stopped: the
|
|
1902
|
+
* writer is switched off while a page exists (somebody turned it off and the
|
|
1903
|
+
* page will now only move by hand), and a run that failed or was refused. Never
|
|
1904
|
+
* red: nothing here can cost a session its memory.
|
|
1905
|
+
*/
|
|
1906
|
+
export function pageWriterFindings(store: Store, config: AdapterConfig): Finding[] {
|
|
1907
|
+
const mode = pageWriterMode(config);
|
|
1908
|
+
const today = dateOf(store.now());
|
|
1909
|
+
const about = pageWriterAbout(today);
|
|
1910
|
+
const last = lastPageWriterRun(store);
|
|
1911
|
+
const page = readSelfPage(store);
|
|
1912
|
+
const data = {
|
|
1913
|
+
mode,
|
|
1914
|
+
lastAbout: last?.about ?? "",
|
|
1915
|
+
lastOutcome: last?.outcome ?? "",
|
|
1916
|
+
ran: last !== null,
|
|
1917
|
+
};
|
|
1918
|
+
// A BLOCK THAT COULD NOT BE READ IS AMBER, AND IT SAYS WHICH KEY. The block is
|
|
1919
|
+
// lenient now (S2 review), so a typo costs the setting rather than the store's
|
|
1920
|
+
// memory — but a setting that silently did nothing is the other half of that
|
|
1921
|
+
// failure, and this is the line that stops it being silent.
|
|
1922
|
+
const ignored = config.pageWriter?.ignored ?? [];
|
|
1923
|
+
if (ignored.length > 0) {
|
|
1924
|
+
return [
|
|
1925
|
+
finding(
|
|
1926
|
+
"page-writer",
|
|
1927
|
+
"amber",
|
|
1928
|
+
"Page writer",
|
|
1929
|
+
`${mode} mode; ${ignored.join("; ")}`,
|
|
1930
|
+
"Fix the pageWriter block in claude-code.json. Nothing else in the file was affected, and memory is unaffected.",
|
|
1931
|
+
{ ...data, ignored: ignored.join(" | ") },
|
|
1932
|
+
),
|
|
1933
|
+
];
|
|
1934
|
+
}
|
|
1935
|
+
if (mode === "off") {
|
|
1936
|
+
// GREEN, always. Off is a setting somebody chose, and a diagnostic that
|
|
1937
|
+
// grades a deliberate choice as a fault is the shape of line people learn to
|
|
1938
|
+
// read past — the same rule `fired.ts` states for a `disabled` mechanism.
|
|
1939
|
+
// The line still says what off MEANS, so nobody has to remember.
|
|
1940
|
+
return [
|
|
1941
|
+
finding(
|
|
1942
|
+
"page-writer",
|
|
1943
|
+
"green",
|
|
1944
|
+
"Page writer",
|
|
1945
|
+
page === null
|
|
1946
|
+
? "off — nothing writes the self page on its own, and nothing has been written by hand either"
|
|
1947
|
+
: "off — the page stands, and from here it changes only when somebody writes it",
|
|
1948
|
+
"",
|
|
1949
|
+
data,
|
|
1950
|
+
),
|
|
1951
|
+
];
|
|
1952
|
+
}
|
|
1953
|
+
if (last === null) {
|
|
1954
|
+
// NEVER RUN. On a store with no yesterday that is the correct state and
|
|
1955
|
+
// says so; on one that has lived a day it is still green, because the
|
|
1956
|
+
// mechanism runs at the NEXT session start and has not been given a turn.
|
|
1957
|
+
const young = !hasDayBefore(store, today);
|
|
1958
|
+
return [
|
|
1959
|
+
finding(
|
|
1960
|
+
"page-writer",
|
|
1961
|
+
"green",
|
|
1962
|
+
"Page writer",
|
|
1963
|
+
young
|
|
1964
|
+
? `${mode} mode; never run — this store has no day before ${today} yet`
|
|
1965
|
+
: `${mode} mode; never run — the next session start is its first turn (${about})`,
|
|
1966
|
+
"",
|
|
1967
|
+
{ ...data, young },
|
|
1968
|
+
),
|
|
1969
|
+
];
|
|
1970
|
+
}
|
|
1971
|
+
const status = pageWriterStatus(store, last.about, today);
|
|
1972
|
+
const when = `last ran for ${last.about}${last.on === "" ? "" : ` on ${last.on}`}`;
|
|
1973
|
+
// IS TONIGHT'S ALREADY OWED, AND HAS IT BEEN OWED FOR A WHILE? The failure
|
|
1974
|
+
// this catches is the one with no row at all behind it: an ask that will not
|
|
1975
|
+
// fit the host's ceiling is DEFERRED, and a deferral leaves only a ring event
|
|
1976
|
+
// that dies with the hook process. Without this line, a writer that stopped
|
|
1977
|
+
// being delivered on day 4 reads exactly like one that ran last night —
|
|
1978
|
+
// which is I32's shape, and the reason this line exists at all.
|
|
1979
|
+
const owed = pageWriterDue(store, {
|
|
1980
|
+
mode,
|
|
1981
|
+
today,
|
|
1982
|
+
observer: store.observer,
|
|
1983
|
+
asksPerDay: SELF_TUNABLES.PAGE_WRITER_ASKS_PER_DAY,
|
|
1984
|
+
});
|
|
1985
|
+
const staleFor = last.on === "" ? 0 : daysBetween(last.on, today);
|
|
1986
|
+
const overdue = owed.due && staleFor > PAGE_WRITER_STALE_DAYS;
|
|
1987
|
+
const bad = status.outcome === "failed" || status.outcome === "refused";
|
|
1988
|
+
const detail =
|
|
1989
|
+
`${mode} mode; ${when} — ${status.outcome}` +
|
|
1990
|
+
(status.derived ? " (derived: it was handed the day and wrote nothing)" : "") +
|
|
1991
|
+
(status.run !== null && status.run.detail.length > 0 && !status.derived
|
|
1992
|
+
? `, ${status.run.detail}`
|
|
1993
|
+
: "") +
|
|
1994
|
+
(owed.due ? `; ${owed.about} is owed` : "") +
|
|
1995
|
+
(overdue ? ` and nothing has been delivered for ${String(staleFor)} days` : "");
|
|
1996
|
+
return [
|
|
1997
|
+
finding(
|
|
1998
|
+
"page-writer",
|
|
1999
|
+
bad || overdue ? "amber" : "green",
|
|
2000
|
+
"Page writer",
|
|
2001
|
+
detail,
|
|
2002
|
+
bad || overdue
|
|
2003
|
+
? "counterparts fired --dir <store> --observer shows the run's own row. A night that is owed but never delivered is usually the host's injection ceiling: the block is deferred rather than truncated, so raise injectionBudgetBytes or run the writer in host mode. counterparts self-page --write amends the page by hand meanwhile."
|
|
2004
|
+
: "",
|
|
2005
|
+
{
|
|
2006
|
+
...data,
|
|
2007
|
+
outcome: status.outcome,
|
|
2008
|
+
derived: status.derived,
|
|
2009
|
+
owedFor: owed.due ? owed.about : "",
|
|
2010
|
+
staleFor,
|
|
2011
|
+
},
|
|
2012
|
+
),
|
|
2013
|
+
];
|
|
2014
|
+
}
|
|
2015
|
+
|
|
2016
|
+
// `daysBetween` is `fired.ts`'s (E2, 2026-09-20) and is imported at the top of
|
|
2017
|
+
// this file rather than written twice. S2 landed a local copy of the same four
|
|
2018
|
+
// lines and the merge put them side by side; one definition is the rule this
|
|
2019
|
+
// module already keeps for every other reading it shares with the fired view.
|
|
2020
|
+
// The one behavioural difference is deliberate: the shared one can return a
|
|
2021
|
+
// NEGATIVE when a clock has moved backwards, and `overdue` below compares with
|
|
2022
|
+
// `>`, so a future date reads "not overdue" rather than being clamped to today.
|
|
2023
|
+
|
|
2024
|
+
/** Calendar days a night may be owed before the line says so. A writer that
|
|
2025
|
+
* missed last night has not failed; one that has missed three has. */
|
|
2026
|
+
export const PAGE_WRITER_STALE_DAYS = 2;
|
|
2027
|
+
|
|
2028
|
+
/** A page that was written and then cleared: when, why, and what is restorable.
|
|
2029
|
+
* Null when no page row exists at all. */
|
|
2030
|
+
function clearedPage(
|
|
2031
|
+
store: Store,
|
|
2032
|
+
): { on: string; reason: string; versions: number; newest: number } | null {
|
|
2033
|
+
const id = findPageRow(store);
|
|
2034
|
+
if (id === null) return null;
|
|
2035
|
+
let marker: { on: string; reason: string } | null = null;
|
|
2036
|
+
try {
|
|
2037
|
+
marker = clearedMarker(store.readProse(id).meta);
|
|
2038
|
+
} catch {
|
|
2039
|
+
return null;
|
|
2040
|
+
}
|
|
2041
|
+
if (marker === null) return null;
|
|
2042
|
+
const versions = store.versions(id);
|
|
2043
|
+
const newest = versions.reduce((n, v) => Math.max(n, v.seq), 0);
|
|
2044
|
+
return { ...marker, versions: versions.length, newest };
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2047
|
+
/**
|
|
2048
|
+
* Calendar days, like every other window here. A date that is absent or does
|
|
2049
|
+
* not READ reads as stale — the same direction `self/#pageStale` takes, and the
|
|
2050
|
+
* two are asserted to agree.
|
|
2051
|
+
*/
|
|
2052
|
+
function pageStaleOn(revisedOn: string, today: string, limit: number): boolean {
|
|
2053
|
+
const on = revisedOn.trim();
|
|
2054
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(on) || !/^\d{4}-\d{2}-\d{2}$/.test(today)) return true;
|
|
2055
|
+
const a = Date.parse(`${on}T00:00:00Z`);
|
|
2056
|
+
const b = Date.parse(`${today}T00:00:00Z`);
|
|
2057
|
+
if (!Number.isFinite(a) || !Number.isFinite(b)) return true;
|
|
2058
|
+
return Math.round((b - a) / 86_400_000) > limit;
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
/**
|
|
2062
|
+
* How to get a memory back. Short enough to survive being read in a panic, and
|
|
2063
|
+
* printed as the remedy on every Snapshot finding that is not green, because the
|
|
2064
|
+
* moment somebody needs it is the moment they will not go looking for it.
|
|
2065
|
+
*/
|
|
2066
|
+
export const RESTORE_STEPS =
|
|
2067
|
+
"To restore: stop every session, copy a snapshot directory to the store's path, " +
|
|
2068
|
+
"then counterparts verify --dir <store> --rebuild (with the embed key exported, or " +
|
|
2069
|
+
"the vectors are dropped and refilled over the following days). Everything comes back " +
|
|
2070
|
+
"with the copy — the memories, their versions and the journal are all in the database; " +
|
|
2071
|
+
"the search index and the vectors are rebuilt. A copy holding operational.sqlite or " +
|
|
2072
|
+
"prose/ is from BEFORE the floor changed and this build cannot open it: it is kept and " +
|
|
2073
|
+
"counted, never rotated, and the build tagged floor/v5-last reads it.";
|
|
2074
|
+
|
|
2075
|
+
/** How stale the newest snapshot may be before this line goes amber. A daily
|
|
2076
|
+
* mechanism that has not fired for two calendar days has missed one. */
|
|
2077
|
+
export const SNAPSHOT_STALE_DAYS = 2;
|
|
2078
|
+
|
|
2079
|
+
/**
|
|
2080
|
+
* IS THERE A RECENT COPY OF THE STORE, AND HOW MANY ARE ACTUALLY THERE.
|
|
2081
|
+
*
|
|
2082
|
+
* The one line that answers "if this database were wiped this afternoon, what
|
|
2083
|
+
* would come back" — so it **counts the directory**, not the row. The first
|
|
2084
|
+
* version of this finding read `kept` and `oldest` straight out of the newest
|
|
2085
|
+
* `snapshot.taken` row, and the F2 review proved what that is worth: delete every
|
|
2086
|
+
* copy from disk and the line still read green, "1 kept", for a full day, then
|
|
2087
|
+
* went amber for the wrong reason. A row says what a run once wrote. The
|
|
2088
|
+
* directory says what you have.
|
|
2089
|
+
*
|
|
2090
|
+
* Reading a directory listing writes nothing, so this is observer-safe.
|
|
2091
|
+
*
|
|
2092
|
+
* Amber, never red: a missing backup is not a broken memory, and a diagnostic
|
|
2093
|
+
* that shouts the same colour for both teaches its reader to read past the one
|
|
2094
|
+
* that matters.
|
|
2095
|
+
*/
|
|
2096
|
+
function snapshotFindings(input: DoctorInput, store: Store): Finding[] {
|
|
2097
|
+
const livedDay = store.livedDay();
|
|
2098
|
+
const resolved = resolveSnapshotsDir(input.dir, input.config.snapshots?.dir);
|
|
2099
|
+
const keep = keepOf(input.config.snapshots?.keep);
|
|
2100
|
+
// What the configuration could not read, said out loud rather than left as a
|
|
2101
|
+
// default nobody asked for (F2 review, MAJOR-2). It rides on every arm below.
|
|
2102
|
+
const ignored = input.config.snapshots?.ignored ?? [];
|
|
2103
|
+
const misread = ignored.length === 0 ? "" : ` — ${ignored.join("; ")}`;
|
|
2104
|
+
const data: Record<string, string | number | boolean | null> = {
|
|
2105
|
+
keep,
|
|
2106
|
+
where: resolved.reason,
|
|
2107
|
+
ignored: ignored.length === 0 ? null : ignored.join("; "),
|
|
2108
|
+
};
|
|
2109
|
+
if (resolved.dir === null) {
|
|
2110
|
+
// Not a fault and not a silence: this store is not the `store/` subdirectory
|
|
2111
|
+
// of a base directory, so there is nowhere by convention to put copies.
|
|
2112
|
+
return [
|
|
2113
|
+
finding(
|
|
2114
|
+
"snapshot",
|
|
2115
|
+
"amber",
|
|
2116
|
+
"Snapshot",
|
|
2117
|
+
`no daily snapshot is being taken: this store is not inside a base directory, so there is no default place to keep copies${misread}`,
|
|
2118
|
+
'Add "snapshots": { "dir": "<an absolute path outside the store>" } to the configuration.',
|
|
2119
|
+
data,
|
|
2120
|
+
),
|
|
2121
|
+
];
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
// THE DISK, FIRST. Everything printed below about how many copies there are
|
|
2125
|
+
// comes from here.
|
|
2126
|
+
const disk = readSnapshotsDir(resolved.dir);
|
|
2127
|
+
const onDisk = disk.names.length;
|
|
2128
|
+
const newest = disk.names[onDisk - 1] ?? null;
|
|
2129
|
+
const oldest = disk.names[0] ?? null;
|
|
2130
|
+
const future = futureNamesIn(disk.names, Date.parse(`${input.today}T00:00:00Z`)).length;
|
|
2131
|
+
// A correctly-named directory the layout rule does not recognise as a copy is
|
|
2132
|
+
// KEPT — this package never deletes what it cannot prove it made — but it is
|
|
2133
|
+
// never counted and never rotated either, so without this clause it would be
|
|
2134
|
+
// permanent, invisible residue in the one directory the owner relies on
|
|
2135
|
+
// (second F2 review, MAJOR-A).
|
|
2136
|
+
const strange =
|
|
2137
|
+
disk.unrecognised.length === 0
|
|
2138
|
+
? ""
|
|
2139
|
+
: `; ${String(disk.unrecognised.length)} director${disk.unrecognised.length === 1 ? "y is" : "ies are"} named like snapshots but do not look like copies of a store, so they are not counted and will never be rotated: ${disk.unrecognised.slice(0, 3).join(", ")}${disk.unrecognised.length > 3 ? ` and ${String(disk.unrecognised.length - 3)} more` : ""}`;
|
|
2140
|
+
// PRE-ROWS COPIES ARE SAID, AND THEY ARE NOT A FAULT (review B, MAJOR-2 and
|
|
2141
|
+
// NIT-3/-4). After cut-over the owner's snapshots directory holds his old
|
|
2142
|
+
// floor's copies permanently: they are never rotated, because this build
|
|
2143
|
+
// cannot open one to know what is in it. That is the right outcome and it
|
|
2144
|
+
// must not read as a problem — a permanently amber Snapshot line is a line
|
|
2145
|
+
// people learn to skip. So it is a clause on the ordinary sentence, and the
|
|
2146
|
+
// grading below deliberately does not consider it.
|
|
2147
|
+
const older =
|
|
2148
|
+
disk.preRows.length === 0
|
|
2149
|
+
? ""
|
|
2150
|
+
: `; ${String(disk.preRows.length)} older-format cop${disk.preRows.length === 1 ? "y" : "ies"} this build cannot open — kept, never rotated, read by the build tagged floor/v5-last: ${disk.preRows.slice(0, 3).join(", ")}${disk.preRows.length > 3 ? ` and ${String(disk.preRows.length - 3)} more` : ""}`;
|
|
2151
|
+
const held = {
|
|
2152
|
+
...data,
|
|
2153
|
+
onDisk,
|
|
2154
|
+
newest,
|
|
2155
|
+
oldest,
|
|
2156
|
+
readable: disk.readable,
|
|
2157
|
+
future,
|
|
2158
|
+
unrecognised: disk.unrecognised.length,
|
|
2159
|
+
preRows: disk.preRows.length,
|
|
2160
|
+
};
|
|
2161
|
+
|
|
2162
|
+
const read = newestRows(store, SNAPSHOT_TAKEN_EVENT, 1, livedDay);
|
|
2163
|
+
const row = read.unknown ? undefined : read.rows[0];
|
|
2164
|
+
const rowDated = rowDate(row);
|
|
2165
|
+
|
|
2166
|
+
// A ROW SAYS A COPY WAS MADE AND THE DIRECTORY HOLDS NONE. The loudest thing
|
|
2167
|
+
// this line can say, and the case the review proved read green.
|
|
2168
|
+
if (onDisk === 0 && (rowDated !== null || read.unknown)) {
|
|
2169
|
+
return [
|
|
2170
|
+
finding(
|
|
2171
|
+
"snapshot",
|
|
2172
|
+
"amber",
|
|
2173
|
+
"Snapshot",
|
|
2174
|
+
`${disk.readable ? "the snapshots directory is empty" : "the snapshots directory is missing or unreadable"} — but a snapshot.taken row says one was made${rowDated === null ? "" : ` on ${rowDated}`}. There is nothing to restore from.${strange}`,
|
|
2175
|
+
RESTORE_STEPS,
|
|
2176
|
+
{ ...held, rows: 1 },
|
|
2177
|
+
),
|
|
2178
|
+
];
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
if (onDisk === 0) {
|
|
2182
|
+
// The same rule the row findings use: an absent copy is only evidence once a
|
|
2183
|
+
// boundary has been reached. On a fresh install there has been no worker run
|
|
2184
|
+
// to take a first one, and an amber there is decoration.
|
|
2185
|
+
const boundaries = newestRows(store, BOUNDARY_EVENT, 1, livedDay);
|
|
2186
|
+
const lived = boundaries.unknown || boundaries.rows.length > 0;
|
|
2187
|
+
const failed = newestRows(store, SNAPSHOT_FAILED_EVENT, 1, livedDay);
|
|
2188
|
+
const failedRow = failed.rows[0];
|
|
2189
|
+
const why =
|
|
2190
|
+
failedRow === undefined
|
|
2191
|
+
? ""
|
|
2192
|
+
: ` — newest ${SNAPSHOT_FAILED_EVENT} ${rowDate(failedRow) ?? "?"} (${str(payloadOf(failedRow), "step") ?? "?"}: ${str(payloadOf(failedRow), "reason") ?? "?"})`;
|
|
2193
|
+
return [
|
|
2194
|
+
lived
|
|
2195
|
+
? finding(
|
|
2196
|
+
"snapshot",
|
|
2197
|
+
"amber",
|
|
2198
|
+
"Snapshot",
|
|
2199
|
+
`no snapshot has ever been taken here${why}${strange}${misread}`,
|
|
2200
|
+
"The worker takes one after the sleep cycle; the next boundary should leave a snapshot.taken row.",
|
|
2201
|
+
{ ...held, rows: 0 },
|
|
2202
|
+
)
|
|
2203
|
+
: finding(
|
|
2204
|
+
"snapshot",
|
|
2205
|
+
"green",
|
|
2206
|
+
"Snapshot",
|
|
2207
|
+
`no snapshot yet — and no boundary has been reached here yet${strange}${misread}`,
|
|
2208
|
+
"",
|
|
2209
|
+
{ ...held, rows: 0 },
|
|
2210
|
+
),
|
|
2211
|
+
];
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
// Copies exist. Their own names carry the date, so the line does not depend on
|
|
2215
|
+
// a row at all — and when a row disagrees with the directory, it says so.
|
|
2216
|
+
const newestDate = (newest ?? "").slice(0, 10);
|
|
2217
|
+
const detail =
|
|
2218
|
+
`last snapshot ${newestDate}, ${onDisk} kept` +
|
|
2219
|
+
(oldest === null ? "" : `, oldest ${oldest.slice(0, 10)}`) +
|
|
2220
|
+
(keep === DEFAULT_KEEP ? "" : ` (keeping ${keep})`) +
|
|
2221
|
+
(future === 0 ? "" : `; ${future} dated in the future, holding a slot each`) +
|
|
2222
|
+
(rowDated !== null && rowDated > newestDate
|
|
2223
|
+
? `; the newest snapshot.taken row says ${rowDated}, which is not on disk`
|
|
2224
|
+
: "") +
|
|
2225
|
+
strange +
|
|
2226
|
+
older +
|
|
2227
|
+
misread;
|
|
2228
|
+
// Two or more calendar days back is a daily mechanism that has missed one, so
|
|
2229
|
+
// the boundary day itself is already amber.
|
|
2230
|
+
const stale = newestDate === "" || newestDate <= daysBefore(input.today, SNAPSHOT_STALE_DAYS);
|
|
2231
|
+
const disagrees = rowDated !== null && rowDated > newestDate;
|
|
2232
|
+
return [
|
|
2233
|
+
stale || disagrees || future > 0 || disk.unrecognised.length > 0 || ignored.length > 0
|
|
2234
|
+
? finding(
|
|
2235
|
+
"snapshot",
|
|
2236
|
+
"amber",
|
|
2237
|
+
"Snapshot",
|
|
2238
|
+
stale ? `${detail} — ${SNAPSHOT_STALE_DAYS} days ago or more` : detail,
|
|
2239
|
+
stale
|
|
2240
|
+
? "The copy is taken by the worker after a boundary; read the Spawn line below."
|
|
2241
|
+
: RESTORE_STEPS,
|
|
2242
|
+
held,
|
|
2243
|
+
)
|
|
2244
|
+
: finding("snapshot", "green", "Snapshot", detail, "", held),
|
|
2245
|
+
];
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
// ── the two steps the user does BY HAND ─────────────────────────────
|
|
2249
|
+
|
|
2250
|
+
/**
|
|
2251
|
+
* DID THE HOOKS BLOCK AND THE MCP REGISTRATION ACTUALLY TAKE (finding 4).
|
|
2252
|
+
*
|
|
2253
|
+
* `install` prints those two and applies neither, correctly: they edit somebody
|
|
2254
|
+
* else's editor configuration. But nothing then checked them, so a user who
|
|
2255
|
+
* pasted the block into a project settings file instead of the user one — or
|
|
2256
|
+
* never restarted — got a fully green `doctor` and total silence. The failure
|
|
2257
|
+
* mode of this product is silence, which is the one thing a diagnostic exists
|
|
2258
|
+
* to break.
|
|
2259
|
+
*
|
|
2260
|
+
* **THE READ IS THE CALLER'S** (`cli/install.ts#readHost`), for the reason
|
|
2261
|
+
* `checkout` and `open` are: it is four small file reads outside this store, in
|
|
2262
|
+
* a format that belongs to the host, and the adapters here are leaves that do
|
|
2263
|
+
* not import each other. What comes in carries the host's own vocabulary —
|
|
2264
|
+
* which events were expected, what the server is called — so this file grades
|
|
2265
|
+
* and keeps nothing it would have to hold in step.
|
|
2266
|
+
*
|
|
2267
|
+
* AMBER, NEVER RED, and it always says which files it read: `~/.claude.json` is
|
|
2268
|
+
* the host's own state file, documented as one the host writes for itself, so a
|
|
2269
|
+
* negative answer here is "I looked at these and did not find it", never "you
|
|
2270
|
+
* did not install it".
|
|
2271
|
+
*/
|
|
2272
|
+
export interface HostReading {
|
|
2273
|
+
/** The events a full install covers, in the host's spelling. */
|
|
2274
|
+
readonly expected: readonly string[];
|
|
2275
|
+
/** Which of `expected` carry a command that looks like ours. */
|
|
2276
|
+
readonly events: readonly string[];
|
|
2277
|
+
/** Events whose command names a path that is not on disk — installed, and
|
|
2278
|
+
* failing silently at every session start. */
|
|
2279
|
+
readonly stale: readonly { event: string; path: string }[];
|
|
2280
|
+
/** Every settings file this read actually opened and parsed. */
|
|
2281
|
+
readonly settingsRead: readonly string[];
|
|
2282
|
+
/** Files that exist and could not be opened or parsed — not the same fact as
|
|
2283
|
+
* "there is no such file", and not something to stay quiet about. */
|
|
2284
|
+
readonly settingsUnreadable: readonly string[];
|
|
2285
|
+
/** True when the MCP server is registered at user scope. */
|
|
2286
|
+
readonly mcp: boolean;
|
|
2287
|
+
readonly mcpName: string;
|
|
2288
|
+
readonly mcpFile: string;
|
|
2289
|
+
/** The MCP file exists but could not be read or parsed. */
|
|
2290
|
+
readonly mcpUnreadable: boolean;
|
|
2291
|
+
}
|
|
2292
|
+
|
|
2293
|
+
function hostFindings(reading: HostReading): Finding[] {
|
|
2294
|
+
const total = reading.expected.length;
|
|
2295
|
+
const missing = reading.expected.filter((e) => !reading.events.includes(e));
|
|
2296
|
+
const stale = reading.stale;
|
|
2297
|
+
const where = [
|
|
2298
|
+
reading.settingsRead.length === 0
|
|
2299
|
+
? "no host settings file was readable"
|
|
2300
|
+
: `read ${reading.settingsRead.join(", ")}`,
|
|
2301
|
+
// AN UNREADABLE FILE IS SAID OUT LOUD. Dropping it silently is how a
|
|
2302
|
+
// mode-000 settings file reads as an absent one, and the reader is then
|
|
2303
|
+
// told to paste a block they have already pasted.
|
|
2304
|
+
reading.settingsUnreadable.length === 0
|
|
2305
|
+
? ""
|
|
2306
|
+
: `could not read ${reading.settingsUnreadable.join(", ")}`,
|
|
2307
|
+
]
|
|
2308
|
+
.filter((s) => s.length > 0)
|
|
2309
|
+
.join("; ");
|
|
2310
|
+
const data: Record<string, string | number | boolean | null> = {
|
|
2311
|
+
events: reading.events.join(","),
|
|
2312
|
+
missing: missing.join(","),
|
|
2313
|
+
stale: stale.map((s) => `${s.event}→${s.path}`).join(","),
|
|
2314
|
+
settingsRead: reading.settingsRead.join(","),
|
|
2315
|
+
settingsUnreadable: reading.settingsUnreadable.join(","),
|
|
2316
|
+
mcp: reading.mcp,
|
|
2317
|
+
mcpFile: reading.mcpFile,
|
|
2318
|
+
};
|
|
2319
|
+
const mcpClause = reading.mcp
|
|
2320
|
+
? `the MCP server is registered in ${reading.mcpFile}`
|
|
2321
|
+
: reading.mcpUnreadable
|
|
2322
|
+
? `${reading.mcpFile} could not be read, so the MCP registration could not be checked`
|
|
2323
|
+
: `no MCP server named "${reading.mcpName}" in ${reading.mcpFile}`;
|
|
2324
|
+
|
|
2325
|
+
if (missing.length === 0 && stale.length === 0 && reading.mcp) {
|
|
2326
|
+
return [
|
|
2327
|
+
finding(
|
|
2328
|
+
"host",
|
|
2329
|
+
"green",
|
|
2330
|
+
"Host",
|
|
2331
|
+
`all ${String(total)} hook events are installed and ${mcpClause}`,
|
|
2332
|
+
"",
|
|
2333
|
+
data,
|
|
2334
|
+
),
|
|
2335
|
+
];
|
|
2336
|
+
}
|
|
2337
|
+
const fixes: string[] = [];
|
|
2338
|
+
if (missing.length > 0) {
|
|
2339
|
+
fixes.push(
|
|
2340
|
+
"Run: counterparts install — it prints the hooks block; paste that into ~/.claude/settings.json and restart the host.",
|
|
2341
|
+
);
|
|
2342
|
+
}
|
|
2343
|
+
if (stale.length > 0) {
|
|
2344
|
+
fixes.push(
|
|
2345
|
+
`Run: counterparts install — it prints the block with the path this install actually has; replace the ${
|
|
2346
|
+
stale.length === 1 ? "stale entry" : "stale entries"
|
|
2347
|
+
} and restart the host.`,
|
|
2348
|
+
);
|
|
2349
|
+
}
|
|
2350
|
+
if (!reading.mcp && !reading.mcpUnreadable) {
|
|
2351
|
+
fixes.push(
|
|
2352
|
+
"Run: counterparts install — it prints the claude mcp add line; run that, then restart the host.",
|
|
2353
|
+
);
|
|
2354
|
+
}
|
|
2355
|
+
// STALE FIRST. "GREEN while nothing fires" is the one outcome this line was
|
|
2356
|
+
// added to prevent, and a block pointing at a deleted checkout is exactly
|
|
2357
|
+
// that: it matches, it is installed, and every session start fails silently.
|
|
2358
|
+
const staleClause =
|
|
2359
|
+
stale.length === 0
|
|
2360
|
+
? ""
|
|
2361
|
+
: `${stale.map((s) => s.event).join(", ")} point${stale.length === 1 ? "s" : ""} at ${stale
|
|
2362
|
+
.map((s) => s.path)
|
|
2363
|
+
.join(", ")}, which is not there`;
|
|
2364
|
+
const installed =
|
|
2365
|
+
missing.length === total
|
|
2366
|
+
? `no hook of ours is installed on any of the ${String(total)} events`
|
|
2367
|
+
: missing.length > 0
|
|
2368
|
+
? `installed on ${reading.events.join(", ")} but NOT on ${missing.join(", ")}`
|
|
2369
|
+
: `all ${String(total)} hook events are installed`;
|
|
2370
|
+
const detail = [staleClause, installed, `(${where})`, mcpClause]
|
|
2371
|
+
.filter((s) => s.length > 0)
|
|
2372
|
+
.join("; ")
|
|
2373
|
+
.replace("; (", " (");
|
|
2374
|
+
return [finding("host", "amber", "Host", detail, fixes.join(" "), data)];
|
|
2375
|
+
}
|
|
2376
|
+
|
|
2377
|
+
// ── the reading ─────────────────────────────────────────────────────────────
|
|
2378
|
+
|
|
2379
|
+
const RANK: Record<Severity, number> = { red: 0, amber: 1, green: 2 };
|
|
2380
|
+
|
|
2381
|
+
/** Worst first, stable within a severity — the order the report and the notice
|
|
2382
|
+
* both read. */
|
|
2383
|
+
export function worstFirst(findings: readonly Finding[]): Finding[] {
|
|
2384
|
+
return [...findings]
|
|
2385
|
+
.map((f, i) => ({ f, i }))
|
|
2386
|
+
.sort((a, b) => RANK[a.f.severity] - RANK[b.f.severity] || a.i - b.i)
|
|
2387
|
+
.map((x) => x.f);
|
|
2388
|
+
}
|
|
2389
|
+
|
|
2390
|
+
/**
|
|
2391
|
+
* THE READING. Pure over its input, worst first, and never a write.
|
|
2392
|
+
*
|
|
2393
|
+
* Groups run cheapest-and-most-diagnostic first, and the budget is checked
|
|
2394
|
+
* BETWEEN them: the config, the credentials and the counters are answered before
|
|
2395
|
+
* anything walks the event log, so a reading that runs out of time still carries
|
|
2396
|
+
* I32's own signature.
|
|
2397
|
+
*/
|
|
2398
|
+
export function doctorFindings(input: DoctorInput): Finding[] {
|
|
2399
|
+
const now = input.now ?? ((): number => Date.now());
|
|
2400
|
+
const deadline = input.budgetMs === undefined ? null : now() + input.budgetMs;
|
|
2401
|
+
const unread = input.configReason === "not-read";
|
|
2402
|
+
const out: Finding[] = [
|
|
2403
|
+
...configFindings(input),
|
|
2404
|
+
// TWO BOUNDED READS, before anything else touches the store: whether a key
|
|
2405
|
+
// has ever worked HERE is what decides red from amber on the line a new
|
|
2406
|
+
// user reads first (finding 1). Cheap enough for the session-start budget —
|
|
2407
|
+
// one indexed row, plus a window of backfill rows.
|
|
2408
|
+
//
|
|
2409
|
+
// NOT WHEN NO CONFIGURATION WAS READ: the credentials file is named by the
|
|
2410
|
+
// configuration, so there is nothing to report on and the Config line above
|
|
2411
|
+
// has already said so.
|
|
2412
|
+
...(unread ? [] : credentialFindings(input, keyHistory(input.store))),
|
|
2413
|
+
// Already READ by the caller (the git calls are its own bounded business),
|
|
2414
|
+
// so this costs nothing here and is answered before any store read.
|
|
2415
|
+
...(input.checkout === undefined ? [] : checkoutFindings(input.checkout)),
|
|
2416
|
+
// Read by the caller for the same reason, and answered beside the `Store`
|
|
2417
|
+
// line it qualifies: "there is a store here" and "it opens" are two facts.
|
|
2418
|
+
...(input.open === undefined ? [] : openFindings(input.open)),
|
|
2419
|
+
// DID THE HOST STEPS TAKE (finding 4). Also read by the caller — it is four
|
|
2420
|
+
// small file reads outside this store, and the hook does not pay for them.
|
|
2421
|
+
...(input.host === undefined ? [] : hostFindings(input.host)),
|
|
2422
|
+
];
|
|
2423
|
+
const store = input.store;
|
|
2424
|
+
if (store === null) return worstFirst(out);
|
|
2425
|
+
|
|
2426
|
+
const groups: (readonly [string, () => Finding[]])[] = [
|
|
2427
|
+
["spawn", () => spawnFindings(input, store)],
|
|
2428
|
+
["clock", () => clockFindings(input, store)],
|
|
2429
|
+
["rows", () => rowFindings(input, store)],
|
|
2430
|
+
["authorship", () => authorshipFindings(input, store)],
|
|
2431
|
+
["journal", () => journalFindings(store)],
|
|
2432
|
+
["vectors", () => vectorFindings(store)],
|
|
2433
|
+
// The snapshot policy lives in the configuration, so with none read this
|
|
2434
|
+
// line would grade a default nobody chose.
|
|
2435
|
+
...(unread ? [] : [["snapshot", (): Finding[] => snapshotFindings(input, store)] as const]),
|
|
2436
|
+
["self-page", () => selfPageFindings(store)],
|
|
2437
|
+
["page-writer", () => pageWriterFindings(store, input.config)],
|
|
2438
|
+
// F6: silent unless a copy failure is standing. Two bounded event reads.
|
|
2439
|
+
["journal-copy", () => journalCopyFindings(store)],
|
|
2440
|
+
// LAST, and deliberately: it is the widest read here — the whole event log,
|
|
2441
|
+
// plus a pass over the ids for the table probes — so when the console's
|
|
2442
|
+
// reading is cut short this is the group that goes, and the `Budget` finding
|
|
2443
|
+
// below says so rather than leaving a silent gap. A budgeted reading does
|
|
2444
|
+
// not take it at all; see `firedFindings`.
|
|
2445
|
+
["fired", () => firedFindings(input, store)],
|
|
2446
|
+
];
|
|
2447
|
+
const skipped: string[] = [];
|
|
2448
|
+
for (const [name, read] of groups) {
|
|
2449
|
+
if (deadline !== null && now() > deadline) {
|
|
2450
|
+
skipped.push(name);
|
|
2451
|
+
continue;
|
|
2452
|
+
}
|
|
2453
|
+
out.push(...read());
|
|
2454
|
+
}
|
|
2455
|
+
if (skipped.length > 0) {
|
|
2456
|
+
out.push(
|
|
2457
|
+
finding(
|
|
2458
|
+
"budget",
|
|
2459
|
+
"amber",
|
|
2460
|
+
"Budget",
|
|
2461
|
+
`the session-start reading stopped after ${String(input.budgetMs)} ms and did not read: ${skipped.join(", ")}`,
|
|
2462
|
+
"Run: counterparts doctor — the console reads without a budget.",
|
|
2463
|
+
{ skipped: skipped.join(","), budgetMs: input.budgetMs ?? 0 },
|
|
2464
|
+
),
|
|
2465
|
+
);
|
|
2466
|
+
}
|
|
2467
|
+
return worstFirst(out);
|
|
2468
|
+
}
|
|
2469
|
+
|
|
2470
|
+
// ── rendering ───────────────────────────────────────────────────────────────
|
|
2471
|
+
|
|
2472
|
+
const SEVERITY_COLUMN = 6;
|
|
2473
|
+
const TITLE_COLUMN = 12;
|
|
2474
|
+
|
|
2475
|
+
/** The console's report: a table, worst first, and a fix under anything that is
|
|
2476
|
+
* not green. */
|
|
2477
|
+
export function reportLines(findings: readonly Finding[], today: string): string[] {
|
|
2478
|
+
const ordered = worstFirst(findings);
|
|
2479
|
+
const reds = ordered.filter((f) => f.severity === "red").length;
|
|
2480
|
+
const ambers = ordered.filter((f) => f.severity === "amber").length;
|
|
2481
|
+
const lines = [`counterparts doctor — ${today} (UTC)`, ""];
|
|
2482
|
+
for (const f of ordered) {
|
|
2483
|
+
// A TITLE AS WIDE AS THE COLUMN STILL GETS ITS SPACE (2026-09-20). `padEnd`
|
|
2484
|
+
// is a floor, not a gap: "Journal mode" is exactly `TITLE_COLUMN` long and
|
|
2485
|
+
// printed as `GREEN Journal modewal (busy timeout 5000 ms)`.
|
|
2486
|
+
const title = f.title.length >= TITLE_COLUMN ? `${f.title} ` : f.title.padEnd(TITLE_COLUMN);
|
|
2487
|
+
lines.push(`${f.severity.toUpperCase().padEnd(SEVERITY_COLUMN)}${title}${f.detail}`);
|
|
2488
|
+
if (f.fix.length > 0) lines.push(`${" ".repeat(SEVERITY_COLUMN + TITLE_COLUMN)}fix: ${f.fix}`);
|
|
2489
|
+
}
|
|
2490
|
+
lines.push("");
|
|
2491
|
+
lines.push(
|
|
2492
|
+
reds === 0 && ambers === 0
|
|
2493
|
+
? "Nothing to fix."
|
|
2494
|
+
: `${reds} red, ${ambers} amber, ${ordered.length - reds - ambers} green.`,
|
|
2495
|
+
);
|
|
2496
|
+
return lines;
|
|
2497
|
+
}
|
|
2498
|
+
|
|
2499
|
+
/** The `--json` shape: ids, counts, severities. Never a credential value. */
|
|
2500
|
+
export function reportJson(findings: readonly Finding[], today: string): Record<string, unknown> {
|
|
2501
|
+
const ordered = worstFirst(findings);
|
|
2502
|
+
return {
|
|
2503
|
+
date: today,
|
|
2504
|
+
red: ordered.filter((f) => f.severity === "red").length,
|
|
2505
|
+
amber: ordered.filter((f) => f.severity === "amber").length,
|
|
2506
|
+
green: ordered.filter((f) => f.severity === "green").length,
|
|
2507
|
+
findings: ordered.map((f) => ({ key: f.key, severity: f.severity, title: f.title, detail: f.detail, fix: f.fix, data: f.data })),
|
|
2508
|
+
};
|
|
2509
|
+
}
|
|
2510
|
+
|
|
2511
|
+
/** True when anything is red — the console's exit code, and the notice's gate. */
|
|
2512
|
+
export function anyRed(findings: readonly Finding[]): boolean {
|
|
2513
|
+
return findings.some((f) => f.severity === "red");
|
|
2514
|
+
}
|
|
2515
|
+
|
|
2516
|
+
/** The last line of every notice, and the only part that is never truncated:
|
|
2517
|
+
* the repair is not a thing to remember. */
|
|
2518
|
+
export const NOTICE_TAIL = "run: counterparts doctor";
|
|
2519
|
+
|
|
2520
|
+
/**
|
|
2521
|
+
* How long a notice may be, in characters.
|
|
2522
|
+
*
|
|
2523
|
+
* The host caps EVERY hook output string at 10,000 characters and replaces
|
|
2524
|
+
* anything longer with a preview and a file path
|
|
2525
|
+
* (https://code.claude.com/docs/en/hooks: "Hook output strings, including
|
|
2526
|
+
* `additionalContext`, `systemMessage`, and plain stdout, are capped at 10,000
|
|
2527
|
+
* characters"). The notice rides in the same JSON object as the wake, so every
|
|
2528
|
+
* character it spends is a character the wake cannot have — and the wake is the
|
|
2529
|
+
* thing the session cannot do without. 400 is enough for a finding, its fix and
|
|
2530
|
+
* the tail; a finding that needs more than that needs the console, which is what
|
|
2531
|
+
* the tail says.
|
|
2532
|
+
*/
|
|
2533
|
+
export const NOTICE_MAX_CHARS = 400;
|
|
2534
|
+
|
|
2535
|
+
/**
|
|
2536
|
+
* THE ONE OR TWO LINES THE OWNER SEES IN THE TERMINAL, or null.
|
|
2537
|
+
*
|
|
2538
|
+
* RED ONLY. Amber never reaches the terminal from a hook: the owner asked for a
|
|
2539
|
+
* warning, not a nag, and a notice that fires on a store with one un-embedded
|
|
2540
|
+
* memory is a notice people learn to scroll past. The last line is always the
|
|
2541
|
+
* same eight characters plus the command, so the repair is never a thing to
|
|
2542
|
+
* remember — and it survives the cap, which the first line does not.
|
|
2543
|
+
*/
|
|
2544
|
+
export function noticeMessage(findings: readonly Finding[]): string | null {
|
|
2545
|
+
const reds = worstFirst(findings).filter((f) => f.severity === "red");
|
|
2546
|
+
const first = reds[0];
|
|
2547
|
+
if (first === undefined) return null;
|
|
2548
|
+
const more =
|
|
2549
|
+
reds.length === 1 ? "" : ` (+${reds.length - 1} more: ${reds.slice(1).map((f) => f.title).join(", ")})`;
|
|
2550
|
+
const fix = first.fix.length === 0 ? "" : ` ${first.fix}`;
|
|
2551
|
+
const head = `counterparts: ${first.title} — ${first.detail}.${fix}${more}`;
|
|
2552
|
+
// The tail and its newline are reserved FIRST, so what is cut is always the
|
|
2553
|
+
// explanation and never the way to get the whole of it.
|
|
2554
|
+
const room = NOTICE_MAX_CHARS - NOTICE_TAIL.length - 1;
|
|
2555
|
+
const line = head.length <= room ? head : `${head.slice(0, Math.max(0, room - 1))}…`;
|
|
2556
|
+
return `${line}\n${NOTICE_TAIL}`;
|
|
2557
|
+
}
|