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.
Files changed (195) hide show
  1. package/CONSTITUTION.md +68 -0
  2. package/LICENSE +21 -0
  3. package/README.md +348 -0
  4. package/docs/ELI5.md +84 -0
  5. package/docs/QUICKSTART.md +1258 -0
  6. package/docs/module-map.md +81 -0
  7. package/package.json +63 -0
  8. package/src/adapters/claude-code/CONTRACT.md +606 -0
  9. package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
  10. package/src/adapters/claude-code/NOTES.md +1055 -0
  11. package/src/adapters/claude-code/bin/hook.ts +820 -0
  12. package/src/adapters/claude-code/bin/runner.ts +522 -0
  13. package/src/adapters/claude-code/config.ts +778 -0
  14. package/src/adapters/claude-code/credentials.ts +199 -0
  15. package/src/adapters/claude-code/doctor.ts +2557 -0
  16. package/src/adapters/claude-code/embed-client.ts +617 -0
  17. package/src/adapters/claude-code/hooks.ts +2240 -0
  18. package/src/adapters/claude-code/index.ts +224 -0
  19. package/src/adapters/claude-code/interpret-client.ts +395 -0
  20. package/src/adapters/claude-code/page-writer.ts +462 -0
  21. package/src/adapters/claude-code/primacy.ts +162 -0
  22. package/src/adapters/claude-code/spawn.ts +241 -0
  23. package/src/adapters/claude-code/standdown.ts +536 -0
  24. package/src/adapters/claude-code/transcript.ts +661 -0
  25. package/src/adapters/claude-code/vectors.ts +415 -0
  26. package/src/adapters/cli/CONTRACT.md +255 -0
  27. package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
  28. package/src/adapters/cli/NOTES.md +936 -0
  29. package/src/adapters/cli/bin/counterparts.ts +74 -0
  30. package/src/adapters/cli/commands.ts +6095 -0
  31. package/src/adapters/cli/export.ts +766 -0
  32. package/src/adapters/cli/index.ts +103 -0
  33. package/src/adapters/cli/install.ts +670 -0
  34. package/src/adapters/cli/removal.ts +1186 -0
  35. package/src/adapters/cli/repair-dates.ts +659 -0
  36. package/src/adapters/cli/self-page.ts +229 -0
  37. package/src/adapters/cli/snapshot.ts +279 -0
  38. package/src/adapters/cli/start-fresh.ts +1228 -0
  39. package/src/adapters/config-path.ts +342 -0
  40. package/src/adapters/dashboard/CONTRACT.md +67 -0
  41. package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
  42. package/src/adapters/dashboard/NOTES.md +474 -0
  43. package/src/adapters/dashboard/activity.ts +121 -0
  44. package/src/adapters/dashboard/ansi.ts +82 -0
  45. package/src/adapters/dashboard/bin/dashboard.ts +479 -0
  46. package/src/adapters/dashboard/browse.ts +298 -0
  47. package/src/adapters/dashboard/identity.ts +182 -0
  48. package/src/adapters/dashboard/index.ts +183 -0
  49. package/src/adapters/dashboard/layout.ts +149 -0
  50. package/src/adapters/dashboard/registries.ts +291 -0
  51. package/src/adapters/dashboard/resolve.ts +206 -0
  52. package/src/adapters/dashboard/source.ts +48 -0
  53. package/src/adapters/dashboard/status.ts +327 -0
  54. package/src/adapters/dashboard/stories.ts +194 -0
  55. package/src/adapters/dashboard/web/app.html +1731 -0
  56. package/src/adapters/dashboard/web/brain.html +463 -0
  57. package/src/adapters/dashboard/web/fired.ts +31 -0
  58. package/src/adapters/dashboard/web/flow.ts +457 -0
  59. package/src/adapters/dashboard/web/narrate.ts +1042 -0
  60. package/src/adapters/dashboard/web/reveal.ts +135 -0
  61. package/src/adapters/dashboard/web/server.ts +287 -0
  62. package/src/adapters/dashboard/web/views.ts +1744 -0
  63. package/src/adapters/expansions.ts +569 -0
  64. package/src/adapters/fired.ts +1580 -0
  65. package/src/adapters/mcp/CONTRACT.md +240 -0
  66. package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
  67. package/src/adapters/mcp/NOTES.md +205 -0
  68. package/src/adapters/mcp/bin/serve.ts +349 -0
  69. package/src/adapters/mcp/deliberate.ts +619 -0
  70. package/src/adapters/mcp/index.ts +101 -0
  71. package/src/adapters/mcp/protocol.ts +170 -0
  72. package/src/adapters/mcp/server.ts +1740 -0
  73. package/src/adapters/mcp/stdio.ts +56 -0
  74. package/src/adapters/mcp/tools.ts +779 -0
  75. package/src/adapters/scopes.ts +657 -0
  76. package/src/adapters/sessions.ts +402 -0
  77. package/src/adapters/snapshots.ts +1069 -0
  78. package/src/adapters/stance-env.ts +137 -0
  79. package/src/core/associate/CONTRACT.md +118 -0
  80. package/src/core/associate/INTERFACE-GAPS.md +173 -0
  81. package/src/core/associate/NOTES.md +194 -0
  82. package/src/core/associate/buffer.ts +66 -0
  83. package/src/core/associate/edges.ts +188 -0
  84. package/src/core/associate/index.ts +570 -0
  85. package/src/core/associate/pending.ts +383 -0
  86. package/src/core/associate/spread.ts +149 -0
  87. package/src/core/associate/tunables.ts +123 -0
  88. package/src/core/bridge.ts +272 -0
  89. package/src/core/briefing.ts +67 -0
  90. package/src/core/counterpart.ts +3855 -0
  91. package/src/core/encode/CONTRACT.md +151 -0
  92. package/src/core/encode/INTERFACE-GAPS.md +135 -0
  93. package/src/core/encode/NOTES.md +146 -0
  94. package/src/core/encode/aliases.ts +71 -0
  95. package/src/core/encode/battery.ts +284 -0
  96. package/src/core/encode/chunk.ts +265 -0
  97. package/src/core/encode/emotion.ts +119 -0
  98. package/src/core/encode/floor.ts +76 -0
  99. package/src/core/encode/index.ts +100 -0
  100. package/src/core/encode/precision.ts +162 -0
  101. package/src/core/encode/preselect.ts +269 -0
  102. package/src/core/encode/salience.ts +108 -0
  103. package/src/core/encode/secrets.ts +265 -0
  104. package/src/core/encode/tunables.ts +99 -0
  105. package/src/core/encode/types.ts +286 -0
  106. package/src/core/encode/words.ts +75 -0
  107. package/src/core/handoff/CONTRACT.md +199 -0
  108. package/src/core/handoff/INTERFACE-GAPS.md +166 -0
  109. package/src/core/handoff/NOTES.md +206 -0
  110. package/src/core/handoff/index.ts +957 -0
  111. package/src/core/mint.ts +279 -0
  112. package/src/core/observer.ts +28 -0
  113. package/src/core/physics/CONTRACT.md +341 -0
  114. package/src/core/physics/NOTES.md +155 -0
  115. package/src/core/physics/clock.ts +51 -0
  116. package/src/core/physics/index.ts +1054 -0
  117. package/src/core/prospective/CONTRACT.md +137 -0
  118. package/src/core/prospective/INTERFACE-GAPS.md +112 -0
  119. package/src/core/prospective/NOTES.md +160 -0
  120. package/src/core/prospective/derive.ts +188 -0
  121. package/src/core/prospective/index.ts +1030 -0
  122. package/src/core/prospective/tunables.ts +72 -0
  123. package/src/core/prospective/windows.ts +187 -0
  124. package/src/core/recall/CONTRACT.md +326 -0
  125. package/src/core/recall/INTERFACE-GAPS.md +163 -0
  126. package/src/core/recall/NOTES.md +472 -0
  127. package/src/core/recall/activate.ts +521 -0
  128. package/src/core/recall/cues.ts +275 -0
  129. package/src/core/recall/gate.ts +441 -0
  130. package/src/core/recall/index.ts +692 -0
  131. package/src/core/recall/probe.ts +239 -0
  132. package/src/core/recall/reference.ts +201 -0
  133. package/src/core/recall/render.ts +285 -0
  134. package/src/core/recall/session.ts +403 -0
  135. package/src/core/recall/tunables.ts +329 -0
  136. package/src/core/remember/CONTRACT.md +293 -0
  137. package/src/core/remember/INTERFACE-GAPS.md +189 -0
  138. package/src/core/remember/NOTES.md +373 -0
  139. package/src/core/remember/fallback.ts +452 -0
  140. package/src/core/remember/index.ts +103 -0
  141. package/src/core/remember/owner-strike-seam.ts +479 -0
  142. package/src/core/remember/proposals.ts +609 -0
  143. package/src/core/remember/spans.ts +1310 -0
  144. package/src/core/remember/tunables.ts +111 -0
  145. package/src/core/remember/updates.ts +198 -0
  146. package/src/core/retrieval.ts +96 -0
  147. package/src/core/revision.ts +441 -0
  148. package/src/core/schemas/CONTRACT.md +190 -0
  149. package/src/core/schemas/INTERFACE-GAPS.md +172 -0
  150. package/src/core/schemas/NOTES.md +260 -0
  151. package/src/core/schemas/aliases.ts +160 -0
  152. package/src/core/schemas/index.ts +1459 -0
  153. package/src/core/schemas/tunables.ts +44 -0
  154. package/src/core/schemas/types.ts +387 -0
  155. package/src/core/self/CONTRACT.md +459 -0
  156. package/src/core/self/INTERFACE-GAPS.md +284 -0
  157. package/src/core/self/NOTES.md +1057 -0
  158. package/src/core/self/briefing.ts +980 -0
  159. package/src/core/self/episodes.ts +483 -0
  160. package/src/core/self/freeze.ts +103 -0
  161. package/src/core/self/identity.ts +604 -0
  162. package/src/core/self/index.ts +2130 -0
  163. package/src/core/self/journal-file.ts +760 -0
  164. package/src/core/self/page.ts +404 -0
  165. package/src/core/self/tunables.ts +244 -0
  166. package/src/core/self/writer.ts +714 -0
  167. package/src/core/sleep/CONTRACT.md +298 -0
  168. package/src/core/sleep/INTERFACE-GAPS.md +262 -0
  169. package/src/core/sleep/NOTES.md +770 -0
  170. package/src/core/sleep/briefing.ts +86 -0
  171. package/src/core/sleep/consolidate.ts +241 -0
  172. package/src/core/sleep/cycle.ts +598 -0
  173. package/src/core/sleep/decay.ts +237 -0
  174. package/src/core/sleep/dedup.ts +373 -0
  175. package/src/core/sleep/index.ts +112 -0
  176. package/src/core/sleep/log.ts +116 -0
  177. package/src/core/sleep/markers.ts +164 -0
  178. package/src/core/sleep/prune.ts +170 -0
  179. package/src/core/sleep/strength-cache.ts +176 -0
  180. package/src/core/sleep/tunables.ts +135 -0
  181. package/src/core/sleep/types.ts +542 -0
  182. package/src/core/store/CONTRACT.md +446 -0
  183. package/src/core/store/NOTES.md +1068 -0
  184. package/src/core/store/cache.ts +709 -0
  185. package/src/core/store/db.ts +275 -0
  186. package/src/core/store/errors.ts +134 -0
  187. package/src/core/store/index.ts +2450 -0
  188. package/src/core/store/operational.ts +610 -0
  189. package/src/core/store/owner-op-seam.ts +428 -0
  190. package/src/core/store/paths.ts +494 -0
  191. package/src/core/store/prose.ts +165 -0
  192. package/src/core/store/render.ts +87 -0
  193. package/src/core/store/walk-seam.ts +78 -0
  194. package/src/core/types.ts +68 -0
  195. package/tools/install-loop/run.sh +1063 -0
