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,657 @@
1
+ /**
2
+ * THE SCOPE REGISTRY — which directories this memory is for, and in what stance.
3
+ *
4
+ * **The ask (owner, 2026-09-10; `claude-code/INTERFACE-GAPS.md` host gaps 6–8).**
5
+ * The hooks are registered globally, so a directory that has never heard of
6
+ * Counterparts inherits capture, deposit and the wake the first time a session
7
+ * opens in it. Until today the only way to say "not here" was a project
8
+ * `.claude/settings.json` with an `env` block naming a second, observer-stanced
9
+ * `claude-code.json` through `COUNTERPARTS_CONFIG` — a JSON file, a second
10
+ * config file and two environment variables to say one word. Three private
11
+ * directories run that way today and MUST KEEP RUNNING that way: nothing here
12
+ * relaxes a stance, it only ever adds one.
13
+ *
14
+ * **Where it lives: beside the configuration, never inside the store.** A store
15
+ * is memory; this is host state about which directories memory is for, and it
16
+ * has to be readable by a process that has not opened a store yet — the hook
17
+ * decides `off` BEFORE anything opens, which is what makes "no output, no
18
+ * write" structural rather than promised. So the file sits next to
19
+ * `claude-code.json`: under `COUNTERPARTS_CONFIG` or `--config`, beside THAT
20
+ * file, so a scratch install's scopes are that install's own
21
+ * (`scopesPath(choice.path)` at every entry point, and `config-path.ts` is
22
+ * still the one rule for which config).
23
+ *
24
+ * **Longest prefix wins, and the match is segment-aware.** A subdirectory
25
+ * inherits its nearest ancestor's entry, so a project turned off is off in
26
+ * every worktree under it, and `/a/b` never matches `/a/bc` — the same class of
27
+ * bug `assertSafeDataDir` resolves both sides to avoid. Both sides go through
28
+ * `canonicalScope` (`sessions.ts`), which is where the `/tmp` vs `/private/tmp`
29
+ * lesson on this host was already paid for.
30
+ *
31
+ * **Absent, unknown or UNREADABLE all mean `unset`, and `unset` means ON.**
32
+ * That is a deliberate choice and the one the owner is asked to confirm: every
33
+ * directory the parallel run touches is unset today, and a registry that
34
+ * defaulted to observer would silently mute the live run on the day it shipped.
35
+ * The fail direction for a CORRUPT file is the same "never fail the host" rule
36
+ * the hooks live by (`claude-code/CONTRACT.md` §5 G2) — never a thrown hook —
37
+ * and the console refuses to overwrite a file it could not parse without
38
+ * `--force`, so the corruption is loud on the one surface that has a person in
39
+ * front of it.
40
+ *
41
+ * **And because that fail direction is ON, a file in trouble is never SILENT**
42
+ * (#92 review, F2). A bad entry is refused BY NAME rather than failing the whole
43
+ * file — whole-file-fail turned every correctly typed `off` in the file on, to
44
+ * protect the one that was typed badly — and `describeScopeTrouble` is the one
45
+ * sentence the two processes with an operator print: the hook's stderr at
46
+ * SessionStart and the server's at launch. The console prints the same facts its
47
+ * own way, a line per entry, because it is talking to somebody who can fix them.
48
+ * "`off` is silent" (§5 G19) and "a corrupt registry is silent" are different
49
+ * exceptions, and only the first was ever ruled.
50
+ *
51
+ * **This module never throws at a reader.** `readScopes` returns a reading;
52
+ * only `writeScopes`, which is a console command with an owner watching, is
53
+ * allowed to fail out loud.
54
+ */
55
+ import {
56
+ mkdirSync,
57
+ readFileSync,
58
+ realpathSync,
59
+ renameSync,
60
+ unlinkSync,
61
+ writeFileSync,
62
+ } from "node:fs";
63
+ import { basename, dirname, join, resolve, sep } from "node:path";
64
+
65
+ /**
66
+ * `sessions.ts#canonicalScope`, extended by one step this rule needs and that
67
+ * one does not.
68
+ *
69
+ * `canonicalScope` realpaths a path that EXISTS and falls back to `resolve`
70
+ * otherwise, which is exactly right for comparing two directories a session is
71
+ * actually running in. A PREFIX rule needs more: on this host a registry key
72
+ * written from `/tmp/x` canonicalises to `/private/tmp/x`, while a query for a
73
+ * subdirectory that does not exist yet stays `/tmp/x/sub` — and an ancestor
74
+ * that governs the parent but not the child is the one answer a prefix rule may
75
+ * never give. So the deepest EXISTING ancestor is realpathed and the rest is
76
+ * appended, which makes both sides land in the same tree whether or not the
77
+ * leaf has been created.
78
+ */
79
+ export function canonicalScopePath(dir: string): string {
80
+ const abs = resolve(dir);
81
+ let head = abs;
82
+ const tail: string[] = [];
83
+ for (;;) {
84
+ try {
85
+ return tail.length === 0 ? realpathSync(head) : join(realpathSync(head), ...tail);
86
+ } catch {
87
+ const parent = dirname(head);
88
+ // The filesystem root did not resolve either: nothing here exists, so the
89
+ // resolved path is the best canonical form available.
90
+ if (parent === head) return abs;
91
+ tail.unshift(basename(head));
92
+ head = parent;
93
+ }
94
+ }
95
+ }
96
+
97
+ /** The file's name. It sits BESIDE the configuration, never inside a store. */
98
+ export const SCOPES_FILE_NAME = "scopes.json";
99
+
100
+ /** The only shape this reads. A file that says anything else is unreadable. */
101
+ export const SCOPES_VERSION = 1;
102
+
103
+ /**
104
+ * The RING event a hook leaves when the registry is there and unreadable —
105
+ * ring-only, for the same reason `adapter.config.file` is: a new DURABLE event
106
+ * name is a core change and this one is not worth one. An ABSENT file emits
107
+ * nothing at all; absent is the ordinary state of every machine.
108
+ */
109
+ export const SCOPE_UNREADABLE_EVENT = "adapter.scope.unreadable";
110
+
111
+ /** The ring event naming the verdict this process ran under. */
112
+ export const SCOPE_EVENT = "adapter.scope";
113
+
114
+ /**
115
+ * THE RING EVENT A BOUNDARY LEAVES WHEN IT JOINED THE MEMORY LATE — a session
116
+ * whose SessionStart ran OUTSIDE it (the directory was `off` or `paused` then,
117
+ * and has been turned back on since), so there is no session record and no span
118
+ * cursor, and the transcript it can see covers a stretch this memory was told
119
+ * not to have. That boundary seals the stretch — cursor forward, nothing
120
+ * deposited — and this is the record that it did. The DURABLE half rides the
121
+ * boundary row's own `joinedLate` field, for the reason `adapter.scope.unreadable`
122
+ * is ring-only: a new durable event NAME is a core change (`AdapterDurableEventName`).
123
+ */
124
+ export const SCOPE_JOINED_LATE_EVENT = "adapter.scope.joined-late";
125
+
126
+ /**
127
+ * The RING event naming the ENTRIES a read refused (#92 review, F2). Those
128
+ * directories read as unset, which is ON — so this is the record that a setting
129
+ * somebody wrote is not being kept. The durable half is the wake row's
130
+ * `scopeRegistry` field, for the same reason the unreadable one is ring-only.
131
+ */
132
+ export const SCOPE_REFUSED_EVENT = "adapter.scope.entries-refused";
133
+
134
+ /** Every mode a directory can be put in. */
135
+ export const SCOPE_MODES = ["on", "observer", "off", "paused"] as const;
136
+ export type ScopeMode = (typeof SCOPE_MODES)[number];
137
+
138
+ /** What `--resume` may restore to. A pause never resumes into `off`. */
139
+ export const RESUME_MODES = ["on", "observer"] as const;
140
+ export type ResumeMode = (typeof RESUME_MODES)[number];
141
+
142
+ /** A mode, or the absence of one. `unset` is not a mode; it is a question. */
143
+ export type EffectiveMode = ScopeMode | "unset";
144
+
145
+ /**
146
+ * THE STANCE a scope resolves to — the vocabulary the adapters act on.
147
+ * `paused` is `off` while it lasts; `unset` is `on` until somebody answers.
148
+ */
149
+ export type ScopeStance = "on" | "observer" | "off";
150
+
151
+ /** Most restrictive last: the combination rule is a max over this order. */
152
+ const STANCE_ORDER: readonly ScopeStance[] = ["on", "observer", "off"];
153
+
154
+ export interface ScopeEntry {
155
+ readonly mode: ScopeMode;
156
+ /** Where `--resume` goes. Only meaningful on a `paused` entry. */
157
+ readonly resumeTo?: ResumeMode;
158
+ /** ISO timestamp of the decision. Written by whoever set it. */
159
+ readonly since: string;
160
+ /** Free text, the owner's own. Never read by anything that decides. */
161
+ readonly note?: string;
162
+ }
163
+
164
+ export interface ScopeRegistry {
165
+ readonly version: number;
166
+ readonly scopes: Readonly<Record<string, ScopeEntry>>;
167
+ }
168
+
169
+ /** One entry the file held and this could not understand. Named, never guessed. */
170
+ export interface RefusedEntry {
171
+ /** The key exactly as the file spelled it. */
172
+ readonly key: string;
173
+ /** Why it was refused, in one clause. */
174
+ readonly detail: string;
175
+ }
176
+
177
+ /**
178
+ * What a read of the file found. It NEVER throws; `error` carries the why.
179
+ *
180
+ * `raw` is the bytes exactly as they were — it is what makes a write a
181
+ * compare-and-swap rather than a hope (`writeScopes`).
182
+ */
183
+ export interface ScopeRead {
184
+ /** The file's text as this read saw it; null when absent or unreadable. */
185
+ readonly raw: string | null;
186
+ /** Null when the file is absent, or present and unreadable. */
187
+ readonly registry: ScopeRegistry | null;
188
+ /** True when the file exists at all — absent and corrupt are different. */
189
+ readonly present: boolean;
190
+ /** One sentence, when a file that IS there could not be understood AS A FILE. */
191
+ readonly error: string | null;
192
+ /**
193
+ * The ENTRIES this read refused, by name. The file parsed and the other
194
+ * entries stand; these directories read as unset. Empty on a healthy file and
195
+ * on a file-level `error`, where there are no entries to speak of.
196
+ */
197
+ readonly refused: readonly RefusedEntry[];
198
+ }
199
+
200
+ /** Which entry decided, and what it said. */
201
+ export interface ScopeVerdict {
202
+ readonly mode: EffectiveMode;
203
+ /** The registry key that matched — the ancestor, when it is one. */
204
+ readonly matched: string | null;
205
+ readonly entry: ScopeEntry | null;
206
+ }
207
+
208
+ /** `<config dir>/scopes.json` — beside the file `config-path.ts` resolved. */
209
+ export function scopesPath(configPath: string): string {
210
+ return join(dirname(configPath), SCOPES_FILE_NAME);
211
+ }
212
+
213
+ /** An empty registry, for a machine that has never answered the question. */
214
+ export function emptyRegistry(): ScopeRegistry {
215
+ return { version: SCOPES_VERSION, scopes: {} };
216
+ }
217
+
218
+ function isMode(value: unknown): value is ScopeMode {
219
+ return typeof value === "string" && (SCOPE_MODES as readonly string[]).includes(value);
220
+ }
221
+
222
+ function isResumeMode(value: unknown): value is ResumeMode {
223
+ return typeof value === "string" && (RESUME_MODES as readonly string[]).includes(value);
224
+ }
225
+
226
+ /**
227
+ * Parse a registry, or say why not — PER ENTRY.
228
+ *
229
+ * **The rule changed on 2026-09-15 (#92 review, F2), and this is why.** A single
230
+ * malformed entry used to fail the WHOLE FILE: the reasoning was that an `off`
231
+ * somebody typed badly must not silently become an `on`. The review measured
232
+ * what that actually did — one typo'd mode in one entry turned EVERY correctly
233
+ * typed `off` in the file on, silently, because the hook's fail direction for an
234
+ * unreadable file is `unset` (⇒ on) and has to be, since a hook may not fail the
235
+ * host (§5 G2). Whole-file-fail did not protect the badly typed entry; it
236
+ * sacrificed all the good ones to it.
237
+ *
238
+ * So: what parses, parses. What does not is REFUSED BY NAME — that directory
239
+ * reads as unset and the name goes out on every surface that has somebody in
240
+ * front of it (the hook's one stderr line at SessionStart, the console, the MCP
241
+ * tool's refusal to write). A file that is not a registry AT ALL — not JSON, not
242
+ * an object, an unknown `version`, a `scopes` that is not an object — is still a
243
+ * whole-file failure, because there are no entries in it to honour.
244
+ */
245
+ export function parseRegistry(raw: unknown): {
246
+ registry: ScopeRegistry | null;
247
+ error: string | null;
248
+ refused: RefusedEntry[];
249
+ } {
250
+ const whole = (error: string): { registry: null; error: string; refused: RefusedEntry[] } => ({
251
+ registry: null,
252
+ error,
253
+ refused: [],
254
+ });
255
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
256
+ return whole("the file is not a JSON object");
257
+ }
258
+ const rec = raw as Record<string, unknown>;
259
+ if (rec["version"] !== SCOPES_VERSION) {
260
+ return whole(
261
+ `"version" is ${JSON.stringify(rec["version"])}, and this reads version ${String(SCOPES_VERSION)}`,
262
+ );
263
+ }
264
+ const scopesRaw = rec["scopes"];
265
+ if (scopesRaw === undefined) return { registry: emptyRegistry(), error: null, refused: [] };
266
+ if (scopesRaw === null || typeof scopesRaw !== "object" || Array.isArray(scopesRaw)) {
267
+ return whole('"scopes" is not an object');
268
+ }
269
+ const scopes: Record<string, ScopeEntry> = {};
270
+ const refused: RefusedEntry[] = [];
271
+ const refuse = (key: string, detail: string): void => {
272
+ refused.push({ key, detail });
273
+ };
274
+ for (const [path, value] of Object.entries(scopesRaw as Record<string, unknown>)) {
275
+ if (!path.startsWith("/")) {
276
+ refuse(path, "the key is not an absolute path");
277
+ continue;
278
+ }
279
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
280
+ refuse(path, "the entry is not an object");
281
+ continue;
282
+ }
283
+ const entry = value as Record<string, unknown>;
284
+ if (!isMode(entry["mode"])) {
285
+ refuse(
286
+ path,
287
+ `mode ${JSON.stringify(entry["mode"])}; it takes ${SCOPE_MODES.join(", ")}`,
288
+ );
289
+ continue;
290
+ }
291
+ const since = entry["since"];
292
+ if (typeof since !== "string" || since.length === 0) {
293
+ refuse(path, 'no "since"');
294
+ continue;
295
+ }
296
+ const resumeTo = entry["resumeTo"];
297
+ if (resumeTo !== undefined && !isResumeMode(resumeTo)) {
298
+ refuse(
299
+ path,
300
+ `resumeTo ${JSON.stringify(resumeTo)}; it takes ${RESUME_MODES.join(", ")}`,
301
+ );
302
+ continue;
303
+ }
304
+ const note = entry["note"];
305
+ if (note !== undefined && typeof note !== "string") {
306
+ refuse(path, 'a "note" that is not text');
307
+ continue;
308
+ }
309
+ scopes[path] = {
310
+ mode: entry["mode"],
311
+ since,
312
+ ...(resumeTo === undefined ? {} : { resumeTo }),
313
+ ...(note === undefined ? {} : { note }),
314
+ };
315
+ }
316
+ return { registry: { version: SCOPES_VERSION, scopes }, error: null, refused };
317
+ }
318
+
319
+ /**
320
+ * Read the registry at `path`. Absent is ordinary and silent; present and
321
+ * unreadable carries a sentence. Never throws.
322
+ */
323
+ export function readScopes(
324
+ path: string,
325
+ read: (p: string) => string = (p) => readFileSync(p, "utf8"),
326
+ ): ScopeRead {
327
+ let text: string;
328
+ try {
329
+ text = read(path);
330
+ } catch (err) {
331
+ const code =
332
+ err !== null && typeof err === "object" && typeof (err as { code?: unknown }).code === "string"
333
+ ? (err as { code: string }).code
334
+ : "UNREADABLE";
335
+ // ENOENT is the ordinary state of every machine that has never answered the
336
+ // question. Anything else — a permission bit, a directory where a file
337
+ // should be — is a file that IS there and could not be read.
338
+ if (code === "ENOENT") {
339
+ return { registry: null, present: false, error: null, refused: [], raw: null };
340
+ }
341
+ return {
342
+ registry: null,
343
+ present: true,
344
+ error: `it could not be read (${code})`,
345
+ refused: [],
346
+ raw: null,
347
+ };
348
+ }
349
+ let raw: unknown;
350
+ try {
351
+ raw = JSON.parse(text);
352
+ } catch (err) {
353
+ return {
354
+ registry: null,
355
+ present: true,
356
+ error: `it is not JSON (${err instanceof Error ? err.message : String(err)})`,
357
+ refused: [],
358
+ raw: text,
359
+ };
360
+ }
361
+ const parsed = parseRegistry(raw);
362
+ return {
363
+ registry: parsed.registry,
364
+ present: true,
365
+ error: parsed.error,
366
+ refused: parsed.refused,
367
+ raw: text,
368
+ };
369
+ }
370
+
371
+ /**
372
+ * THE ONE SENTENCE a registry in trouble gets, wherever there is somebody to
373
+ * read it — the hook's stderr at SessionStart, the console, the server's launch
374
+ * line. Null when the file is healthy or simply absent.
375
+ *
376
+ * It exists because `off` being silent (CONTRACT §5 G19) and a CORRUPT REGISTRY
377
+ * being silent are different exceptions, and only the first one was ever ruled.
378
+ * A directory the owner set `off` that quietly comes back ON because the file
379
+ * beside it grew a typo is the failure scar §2.4 is about: the absence of the
380
+ * stand-down and the absence of a working registry looked identical.
381
+ */
382
+ export function describeScopeTrouble(read: ScopeRead, path: string): string | null {
383
+ if (read.error !== null) {
384
+ return `[counterparts] scope registry ${path} could not be read — ${read.error}. Every directory reads as unset (on) until it is fixed.`;
385
+ }
386
+ if (read.refused.length === 0) return null;
387
+ const one = read.refused.length === 1;
388
+ const list = read.refused.map((r) => `${r.key} (${r.detail})`).join("; ");
389
+ return (
390
+ `[counterparts] scope registry ${path}: ${String(read.refused.length)} ${one ? "entry" : "entries"} ` +
391
+ `could not be read and ${one ? "is" : "are"} IGNORED — ${list}. ` +
392
+ `${one ? "That directory reads" : "Those directories read"} as unset (on); every other entry stands.`
393
+ );
394
+ }
395
+
396
+ /** How restrictive a mode is, on the same order the combination rule uses.
397
+ * `paused` and `off` are one rank: they differ in what `--resume` restores,
398
+ * not in what a session may do. */
399
+ function restrictionOf(mode: ScopeMode): number {
400
+ return rankOf(mode);
401
+ }
402
+
403
+ /** Is `dir` at or under `key`? Segment-aware: `/a/b` never matches `/a/bc`. */
404
+ function under(key: string, dir: string): boolean {
405
+ if (key === dir) return true;
406
+ const base = key.endsWith(sep) ? key : `${key}${sep}`;
407
+ return dir.startsWith(base);
408
+ }
409
+
410
+ /**
411
+ * Which entry governs `dir` — the LONGEST matching ancestor, or `unset`.
412
+ *
413
+ * Both sides go through `canonicalScopePath`, so a registry written from
414
+ * `/tmp/x` still governs a hook whose cwd arrives as `/private/tmp/x`, and a
415
+ * subdirectory that does not exist yet still inherits its ancestor. Specificity
416
+ * is measured on the canonical key, which is the only form the comparison saw.
417
+ */
418
+ export function lookupScope(registry: ScopeRegistry | null, dir: string): ScopeVerdict {
419
+ if (registry === null) return { mode: "unset", matched: null, entry: null };
420
+ const target = canonicalScopePath(dir);
421
+ let best: { key: string; canonical: string; entry: ScopeEntry } | null = null;
422
+ for (const [key, entry] of Object.entries(registry.scopes)) {
423
+ const canonical = canonicalScopePath(key);
424
+ if (!under(canonical, target)) continue;
425
+ if (best === null || canonical.length > best.canonical.length) {
426
+ best = { key, canonical, entry };
427
+ continue;
428
+ }
429
+ // THE TIE, AND WHY IT IS RESOLVED TOWARDS RESTRICTION (#92 review, F4).
430
+ // Equal length here means the same canonical string — both are prefixes of
431
+ // one target — so a tie is two KEYS for one directory, e.g. a hand-edited
432
+ // `/tmp/x` beside a written `/private/tmp/x`, or `…/proj` beside `…/proj/.`.
433
+ // `setScope` replaces every such key, so this only happens on a file a
434
+ // person edited; deciding it by iteration order meant an `off` and an `on`
435
+ // for one directory resolved by whichever JSON key happened to come first.
436
+ // The safe half of an ambiguity is the more restrictive one.
437
+ if (canonical !== best.canonical) continue;
438
+ if (restrictionOf(entry.mode) > restrictionOf(best.entry.mode)) best = { key, canonical, entry };
439
+ }
440
+ if (best === null) return { mode: "unset", matched: null, entry: null };
441
+ return { mode: best.entry.mode, matched: best.key, entry: best.entry };
442
+ }
443
+
444
+ /**
445
+ * The stance a mode resolves to. `unset` is ON — today's behaviour, and the
446
+ * choice this whole file asks the owner to confirm. `paused` is OFF while it
447
+ * lasts; the difference between them is what `--resume` restores, not what a
448
+ * session may do.
449
+ */
450
+ export function stanceOfMode(mode: EffectiveMode): ScopeStance {
451
+ switch (mode) {
452
+ case "observer":
453
+ return "observer";
454
+ case "off":
455
+ case "paused":
456
+ return "off";
457
+ default:
458
+ return "on";
459
+ }
460
+ }
461
+
462
+ /**
463
+ * THE SECOND COMBINATION RULE: the most restrictive of TWO VERDICTS, when one
464
+ * event has two directories to answer for.
465
+ *
466
+ * A session has a stable scope — the directory it started in, which is where
467
+ * everything it captures is filed (`claude-code/bin/hook.ts#sessionScope`) — and
468
+ * an event has a current one, which follows the agent's shell into a worktree or
469
+ * anywhere else it is told to go. Filing follows the first. PRIVACY MUST FOLLOW
470
+ * BOTH: a session that starts in a directory the owner said yes to and then
471
+ * walks into one he said `off` to has to go as quiet as the directory it walked
472
+ * into, or the stable scope would become a way to carry capture past an opt-out.
473
+ *
474
+ * So the two are looked up separately and the safe half wins, on the same order
475
+ * `effectiveStance` uses. `primary` is the SESSION's verdict and wins every tie,
476
+ * because a tie is two directories of equal stance and the session's own is the
477
+ * one whose entry should be named in the record — and the one the first-launch
478
+ * question (`unset`) is about.
479
+ */
480
+ export function mostRestrictiveVerdict(primary: ScopeVerdict, other: ScopeVerdict): ScopeVerdict {
481
+ return rankOf(other.mode) > rankOf(primary.mode) ? other : primary;
482
+ }
483
+
484
+ /** How restrictive an effective mode is, on the one order every rule here uses. */
485
+ function rankOf(mode: EffectiveMode): number {
486
+ return STANCE_ORDER.indexOf(stanceOfMode(mode));
487
+ }
488
+
489
+ /**
490
+ * THE COMBINATION RULE: the MOST RESTRICTIVE of the stance the configuration
491
+ * and the environment already produced, and the one the registry names.
492
+ *
493
+ * It only ever adds restriction. The three private directories running under
494
+ * `COUNTERPARTS_CONFIG` + `COUNTERPARTS_OBSERVER` today have no registry entry
495
+ * at all, so they combine `observer` with `unset` and stay exactly observer —
496
+ * which is the one property this feature was not allowed to break.
497
+ */
498
+ export function effectiveStance(configObserver: boolean, mode: EffectiveMode): ScopeStance {
499
+ const fromConfig: ScopeStance = configObserver ? "observer" : "on";
500
+ const fromScope = stanceOfMode(mode);
501
+ return STANCE_ORDER.indexOf(fromConfig) >= STANCE_ORDER.indexOf(fromScope)
502
+ ? fromConfig
503
+ : fromScope;
504
+ }
505
+
506
+ /**
507
+ * THIS directory's OWN entry — never an ancestor's, and found by canonical
508
+ * path rather than by string key, so a hand-edited `/tmp/x` is the same entry
509
+ * as a written `/private/tmp/x`.
510
+ *
511
+ * It is separate from `lookupScope` because the two answer different questions:
512
+ * "what governs here" inherits, and "what did somebody set HERE" must not —
513
+ * `--resume` on a directory that merely inherits an ancestor's pause would
514
+ * quietly create a new entry and leave the ancestor paused.
515
+ */
516
+ export function ownEntry(registry: ScopeRegistry | null, dir: string): ScopeEntry | null {
517
+ if (registry === null) return null;
518
+ const key = canonicalScopePath(dir);
519
+ for (const [existing, entry] of Object.entries(registry.scopes)) {
520
+ if (canonicalScopePath(existing) === key) return entry;
521
+ }
522
+ return null;
523
+ }
524
+
525
+ /** Where `--resume` puts this entry. A pause with no memory resumes to `on`. */
526
+ export function resumeTarget(entry: ScopeEntry | null): ResumeMode {
527
+ return entry?.resumeTo ?? "on";
528
+ }
529
+
530
+ /**
531
+ * Set one directory's entry. PURE — it returns the registry to write, so the
532
+ * caller decides when a file changes and nothing here can half-write one.
533
+ *
534
+ * `--pause` remembers what it interrupted (`resumeTo`), which is the whole
535
+ * difference between pausing and turning off: an afternoon that is not recorded
536
+ * does not change what the directory thinks it is.
537
+ */
538
+ export function setScope(
539
+ registry: ScopeRegistry | null,
540
+ dir: string,
541
+ mode: ScopeMode,
542
+ opts: { at: string; note?: string; resumeTo?: ResumeMode },
543
+ ): ScopeRegistry {
544
+ const base = registry ?? emptyRegistry();
545
+ const key = canonicalScopePath(dir);
546
+ const prior = ownEntry(base, dir) ?? undefined;
547
+ const resumeTo =
548
+ opts.resumeTo ??
549
+ (mode === "paused"
550
+ ? prior !== undefined && (prior.mode === "on" || prior.mode === "observer")
551
+ ? prior.mode
552
+ : resumeTarget(prior ?? null)
553
+ : undefined);
554
+ const entry: ScopeEntry = {
555
+ mode,
556
+ since: opts.at,
557
+ ...(resumeTo === undefined ? {} : { resumeTo }),
558
+ // A note is REPLACED when one is given and CARRIED when one is not: the
559
+ // reason a directory is off outlives the flag that paused it.
560
+ ...(opts.note !== undefined
561
+ ? opts.note.length === 0
562
+ ? {}
563
+ : { note: opts.note }
564
+ : prior?.note === undefined
565
+ ? {}
566
+ : { note: prior.note }),
567
+ };
568
+ // EVERY key that names this directory is replaced, not just the canonical
569
+ // spelling. A registry may have been hand-edited with `/tmp/x` where this
570
+ // writes `/private/tmp/x`; leaving the old one behind would put two entries
571
+ // for one directory in the file, and `lookupScope` would go on honouring
572
+ // whichever of them happened to sort first — a setting that appears to change
573
+ // and does not.
574
+ const scopes: Record<string, ScopeEntry> = {};
575
+ for (const [existing, value] of Object.entries(base.scopes)) {
576
+ if (canonicalScopePath(existing) === key) continue;
577
+ scopes[existing] = value;
578
+ }
579
+ scopes[key] = entry;
580
+ return { version: SCOPES_VERSION, scopes };
581
+ }
582
+
583
+ /**
584
+ * Write the registry: temp file beside the target, then `rename` — the same
585
+ * shape `sessions.ts` uses, and for the same reason (a reader never sees half a
586
+ * file, and same directory means same filesystem means the rename is a rename).
587
+ *
588
+ * It is a COMPARE-AND-SWAP when the caller hands it the read it worked from:
589
+ * the file is re-read immediately before the rename, and a file that changed
590
+ * since sends the caller's change through `reapply` against the new content
591
+ * rather than overwriting it. Two writers exist — the console `scope` command
592
+ * and the MCP `scope` tool — and before this the second one to rename simply
593
+ * deleted the first one's entry (#92 review, F3).
594
+ *
595
+ * This one MAY throw: its only caller is a console command with an owner
596
+ * watching, and a write that failed silently is the failure this whole package
597
+ * keeps recording.
598
+ */
599
+ export function writeScopes(
600
+ path: string,
601
+ registry: ScopeRegistry,
602
+ /**
603
+ * THE COMPARE-AND-SWAP, when the caller can supply one (#92 review, F3).
604
+ *
605
+ * `basedOn` is the read this registry was computed from; `reapply` says how to
606
+ * compute it again against whatever is there now. Omit them and this is the
607
+ * plain overwrite it always was — which is right for `--force`, whose whole
608
+ * job is to replace a file nobody could read, and wrong for everything else:
609
+ * a caller that READ this file before computing `registry` owes the CAS, or it
610
+ * is the lost update again under a new name.
611
+ */
612
+ cas?: {
613
+ readonly basedOn: ScopeRead;
614
+ readonly reapply: (fresh: ScopeRegistry | null) => ScopeRegistry;
615
+ },
616
+ ): void {
617
+ mkdirSync(dirname(path), { recursive: true });
618
+ const write = (next: ScopeRegistry, expect: string | null | undefined): boolean => {
619
+ const tmp = `${path}.${String(process.pid)}.tmp`;
620
+ writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
621
+ // THE CHECK, as late as it can be: immediately before the rename, so the
622
+ // window a change can hide in is the syscall itself rather than everything
623
+ // the caller did between its read and this call.
624
+ if (expect !== undefined && rawScopes(path) !== expect) {
625
+ try {
626
+ unlinkSync(tmp);
627
+ } catch {
628
+ /* a temp file that is already gone is the outcome we wanted */
629
+ }
630
+ return false;
631
+ }
632
+ renameSync(tmp, path);
633
+ return true;
634
+ };
635
+ if (cas === undefined) {
636
+ write(registry, undefined);
637
+ return;
638
+ }
639
+ if (write(registry, cas.basedOn.raw)) return;
640
+ // Somebody wrote between the caller's read and now. Their entry is IN the file
641
+ // and this registry does not have it — writing it would delete their change,
642
+ // which is exactly the lost update the review measured (two `scope` writers,
643
+ // one absent file, one surviving entry). So the caller's change is re-applied
644
+ // to what is actually there, and written once more. Once: a second loser is a
645
+ // third writer, and a console command that spun would be worse than a console
646
+ // command that reports.
647
+ write(cas.reapply(readScopes(path).registry), undefined);
648
+ }
649
+
650
+ /** The file's bytes exactly as they are, or null — the CAS comparand. */
651
+ function rawScopes(path: string): string | null {
652
+ try {
653
+ return readFileSync(path, "utf8");
654
+ } catch {
655
+ return null;
656
+ }
657
+ }