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,205 @@
1
+ # `adapters/mcp/` — NOTES
2
+
3
+ *Decisions taken while building, and the ones deliberately left open. Working
4
+ defaults, revisable without ceremony (constitution 13).*
5
+
6
+ ## Built
7
+
8
+ `protocol.ts` (JSON-RPC 2.0 framing) · `tools.ts` (the registry that makes a
9
+ description auditable) · `deliberate.ts` (the deeper look) · `server.ts` (message
10
+ dispatch and the four tools) · `stdio.ts` (the pump) · `bin/serve.ts` (entry).
11
+ No SDK, no dependency: the wire is ~160 lines because newline-delimited JSON-RPC
12
+ is a small thing to write and a large thing to depend on.
13
+
14
+ ## Four tools, and why not three
15
+
16
+ The contract says three verbs. `session_end` is the fourth because
17
+ `claude-code/INTERFACE-GAPS.md` §7 filed a live gap: the boundary raises an
18
+ Stop ask into the model's context, and a hook cannot receive the answer.
19
+ In this host, the return channel is a tool. Without it, `Counterpart.submitSessionEnd`
20
+ — the primary path by which memory is supposed to form — is reachable only by a
21
+ caller holding the object, and the crash fallback silently carries the whole
22
+ load.
23
+
24
+ It is deliberately NOT a general "write a memory" tool: it is bound to one
25
+ session at launch, and it refuses when unbound. That refusal is what keeps it
26
+ from becoming the second front door CONTRACT §7 OQ1 warns about.
27
+
28
+ ## Open, and left open
29
+
30
+ 1. **OQ1 — does `note` still need to exist?** Both `note` and `session_end` now
31
+ ship, which is two doors to one room. The answer will come from telemetry:
32
+ `mcp.note` versus `mcp.session_end` counts over real use. If the dump carries
33
+ everything, `note` is the one to drop.
34
+ 2. **OQ3 — tier name or number?** Shipped as NAMES (`vivid`/`quiet`/`dim`), with
35
+ the meaning of each spelled out in the payload. A number would imply a
36
+ calibration nobody has done (scar §2.8).
37
+ 3. **Confidentiality has no writer** — see INTERFACE-GAPS §2. Owner call.
38
+ 4. **Protocol versions** are a hardcoded list. When the MCP spec moves, adding a
39
+ string to `PROTOCOL_VERSIONS` is the whole change; unknown versions already
40
+ negotiate down rather than failing.
41
+
42
+ ## Not built, on purpose
43
+
44
+ - **No self-authorship tool** (§4 — superseded by experiencer authorship).
45
+ - **No `protected.add`** (§4, and the module-map Rulings list it under settled
46
+ drops).
47
+ - **No tool that writes an entity, a belief, or a revision.** Entities are born
48
+ by mention; revision is `updates:` plus arithmetic. `session_end` accepts an
49
+ `updates` field on an entry, which is the experiencer DECLARING a revision, not
50
+ a tool performing one — the arithmetic still happens in `physics/`.
51
+ - **No `tools/list` change notifications, no resources, no prompts.** The
52
+ capability block advertises `tools` only.
53
+
54
+ ## Host wiring the owner still has to do
55
+
56
+ `package.json` has no `bin` entry for the server (this build was scoped to
57
+ `src/adapters/mcp/`, `src/adapters/cli/` and their two test files). A host
58
+ registers it as:
59
+
60
+ ```
61
+ bun run <repo>/src/adapters/mcp/bin/serve.ts --session <id> --scope <project dir>
62
+ ```
63
+
64
+ Neither flag is reachable on Claude Code, which registers MCP servers from a static
65
+ configuration. Without `--scope` the server resolves `CLAUDE_PROJECT_DIR` and then its
66
+ own working directory (`server.ts#hostScope`) — the first of those is the one the hooks
67
+ also file a session under, which is what makes a deposit's coverage land on the spans it
68
+ covers rather than in another directory.
69
+
70
+ `--owner` marks the owner's own session (confidential material is returned only
71
+ there); `--observer` stands every tool down over the wire.
72
+
73
+ ## Verified live? No — and the suite says so
74
+
75
+ Every test here runs against a temp store with a faked stdin. Nothing has spoken
76
+ to a real MCP client. Per CLAUDE.md's definition of done, that makes this
77
+ **merged, not verified**: the outstanding proof is one real host completing a
78
+ handshake, listing the tools, and calling `session_end` at a real boundary.
79
+
80
+ ## The configuration is named the same way everywhere now (2026-09-05)
81
+
82
+ `bin/serve.ts` read `~/.counterparts/claude-code.json` and nothing else, which is
83
+ how the cold-stranger critic of 2026-09-04 came to embed on the owner's key: the
84
+ store was redirected with `COUNTERPARTS_DATA_DIR` and the credentials were not,
85
+ because there was no way to redirect them.
86
+
87
+ The rule is `adapters/config-path.ts`, shared with the hook, the worker and the
88
+ console: `--config <absolute path>`, else `COUNTERPARTS_CONFIG`, else the same
89
+ default as before. **The environment variable exists FOR THIS ENTRY POINT.** This
90
+ host registers an MCP server from a static configuration — command, args, env —
91
+ so there is no command line for an operator to add a flag to; `-e
92
+ COUNTERPARTS_CONFIG=…` in the `claude mcp add` line is the only channel, and
93
+ `counterparts install --config` prints exactly that line.
94
+
95
+ Two properties, both deliberate:
96
+
97
+ - **The store is still not decided here.** `--dir` / `COUNTERPARTS_DATA_DIR` /
98
+ the default choose the store; the configuration answers "whose keys, whose
99
+ embedder knob". Reading `config.dataDir` here would quietly fix half of
100
+ QUICKSTART §11.3 and leave the docs claiming the other half.
101
+ - **A named configuration that cannot be honoured refuses the launch** — exit 1,
102
+ the reason on stderr — rather than falling back to a default that, on a machine
103
+ with an install, is somebody else's keys. "Cannot be honoured" includes an
104
+ absolute path to a file that is not there, which the first version honoured
105
+ silently (`claude-code/NOTES.md` §11). The server also writes the file it
106
+ read to stderr at every launch, before a byte of protocol: stdout is the wire.
107
+
108
+ ## 2026-09-10 — `COUNTERPARTS_OBSERVER` and `COUNTERPARTS_OWNER` learn the guard's vocabulary
109
+
110
+ **The defect (LAUNCH-STATUS G39).** `launchOptions` matched both stance variables
111
+ by exact, untrimmed string — `"1"` or `"true"` — through a single `flag()`
112
+ closure. One directory over, `COUNTERPARTS_REQUIRE_EXPLICIT_DIR` accepts
113
+ `1|true|on`, trimmed and case-insensitive, and `store/paths.ts` describes itself
114
+ in a comment as *"a SUPERSET of the two `COUNTERPARTS_OBSERVER` accepts"*. That
115
+ sentence is an invitation to reason by analogy, and a person who did — exporting
116
+ `COUNTERPARTS_OBSERVER=on`, or `=True`, or with a stray space — got an **ordinary**
117
+ server: the stance they were trying to leave. The console had the identical bug
118
+ in `cli/commands.ts`.
119
+
120
+ **Why it was deferred, and why it is not any more.** #80 widened the guard and
121
+ promised to leave this launch path instruction-for-instruction identical, so
122
+ `store/NOTES.md` recorded the mismatch and said widening observer *"is a
123
+ behaviour change to an unrelated variable and wants its own ruling"*. G39 is that
124
+ ruling (HANDOFF 2026-09-08, follow-up 4).
125
+
126
+ **The shape.** `adapters/stance-env.ts` — beside `config-path.ts`, at the level
127
+ both the console and this entry point already share — imports
128
+ `EXPLICIT_DIR_ARMING_VALUES` and `EXPLICIT_DIR_DISARMING_VALUES` rather than
129
+ retyping them. Two lists that must agree and are written twice have already begun
130
+ to disagree; that is what this whole entry is about.
131
+
132
+ **The two fail directions are opposite, and both are "less power."** Observer
133
+ collapses an unreadable value to **observer** — `docs/observer-mode.md` G5, "fail
134
+ toward standing down", already mechanized in `core/observer.ts`, where a
135
+ non-boolean stance field resolves to observer rather than to "encode anyway".
136
+ Owner collapses it to **not owner**. Same helper, one line apart, because the
137
+ polarity of the boolean is opposite: `owner` grants reach and `observer`
138
+ withholds it, so least privilege is `false` for one and `true` for the other.
139
+
140
+ Note that observer's junk handling is deliberately **not** the guard's. The
141
+ explicit-dir guard REFUSES junk, because refusing is fail-closed for a thing
142
+ whose job is to stop a run. A stance's job is to withhold writes, so standing
143
+ down is fail-closed for it — and the failure is far cheaper: a refused MCP server
144
+ answers nothing and the host reports only "MCP server failed", while a stood-down
145
+ one answers every read. Junk is never silent either way: `launchOptions` returns
146
+ `unreadable`, a list of ready-made lines, and `main` prints them on stderr before
147
+ anything else (stdout is the wire). Keeping the printing outside `launchOptions`
148
+ is what keeps that function the one thing here a test can call over a fresh
149
+ object with no process involved.
150
+
151
+ **Still owed, in core, for the owner:** three comments now describe the world
152
+ before this ruling and call the guard's word lists a superset —
153
+ `store/paths.ts` above `EXPLICIT_DIR_ARMING_VALUES`, `store/NOTES.md`
154
+ 2026-09-05, and `store/CONTRACT.md` §5. They are text, not behaviour.
155
+
156
+ ## 2026-09-20 — `mcp.recall`, the first durable row this adapter has ever written
157
+
158
+ `docs/recall-surfacing-diagnosis-2026-09-18.md` put it plainly: the whole tool surface
159
+ wrote no durable row. `deliberate.ts` ran every time a session went looking for something
160
+ on purpose and left nothing but an in-process ring, so "the session asked and nothing came
161
+ back" and "the session never asked" were the same silence, and `fired` could only mark the
162
+ mechanism blind.
163
+
164
+ One row per `recall` call, through `Counterpart.noteAdapterEvent` like every other adapter
165
+ fact, so an observer stands down at the core's own seam rather than by a check here.
166
+
167
+ **What it carries, and what it deliberately does not.** Counts, verdicts, sizes. Never the
168
+ question — `queryChars` is its LENGTH, because a deliberate question is the one string on
169
+ this path that could carry somebody's private words and a row read months later may not
170
+ hold it (scar §2.20). And no memory ids: the counts answer this row's question, and a
171
+ durable pairing of ids with the moment somebody asked for them is a link the store has no
172
+ need of. `recall.credit` carries ids because crediting is *about* those ids; this is not.
173
+
174
+ **`blockedBy` carries `confidential-withheld`. THREE audiences, not two.** An adversarial
175
+ review corrected the first version of this note, which said "the durable row" versus "the
176
+ wire" and missed the third.
177
+
178
+ 1. **The wire** — whoever called the tool, who may be any session. Silent, unchanged:
179
+ §9.1 G5's rule is that a list announcing its gaps leaks their existence, and
180
+ `answerQuestion` still `continue`s past the verdict before building `memories`.
181
+ 2. **The durable row** — the owner, reading their own store, where the memory itself is
182
+ already sitting. It carries the count, keyed by verdict name and nothing else. Without
183
+ it the confidentiality gate stays exactly as unreadable as the 2026-09-17 inventory
184
+ found it: "a withholding that happened and one that never had to are the same absence."
185
+ 3. **A SCREEN** — the dashboard's narration and the `fired` view. Silent, and this was the
186
+ correction: the first version printed "1 more was kept out (confidential-withheld)" in
187
+ plain English on a page. No id, no title, no body — but a page gets screenshotted,
188
+ screen-shared and demoed, and that sentence is the gap announced. `narrate.ts`'s
189
+ `UNNAMEABLE_VERDICTS` folds it into an unnamed total ("kept out by a gate"), and
190
+ `fired.ts`'s reader for this row counts only `dim-cap:*`.
191
+
192
+ The rule that came out of it, worth keeping: **the row records it; no renderer names it.**
193
+
194
+ **The row is inside `operational.sqlite`**, so it travels in any `backup` or snapshot like
195
+ every other event row. No `export` surface serialises the event log.
196
+
197
+ **No `dedupKey`.** A tool call is a deliberate act by a session, bounded by the host's own
198
+ tool budget — not a boundary that repeats on a timer. The spawn seam's rows are latched
199
+ because they fire at every boundary; this one is not.
200
+
201
+ One test narrowed with it, and it was hiding something: "recall writes nothing"
202
+ fingerprinted `operational.sqlite`, which has been in WAL mode since F1 — the file is
203
+ unchanged whatever is written to it until a checkpoint, so that assertion proved nothing
204
+ either way. It now asserts what §9.1 G4 actually guarantees: no memory, no version, no
205
+ use, no `recall.decision` row.
@@ -0,0 +1,349 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * The MCP entry point. Speaks JSON-RPC over stdio and nothing else.
4
+ *
5
+ * Run by a host as, e.g.:
6
+ *
7
+ * bun run <repo>/src/adapters/mcp/bin/serve.ts --session <id> --scope <dir>
8
+ *
9
+ * Everything host-specific arrives as an ARGUMENT or a named environment
10
+ * variable, and the session id is one of them when the host can supply it: this
11
+ * server deposits under exactly one session (`server.ts`, refusal 1), and being
12
+ * TOLD which one at launch is still the preferred path.
13
+ *
14
+ * **Measured 2026-09-04:** Claude Code cannot use that path. Its MCP servers are
15
+ * registered from a static configuration — command, args, env — with no per-
16
+ * session substitution, so neither `--session` nor `COUNTERPARTS_SESSION` ever
17
+ * arrives, and for the whole first run every dump was refused `no-bound-session`.
18
+ * The flags below are unchanged and still win; a launch without them now falls
19
+ * through to `server.ts`'s lazy bind against `adapters/sessions.ts`'s registry.
20
+ *
21
+ * `--dir` is here for the same reason `hook.ts` pins the data dir onto its
22
+ * child: the registry is found under the data dir, so the two sides have to
23
+ * resolve the SAME one. Absent, both fall back to `dataDir()` and agree anyway.
24
+ *
25
+ * Nothing in this file is a memory rule; all of it is host trivia (§5 G8).
26
+ */
27
+ import { readFileSync } from "node:fs";
28
+ import { resolve } from "node:path";
29
+ import { fileURLToPath } from "node:url";
30
+ import { parseArgs } from "node:util";
31
+
32
+ import {
33
+ configLine,
34
+ defaultConfigPath,
35
+ implicitConfigRefusal,
36
+ namedConfigRefusal,
37
+ namedUnreadableRefusal,
38
+ resolveConfigPath,
39
+ } from "../../config-path.js";
40
+ import type { ConfigChoice } from "../../config-path.js";
41
+ import {
42
+ describeScopeTrouble,
43
+ effectiveStance,
44
+ lookupScope,
45
+ readScopes,
46
+ scopesPath,
47
+ } from "../../scopes.js";
48
+ import { loadConfig } from "../../claude-code/config.js";
49
+ import { loadCredentials, permissionWarning } from "../../claude-code/credentials.js";
50
+ import type { CredentialLoad } from "../../claude-code/credentials.js";
51
+ import { openEmbedder } from "../../claude-code/embed-client.js";
52
+ import type { LiveEmbedder } from "../../claude-code/embed-client.js";
53
+ import { hostScope, openServer } from "../index.js";
54
+ import { serveStdio } from "../stdio.js";
55
+ import { DATA_DIR_ENV, describeGuardRefusal } from "../../../core/store/index.js";
56
+ import {
57
+ OBSERVER_ENV,
58
+ OWNER_ENV,
59
+ observerFromEnv,
60
+ ownerFromEnv,
61
+ unreadableStanceLine,
62
+ } from "../../stance-env.js";
63
+
64
+ /**
65
+ * The same file `bin/hook.ts` and `bin/runner.ts` read by default. One
66
+ * configuration for this host, four entry points — never four ideas of where the
67
+ * keys live, and since 2026-09-05 never four ideas of how to move it either:
68
+ * `--config <absolute path>`, else `COUNTERPARTS_CONFIG`, else this
69
+ * (`adapters/config-path.ts`).
70
+ *
71
+ * The environment variable matters MORE here than anywhere else. This host
72
+ * registers an MCP server from a static configuration — command, args, env — so
73
+ * `-e COUNTERPARTS_CONFIG=…` in the `claude mcp add` line is the only way a
74
+ * server launched by it can be pointed at anything but the default. That is why
75
+ * the variable exists at all.
76
+ */
77
+ export const CONFIG_PATH = defaultConfigPath();
78
+
79
+ export const ENV = {
80
+ session: "COUNTERPARTS_SESSION",
81
+ scope: "COUNTERPARTS_SCOPE",
82
+ dir: "COUNTERPARTS_DATA_DIR",
83
+ // The two stance names come from `adapters/stance-env.ts`, not from a second
84
+ // pair of string literals here. That module's whole argument is that two
85
+ // strings which must agree and are written twice have already begun to
86
+ // disagree — it would be a poor place to start a third copy (G39).
87
+ owner: OWNER_ENV,
88
+ observer: OBSERVER_ENV,
89
+ } as const;
90
+
91
+ export interface LaunchOptions {
92
+ session?: string;
93
+ scope?: string;
94
+ dir?: string;
95
+ owner: boolean;
96
+ observer: boolean;
97
+ /**
98
+ * One line per stance variable this launch could not read, ready for stderr.
99
+ * ALWAYS present, usually empty — a caller destructures it off before the
100
+ * rest goes to `openServer`, so the stance stays a pair of booleans and the
101
+ * complaint stays a string. Keeping it here rather than printing from inside
102
+ * `launchOptions` is what keeps that function pure: it is the one thing in
103
+ * this file a test can call over a fresh object with no process involved.
104
+ */
105
+ unreadable: readonly string[];
106
+ }
107
+
108
+ /** Flags beat environment; absent means absent, never a guessed default. */
109
+ export function launchOptions(
110
+ argv: readonly string[],
111
+ env: Record<string, string | undefined>,
112
+ ): LaunchOptions {
113
+ const { values } = parseArgs({
114
+ args: [...argv],
115
+ options: {
116
+ session: { type: "string" },
117
+ scope: { type: "string" },
118
+ dir: { type: "string" },
119
+ owner: { type: "boolean" },
120
+ observer: { type: "boolean" },
121
+ // Declared so `strict: false` does not read `--config <path>` as a boolean
122
+ // and leave the path as a stray positional. The VALUE is resolved by
123
+ // `serverConfigChoice` below, which is the one rule all four entry points
124
+ // share; this declaration only keeps the parse honest.
125
+ config: { type: "string" },
126
+ },
127
+ strict: false,
128
+ });
129
+ // THE TWO STANCE VARIABLES ARE READ THE WAY THE GUARD NEXT DOOR IS READ
130
+ // (G39). This used to be one `flag()` closure matching `"1"` and `"true"`
131
+ // exactly, so `=on`, `=True` and `= 1 ` — the set
132
+ // `COUNTERPARTS_REQUIRE_EXPLICIT_DIR` documents — all fell silently to
133
+ // "ordinary session". `adapters/stance-env.ts` carries the shared reading and
134
+ // the argument for each fail direction: observer collapses junk to OBSERVER
135
+ // (`docs/observer-mode.md` G5, fail toward standing down), owner collapses it
136
+ // to NOT owner. Same helper, opposite boolean, because least privilege is the
137
+ // opposite boolean for a bit that grants reach and a bit that withholds it.
138
+ const observer = observerFromEnv(env, values["observer"] === true, ENV.observer);
139
+ const owner = ownerFromEnv(env, values["owner"] === true, ENV.owner);
140
+ const unreadable: string[] = [];
141
+ if (observer.malformed !== null) {
142
+ unreadable.push(
143
+ unreadableStanceLine(ENV.observer, observer.malformed, "standing down to observer stance"),
144
+ );
145
+ }
146
+ if (owner.malformed !== null) {
147
+ unreadable.push(
148
+ unreadableStanceLine(ENV.owner, owner.malformed, "this launch is NOT owner-stanced"),
149
+ );
150
+ }
151
+ const session = (values["session"] as string | undefined) ?? env[ENV.session];
152
+ const scope = (values["scope"] as string | undefined) ?? env[ENV.scope];
153
+ const dir = (values["dir"] as string | undefined) ?? env[ENV.dir];
154
+ return {
155
+ ...(session === undefined || session.length === 0 ? {} : { session }),
156
+ ...(scope === undefined || scope.length === 0 ? {} : { scope }),
157
+ ...(dir === undefined || dir.length === 0 ? {} : { dir }),
158
+ owner: owner.on,
159
+ observer: observer.on,
160
+ unreadable,
161
+ };
162
+ }
163
+
164
+ /**
165
+ * The embedder this server may use, and the credential load that made it
166
+ * possible — read HERE, at the process entry point, for the same reason
167
+ * `bin/hook.ts` reads it there: the host hands MCP servers a process
168
+ * environment that carries neither key (measured, day 0 of the parallel run),
169
+ * so a server that only consults `process.env` embeds nothing, ever.
170
+ *
171
+ * It is the ONE thing this entry point adds to the server's powers, and it is
172
+ * used for exactly one call: embedding a deliberate question. `env` is injected
173
+ * so a test proves the whole path over a fresh object rather than the suite's
174
+ * own process, and no value is ever returned, logged or emitted — only names.
175
+ */
176
+ export function questionEmbedder(
177
+ path = CONFIG_PATH,
178
+ env: NodeJS.ProcessEnv = process.env,
179
+ ): {
180
+ embedder: LiveEmbedder | null;
181
+ credentials: CredentialLoad;
182
+ credentialsFile?: string;
183
+ reason: string;
184
+ } {
185
+ let raw: unknown;
186
+ try {
187
+ raw = JSON.parse(readFileSync(path, "utf8"));
188
+ } catch {
189
+ // Absent is ordinary; unreadable resolves to OBSERVER inside `loadConfig`,
190
+ // and an observer opens no socket at all.
191
+ raw = undefined;
192
+ }
193
+ const load = loadConfig(raw);
194
+ const config = load.config;
195
+ const credentials = loadCredentials(config.credentialsFile, env);
196
+ return {
197
+ reason: load.reason,
198
+ // `openEmbedder` is the ONE answer to "is there an embedder": the knob is
199
+ // the gate, an observer gets none, and a missing key refuses by name on the
200
+ // first call rather than being re-checked here.
201
+ embedder: openEmbedder(config),
202
+ credentials,
203
+ ...(config.credentialsFile === undefined ? {} : { credentialsFile: config.credentialsFile }),
204
+ };
205
+ }
206
+
207
+ /**
208
+ * Which configuration this server will read, and which rule chose it. Exported
209
+ * and injectable for the same reason `launchOptions` is: the rule is provable
210
+ * without a process on stdin.
211
+ *
212
+ * **The store is NOT decided here.** It still comes from `--dir`, else
213
+ * `COUNTERPARTS_DATA_DIR`, else the default — this file answers "whose keys and
214
+ * whose embedder knob", which is the other half of the trap QUICKSTART §11.3
215
+ * names, not the same half.
216
+ */
217
+ export function serverConfigChoice(
218
+ argv: readonly string[] = process.argv.slice(2),
219
+ env: NodeJS.ProcessEnv = process.env,
220
+ ): ConfigChoice {
221
+ return resolveConfigPath(argv, env as Record<string, string | undefined>);
222
+ }
223
+
224
+ async function main(): Promise<void> {
225
+ const { unreadable: stanceNotices, ...opts } = launchOptions(process.argv.slice(2), process.env);
226
+ // stderr, never stdout (stdout is the JSON-RPC wire), and BEFORE the config
227
+ // refusals: a stance variable nobody could read changed what this server may
228
+ // do, and the transcript has to say so even on a launch that then refuses for
229
+ // an unrelated reason (scar §2.4 — a path that discards something says what).
230
+ for (const line of stanceNotices) process.stderr.write(`${line}\n`);
231
+ const choice = serverConfigChoice();
232
+ // The second refusal is the explicit-dir guard (`config-path.ts#implicitConfigRefusal`):
233
+ // armed, an UNNAMED configuration refuses the launch too — the default one is
234
+ // somebody's keys and names somebody's store. Never armed on the live host.
235
+ const refusal = namedConfigRefusal(choice) ?? implicitConfigRefusal(choice);
236
+ if (refusal !== null) {
237
+ // A server told to read a configuration it cannot resolve — relative, or
238
+ // absolute and not there — does not fall back to the default one: on a
239
+ // machine with an install, that default is somebody else's keys. It refuses
240
+ // to start, loudly, on stderr.
241
+ process.stderr.write(`${refusal}\n`);
242
+ process.exitCode = 1;
243
+ return;
244
+ }
245
+ const { embedder, credentials, credentialsFile, reason } = questionEmbedder(choice.path);
246
+ const unreadable = namedUnreadableRefusal(choice, reason);
247
+ if (unreadable !== null) {
248
+ process.stderr.write(`${unreadable}\n`);
249
+ process.exitCode = 1;
250
+ return;
251
+ }
252
+ // stderr, never stdout — stdout is the JSON-RPC wire. This is this entry
253
+ // point's "which file answered": printed at every launch, before a byte of
254
+ // protocol, because a server reading a configuration nobody named is exactly
255
+ // how a scratch run came to embed on the owner's key (2026-09-04).
256
+ process.stderr.write(`[counterparts] config: ${configLine(choice)}\n`);
257
+ const warning = permissionWarning(credentialsFile, credentials);
258
+ // stderr, never stdout: stdout is the JSON-RPC wire. Warned, never refused.
259
+ if (warning !== null) process.stderr.write(`${warning}\n`);
260
+ // WHICH DIRECTORY, AND WHAT THE HOST WAS TOLD ABOUT IT. The registry sits
261
+ // beside the configuration this launch resolved, so `-e COUNTERPARTS_CONFIG=…`
262
+ // moves both together and a scratch install's scopes are its own.
263
+ //
264
+ // The server still STARTS in a directory set `off`: a server that refused to
265
+ // launch is reported by this host as "MCP server failed", which is a broken
266
+ // tool rather than a directory that asked to be left alone — and the `scope`
267
+ // tool is what turns it back on, so it has to be reachable. Every other tool
268
+ // refuses `scope-off`, per call, from the file as it stands at that moment.
269
+ const scopesFile = scopesPath(choice.path);
270
+ const scopeRead = readScopes(scopesFile);
271
+ // THE SAME RULE THE SERVER ITSELF WILL APPLY, from the same function: the
272
+ // launch's own `--scope`, else `CLAUDE_PROJECT_DIR` — which this host exports
273
+ // to stdio MCP servers and to hooks alike, and which is what makes this
274
+ // server's scope and the hooks' session scope the same string — else this
275
+ // process's working directory. Resolved once, so the registry is consulted
276
+ // about exactly the directory the server goes on to run in.
277
+ const serverScope = hostScope(opts.scope)?.scope ?? process.cwd();
278
+ const scopeVerdict = lookupScope(scopeRead.registry, serverScope);
279
+ // THE SAME SENTENCE THE HOOK PRINTS, from the same function (#92 review, F2).
280
+ // It was written out inline here and covered only a whole-file failure, so a
281
+ // registry whose ENTRIES were refused — one typo'd `off` among good ones —
282
+ // gave the operator nothing at the one moment this process can speak to them.
283
+ const trouble = describeScopeTrouble(scopeRead, scopesFile);
284
+ if (trouble !== null) process.stderr.write(`${trouble}\n`);
285
+ // ONE line at launch when this directory is not an ordinary one — the only
286
+ // channel this process has to the operator, and the difference between a
287
+ // muted server and a broken one (scar §2.4).
288
+ const stance = effectiveStance(opts.observer, scopeVerdict.mode);
289
+ if (stance !== "on" || scopeVerdict.mode !== "unset") {
290
+ process.stderr.write(
291
+ `[counterparts] scope: ${serverScope} is ${scopeVerdict.mode}` +
292
+ `${scopeVerdict.matched === null ? "" : ` (set by ${scopeVerdict.matched})`}` +
293
+ ` — this server runs ${stance}.\n`,
294
+ );
295
+ }
296
+ const server = openServer({
297
+ ...opts,
298
+ // THE COMBINATION, most restrictive wins: a registry that says `observer`
299
+ // stands the server down even when the configuration did not, and a
300
+ // configuration that already said so is never relaxed by a registry.
301
+ //
302
+ // `off` deliberately does NOT set the observer bit. Under observer every
303
+ // tool stands down INCLUDING `scope`'s write, and `scope` is the one door
304
+ // that has to keep working in an off directory or the switch only turns one
305
+ // way. Nothing is at risk: every other tool refuses `scope-off` one layer
306
+ // above, per call, before it can reach a store.
307
+ observer: stance === "observer" || opts.observer,
308
+ scopesFile,
309
+ embedder,
310
+ });
311
+ try {
312
+ await serveStdio(server, process.stdin, {
313
+ write: (chunk) => {
314
+ process.stdout.write(chunk);
315
+ },
316
+ });
317
+ } finally {
318
+ server.counterpart.close();
319
+ }
320
+ }
321
+
322
+ /** True only when this file is the process entry point — so a test may import
323
+ * `launchOptions` without the server starting itself on stdin. */
324
+ export function isEntryPoint(argv1: string | undefined, url: string): boolean {
325
+ if (argv1 === undefined) return false;
326
+ return resolve(argv1) === fileURLToPath(new URL(url));
327
+ }
328
+
329
+ if (isEntryPoint(process.argv[1], import.meta.url)) {
330
+ void main().then(
331
+ // `process.exitCode` is 1 when the launch refused a named configuration it
332
+ // could not honour; every other path ends 0.
333
+ () => process.exit(process.exitCode === 1 ? 1 : 0),
334
+ (err: unknown) => {
335
+ // A server that cannot start SAYS why, on stderr (stdout is the wire).
336
+ // Before this line, the gap between the two guards — a named configuration
337
+ // that names no store, no `--dir`, no variable — was a bare exit 1 that
338
+ // the host reports as "MCP server failed" and nothing else (#80 review).
339
+ // The explicit-dir guard gets a sentence with THIS entry point's remedy;
340
+ // any other failure gets its own message.
341
+ const detail = err instanceof Error ? err.message : String(err);
342
+ const remedy = `Name the store: --dir <path>, or ${DATA_DIR_ENV}.`;
343
+ process.stderr.write(
344
+ `${describeGuardRefusal(err, remedy) ?? `[counterparts] server did not start: ${detail}`}\n`,
345
+ );
346
+ process.exit(1);
347
+ },
348
+ );
349
+ }