@@ -0,0 +1,536 @@
1
+ /**
2
+ * WHY A HOOK STOOD DOWN, IN WORDS, AND WHETHER THE OWNER SHOULD HEAR IT.
3
+ *
4
+ * **The gap this closes (H1, 2026-09-18).** `bin/hook.ts` has always ended a
5
+ * failed run with one line on stderr and exit 0 — "a failed hook is a quiet
6
+ * hook, never a failed session". The principle is right; the quiet is the
7
+ * problem. A hook's stderr goes nowhere the owner looks, and three reviews in
8
+ * one day hit the same wall: a fully-removed belief left a row that made
9
+ * `Counterpart.open` throw at every session start; a missing prose file on any
10
+ * schema row still does; a config typo that stood the adapter down was equally
11
+ * invisible. No wake, no recall, no capture, every session — and every visible
12
+ * surface green. The constitution's own sentence: silence must never masquerade
13
+ * as health.
14
+ *
15
+ * So a stand-down is now one of two things, and this file is where they are told
16
+ * apart:
17
+ *
18
+ * - **DELIBERATE** — a directory scoped `off`, an observer with no store to
19
+ * read, the explicit-dir guard refusing a store nobody named. Nothing is
20
+ * wrong; the stand-down IS the behaviour. Quiet, exactly as before.
21
+ * - **A FAULT** — the store would not open, the named configuration could not
22
+ * be honoured. Something the owner has to fix, and until he does he has no
23
+ * memory. Said out loud, on the two events the host displays a
24
+ * `systemMessage` on (`bin/hook.ts#standDown`).
25
+ *
26
+ * It sits beside `doctor.ts` rather than under `bin/` because both read it: the
27
+ * console's `Store open` finding asks the same question the hook's catch asks —
28
+ * "would this store open the way a session opens it, and if not, in what words?"
29
+ * — and two vocabularies for one question is how the terminal and the console
30
+ * come to disagree about what "healthy" means (constitution 16).
31
+ */
32
+ import { lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
33
+ import { homedir } from "node:os";
34
+ import { join } from "node:path";
35
+
36
+ import { isLocked } from "../../core/store/db.js";
37
+ import { assertSafeDataDir, isStoreError } from "../../core/store/index.js";
38
+ import type { StoreErrorCode } from "../../core/store/index.js";
39
+ import { SESSIONS_DIR, isSessionId } from "../sessions.js";
40
+
41
+ /** The last words of every stand-down message, and the only ones never cut. */
42
+ export const STANDDOWN_TAIL = "Run: counterparts doctor";
43
+
44
+ /**
45
+ * How long the REASON clause may be.
46
+ *
47
+ * The message rides the same 10,000-character channel the notice does
48
+ * (`doctor.ts#NOTICE_MAX_CHARS` states the host's cap), but the ceiling that
49
+ * matters here is smaller and is about content, not transport: an error's own
50
+ * message is the one part of this that nobody here wrote, and a stand-down line
51
+ * that fills the terminal with somebody's stack trace is a line people learn to
52
+ * scroll past. Two hundred characters holds a code, a path and a sentence.
53
+ */
54
+ export const STANDDOWN_REASON_MAX_CHARS = 200;
55
+
56
+ /**
57
+ * WHICH KIND OF FAULT — and the distinction is not cosmetic, it is what keeps
58
+ * this from becoming wallpaper.
59
+ *
60
+ * - `persistent` — the store will not open, or the configuration cannot be
61
+ * honoured. It will be exactly as broken next turn, and the session has no
62
+ * memory until somebody fixes it.
63
+ * - `transient` — the database was BUSY: another process held it for the
64
+ * moment this hook wanted it (`db.ts#isLocked`, which is also what F1's
65
+ * WAL conversion swallows). The turn really did nothing, and the next one
66
+ * will probably be fine. Measured on a fresh store on 2026-09-18, before
67
+ * WAL: roughly one prompt in ten. A line that says "memory is OFF for this
68
+ * session" about that is both untrue and, at that rate, a line people learn
69
+ * to scroll past.
70
+ */
71
+ export type StandDownKind = "persistent" | "transient";
72
+
73
+ /** A stand-down worth saying out loud: a stable code, and plain words for it. */
74
+ export interface StandDownFault {
75
+ /** A `StoreErrorCode`, or one of this file's own for a non-store failure. */
76
+ readonly code: string;
77
+ /** One clause of plain words. Never memory text; a path is allowed. */
78
+ readonly reason: string;
79
+ readonly kind: StandDownKind;
80
+ }
81
+
82
+ /** The configuration a caller NAMED could not be honoured (`config-path.ts`). */
83
+ export const CONFIG_REFUSED = "CONFIG_REFUSED";
84
+ /** A named configuration parsed but did not typecheck, so it resolved observer. */
85
+ export const CONFIG_UNREADABLE = "CONFIG_UNREADABLE";
86
+ /** Anything that is not a `StoreError` — the code is the error's own message. */
87
+ export const HOOK_FAILED = "HOOK_FAILED";
88
+
89
+ /**
90
+ * THE STAND-DOWNS THAT STAY QUIET, and why each one is not a fault.
91
+ *
92
+ * - `IMPLICIT_DEFAULT_DIR_REFUSED` / `EXPLICIT_DIR_GUARD_MALFORMED` — the
93
+ * explicit-dir guard. In a real session it is a fault from the owner's point
94
+ * of view, and it is also the NORMAL state of every agent and test shell in
95
+ * this project, which all export `COUNTERPARTS_REQUIRE_EXPLICIT_DIR=1`.
96
+ * `describeGuardRefusal` already gives it a sentence with the entry point's
97
+ * own remedy, and the red notice has never carried it; that treatment is
98
+ * kept rather than turned into a red line in every hermetic shell.
99
+ * - `STORE_UNINITIALIZED` — an OBSERVER opened a store that is not there yet,
100
+ * or is a schema behind (`cli/INTERFACE-GAPS` §7). Initializing would be
101
+ * writing at open, which an instrument may not do, so standing down is the
102
+ * behaviour and not a fault. An owner hook on the same store initializes and
103
+ * migrates it.
104
+ */
105
+ export function isDeliberate(err: unknown): boolean {
106
+ return (
107
+ isStoreError(err, "IMPLICIT_DEFAULT_DIR_REFUSED") ||
108
+ isStoreError(err, "EXPLICIT_DIR_GUARD_MALFORMED") ||
109
+ isStoreError(err, "STORE_UNINITIALIZED")
110
+ );
111
+ }
112
+
113
+ /**
114
+ * Plain words for the store codes a session's READ PATH can actually meet.
115
+ *
116
+ * Deliberately partial. A code with no entry gets the general sentence below,
117
+ * which is true of every one of them; inventing prose for codes nobody has seen
118
+ * from a hook would be a glossary that goes stale where nobody reads it.
119
+ */
120
+ const PLAIN_WORDS: Partial<Record<StoreErrorCode, string>> = {
121
+ MEMORY_BODY_MISSING: "a memory's row is in the store and its words are not",
122
+ MEMORY_META_MALFORMED: "a memory's metadata is not something this build can read",
123
+ PROSE_PAYLOAD_MISMATCH: "a row and the memory it was read for disagree about which memory it is",
124
+ PROSE_BODY_INVALID: "a memory has a body this build cannot write",
125
+ ID_DANGLING: "a row points at a memory that is not in the store",
126
+ ID_CYCLE: "a revision chain in the store points back at itself",
127
+ ID_CHAIN_TOO_DEEP: "a revision chain in the store is longer than this build follows",
128
+ SCHEMA_AHEAD: "this store was written by a newer build than the one running",
129
+ // The one entry that carries an INSTRUCTION, because it is the one fault a
130
+ // reader can act on without another command: the tag is the way back in, and
131
+ // a bare `floor/v5-last` in a JSON payload told nobody it was a thing to check
132
+ // out (review A, NIT-2). It fits the 200-character reason cap with room.
133
+ STORE_PRE_ROWS:
134
+ "this store keeps its memories in files, which this build does not read — it was written before the floor changed; the build that reads it is the tag floor/v5-last",
135
+ SQLITE_UNAVAILABLE: "this runtime has no SQLite binding",
136
+ DATA_DIR_FORBIDDEN: "the configured data dir is one this build refuses to open",
137
+ STORE_UNINITIALIZED: "there is no store here yet, or it is a schema behind",
138
+ };
139
+
140
+ /** The sentence for a code with no entry above. True of all of them. */
141
+ export const OPEN_FAILED_WORDS = "the store would not open";
142
+
143
+ /**
144
+ * A code and plain words for ANY failure — including the deliberate ones, which
145
+ * `doctor` still has to name even though the hook stays quiet about them.
146
+ */
147
+ /**
148
+ * The pre-rows reason clause, which depends on WHICH pre-rows case this is.
149
+ *
150
+ * `PLAIN_WORDS` is a constant table and cannot look at the error; for the
151
+ * LOCKOUT case (a v6 store an older build left its empty leftovers in) the
152
+ * constant sentence sends the owner at `floor/v5-last` — the build that has just
153
+ * stood down on this same directory. That is A-MAJOR-1's circle surviving in the
154
+ * one channel the owner actually reads (third review, NEW-MINOR-1); the correct
155
+ * sentence was on stderr and in doctor only.
156
+ *
157
+ * So when the refusal carries its own `remedy` — which it does exactly when this
158
+ * directory also holds a `counterparts.sqlite` — the reason says that instead,
159
+ * and points at the door that has the full sentence.
160
+ */
161
+ function preRowsReason(err: unknown): string | null {
162
+ if (!isStoreError(err, "STORE_PRE_ROWS")) return null;
163
+ if (typeof err.detail["remedy"] !== "string") return null;
164
+ return (
165
+ "this directory holds this build's store AND an older build's leftovers, so it will not " +
166
+ "open either by guess — run counterparts doctor for the names and what to move"
167
+ );
168
+ }
169
+
170
+ export function describeFault(err: unknown): StandDownFault {
171
+ // TOTAL, and the reason is not theoretical politeness: this runs inside the
172
+ // handler that exists so a hook never fails the host, and everything below
173
+ // touches a property of an object nobody here made. A throwable with a
174
+ // throwing `code` getter, or one with a null prototype, would throw out of the
175
+ // handler and take the process's exit code with it. The general sentence is
176
+ // true of every failure, so it is the right thing to fall back to.
177
+ try {
178
+ return readFault(err);
179
+ } catch {
180
+ return { code: HOOK_FAILED, reason: OPEN_FAILED_WORDS, kind: "persistent" };
181
+ }
182
+ }
183
+
184
+ function readFault(err: unknown): StandDownFault {
185
+ // BUSY FIRST, because a contended database arrives under several spellings —
186
+ // a bare `Error` from either driver, or a `StoreError` wrapping one — and
187
+ // which class it is says nothing about whether it will still be true next
188
+ // turn. `isLocked` is `db.ts`'s own test, imported rather than mirrored.
189
+ const kind: StandDownKind = isLocked(err) ? "transient" : "persistent";
190
+ if (isStoreError(err)) {
191
+ return {
192
+ code: err.code,
193
+ reason: preRowsReason(err) ?? PLAIN_WORDS[err.code] ?? OPEN_FAILED_WORDS,
194
+ kind,
195
+ };
196
+ }
197
+ const message = err instanceof Error ? err.message : String(err);
198
+ return {
199
+ code: HOOK_FAILED,
200
+ reason: message.trim().length === 0 ? OPEN_FAILED_WORDS : message,
201
+ kind,
202
+ };
203
+ }
204
+
205
+ /** The fault to SAY, or null when this stand-down is one of the quiet ones. */
206
+ export function classifyStandDown(err: unknown): StandDownFault | null {
207
+ return isDeliberate(err) ? null : describeFault(err);
208
+ }
209
+
210
+ /**
211
+ * The ONE PATH-SHAPED FACT a repair needs, when the error carried one.
212
+ *
213
+ * `StoreError.detail` is ids and counts by contract (§5 G10) — never body text —
214
+ * so taking one named field out of it is safe to print. Only `path`, because
215
+ * that is the field the read path's own failures carry and the only one a reader
216
+ * can act on.
217
+ */
218
+ export function faultPath(err: unknown): string | null {
219
+ if (!isStoreError(err)) return null;
220
+ const path = err.detail["path"];
221
+ return typeof path === "string" && path.length > 0 ? path : null;
222
+ }
223
+
224
+ /**
225
+ * The ROW a store fault is about, when the fault is about one.
226
+ *
227
+ * `faultPath`'s counterpart on this floor. `MEMORY_BODY_MISSING` carries
228
+ * `{ id }` and no path, because there is no file to restore — and doctor's
229
+ * red line named the CLASS and not the row, so every session was down and the
230
+ * owner could not find which of ~17,000 rows to act on (review B, MAJOR-3).
231
+ * An id is the one thing that makes the fault addressable.
232
+ */
233
+ export function faultId(err: unknown): string | null {
234
+ if (!isStoreError(err)) return null;
235
+ const id = err.detail["id"];
236
+ return typeof id === "string" && id.length > 0 ? id : null;
237
+ }
238
+
239
+ /** Whitespace collapsed: an error message is not this file's to format. */
240
+ function oneLine(text: string): string {
241
+ return text.replace(/\s+/g, " ").trim();
242
+ }
243
+
244
+ /**
245
+ * The home directory written `~`, the way every shell writes it.
246
+ *
247
+ * The `HOOK_FAILED` reason is a THIRD-PARTY message — `EACCES: permission
248
+ * denied, mkdir '/Users/…/store/prose'` — and the absolute path in it is both
249
+ * noise and the owner's name on his own screen. Only the prefix is replaced:
250
+ * the rest of the path is what a reader acts on. The full message is still on
251
+ * stderr, verbatim, where a diagnostic belongs.
252
+ */
253
+ function tildeHome(text: string, home: string = homedir()): string {
254
+ return home.length > 1 ? text.split(home).join("~") : text;
255
+ }
256
+
257
+ /**
258
+ * THE ONE RED LINE IN THE OWNER'S TERMINAL.
259
+ *
260
+ * Short on purpose. It says the consequence first — memory is off — because that
261
+ * is the fact a person scanning a session start needs, then the reason, then the
262
+ * code a search finds, then the one command that explains the rest. Nothing from
263
+ * a memory ever reaches it: the reason is either this file's own prose or an
264
+ * error message, and error messages in this codebase carry codes, ids and paths.
265
+ */
266
+ export function standDownMessage(fault: StandDownFault): string {
267
+ const reason = tildeHome(oneLine(fault.reason));
268
+ const said =
269
+ reason.length <= STANDDOWN_REASON_MAX_CHARS
270
+ ? reason
271
+ : `${reason.slice(0, STANDDOWN_REASON_MAX_CHARS - 1)}…`;
272
+ return `Counterparts memory is OFF for this session: ${said} (${fault.code}). ${STANDDOWN_TAIL}`;
273
+ }
274
+
275
+ /**
276
+ * THE TWO THINGS A BUSY DATABASE SAYS, and neither of them says OFF.
277
+ *
278
+ * A lock at a PROMPT costs that turn: no recall was composed, nothing was
279
+ * captured, and the next turn is very likely fine. A lock at SESSION START
280
+ * costs the whole session's wake — nothing was injected and nothing will be,
281
+ * because SessionStart does not come round again — so it is not a blip and is
282
+ * said the first time it happens. Both are fixed sentences: there is exactly one
283
+ * cause, and an error message adds nothing a reader can act on.
284
+ */
285
+ export const BUSY_TURN_MESSAGE =
286
+ "Counterparts skipped this turn: the memory database was busy (database is locked). " +
287
+ "If this keeps happening, run: counterparts doctor";
288
+
289
+ export const BUSY_SESSION_START_MESSAGE =
290
+ "Counterparts could not load memory at session start: the memory database was busy. " +
291
+ "This session has no wake; recall will work once the database is free. " +
292
+ "If this keeps happening, run: counterparts doctor";
293
+
294
+ /**
295
+ * HOW MANY SKIPPED TURNS BEFORE "BUSY" STOPS MEANING TEMPORARY.
296
+ *
297
+ * `isLocked` is a test on an error, and an error cannot tell a 40 ms contention
298
+ * from a lock nothing will ever release — a crashed worker, a stale `-shm` a
299
+ * reboot left wedged, a network filesystem. Without this the wedged case is I32
300
+ * again inside the transient branch: one soft line that says it will pass, and
301
+ * then silence for however many turns die. Five is where a run of them stops
302
+ * being a coincidence and is small enough that the owner hears it in the same
303
+ * sitting; nothing downstream depends on the number.
304
+ */
305
+ export const TRANSIENT_ESCALATE_AFTER = 5;
306
+
307
+ /** The escalation, said once. It is allowed to say OFF, because by now it is true. */
308
+ export function busyWedgedMessage(count: number): string {
309
+ return (
310
+ `Counterparts has skipped ${String(count)} turns this session: the memory database stays ` +
311
+ "busy (database is locked). Memory is effectively off until that clears. " +
312
+ "Run: counterparts doctor"
313
+ );
314
+ }
315
+
316
+ // ── saying it once per session ──────────────────────────────────────────────
317
+
318
+ /**
319
+ * WHAT THIS SESSION HAS ALREADY BEEN TOLD, and why it is a file.
320
+ *
321
+ * A store that will not open cannot remember anything, and `UserPromptSubmit`
322
+ * fires every turn — so without a mark the owner would get the same line on
323
+ * every prompt for the rest of the session, which is how a warning becomes
324
+ * wallpaper. The mark therefore has to survive in something that does not need
325
+ * the database: `<dataDir>/sessions/`, where `adapters/sessions.ts` already
326
+ * keeps one small file per session and `adapters/expansions.ts` keeps its own.
327
+ * It is host state, never memory (constitution 5) — an id, times, an event name,
328
+ * a code and two counters.
329
+ *
330
+ * THE TWO KINDS ARE TRACKED APART. A session that met a busy database and then
331
+ * met a store that will not open has learned two different things, and the
332
+ * second has to be said whether or not the first was.
333
+ *
334
+ * Everything here swallows its own failures. An unwritable mark means the
335
+ * message is said again next turn, which is the fail direction this whole track
336
+ * is about: repeating is noise, and silence is I32.
337
+ */
338
+ export const STANDDOWN_MARKER_SUFFIX = ".standdown.json";
339
+
340
+ export interface StandDownMark {
341
+ readonly sessionId: string;
342
+ /** When the last stand-down of this session was recorded, ISO. */
343
+ readonly at: string;
344
+ /** The event and code of that last one — facts, for the durable row (3) owes. */
345
+ readonly event: string;
346
+ readonly code: string;
347
+ /** A PERSISTENT stand-down has been said out loud in this session. */
348
+ readonly told: boolean;
349
+ /**
350
+ * The busy-database story: how many this session has met, when the last one
351
+ * was, whether one has been said, and whether the "this is not passing"
352
+ * escalation has been said. Two flags rather than one, because they are said
353
+ * at two different moments and each is once.
354
+ */
355
+ readonly transient: {
356
+ readonly count: number;
357
+ readonly at: string;
358
+ readonly told: boolean;
359
+ readonly escalated: boolean;
360
+ };
361
+ }
362
+
363
+ export function standDownMarkerPath(dataDir: string, sessionId: string): string | null {
364
+ if (!isSessionId(sessionId)) return null;
365
+ return join(dataDir, SESSIONS_DIR, `${sessionId}${STANDDOWN_MARKER_SUFFIX}`);
366
+ }
367
+
368
+ /**
369
+ * The mark, or null on every failure — absent, unreadable, no store named.
370
+ *
371
+ * TOLERANT OF THE SHAPE BEFORE THIS ONE, which carried no `told` and no
372
+ * `transient`: a file existing at all meant a persistent line had been said, so
373
+ * that is what an absent `told` reads as. A field that is not the type it should
374
+ * be reads as its own zero rather than rejecting the whole record; the worst a
375
+ * wrong guess costs is one repeated line.
376
+ */
377
+ export function readMark(dataDir: string | undefined, sessionId: string): StandDownMark | null {
378
+ if (dataDir === undefined || dataDir.length === 0) return null;
379
+ const path = standDownMarkerPath(dataDir, sessionId);
380
+ if (path === null) return null;
381
+ let raw: unknown;
382
+ try {
383
+ // THE WALL, ASKED ON THE READ SIDE TOO. The rule is that this repository's
384
+ // code never touches v1's live stores — not writes them, not reads them —
385
+ // and a `dataDir` reaches this function before anything else has validated
386
+ // it (`Store.open` is what usually throws, and by then we are in the
387
+ // handler). Inside the `try`, so a refusal reads as "no prior mark".
388
+ assertSafeDataDir(dataDir);
389
+ raw = JSON.parse(readFileSync(path, "utf8"));
390
+ } catch {
391
+ return null;
392
+ }
393
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
394
+ const rec = raw as Record<string, unknown>;
395
+ const t = rec["transient"];
396
+ const trans = t !== null && typeof t === "object" ? (t as Record<string, unknown>) : {};
397
+ return {
398
+ sessionId: typeof rec["sessionId"] === "string" ? rec["sessionId"] : sessionId,
399
+ at: typeof rec["at"] === "string" ? rec["at"] : "",
400
+ event: typeof rec["event"] === "string" ? rec["event"] : "",
401
+ code: typeof rec["code"] === "string" ? rec["code"] : "",
402
+ told: rec["told"] === undefined ? true : rec["told"] === true,
403
+ transient: {
404
+ // CLAMPED, and not out of tidiness: a negative count read verbatim
405
+ // suppresses every transient message for the life of the session, so a
406
+ // hand-edited or half-written file could buy back exactly the silence
407
+ // this track exists to end.
408
+ count:
409
+ typeof trans["count"] === "number" && Number.isFinite(trans["count"])
410
+ ? Math.max(0, Math.floor(trans["count"]))
411
+ : 0,
412
+ at: typeof trans["at"] === "string" ? trans["at"] : "",
413
+ told: trans["told"] === true,
414
+ escalated: trans["escalated"] === true,
415
+ },
416
+ };
417
+ }
418
+
419
+ /**
420
+ * Leave the mark. Returns whether it landed; never throws.
421
+ *
422
+ * **It may not write into a store this build refuses to open.** `said.dataDir`
423
+ * is whatever the configuration named, and it is set BEFORE `Store.open` has
424
+ * had a chance to refuse it — so without this line a config naming
425
+ * `~/.bansai/anything` gets a `mkdir -p` and a file through the wall that exists
426
+ * so nothing here can touch v1's live memory (CLAUDE.md's second standing rule).
427
+ * It never fires on the owner's own deployment; it fires for agents, reviewers
428
+ * and replay tooling, which is the population the guard was built for. A refusal
429
+ * costs the mark and nothing else — the message is still shown.
430
+ *
431
+ * **And it is atomic, and does not follow a symlink**, which is `sessions.ts`'s
432
+ * own rule 3 for the same directory: a temp file beside the target and a
433
+ * `rename`, which REPLACES a symlink rather than writing through it, plus a
434
+ * refusal if what is there is not a regular file. Same directory, so the rename
435
+ * is a rename.
436
+ */
437
+ export function writeMark(
438
+ dataDir: string | undefined,
439
+ sessionId: string,
440
+ mark: StandDownMark,
441
+ ): boolean {
442
+ if (dataDir === undefined || dataDir.length === 0) return false;
443
+ const path = standDownMarkerPath(dataDir, sessionId);
444
+ if (path === null) return false;
445
+ const tmp = `${path}.${String(process.pid)}.tmp`;
446
+ try {
447
+ assertSafeDataDir(dataDir);
448
+ // `lstat`, not `stat`: the question is what is AT the path, and a symlink
449
+ // answers for its target under `stat`. Anything but a regular file — a
450
+ // symlink, a directory, a socket — is refused rather than replaced.
451
+ const there = lstatSync(path, { throwIfNoEntry: false });
452
+ if (there !== undefined && !there.isFile()) return false;
453
+ mkdirSync(join(dataDir, SESSIONS_DIR), { recursive: true });
454
+ writeFileSync(tmp, `${JSON.stringify(mark)}\n`, { encoding: "utf8", mode: 0o600 });
455
+ renameSync(tmp, path);
456
+ return true;
457
+ } catch {
458
+ return false;
459
+ }
460
+ }
461
+
462
+ /** The two events the host DISPLAYS a `systemMessage` on. */
463
+ export type SaysSoHook = "session-start" | "user-prompt-submit";
464
+
465
+ /** What this event should print, and what the session should remember of it. */
466
+ export interface SayDecision {
467
+ /** The message to display, or null to stay on stderr alone. */
468
+ readonly message: string | null;
469
+ /** The mark this event leaves. Written whether or not anything was said — a
470
+ * transient nobody was told about is still one this session has met. */
471
+ readonly mark: StandDownMark;
472
+ }
473
+
474
+ /**
475
+ * WHETHER TO SAY IT, given what this session has already been told. Pure, so the
476
+ * rule is provable without a process and without a filesystem.
477
+ *
478
+ * **Persistent**: SessionStart always says it — a compaction re-fires that event
479
+ * and the owner has just had his terminal rewritten. UserPromptSubmit says it
480
+ * only while the session has not been told.
481
+ *
482
+ * **Transient**: at most once per session, and — at a PROMPT — only from the
483
+ * SECOND one. One blip is noise at the rate a contended database produced before
484
+ * F1's WAL conversion (roughly one prompt in ten, measured 2026-09-18); a repeat
485
+ * inside one session is a signal. The first is recorded in the mark and stays on
486
+ * stderr. SessionStart is the exception and says it the first time: a lock there
487
+ * means no wake was injected at all, and that event does not come round again.
488
+ *
489
+ * **And once more, at `TRANSIENT_ESCALATE_AFTER`.** The soft line tells the owner
490
+ * the database is busy and will clear. When it does not clear — a wedged lock,
491
+ * which no test on an error can tell from a contended one — that sentence is a
492
+ * lie and the silence after it is I32 wearing the transient branch's clothes. So
493
+ * a session that reaches five skipped turns says so once, and that one is
494
+ * allowed to use the word OFF, because by then it is true.
495
+ */
496
+ export function decideSay(
497
+ fault: StandDownFault,
498
+ hook: SaysSoHook,
499
+ sessionId: string,
500
+ prior: StandDownMark | null,
501
+ at: number = Date.now(),
502
+ ): SayDecision {
503
+ const now = new Date(at).toISOString();
504
+ const was = prior?.transient ?? { count: 0, at: "", told: false, escalated: false };
505
+ const base = {
506
+ sessionId,
507
+ at: now,
508
+ event: hook,
509
+ code: fault.code,
510
+ told: prior?.told === true,
511
+ transient: was,
512
+ };
513
+ if (fault.kind === "persistent") {
514
+ const say = hook === "session-start" || !base.told;
515
+ return { message: say ? standDownMessage(fault) : null, mark: { ...base, told: base.told || say } };
516
+ }
517
+ const count = was.count + 1;
518
+ // THE ESCALATION OUTRANKS THE SOFT LINE, and is its own once: a session that
519
+ // has already been told "busy" is exactly the session that must hear it when
520
+ // busy turns out to be permanent.
521
+ if (count >= TRANSIENT_ESCALATE_AFTER && !was.escalated) {
522
+ return {
523
+ message: busyWedgedMessage(count),
524
+ mark: { ...base, transient: { count, at: now, told: true, escalated: true } },
525
+ };
526
+ }
527
+ const say = !was.told && (hook === "session-start" || count >= 2);
528
+ return {
529
+ message: say
530
+ ? hook === "session-start"
531
+ ? BUSY_SESSION_START_MESSAGE
532
+ : BUSY_TURN_MESSAGE
533
+ : null,
534
+ mark: { ...base, transient: { count, at: now, told: was.told || say, escalated: was.escalated } },
535
+ };
536
+ }