counterparts 0.3.37 → 0.3.39

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.
Files changed (129) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/README.md +2 -1
  3. package/docs/QUICKSTART.md +14 -8
  4. package/docs/module-map.md +4 -2
  5. package/package.json +9 -1
  6. package/src/adapters/claude-code/CONTRACT.md +26 -4
  7. package/src/adapters/claude-code/NOTES.md +116 -0
  8. package/src/adapters/claude-code/bin/hook.ts +70 -6
  9. package/src/adapters/claude-code/bin/nightly.ts +2 -0
  10. package/src/adapters/claude-code/bin/runner.ts +64 -2
  11. package/src/adapters/claude-code/child-error.ts +211 -0
  12. package/src/adapters/claude-code/child.ts +29 -10
  13. package/src/adapters/claude-code/doctor-checkout.ts +4 -2
  14. package/src/adapters/claude-code/doctor-host.ts +31 -0
  15. package/src/adapters/claude-code/doctor-meaning.ts +200 -0
  16. package/src/adapters/claude-code/doctor-modes.ts +115 -0
  17. package/src/adapters/claude-code/doctor-open.ts +12 -2
  18. package/src/adapters/claude-code/doctor-self-page.ts +2 -0
  19. package/src/adapters/claude-code/doctor-write-ups.ts +84 -19
  20. package/src/adapters/claude-code/doctor.ts +199 -23
  21. package/src/adapters/claude-code/hooks.ts +162 -11
  22. package/src/adapters/claude-code/index.ts +15 -0
  23. package/src/adapters/claude-code/night-catch-up.ts +25 -5
  24. package/src/adapters/claude-code/night-run.ts +86 -11
  25. package/src/adapters/claude-code/stale-windows.ts +160 -0
  26. package/src/adapters/claude-code/standdown.ts +70 -3
  27. package/src/adapters/cli/INTERFACE-GAPS.md +14 -0
  28. package/src/adapters/cli/NOTES.md +25 -0
  29. package/src/adapters/cli/bin/counterparts.ts +4 -2
  30. package/src/adapters/cli/commands-dashboard.ts +8 -5
  31. package/src/adapters/cli/commands-install.ts +12 -14
  32. package/src/adapters/cli/commands.ts +5 -2
  33. package/src/adapters/cli/coverage.ts +28 -6
  34. package/src/adapters/cli/help.ts +6 -1
  35. package/src/adapters/cli/index.ts +2 -0
  36. package/src/adapters/cli/install.ts +24 -1
  37. package/src/adapters/cli/mechanisms.ts +31 -8
  38. package/src/adapters/cli/rollback.ts +3 -3
  39. package/src/adapters/cli/snapshot.ts +4 -4
  40. package/src/adapters/cli/ui.ts +10 -0
  41. package/src/adapters/cli/uninstall.ts +16 -74
  42. package/src/adapters/cli/wire.ts +227 -33
  43. package/src/adapters/config.ts +23 -0
  44. package/src/adapters/dashboard/bin/dashboard.ts +2 -0
  45. package/src/adapters/dashboard/registries.ts +1 -1
  46. package/src/adapters/dashboard/web/mechanisms/index.js +2 -0
  47. package/src/adapters/dashboard/web/mechanisms/schema/index.js +9 -6
  48. package/src/adapters/dashboard/web/mechanisms/schema/panel.js +14 -0
  49. package/src/adapters/dashboard/web/narrate.ts +10 -3
  50. package/src/adapters/dashboard/web/views/mechanism-panel.ts +44 -0
  51. package/src/adapters/dashboard/web/views/mechanisms.ts +13 -1
  52. package/src/adapters/expansions.ts +4 -3
  53. package/src/adapters/fired.ts +29 -0
  54. package/src/adapters/host-wiring.ts +56 -1
  55. package/src/adapters/hosts.ts +51 -0
  56. package/src/adapters/lifecycle.ts +4 -2
  57. package/src/adapters/mcp/CONTRACT.md +26 -3
  58. package/src/adapters/mcp/INTERFACE-GAPS.md +11 -0
  59. package/src/adapters/mcp/NOTES.md +149 -0
  60. package/src/adapters/mcp/bin/serve.ts +83 -4
  61. package/src/adapters/mcp/chat-wake.ts +111 -0
  62. package/src/adapters/mcp/deliberate.ts +5 -2
  63. package/src/adapters/mcp/index.ts +3 -1
  64. package/src/adapters/mcp/nights.ts +434 -9
  65. package/src/adapters/mcp/protocol.ts +11 -2
  66. package/src/adapters/mcp/server-args.ts +6 -0
  67. package/src/adapters/mcp/server-options.ts +19 -2
  68. package/src/adapters/mcp/server-self-tools.ts +23 -8
  69. package/src/adapters/mcp/server-session-end.ts +5 -3
  70. package/src/adapters/mcp/server-words.ts +218 -4
  71. package/src/adapters/mcp/server.ts +524 -56
  72. package/src/adapters/mcp/tools.ts +266 -12
  73. package/src/adapters/mechanism-evidence.ts +90 -15
  74. package/src/adapters/owned-names.ts +105 -0
  75. package/src/adapters/plugin.ts +34 -7
  76. package/src/adapters/private-base.ts +175 -0
  77. package/src/adapters/private-umask.ts +71 -0
  78. package/src/adapters/remote/CONTRACT.md +75 -0
  79. package/src/adapters/remote/INTERFACE-GAPS.md +20 -0
  80. package/src/adapters/remote/NOTES.md +80 -0
  81. package/src/adapters/remote/bin/serve-http.ts +258 -0
  82. package/src/adapters/remote/call-log.ts +206 -0
  83. package/src/adapters/remote/http.ts +500 -0
  84. package/src/adapters/sessions.ts +121 -7
  85. package/src/adapters/snapshots.ts +3 -3
  86. package/src/adapters/spawn.ts +13 -6
  87. package/src/adapters/update-check.ts +870 -0
  88. package/src/adapters/update-words.ts +230 -0
  89. package/src/core/counterpart-deposit.ts +35 -2
  90. package/src/core/counterpart-sweep.ts +7 -1
  91. package/src/core/counterpart-types.ts +7 -0
  92. package/src/core/counterpart.ts +185 -23
  93. package/src/core/coverage/CONTRACT.md +12 -5
  94. package/src/core/coverage/NOTES.md +40 -1
  95. package/src/core/coverage/index.ts +73 -14
  96. package/src/core/coverage/tunables.ts +15 -1
  97. package/src/core/dream/CONTRACT.md +47 -9
  98. package/src/core/dream/NOTES.md +115 -0
  99. package/src/core/dream/index.ts +51 -6
  100. package/src/core/dream/recalled.ts +90 -0
  101. package/src/core/dream/reflect.ts +156 -25
  102. package/src/core/dream/tunables.ts +61 -0
  103. package/src/core/handoff/CONTRACT.md +8 -1
  104. package/src/core/handoff/NOTES.md +52 -0
  105. package/src/core/handoff/last-here.ts +52 -0
  106. package/src/core/mint.ts +8 -1
  107. package/src/core/onboarding.ts +35 -8
  108. package/src/core/recall/CONTRACT.md +11 -0
  109. package/src/core/reconsolidation.ts +2 -1
  110. package/src/core/remember/CONTRACT.md +2 -1
  111. package/src/core/remember/owes.ts +7 -1
  112. package/src/core/remember/proposals.ts +41 -1
  113. package/src/core/schemas/CONTRACT.md +4 -2
  114. package/src/core/self/INTERFACE-GAPS.md +20 -0
  115. package/src/core/self/briefing.ts +37 -1
  116. package/src/core/self/identity.ts +54 -4
  117. package/src/core/self/index.ts +69 -4
  118. package/src/core/self/work.ts +20 -0
  119. package/src/core/self/writer.ts +15 -1
  120. package/src/core/store/CONTRACT.md +28 -2
  121. package/src/core/store/NOTES.md +97 -2
  122. package/src/core/store/db.ts +24 -1
  123. package/src/core/store/index.ts +28 -2
  124. package/src/core/store/operational.ts +37 -1
  125. package/src/core/store/pre-migration.ts +6 -2
  126. package/src/core/store/private.ts +319 -0
  127. package/src/core/store/shapes.ts +6 -0
  128. package/src/core/types.ts +28 -0
  129. package/tools/install-loop/run.sh +3 -0
@@ -0,0 +1,200 @@
1
+ /**
2
+ * SEARCH BY MEANING THAT CANNOT RUN, said by the wake (2026-10-27, W1), and
3
+ * the install routes doctor's Recall by meaning line shares with it.
4
+ *
5
+ * Why it exists: a plugin install ran for days with no meaning weights
6
+ * (`NO_WEIGHTS`) — the plugin's dependency step had not run — and only a
7
+ * doctor run said so. The person's counterpart could have told them, had its
8
+ * wake carried one line. This is that line: written for the model to say to
9
+ * its person, in words a regular user can act on, with the fix for the route
10
+ * this copy came by (`plugin.ts#installRoute`) — the same route, and the same
11
+ * steps, as doctor's own fix line and `install`'s hint, because all three are
12
+ * built here.
13
+ *
14
+ * Cheap by construction (it is read on a hook's hot path): the durable rows
15
+ * the worker already writes (`vectors.ts#backfillVectors`' row, the runner's
16
+ * `adapter.runner.failed`), plus one look for the table's files on disk. It
17
+ * never loads the weights and never starts a worker.
18
+ */
19
+ import { existsSync } from "node:fs";
20
+ import { join } from "node:path";
21
+
22
+ import { EMBED_BACKFILL_EVENT, RUNNER_FAILED_EVENT } from "../../core/counterpart.js";
23
+ import type { Store } from "../../core/store/index.js";
24
+ import { MODEL_FILE, VOCAB_FILE, resolveStaticWeights } from "../../core/embed/static.js";
25
+ import { bundledModelDir } from "../runtime.js";
26
+ import type { RuntimeKind } from "../runtime.js";
27
+ import type { AdapterConfig } from "../config.js";
28
+ import type { InstallRoute } from "../plugin.js";
29
+ import { payloadOf, str } from "./doctor-finding.js";
30
+
31
+ // ── the install routes, shared with doctor.ts and `install` ────────────────
32
+
33
+ // The steps themselves live in the adapters' shared leaf since U1a
34
+ // (`../update-words.ts`): the MCP server's refusal says them too, and it may
35
+ // not import this adapter. Re-exported here, where doctor and the wake read them.
36
+ import { PLUGIN_UPDATE, byRoute, npmTableCommand } from "../update-words.js";
37
+ export { PLUGIN_UPDATE, RELOAD_STEP, byRoute, npmTableCommand, npmUpdateCommand } from "../update-words.js";
38
+
39
+ /** The plugin's way to the meaning table: its update reruns the dependency
40
+ * step, which needs npm (#396: a Bun-only computer has none). */
41
+ export const PLUGIN_TABLE_UPDATE = `${PLUGIN_UPDATE}; the plugin installs its files with npm, so with no npm on this computer install Node.js (https://nodejs.org) first`;
42
+
43
+ // ── the table on disk ──────────────────────────────────────────────────────
44
+
45
+ /**
46
+ * Where this process would load the meaning table from, and whether its two
47
+ * files are there — the same resolution the worker's embedder makes
48
+ * (`embed-client.ts#openStaticEmbedder`), without reading a byte of either.
49
+ * `found` is null when no rule names a directory at all; `complete` says both
50
+ * files exist in the one that was named (the loader refuses a folder missing
51
+ * either, `MISSING_FILE`).
52
+ */
53
+ export function tableOnDisk(opts: { env?: Record<string, string | undefined>; packageDir?: string } = {}): {
54
+ found: { dir: string; source: string } | null;
55
+ complete: boolean;
56
+ } {
57
+ const packageDir = opts.packageDir ?? bundledModelDir();
58
+ const found = resolveStaticWeights({
59
+ ...(opts.env === undefined ? {} : { env: opts.env }),
60
+ ...(packageDir === undefined ? {} : { packageDir }),
61
+ });
62
+ if (found === null) return { found: null, complete: false };
63
+ return { found, complete: existsSync(join(found.dir, MODEL_FILE)) && existsSync(join(found.dir, VOCAB_FILE)) };
64
+ }
65
+
66
+ // ── the wake's line ────────────────────────────────────────────────────────
67
+
68
+ /** The refusals that mean "the files are not there" — fixed by putting them
69
+ * there, so a table found whole now is a table restored. Every other code
70
+ * (`HASH_MISMATCH`, `BAD_*`, `LOAD_FAILED`, …) is files that would not load,
71
+ * and stands until the worker's next row says otherwise. */
72
+ const NOT_THERE: ReadonlySet<string> = new Set(["NO_WEIGHTS", "MISSING_FILE"]);
73
+
74
+ /**
75
+ * How many dates the worker's vector step must have failed on, with no
76
+ * backfill row since the earlier of them, before the wake says it stopped.
77
+ * The runner latches one `adapter.runner.failed` row per step per date, and
78
+ * its `vectors` step covers the lagged cue as well as the backfill, so one
79
+ * failure is one bad boundary — not a feature that has stopped.
80
+ */
81
+ export const MEANING_FAILED_DATES = 2;
82
+
83
+ /** How many of the newest runner failures are read for `vectors` ones. */
84
+ const RUNNER_FAILED_ROWS = 20;
85
+
86
+ /** Why search by meaning is not running, for the person. */
87
+ export type MeaningOff = "missing" | "unloadable" | "stopped";
88
+
89
+ /** The person's sentence for each, before the fix. First person: the model says it. */
90
+ export const MEANING_OFF_WORDS: Readonly<Record<MeaningOff, string>> = {
91
+ missing: "My search by meaning is off on this computer (its files didn't install), so I can only find memories by their words.",
92
+ unloadable: "My search by meaning is off on this computer (its files are there but won't load), so I can only find memories by their words.",
93
+ stopped: "My search by meaning has stopped working on this computer, so I can only find memories by their words.",
94
+ };
95
+
96
+ /** What the line is introduced by, for the model. */
97
+ export const MEANING_OFF_LEAD = "Counterparts — tell your person when it fits, once this session:";
98
+
99
+ /** The date the `stopped` line was last told: it is said at most once a day. */
100
+ export const MEANING_STOPPED_TOLD_KEY = "adapter.meaning.stopped.told";
101
+
102
+ export interface MeaningOffInput {
103
+ readonly config: AdapterConfig;
104
+ readonly store: Store;
105
+ /** How this copy came (`plugin.ts#installRoute`); absent: both routes are named. */
106
+ readonly install?: InstallRoute;
107
+ /** The environment the table is resolved from; absent, this process's. */
108
+ readonly env?: Record<string, string | undefined>;
109
+ /** The single binary's carried table; absent, `runtime.ts#bundledModelDir`. */
110
+ readonly packageDir?: string;
111
+ /** The runtime the npm step names; absent, this process's. */
112
+ readonly runtime?: RuntimeKind;
113
+ }
114
+
115
+ /**
116
+ * Why search by meaning is configured ON and cannot run here, or null:
117
+ *
118
+ * - **switched off** (`embedder.enabled` not true) or an observer: null.
119
+ * Off by choice is not a fault, and doctor already says OFF.
120
+ * - `missing`: this process finds no whole table — before any boundary too,
121
+ * which is a fresh plugin install's first wake. A worker row that said
122
+ * `NO_WEIGHTS`/`MISSING_FILE` while the table IS whole now reads as
123
+ * restored: the wake says nothing, and the next boundary writes a new row.
124
+ * - `unloadable`: the worker's newest row says the table was there and
125
+ * would not load (any other refusal code). It stands until the next row.
126
+ * - `stopped`: the worker's vector step threw on `MEANING_FAILED_DATES`
127
+ * separate dates, with no backfill row since the earlier one.
128
+ *
129
+ * NOT A CASE: a backfill "stuck at 0". The static table blames every miss on
130
+ * the memory and sets it aside on its third (`EMBED_SKIP_AFTER`), so its
131
+ * `remaining` falls; what stays flat is the store refusing vectors (doctor's
132
+ * held / cache-ahead lines) or lost counter writes — not a person's fix.
133
+ *
134
+ * The hook's environment IS the worker's (the hook starts it), so the look at
135
+ * the disk is the same look the worker makes. Never throws: a reading that
136
+ * fails is no line.
137
+ */
138
+ export function meaningOff(input: MeaningOffInput): MeaningOff | null {
139
+ if (input.config.embedder?.enabled !== true || input.config.observer === true) return null;
140
+ try {
141
+ const table = tableOnDisk({
142
+ ...(input.env === undefined ? {} : { env: input.env }),
143
+ ...(input.packageDir === undefined ? {} : { packageDir: input.packageDir }),
144
+ });
145
+ if (!table.complete) return "missing";
146
+ const store = input.store;
147
+ // The NEWEST backfill row, read straight off the log's end — never through
148
+ // a day window, which would stop at today's rows.
149
+ const newest = store.eventLog({ name: EMBED_BACKFILL_EVENT, order: "desc", limit: 1 })[0];
150
+ const p = payloadOf(newest);
151
+ if (newest !== undefined && str(p, "reason") === "embedder-unavailable") {
152
+ const code = str(p, "codes") ?? "NO_WEIGHTS";
153
+ return NOT_THERE.has(code) ? null : "unloadable";
154
+ }
155
+ const failures = store
156
+ .eventLog({ name: RUNNER_FAILED_EVENT, order: "desc", limit: RUNNER_FAILED_ROWS })
157
+ .filter((r) => str(payloadOf(r), "step") === "vectors");
158
+ const dates = new Set(failures.map((r) => str(payloadOf(r), "date") ?? String(r.day)));
159
+ const earliest = failures[MEANING_FAILED_DATES - 1];
160
+ if (dates.size >= MEANING_FAILED_DATES && earliest !== undefined && (newest === undefined || newest.seq < earliest.seq)) {
161
+ return "stopped";
162
+ }
163
+ return null;
164
+ } catch {
165
+ return null;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * THE WAKE'S ONE LINE, or null (`meaningOff`). The fix is the route's: the
171
+ * table's install for `missing`, its reinstall for `unloadable` — doctor's own
172
+ * steps — and doctor itself for `stopped`, whose reasons are many and are its
173
+ * to name.
174
+ *
175
+ * `stopped` is said at most ONCE A DAY: with `today`, the first wake that
176
+ * says it records the date (`MEANING_STOPPED_TOLD_KEY`), and later wakes that
177
+ * day say nothing. `missing` and `unloadable` are said on every wake until
178
+ * fixed: they are one install away, and the person is the one who installs.
179
+ */
180
+ export function wakeMeaningLine(input: MeaningOffInput & { readonly today?: string }): string | null {
181
+ const why = meaningOff(input);
182
+ if (why === null) return null;
183
+ if (why === "stopped" && input.today !== undefined) {
184
+ try {
185
+ if (input.store.getMeta(MEANING_STOPPED_TOLD_KEY) === input.today) return null;
186
+ input.store.setMeta(MEANING_STOPPED_TOLD_KEY, input.today);
187
+ } catch {
188
+ // A claim that could not be written costs the once-a-day, not the line.
189
+ }
190
+ }
191
+ const npm = `in a terminal, run ${npmTableCommand(input.runtime)}`;
192
+ const fix =
193
+ why === "missing"
194
+ ? byRoute(input.install, npm, PLUGIN_TABLE_UPDATE)
195
+ : why === "unloadable"
196
+ ? byRoute(input.install, npm, PLUGIN_UPDATE)
197
+ : byRoute(input.install, "in a terminal, run counterparts doctor", "in Claude Code, run /counterparts:doctor");
198
+ const step = why === "stopped" ? "To see why" : "To fix it";
199
+ return `${MEANING_OFF_LEAD} "${MEANING_OFF_WORDS[why]} ${step}: ${fix}."`;
200
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * `doctor`'s line on who can read the store (2026-10-27, R1): amber when the
3
+ * store, its database, our entries in the base directory beside it (and the
4
+ * base itself when it is ours) or ours in the snapshots directory is readable
5
+ * by group or other, with the two commands that close
6
+ * it. A handful of `stat` calls, no store read, never red: the store opens
7
+ * either way, and a writer's open tightens it by itself (`core/store/private.ts`),
8
+ * so a line that stays amber is a filesystem that does not keep modes or a
9
+ * store nothing has written to since this version came.
10
+ */
11
+ import { existsSync, lstatSync } from "node:fs";
12
+ import { join } from "node:path";
13
+
14
+ import { DATABASE_FILE, OPEN_BITS, SPECIAL_BITS, realRoot, storeRoots } from "../../core/store/index.js";
15
+ import { configuredMirror, configuredSnapshots, installBaseRoots } from "../private-base.js";
16
+ import { finding } from "./doctor-finding.js";
17
+ import type { Finding } from "./doctor-finding.js";
18
+
19
+ function modeOf(path: string): number | null {
20
+ try {
21
+ const st = lstatSync(path);
22
+ // A link is never chmodded through (`core/store/private.ts`), so never graded either.
23
+ return st.isSymbolicLink() ? null : st.mode & 0o7777;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * The paths the line reads, each with the mode it should have at most: exactly
31
+ * the roots a session start (or `connect`) and a writer's open tighten
32
+ * (`private-base.ts#installBaseRoots`, `core/store/private.ts#storeRoots`), a
33
+ * configured snapshots directory outside the base included, plus the database.
34
+ * Each root by itself: a tree is read at its top, as the gate reads it.
35
+ */
36
+ export function privatePaths(storeDir: string, configPath?: string, home?: string): { path: string; dir: boolean }[] {
37
+ const store = realRoot(storeDir);
38
+ // The base only when this IS an install's layout (`private-base.ts`), the
39
+ // configuration sitting in it: a dir that is merely named `store` says nothing.
40
+ const roots =
41
+ (configPath === undefined ? null : installBaseRoots(configPath, storeDir, home)) ??
42
+ storeRoots(storeDir, configPath === undefined ? null : (configuredSnapshots(configPath) ?? null), home);
43
+ const out: { path: string; dir: boolean }[] = [];
44
+ const seen = new Set<string>();
45
+ const add = (path: string): void => {
46
+ if (seen.has(path)) return;
47
+ seen.add(path);
48
+ out.push({ path, dir: isDir(path) });
49
+ };
50
+ add(store);
51
+ out.push({ path: join(store, DATABASE_FILE), dir: false });
52
+ for (const p of [...(roots.only ?? []), ...roots.recursive]) add(p);
53
+ return out;
54
+ }
55
+
56
+ function isDir(path: string): boolean {
57
+ try {
58
+ return lstatSync(path).isDirectory();
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+
64
+ export function modesFindings(storeDir: string, platform: string = process.platform, configPath?: string, home?: string): Finding[] {
65
+ if (platform === "win32") return [];
66
+ const paths = privatePaths(storeDir, configPath, home).filter((p) => existsSync(p.path));
67
+ if (paths.length === 0) return [];
68
+ const open = paths
69
+ .map((p) => ({ ...p, mode: modeOf(p.path) }))
70
+ .filter((p): p is { path: string; dir: boolean; mode: number } => p.mode !== null && (p.mode & OPEN_BITS) !== 0);
71
+ const data = { open: open.map((p) => `${p.path}:${p.mode.toString(8)}`).join(",") };
72
+ // A configured mirror is never tightened (R8): copies an older build put
73
+ // there stay as they were. Not graded here, and the line says so.
74
+ const mirror = configPath === undefined ? undefined : configuredMirror(configPath);
75
+ const mirrorNote = mirror === undefined ? "" : `; the snapshot mirror at ${mirror} is not checked here`;
76
+ if (open.length === 0) {
77
+ return [finding("modes", "green", "Privacy", `the store is readable by you alone (directories 700, database 600)${mirrorNote}`, "", data)];
78
+ }
79
+ // A path carrying setuid, setgid or sticky is never chmodded by a session
80
+ // (`core/store/private.ts#tightenRoots`): on Linux a directory made inside a
81
+ // setgid one inherits g+s, so a 2755 store dir stays open until closed by
82
+ // hand. `go-rwx` closes it and leaves the special bit as it is.
83
+ const special = open.filter((p) => (p.mode & SPECIAL_BITS) !== 0);
84
+ const plain = open.filter((p) => (p.mode & SPECIAL_BITS) === 0);
85
+ const dirs = plain.filter((p) => p.dir).map((p) => `"${p.path}"`);
86
+ const files = plain.filter((p) => !p.dir).map((p) => `"${p.path}"`);
87
+ const fix = [
88
+ ...(dirs.length === 0 ? [] : [`chmod 700 ${dirs.join(" ")}`]),
89
+ ...(files.length === 0 ? [] : [`chmod 600 ${files.join(" ")}*`]),
90
+ ].join(" && ");
91
+ const byHand = special.map((p) => `"${p.path}"`).join(" ");
92
+ const hint = [
93
+ ...(plain.length === 0
94
+ ? []
95
+ : [`Run: ${fix} — the next Claude Code session (or counterparts connect) does the same, the whole store included.`]),
96
+ ...(special.length === 0
97
+ ? []
98
+ : [
99
+ `Run by hand: chmod go-rwx ${byHand} — ${special.length === 1 ? "it carries" : "they carry"} a setuid, setgid or sticky bit, ` +
100
+ "which a session never changes, so no session will close " +
101
+ `${special.length === 1 ? "it" : "them"}.`,
102
+ ]),
103
+ "A filesystem that does not keep modes (exFAT, some network drives) reads this way and cannot be tightened.",
104
+ ].join(" ");
105
+ return [
106
+ finding(
107
+ "modes",
108
+ "amber",
109
+ "Privacy",
110
+ `readable by other accounts on this machine: ${open.map((p) => `${p.path} (${p.mode.toString(8)})`).join(", ")}${mirrorNote}`,
111
+ hint,
112
+ data,
113
+ ),
114
+ ];
115
+ }
@@ -169,7 +169,13 @@ export function readCounterpartOpen(
169
169
  }
170
170
  }
171
171
 
172
- export function openFindings(reading: OpenReading): Finding[] {
172
+ export function openFindings(
173
+ reading: OpenReading,
174
+ /** The fix for a store a newer Counterparts upgraded (`SCHEMA_AHEAD`), in
175
+ * this copy's route's words (`update-words.ts#newerStoreWords`, U1a) — the
176
+ * sentence the hook and the MCP server say. Absent: the general fix. */
177
+ opts: { readonly aheadFix?: string } = {},
178
+ ): Finding[] {
173
179
  // The Rollback line says it, with what to do (`rollbackFindings`).
174
180
  if (reading.code === "STORE_ROLLED_BACK") return [];
175
181
  const data: Record<string, string | number | boolean | null> = {
@@ -244,7 +250,11 @@ export function openFindings(reading: OpenReading): Finding[] {
244
250
  "red",
245
251
  "Store open",
246
252
  said,
247
- reading.path !== null
253
+ // First: SCHEMA_AHEAD carries the database's own path, and "restore" it
254
+ // would be the wrong advice — the store is fine, this copy is old.
255
+ reading.code === "SCHEMA_AHEAD" && opts.aheadFix !== undefined
256
+ ? `Every session's hooks running this copy stand down here. ${opts.aheadFix}`
257
+ : reading.path !== null
248
258
  ? `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.`
249
259
  : reading.id !== null
250
260
  ? // THE ROW, NAMED. On the file floor this said "restore <path>" and the
@@ -202,6 +202,8 @@ export function nightRunFindings(input: DoctorInput, store: Store): Finding[] {
202
202
  const fix =
203
203
  run.reason === "no-claude"
204
204
  ? "The headless run starts claude -p: put the claude command on the PATH the hooks see, or set dreaming to ask (counterparts dream --setting ask)."
205
+ : run.reason === "signed-out"
206
+ ? "Claude Code lost its sign-in while the run went (a switched account, an expired login). Once it is signed in, the next session asks: say dream there to run it."
205
207
  : run.reason === "quick-exit"
206
208
  ? "Run claude -p once by hand in a terminal to see why it stops (a login, an update prompt, or a claude too old for the night's flags — update it). Meanwhile the session asks instead."
207
209
  : run.reason === "nothing-ran"
@@ -7,13 +7,14 @@ import { TUNABLES } from "../config.js";
7
7
  // promise a different number from the job that does the deleting. READ-ONLY:
8
8
  // `remember/index.ts` re-exports the plan and the readers, never the deleter.
9
9
  import { SpanBuffer } from "../../core/remember/index.js";
10
- import { lapsesSince, ledger } from "../../core/coverage/index.js";
10
+ import { COVERAGE_TUNABLES, lapsesSince, ledger } from "../../core/coverage/index.js";
11
11
  import type { LedgerEntry } from "../../core/coverage/index.js";
12
12
  import {
13
13
  hostOf,
14
14
  hostSessionEvidence,
15
15
  listSessions,
16
- pointable,
16
+ lapsingWords,
17
+ notPointableWhy,
17
18
  progressKey,
18
19
  readWriteUpPointer,
19
20
  readWriteUpProgress,
@@ -38,10 +39,11 @@ export const WRITE_UP_LAPSE_WINDOW_DAYS = 7;
38
39
  *
39
40
  * It says yesterday's state: how many sessions captured something that date
40
41
  * and how much of it is written up; how many sessions owe a write-up now; and
41
- * how many stretches lapsed in the last week. AMBER when a stretch from
42
- * yesterday or earlier is owed — the next session in that project is pointed
43
- * at it, so one still owed the morning after is one whose project nobody has
44
- * opened. Never red: nothing is deleted while a stretch is owed, and a lapse
42
+ * how many stretches lapsed in the last week. AMBER when an owed stretch is
43
+ * OVERDUE (`overdue`, S2c 2026-10-26): the catch-up had its chance and it is
44
+ * still here. Until S2c it was amber for any stretch from yesterday or
45
+ * earlier — and once a short check-in owed its write-up (S2), that was every
46
+ * morning before the first prompt, which is where the night runs. Never red: nothing is deleted while a stretch is owed, and a lapse
45
47
  * deletes nothing either. The two ambers #192 added for the pointer itself —
46
48
  * deferred for room, and a session finished here waiting on another project —
47
49
  * are kept as they were.
@@ -55,16 +57,68 @@ export interface OwedReading {
55
57
  readonly now: number;
56
58
  /** Sessions that owe a write-up the pointer can offer (`coverage/`'s rule). */
57
59
  readonly waiting: number;
58
- /** ...of which the stretch is from yesterday or earlier. */
60
+ /** ...of which are OVERDUE (`overdue`): the catch-up had its chance and the
61
+ * debt is still here. The field keeps its old name; until S2c it counted
62
+ * every stretch from yesterday or earlier. */
59
63
  readonly stale: number;
60
- /** Small debts the pointer never offers (no registry record, or not a
61
- * person's session): they owe, and lapse with their days of use. */
64
+ /** Short debts the pointer never offers (`sessions.ts#notPointableWhy`):
65
+ * they owe, and lapse with their days of use. */
62
66
  readonly unpointed: number;
67
+ /** ...of which from a headless run (`claude -p`, the Agent SDK). */
68
+ readonly unpointedHeadless: number;
69
+ /** ...of which from a session with no registry record. */
70
+ readonly unpointedNoRecord: number;
71
+ /** The newest catch-up row's time (`catchUpOf`, any age), or null. */
72
+ readonly lastCatchUpAt: number | null;
73
+ }
74
+
75
+ /** "1 overdue (a catch-up has run since, or 2 days of use)": the clause the
76
+ * Catch-up and Authorship lines add after the owed count. */
77
+ export function overdueWords(n: number): string {
78
+ return `${String(n)} overdue (a catch-up has run since, or ${String(OVERDUE_DAYS_OF_USE)} days of use)`;
79
+ }
80
+
81
+ /** Days of use after a stretch's date, with no catch-up run since, that make
82
+ * it overdue: the person came back on a later day and nothing cleared it. */
83
+ export const OVERDUE_DAYS_OF_USE = 2;
84
+
85
+ /**
86
+ * OVERDUE (S2c, 2026-10-26): a debt the catch-up had its chance at and did
87
+ * not clear — not a debt waiting for its first night. The night runs at the
88
+ * next day of use's first prompt, so yesterday's check-ins are owed every
89
+ * morning until then; that is the ordinary state, not a problem.
90
+ *
91
+ * Overdue when a catch-up ran on a LATER DATE than the stretch's latest piece
92
+ * (dates in the store's zone: the night is launched from the morning session's
93
+ * first prompt, so that session's own pieces land around the run's row, and a
94
+ * second run the same day — a whole night after a catch-up-only one — is not
95
+ * a chance at that day's sessions in any way a person could tell apart); or
96
+ * when `OVERDUE_DAYS_OF_USE` days of use came after it and no catch-up has run
97
+ * since — where nights never run (dreaming off, or a night that never starts),
98
+ * the next session's pointer had a whole day of use to offer it. Loose on
99
+ * purpose (guards loose-first): a run that was bounded and left a part counts
100
+ * as a chance too.
101
+ */
102
+ export function overdue(e: LedgerEntry, zone: string, lastCatchUpAt: number | null): boolean {
103
+ if (e.stretch === null) return false;
104
+ const day = localDate(e.stretch.lastAt, zone);
105
+ if (lastCatchUpAt !== null && localDate(lastCatchUpAt, zone) > day) return true;
106
+ // No catch-up on a later date (the arm above), so none since that counts.
107
+ return e.daysOfUseSince >= OVERDUE_DAYS_OF_USE;
108
+ }
109
+
110
+ /** The newest catch-up row's time, or null when none ran (or it cannot be read). */
111
+ function lastCatchUpAt(store: Store): number | null {
112
+ try {
113
+ return catchUpOf(store)?.at ?? null;
114
+ } catch {
115
+ return null;
116
+ }
63
117
  }
64
118
 
65
119
  /** `failed` when it cannot be read. It reads every scope's captured words, so
66
120
  * the budgeted session-start reading never calls it. */
67
- export function readOwed(store: Store, today: string): OwedReading | "failed" {
121
+ export function readOwed(store: Store): OwedReading | "failed" {
68
122
  try {
69
123
  const now = store.now();
70
124
  // READ-ONLY by construction: an observer buffer writes nothing, and it
@@ -75,9 +129,13 @@ export function readOwed(store: Store, today: string): OwedReading | "failed" {
75
129
  const host = hostSessionEvidence(store);
76
130
  const entries = ledger(spans, { now, zone, host: (s) => ({ endedAt: host(s).endedAt }) });
77
131
  const all = entries.filter((e) => e.owed);
78
- const owed = all.filter((e) => pointable(e, store.dir));
79
- const stale = owed.filter((e) => e.stretch !== null && localDate(e.stretch.lastAt, zone) < today).length;
80
- return { spans, plan, entries, now, waiting: owed.length, stale, unpointed: all.length - owed.length };
132
+ const why = new Map(all.map((e) => [e.session, notPointableWhy(e, store.dir)]));
133
+ const owed = all.filter((e) => why.get(e.session) === null);
134
+ const night = lastCatchUpAt(store);
135
+ const stale = owed.filter((e) => overdue(e, zone, night)).length;
136
+ const headless = all.filter((e) => why.get(e.session) === "headless").length;
137
+ const noRecord = all.filter((e) => why.get(e.session) === "no-record").length;
138
+ return { spans, plan, entries, now, waiting: owed.length, stale, unpointed: headless + noRecord, unpointedHeadless: headless, unpointedNoRecord: noRecord, lastCatchUpAt: night };
81
139
  } catch {
82
140
  return "failed";
83
141
  }
@@ -93,6 +151,8 @@ export function crashWriteUpFindings(input: DoctorInput, store: Store, owedReadi
93
151
  let waiting: number | null = null;
94
152
  let stale = 0;
95
153
  let unpointed = 0;
154
+ let unpointedHeadless = 0;
155
+ let unpointedNoRecord = 0;
96
156
  let yesterdayWords = "";
97
157
  let yesterdayData: { sessions: number; pieces: number; written: number } | null = null;
98
158
  /** Sessions FINISHED in one project and waiting on words they left in
@@ -105,6 +165,8 @@ export function crashWriteUpFindings(input: DoctorInput, store: Store, owedReadi
105
165
  waiting = reading.waiting;
106
166
  stale = reading.stale;
107
167
  unpointed = reading.unpointed;
168
+ unpointedHeadless = reading.unpointedHeadless;
169
+ unpointedNoRecord = reading.unpointedNoRecord;
108
170
  // YESTERDAY, keyed on the pieces' own dates in the store's zone.
109
171
  const day = entries
110
172
  .map((e) => e.perDate[yesterday])
@@ -143,8 +205,9 @@ export function crashWriteUpFindings(input: DoctorInput, store: Store, owedReadi
143
205
  );
144
206
  if (elsewhere.length === 0) continue;
145
207
  const e = entries.find((x) => x.session === session);
146
- const from = e?.stretch === null || e === undefined ? input.today : localDate(e.stretch.lastAt, store.zone());
147
- shares.push({ session, here, elsewhere, stale: from < input.today });
208
+ // OVERDUE AS THE COUNT IS (S2c): waiting on another project is the
209
+ // ordinary state until the catch-up has had its chance.
210
+ shares.push({ session, here, elsewhere, stale: e !== undefined && overdue(e, store.zone(), reading.lastCatchUpAt) });
148
211
  }
149
212
  shares.sort((a, b) => Number(b.stale) - Number(a.stale));
150
213
  } catch {
@@ -157,7 +220,7 @@ export function crashWriteUpFindings(input: DoctorInput, store: Store, owedReadi
157
220
  : waiting === 0
158
221
  ? "nothing owed"
159
222
  : `${String(waiting)} session${waiting === 1 ? "" : "s"} to catch up` +
160
- (stale === 0 ? "" : `, ${String(stale)} from yesterday or earlier`);
223
+ (stale === 0 ? "" : `, ${overdueWords(stale)}`);
161
224
  // THE NIGHTLY RUN'S CATCH-UP (2026-10-01): its newest row, within two days.
162
225
  let night: ReturnType<typeof catchUpOf> = null;
163
226
  try {
@@ -183,7 +246,7 @@ export function crashWriteUpFindings(input: DoctorInput, store: Store, owedReadi
183
246
  yesterdayWords,
184
247
  nightWords,
185
248
  owedWords,
186
- unpointed === 0 ? "" : `${String(unpointed)} small, not known as a person's session: left to lapse`,
249
+ lapsingWords(unpointedHeadless, unpointedNoRecord),
187
250
  lapses === 0 ? "" : `${String(lapses)} lost unwritten this week`,
188
251
  ]
189
252
  .filter((w) => w.length > 0)
@@ -194,6 +257,8 @@ export function crashWriteUpFindings(input: DoctorInput, store: Store, owedReadi
194
257
  waiting,
195
258
  stale,
196
259
  unpointed,
260
+ unpointedHeadless,
261
+ unpointedNoRecord,
197
262
  lapsedWeek: lapses,
198
263
  yesterday,
199
264
  yesterdaySessions: yesterdayData?.sessions ?? null,
@@ -267,9 +332,9 @@ export function crashWriteUpFindings(input: DoctorInput, store: Store, owedReadi
267
332
  title,
268
333
  detail,
269
334
  (auto
270
- ? "The nightly run catches up on everything owed each morning; counterparts catch-up does it now. "
335
+ ? "The nightly run had its chance at these, or has not run in two days of use, and they are still owed; counterparts catch-up does it now. "
271
336
  : "Run counterparts catch-up to write them up now, or open a session in the project each one is in: its start points at the oldest. ") +
272
- "counterparts coverage says which. A stretch nobody writes up lapses after two more days of use — nothing is deleted, it stops being owed.",
337
+ `counterparts coverage says which. A stretch nobody writes up lapses after ${String(COVERAGE_TUNABLES.LAPSE_DAYS_OF_USE)} days of use — nothing is deleted, it stops being owed.`,
273
338
  data,
274
339
  ),
275
340
  ];