counterparts 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONSTITUTION.md +68 -0
- package/LICENSE +21 -0
- package/README.md +348 -0
- package/docs/ELI5.md +84 -0
- package/docs/QUICKSTART.md +1258 -0
- package/docs/module-map.md +81 -0
- package/package.json +63 -0
- package/src/adapters/claude-code/CONTRACT.md +606 -0
- package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
- package/src/adapters/claude-code/NOTES.md +1055 -0
- package/src/adapters/claude-code/bin/hook.ts +820 -0
- package/src/adapters/claude-code/bin/runner.ts +522 -0
- package/src/adapters/claude-code/config.ts +778 -0
- package/src/adapters/claude-code/credentials.ts +199 -0
- package/src/adapters/claude-code/doctor.ts +2557 -0
- package/src/adapters/claude-code/embed-client.ts +617 -0
- package/src/adapters/claude-code/hooks.ts +2240 -0
- package/src/adapters/claude-code/index.ts +224 -0
- package/src/adapters/claude-code/interpret-client.ts +395 -0
- package/src/adapters/claude-code/page-writer.ts +462 -0
- package/src/adapters/claude-code/primacy.ts +162 -0
- package/src/adapters/claude-code/spawn.ts +241 -0
- package/src/adapters/claude-code/standdown.ts +536 -0
- package/src/adapters/claude-code/transcript.ts +661 -0
- package/src/adapters/claude-code/vectors.ts +415 -0
- package/src/adapters/cli/CONTRACT.md +255 -0
- package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
- package/src/adapters/cli/NOTES.md +936 -0
- package/src/adapters/cli/bin/counterparts.ts +74 -0
- package/src/adapters/cli/commands.ts +6095 -0
- package/src/adapters/cli/export.ts +766 -0
- package/src/adapters/cli/index.ts +103 -0
- package/src/adapters/cli/install.ts +670 -0
- package/src/adapters/cli/removal.ts +1186 -0
- package/src/adapters/cli/repair-dates.ts +659 -0
- package/src/adapters/cli/self-page.ts +229 -0
- package/src/adapters/cli/snapshot.ts +279 -0
- package/src/adapters/cli/start-fresh.ts +1228 -0
- package/src/adapters/config-path.ts +342 -0
- package/src/adapters/dashboard/CONTRACT.md +67 -0
- package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
- package/src/adapters/dashboard/NOTES.md +474 -0
- package/src/adapters/dashboard/activity.ts +121 -0
- package/src/adapters/dashboard/ansi.ts +82 -0
- package/src/adapters/dashboard/bin/dashboard.ts +479 -0
- package/src/adapters/dashboard/browse.ts +298 -0
- package/src/adapters/dashboard/identity.ts +182 -0
- package/src/adapters/dashboard/index.ts +183 -0
- package/src/adapters/dashboard/layout.ts +149 -0
- package/src/adapters/dashboard/registries.ts +291 -0
- package/src/adapters/dashboard/resolve.ts +206 -0
- package/src/adapters/dashboard/source.ts +48 -0
- package/src/adapters/dashboard/status.ts +327 -0
- package/src/adapters/dashboard/stories.ts +194 -0
- package/src/adapters/dashboard/web/app.html +1731 -0
- package/src/adapters/dashboard/web/brain.html +463 -0
- package/src/adapters/dashboard/web/fired.ts +31 -0
- package/src/adapters/dashboard/web/flow.ts +457 -0
- package/src/adapters/dashboard/web/narrate.ts +1042 -0
- package/src/adapters/dashboard/web/reveal.ts +135 -0
- package/src/adapters/dashboard/web/server.ts +287 -0
- package/src/adapters/dashboard/web/views.ts +1744 -0
- package/src/adapters/expansions.ts +569 -0
- package/src/adapters/fired.ts +1580 -0
- package/src/adapters/mcp/CONTRACT.md +240 -0
- package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
- package/src/adapters/mcp/NOTES.md +205 -0
- package/src/adapters/mcp/bin/serve.ts +349 -0
- package/src/adapters/mcp/deliberate.ts +619 -0
- package/src/adapters/mcp/index.ts +101 -0
- package/src/adapters/mcp/protocol.ts +170 -0
- package/src/adapters/mcp/server.ts +1740 -0
- package/src/adapters/mcp/stdio.ts +56 -0
- package/src/adapters/mcp/tools.ts +779 -0
- package/src/adapters/scopes.ts +657 -0
- package/src/adapters/sessions.ts +402 -0
- package/src/adapters/snapshots.ts +1069 -0
- package/src/adapters/stance-env.ts +137 -0
- package/src/core/associate/CONTRACT.md +118 -0
- package/src/core/associate/INTERFACE-GAPS.md +173 -0
- package/src/core/associate/NOTES.md +194 -0
- package/src/core/associate/buffer.ts +66 -0
- package/src/core/associate/edges.ts +188 -0
- package/src/core/associate/index.ts +570 -0
- package/src/core/associate/pending.ts +383 -0
- package/src/core/associate/spread.ts +149 -0
- package/src/core/associate/tunables.ts +123 -0
- package/src/core/bridge.ts +272 -0
- package/src/core/briefing.ts +67 -0
- package/src/core/counterpart.ts +3855 -0
- package/src/core/encode/CONTRACT.md +151 -0
- package/src/core/encode/INTERFACE-GAPS.md +135 -0
- package/src/core/encode/NOTES.md +146 -0
- package/src/core/encode/aliases.ts +71 -0
- package/src/core/encode/battery.ts +284 -0
- package/src/core/encode/chunk.ts +265 -0
- package/src/core/encode/emotion.ts +119 -0
- package/src/core/encode/floor.ts +76 -0
- package/src/core/encode/index.ts +100 -0
- package/src/core/encode/precision.ts +162 -0
- package/src/core/encode/preselect.ts +269 -0
- package/src/core/encode/salience.ts +108 -0
- package/src/core/encode/secrets.ts +265 -0
- package/src/core/encode/tunables.ts +99 -0
- package/src/core/encode/types.ts +286 -0
- package/src/core/encode/words.ts +75 -0
- package/src/core/handoff/CONTRACT.md +199 -0
- package/src/core/handoff/INTERFACE-GAPS.md +166 -0
- package/src/core/handoff/NOTES.md +206 -0
- package/src/core/handoff/index.ts +957 -0
- package/src/core/mint.ts +279 -0
- package/src/core/observer.ts +28 -0
- package/src/core/physics/CONTRACT.md +341 -0
- package/src/core/physics/NOTES.md +155 -0
- package/src/core/physics/clock.ts +51 -0
- package/src/core/physics/index.ts +1054 -0
- package/src/core/prospective/CONTRACT.md +137 -0
- package/src/core/prospective/INTERFACE-GAPS.md +112 -0
- package/src/core/prospective/NOTES.md +160 -0
- package/src/core/prospective/derive.ts +188 -0
- package/src/core/prospective/index.ts +1030 -0
- package/src/core/prospective/tunables.ts +72 -0
- package/src/core/prospective/windows.ts +187 -0
- package/src/core/recall/CONTRACT.md +326 -0
- package/src/core/recall/INTERFACE-GAPS.md +163 -0
- package/src/core/recall/NOTES.md +472 -0
- package/src/core/recall/activate.ts +521 -0
- package/src/core/recall/cues.ts +275 -0
- package/src/core/recall/gate.ts +441 -0
- package/src/core/recall/index.ts +692 -0
- package/src/core/recall/probe.ts +239 -0
- package/src/core/recall/reference.ts +201 -0
- package/src/core/recall/render.ts +285 -0
- package/src/core/recall/session.ts +403 -0
- package/src/core/recall/tunables.ts +329 -0
- package/src/core/remember/CONTRACT.md +293 -0
- package/src/core/remember/INTERFACE-GAPS.md +189 -0
- package/src/core/remember/NOTES.md +373 -0
- package/src/core/remember/fallback.ts +452 -0
- package/src/core/remember/index.ts +103 -0
- package/src/core/remember/owner-strike-seam.ts +479 -0
- package/src/core/remember/proposals.ts +609 -0
- package/src/core/remember/spans.ts +1310 -0
- package/src/core/remember/tunables.ts +111 -0
- package/src/core/remember/updates.ts +198 -0
- package/src/core/retrieval.ts +96 -0
- package/src/core/revision.ts +441 -0
- package/src/core/schemas/CONTRACT.md +190 -0
- package/src/core/schemas/INTERFACE-GAPS.md +172 -0
- package/src/core/schemas/NOTES.md +260 -0
- package/src/core/schemas/aliases.ts +160 -0
- package/src/core/schemas/index.ts +1459 -0
- package/src/core/schemas/tunables.ts +44 -0
- package/src/core/schemas/types.ts +387 -0
- package/src/core/self/CONTRACT.md +459 -0
- package/src/core/self/INTERFACE-GAPS.md +284 -0
- package/src/core/self/NOTES.md +1057 -0
- package/src/core/self/briefing.ts +980 -0
- package/src/core/self/episodes.ts +483 -0
- package/src/core/self/freeze.ts +103 -0
- package/src/core/self/identity.ts +604 -0
- package/src/core/self/index.ts +2130 -0
- package/src/core/self/journal-file.ts +760 -0
- package/src/core/self/page.ts +404 -0
- package/src/core/self/tunables.ts +244 -0
- package/src/core/self/writer.ts +714 -0
- package/src/core/sleep/CONTRACT.md +298 -0
- package/src/core/sleep/INTERFACE-GAPS.md +262 -0
- package/src/core/sleep/NOTES.md +770 -0
- package/src/core/sleep/briefing.ts +86 -0
- package/src/core/sleep/consolidate.ts +241 -0
- package/src/core/sleep/cycle.ts +598 -0
- package/src/core/sleep/decay.ts +237 -0
- package/src/core/sleep/dedup.ts +373 -0
- package/src/core/sleep/index.ts +112 -0
- package/src/core/sleep/log.ts +116 -0
- package/src/core/sleep/markers.ts +164 -0
- package/src/core/sleep/prune.ts +170 -0
- package/src/core/sleep/strength-cache.ts +176 -0
- package/src/core/sleep/tunables.ts +135 -0
- package/src/core/sleep/types.ts +542 -0
- package/src/core/store/CONTRACT.md +446 -0
- package/src/core/store/NOTES.md +1068 -0
- package/src/core/store/cache.ts +709 -0
- package/src/core/store/db.ts +275 -0
- package/src/core/store/errors.ts +134 -0
- package/src/core/store/index.ts +2450 -0
- package/src/core/store/operational.ts +610 -0
- package/src/core/store/owner-op-seam.ts +428 -0
- package/src/core/store/paths.ts +494 -0
- package/src/core/store/prose.ts +165 -0
- package/src/core/store/render.ts +87 -0
- package/src/core/store/walk-seam.ts +78 -0
- package/src/core/types.ts +68 -0
- package/tools/install-loop/run.sh +1063 -0
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The handle-resolution log — what a deliberate expansion BY HANDLE actually
|
|
3
|
+
* reached, left where the credit pass can read it.
|
|
4
|
+
*
|
|
5
|
+
* **The gap it closes (LAUNCH-STATUS G50).** `recall/reference.ts` credits an
|
|
6
|
+
* expansion from the recall tool call's own input, and it resolves NOTHING: an
|
|
7
|
+
* `ids`/`handle` value that is not literally a `mem_…` address is counted
|
|
8
|
+
* `unresolvedHandles` and credits nothing. But `mcp/tools.ts` documents `handle`
|
|
9
|
+
* as "a memory id or exact handle", and `mcp/deliberate.ts#expandHandle` answers
|
|
10
|
+
* a TITLE with the whole body. So the most deliberate thing a session can do —
|
|
11
|
+
* name a memory and read it — earned no credit at all. Under-credit, and
|
|
12
|
+
* invisible: the boundary row said `expanded: 0, unresolvedHandles: 1`.
|
|
13
|
+
*
|
|
14
|
+
* **Why a log and not a session field.** There is no per-session "expanded ids"
|
|
15
|
+
* state the credit pass reads; `claude-code/hooks.ts#creditAtBoundary` takes its
|
|
16
|
+
* expansions from the TRANSCRIPT (`transcript.ts#expansionIdsOf`) and slices
|
|
17
|
+
* them by the same turn cursor capture uses. That is the thing to preserve: the
|
|
18
|
+
* transcript already decides WHICH handles this session used and WHEN. This file
|
|
19
|
+
* supplies only the translation — what the tool resolved that handle to.
|
|
20
|
+
*
|
|
21
|
+
* **That is not the same as "credit is not widened", which is what the first two
|
|
22
|
+
* commits of this leaf claimed.** The transcript says which handle and when; it
|
|
23
|
+
* cannot say whose ANSWER resolved it, and this table is shared. So the honest
|
|
24
|
+
* statement is narrower: the boundary credits a memory only for a handle THIS
|
|
25
|
+
* session's transcript carries, translated through an answer given in THIS
|
|
26
|
+
* PROJECT (`readHandleResolutions`'s scope filter) and no earlier than THIS
|
|
27
|
+
* SESSION's own start (its `since` floor). What remains is stated where the
|
|
28
|
+
* filters are: two sessions running at once in one project directory share one
|
|
29
|
+
* table.
|
|
30
|
+
*
|
|
31
|
+
* A list of ids keyed by session would fail twice over: this host launches the MCP
|
|
32
|
+
* server from a static config, so it is usually UNBOUND and has no session id to
|
|
33
|
+
* key by (mcp/INTERFACE-GAPS §6, §8), and a flat list cannot be positioned
|
|
34
|
+
* against the turn cursor, so an expansion from turn 3 would be re-credited at
|
|
35
|
+
* every later boundary.
|
|
36
|
+
*
|
|
37
|
+
* **Neither adapter imports the other.** The MCP tool writes, the Claude Code
|
|
38
|
+
* hook reads, and they meet here — the same shape, and for the same reason, as
|
|
39
|
+
* `adapters/sessions.ts` (mcp/INTERFACE-GAPS §7: adapters are leaves, a shared
|
|
40
|
+
* sibling is what that rule allows).
|
|
41
|
+
*
|
|
42
|
+
* **Host state, not memory, and it says so on disk.** The record is a HASH of
|
|
43
|
+
* the handle, the id it reached (or `null` — see `HandleResolution.id`), a
|
|
44
|
+
* timestamp, and the scope that asked —
|
|
45
|
+
* deliberately no handle text, because a handle IS a memory's title and
|
|
46
|
+
* `store/paths.ts` classifies `sessions/` as carrying no content (`backup:
|
|
47
|
+
* false`). Hashing is what keeps that classification true without editing it.
|
|
48
|
+
*
|
|
49
|
+
* **And the hash is SALTED, per store** (G58, review of #112). An unsalted
|
|
50
|
+
* sha256 prefix is not the absence of content, it is a MEMBERSHIP ORACLE: a
|
|
51
|
+
* title is short and guessable, so anyone holding the file can hash a candidate
|
|
52
|
+
* and learn whether this memory has been asked for by that name — the exact
|
|
53
|
+
* thing the no-content classification promises the file cannot tell. One random
|
|
54
|
+
* per-store value, written once beside the log, turns the oracle back into what
|
|
55
|
+
* the classification already claims: a key that means nothing outside the store
|
|
56
|
+
* that made it. See `expansionSalt`.
|
|
57
|
+
*
|
|
58
|
+
* **A LOST WRITE IS NOT ALWAYS THE SAFE DIRECTION, and saying it was is what the
|
|
59
|
+
* first draft got wrong.** Losing a RESOLUTION costs one handle's credit —
|
|
60
|
+
* under-credit, the direction this repo errs in on purpose. Losing a REFUSAL is
|
|
61
|
+
* the opposite: the shadow that should have overridden an earlier resolution
|
|
62
|
+
* never lands, and the next asking of that handle is translated through an
|
|
63
|
+
* answer it was never given. So the whole file being lost is under-credit only
|
|
64
|
+
* because the resolutions go with the refusals; a file that can be READ but not
|
|
65
|
+
* APPENDED to is the dangerous shape, and it is one of the three in
|
|
66
|
+
* `readHandleResolutions`'s list. That is why the scope filter, and not the
|
|
67
|
+
* shadow, is the confidentiality boundary here: across projects a lost refusal
|
|
68
|
+
* cannot reach another project's boundary at all. Within ONE project directory
|
|
69
|
+
* it still can, and that residual is recorded rather than papered over.
|
|
70
|
+
*
|
|
71
|
+
* Three rules, mechanized below, inherited from `sessions.ts`:
|
|
72
|
+
*
|
|
73
|
+
* 1. **Nothing here ever throws at a caller.** A tool may not fail on host
|
|
74
|
+
* bookkeeping and a hook may not fail the host. Every entry point returns
|
|
75
|
+
* a falsy answer instead.
|
|
76
|
+
* 2. **Appends are appends.** One line per resolution, `O_APPEND`, so two
|
|
77
|
+
* servers writing at once interleave lines rather than clobbering a file.
|
|
78
|
+
* 3. **Compaction is atomic** — temp file beside the target, then `rename`,
|
|
79
|
+
* so a reader never sees half a log.
|
|
80
|
+
*/
|
|
81
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
82
|
+
import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
83
|
+
import { join } from "node:path";
|
|
84
|
+
|
|
85
|
+
import { SESSIONS_DIR, canonicalScope } from "./sessions.js";
|
|
86
|
+
|
|
87
|
+
/** One file, inside the registry's directory — see the header on placement. */
|
|
88
|
+
export const EXPANSIONS_FILE = "expansions.jsonl";
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* **CAL.** How long a resolution may still translate a handle.
|
|
92
|
+
*
|
|
93
|
+
* It only has to outlive the gap between a `recall` call and the boundary that
|
|
94
|
+
* judges it, and a boundary fires at every Stop. A day is generous by orders of
|
|
95
|
+
* magnitude and still short enough that a renamed memory cannot be credited
|
|
96
|
+
* under last week's title.
|
|
97
|
+
*/
|
|
98
|
+
export const EXPANSION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
99
|
+
|
|
100
|
+
/** **CAL.** Compact when the file passes this. ~90 bytes a line, so ~700 lines. */
|
|
101
|
+
export const EXPANSIONS_MAX_BYTES = 64 * 1024;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* **CAL.** How many live resolutions a compaction keeps.
|
|
105
|
+
*
|
|
106
|
+
* "Newest" means newest by `at`, and that is a correction: it used to mean
|
|
107
|
+
* newest by position in the file, which is not the same thing once a handle is
|
|
108
|
+
* re-resolved. `compactExpansions` sorts before it slices. READING is still
|
|
109
|
+
* arrival order — `readHandleResolutions` takes the LAST line for a key, which
|
|
110
|
+
* is how a shadow appended a moment ago overrides the resolution above it, and
|
|
111
|
+
* why the lines `compactExpansions` splices back in go after the sorted block.
|
|
112
|
+
*/
|
|
113
|
+
export const EXPANSIONS_KEEP = 256;
|
|
114
|
+
|
|
115
|
+
export interface HandleResolution {
|
|
116
|
+
/** `handleKey` of the handle the model passed. Never the handle itself. */
|
|
117
|
+
readonly key: string;
|
|
118
|
+
/**
|
|
119
|
+
* The id `expandHandle` actually reached — or NULL, which is a SHADOW: this
|
|
120
|
+
* handle was asked and answered with nothing, and the newest answer wins.
|
|
121
|
+
*
|
|
122
|
+
* The shadow is not bookkeeping. The log is keyed by handle, not by session,
|
|
123
|
+
* because the resolution is deterministic — but a refusal is not: the owner's
|
|
124
|
+
* own session resolves a confidential title and a stranger's session is told
|
|
125
|
+
* nothing, and without a shadow the stranger's boundary would translate the
|
|
126
|
+
* same handle through the owner's entry and credit a memory it was never
|
|
127
|
+
* shown. Same shape for a title that has since gone ambiguous, or been renamed
|
|
128
|
+
* away.
|
|
129
|
+
*
|
|
130
|
+
* It is NOT the confidentiality boundary, though the first draft said so: a
|
|
131
|
+
* shadow only exists where an answer was given, and three askings get none.
|
|
132
|
+
* `readHandleResolutions`'s scope filter is what covers those.
|
|
133
|
+
*/
|
|
134
|
+
readonly id: string | null;
|
|
135
|
+
readonly at: number;
|
|
136
|
+
/**
|
|
137
|
+
* The project the resolving server was serving, canonical. It IS a filter —
|
|
138
|
+
* see `readHandleResolutions` — and it is the only thing on a record that can
|
|
139
|
+
* say whose asking this answer belongs to. A record without one cannot pass
|
|
140
|
+
* the filter at all.
|
|
141
|
+
*/
|
|
142
|
+
readonly scope?: string;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function expansionsPath(dataDir: string): string {
|
|
146
|
+
return join(dataDir, SESSIONS_DIR, EXPANSIONS_FILE);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The salt file, beside the log — see `expansionSalt`. */
|
|
150
|
+
export const EXPANSIONS_SALT_FILE = "expansions.salt";
|
|
151
|
+
|
|
152
|
+
/** 16 random bytes, hex. Long enough that guessing it is not the cheap attack. */
|
|
153
|
+
const SALT_BYTES = 16;
|
|
154
|
+
|
|
155
|
+
export function expansionsSaltPath(dataDir: string): string {
|
|
156
|
+
return join(dataDir, SESSIONS_DIR, EXPANSIONS_SALT_FILE);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* The store's own handle salt — read if it is there, minted once if it is not.
|
|
161
|
+
*
|
|
162
|
+
* **Per STORE, not per process and not per project.** Both sides of this seam
|
|
163
|
+
* must derive the same key from the same handle, and they are two processes
|
|
164
|
+
* that share nothing but the data directory: the MCP server writes a record and
|
|
165
|
+
* the Stop hook, minutes later, looks one up. So the salt lives on disk beside
|
|
166
|
+
* the log it keys, inside the directory `store/paths.ts` already classifies as
|
|
167
|
+
* host state, and it moves with the store the way the log does.
|
|
168
|
+
*
|
|
169
|
+
* **`wx`, and a re-read after it.** Two servers can reach this at once on a
|
|
170
|
+
* store nobody has expanded a handle in yet; exclusive-create means exactly one
|
|
171
|
+
* of them writes, and the loser reads what the winner wrote instead of racing a
|
|
172
|
+
* second salt over the first. A salt that changed under a live log would orphan
|
|
173
|
+
* every key already in it.
|
|
174
|
+
*
|
|
175
|
+
* **Null is the honest answer, and the callers fail closed on it.** A salt this
|
|
176
|
+
* process cannot read or create is not a reason to fall back to the unsalted
|
|
177
|
+
* key: an unsalted key written into a salted log is both a leak and a record
|
|
178
|
+
* nothing will ever match. `recordHandleResolution` returns false, and
|
|
179
|
+
* `readHandleResolutions` answers `unreadable` — the same shape, and the same
|
|
180
|
+
* reason, as a log this process cannot open.
|
|
181
|
+
*/
|
|
182
|
+
export function expansionSalt(dataDir: string): string | null {
|
|
183
|
+
const path = expansionsSaltPath(dataDir);
|
|
184
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
185
|
+
let salt: string | null = null;
|
|
186
|
+
try {
|
|
187
|
+
salt = readFileSync(path, "utf8").trim();
|
|
188
|
+
} catch {
|
|
189
|
+
/* Not there yet on the first pass — minted below. On the second pass this
|
|
190
|
+
is a file that exists and cannot be read, and there is nothing else to
|
|
191
|
+
try. */
|
|
192
|
+
}
|
|
193
|
+
if (salt !== null) return salt.length === SALT_BYTES * 2 ? salt : null;
|
|
194
|
+
if (attempt === 1) return null;
|
|
195
|
+
try {
|
|
196
|
+
mkdirSync(join(dataDir, SESSIONS_DIR), { recursive: true });
|
|
197
|
+
writeFileSync(path, `${randomBytes(SALT_BYTES).toString("hex")}\n`, {
|
|
198
|
+
encoding: "utf8",
|
|
199
|
+
mode: 0o600,
|
|
200
|
+
flag: "wx",
|
|
201
|
+
});
|
|
202
|
+
} catch {
|
|
203
|
+
/* EEXIST (another process won the race) or a directory this cannot write:
|
|
204
|
+
either way the re-read is what decides. */
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* The lookup key: the handle, trimmed and case-folded, SALTED and hashed.
|
|
212
|
+
*
|
|
213
|
+
* Trim-and-fold is not a normalization of this module's invention — it is
|
|
214
|
+
* EXACTLY the comparison `mcp/deliberate.ts#expandHandle` makes against a title
|
|
215
|
+
* (`title.trim().toLowerCase() === handle.toLowerCase()`, on a handle the
|
|
216
|
+
* dispatcher already trimmed). Two spellings that the resolver treats as the
|
|
217
|
+
* same handle must land on the same key, or the translation misses the case the
|
|
218
|
+
* session actually used.
|
|
219
|
+
*/
|
|
220
|
+
export function handleKey(handle: string, salt: string): string {
|
|
221
|
+
// The separator is what stops `salt + handle` from being ambiguous: without
|
|
222
|
+
// it a salt one character longer and a handle one shorter collide.
|
|
223
|
+
return createHash("sha256")
|
|
224
|
+
.update(salt)
|
|
225
|
+
.update("\u0000")
|
|
226
|
+
.update(handle.trim().toLowerCase())
|
|
227
|
+
.digest("hex")
|
|
228
|
+
.slice(0, 16);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Record what a handle resolved to — an id, or `null` for "this handle was
|
|
233
|
+
* asked and answered with nothing". Returns false on any failure at all.
|
|
234
|
+
*
|
|
235
|
+
* EVERY handle-path outcome is recorded, not only the expansions. A refusal
|
|
236
|
+
* that left no trace would let an earlier session's resolution translate a
|
|
237
|
+
* later session's identical handle, and the later session may have been refused
|
|
238
|
+
* for a reason the earlier one was not — confidentiality above all. Writing the
|
|
239
|
+
* refusal as a shadow is what keeps the log's key (the handle) honest about the
|
|
240
|
+
* thing it is standing in for (what THIS asking reached).
|
|
241
|
+
*/
|
|
242
|
+
export function recordHandleResolution(
|
|
243
|
+
dataDir: string,
|
|
244
|
+
input: { handle: string; id: string | null; scope?: string; at?: number },
|
|
245
|
+
): boolean {
|
|
246
|
+
const handle = input.handle.trim();
|
|
247
|
+
if (handle.length === 0) return false;
|
|
248
|
+
if (input.id !== null && input.id.length === 0) return false;
|
|
249
|
+
// FAIL CLOSED (G58): no salt, no record. An unsalted key in a salted log is a
|
|
250
|
+
// leak AND a line nothing will ever match; a missing line costs one handle's
|
|
251
|
+
// credit, which is the direction this module errs in.
|
|
252
|
+
const salt = expansionSalt(dataDir);
|
|
253
|
+
if (salt === null) return false;
|
|
254
|
+
const record: HandleResolution = {
|
|
255
|
+
key: handleKey(handle, salt),
|
|
256
|
+
id: input.id,
|
|
257
|
+
at: input.at ?? Date.now(),
|
|
258
|
+
...(input.scope === undefined || input.scope.length === 0 ? {} : { scope: canonicalScope(input.scope) }),
|
|
259
|
+
};
|
|
260
|
+
const path = expansionsPath(dataDir);
|
|
261
|
+
try {
|
|
262
|
+
mkdirSync(join(dataDir, SESSIONS_DIR), { recursive: true });
|
|
263
|
+
const line = `${JSON.stringify(record)}\n`;
|
|
264
|
+
let size = 0;
|
|
265
|
+
try {
|
|
266
|
+
size = statSync(path).size;
|
|
267
|
+
} catch {
|
|
268
|
+
/* no file yet */
|
|
269
|
+
}
|
|
270
|
+
if (size + line.length > EXPANSIONS_MAX_BYTES) compactExpansions(path, record.at);
|
|
271
|
+
appendFileSync(path, line, { encoding: "utf8", mode: 0o600 });
|
|
272
|
+
} catch {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
return true;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Every live answer as `key → id | null`, the LAST line for a key winning — the
|
|
280
|
+
* file's own arrival order, which is what makes a shadow appended a moment ago
|
|
281
|
+
* override the resolution above it. (`compactExpansions` sorts by `at` when it
|
|
282
|
+
* decides what to KEEP; that is a different question from what wins.) A `null`
|
|
283
|
+
* value is a shadow and translates nothing (see `HandleResolution.id`).
|
|
284
|
+
*
|
|
285
|
+
* **FILTERED BY SCOPE when `opts.scope` is given, and the caller that credits
|
|
286
|
+
* always gives it.** The first draft of this module refused to filter, reasoning
|
|
287
|
+
* that a RESOLUTION is deterministic — one store, one exact-title match — so it
|
|
288
|
+
* could not matter which project's server performed it, and that the refusals
|
|
289
|
+
* were covered by the shadow. That reasoning has a hole, and it is the one this
|
|
290
|
+
* whole leaf exists to close. The log records the last answer ANYONE got, so a
|
|
291
|
+
* session that got no answer at all still reads someone else's, and there are
|
|
292
|
+
* three routes to that which leave no shadow behind them:
|
|
293
|
+
*
|
|
294
|
+
* - the tool call never reached `expandHandle` (the server was down, or threw
|
|
295
|
+
* before the resolver ran) — nothing is refused, so nothing is recorded;
|
|
296
|
+
* - the call was `recall { handle, question }`, which the dispatcher refuses
|
|
297
|
+
* as `both-arguments` on path `none`, before the handle path exists;
|
|
298
|
+
* - the call WAS refused `handle-confidential-withheld`, and the shadow could
|
|
299
|
+
* not be written (a read-only log, a full disk) — `recordHandleResolution`
|
|
300
|
+
* returns false, because it may not throw at a tool.
|
|
301
|
+
*
|
|
302
|
+
* In each of those the transcript still carries the title, so the boundary still
|
|
303
|
+
* translates it — through the only line in the log, which may be the owner's
|
|
304
|
+
* resolution of a CONFIDENTIAL memory. The shadow cannot cover a case in which
|
|
305
|
+
* nothing was written.
|
|
306
|
+
*
|
|
307
|
+
* The scope is the discriminator that covers all three at once, and it is the
|
|
308
|
+
* same one the server already trusts for session binding (`sessions.ts#sameScope`
|
|
309
|
+
* at `server.ts#requireBoundSession`): a comparison the two adapters disagree
|
|
310
|
+
* about costs a translation, which is under-credit, the safe direction. A record
|
|
311
|
+
* with no scope at all is dropped for the same reason — a line that cannot say
|
|
312
|
+
* where it came from cannot be matched to where this is.
|
|
313
|
+
*
|
|
314
|
+
* Filtering also removes the opposite race the first draft accepted: a
|
|
315
|
+
* stranger's refusal landing between the owner's call and the owner's Stop cost
|
|
316
|
+
* the owner that credit. The stranger's shadow now carries the stranger's scope,
|
|
317
|
+
* so it never reaches the owner's boundary.
|
|
318
|
+
*
|
|
319
|
+
* **`opts.since` is the other half: the asking session's own start.** A project
|
|
320
|
+
* is a place, not a conversation — the same directory carries Monday's session
|
|
321
|
+
* and Tuesday's, and two at once — so the scope alone still lets last week's
|
|
322
|
+
* resolution of a title answer today's typed guess. The credit pass passes the
|
|
323
|
+
* session's `startedAt` from the live-session registry, and a record stamped
|
|
324
|
+
* before it is dropped. Inclusive at the boundary: a resolution in the same
|
|
325
|
+
* millisecond the session was registered is that session's own.
|
|
326
|
+
*
|
|
327
|
+
* What is LEFT is stated rather than hidden: two sessions running CONCURRENTLY
|
|
328
|
+
* in one project directory share one table, so a call that did not reach
|
|
329
|
+
* `expandHandle` can still be translated through a resolution the other one
|
|
330
|
+
* made. And a session with no registry record has no floor at all.
|
|
331
|
+
*/
|
|
332
|
+
export function readHandleResolutions(
|
|
333
|
+
dataDir: string,
|
|
334
|
+
opts: { now?: number; ttlMs?: number; scope?: string; since?: number } = {},
|
|
335
|
+
): HandleResolutions {
|
|
336
|
+
const now = opts.now ?? Date.now();
|
|
337
|
+
const ttl = opts.ttlMs ?? EXPANSION_TTL_MS;
|
|
338
|
+
const since = opts.since;
|
|
339
|
+
// Canonicalized ONCE: `canonicalScope` is a `realpath` syscall, and the file
|
|
340
|
+
// may hold hundreds of lines.
|
|
341
|
+
const want =
|
|
342
|
+
opts.scope === undefined || opts.scope.length === 0 ? null : canonicalScope(opts.scope);
|
|
343
|
+
const map = new Map<string, string | null>();
|
|
344
|
+
// The salt comes FIRST, and its absence is `unreadable` (G58): a map handed
|
|
345
|
+
// back with the wrong salt would key every lookup to nothing, and a zero that
|
|
346
|
+
// cannot say why is the shape I32 is named for.
|
|
347
|
+
const salt = expansionSalt(dataDir);
|
|
348
|
+
if (salt === null) return { map, salt: "", ok: false, reason: "unreadable" };
|
|
349
|
+
let raw: string;
|
|
350
|
+
try {
|
|
351
|
+
raw = readFileSync(expansionsPath(dataDir), "utf8");
|
|
352
|
+
} catch (err) {
|
|
353
|
+
// Absent or unreadable: no translations, which credits exactly what a
|
|
354
|
+
// pre-2026-09-15 store credited. Never a reason to fail a boundary — but
|
|
355
|
+
// the two are told apart, because "no file" and "a file nobody can open"
|
|
356
|
+
// call for different repairs.
|
|
357
|
+
const absent = (err as NodeJS.ErrnoException | null)?.code === "ENOENT";
|
|
358
|
+
return { map, salt, ok: false, reason: absent ? "absent" : "unreadable" };
|
|
359
|
+
}
|
|
360
|
+
const parsed = parseLines(raw);
|
|
361
|
+
for (const record of parsed.records) {
|
|
362
|
+
if (now - record.at > ttl) continue;
|
|
363
|
+
if (want !== null && !scopeMatches(record.scope, want)) continue;
|
|
364
|
+
// The session floor. INCLUSIVE, because a resolution stamped in the same
|
|
365
|
+
// millisecond the session was registered is this session's own.
|
|
366
|
+
if (since !== undefined && record.at < since) continue;
|
|
367
|
+
map.set(record.key, record.id);
|
|
368
|
+
}
|
|
369
|
+
// A file with lines in it and not one of them a record: a writer on the other
|
|
370
|
+
// side of this seam is producing something this side cannot read, which is
|
|
371
|
+
// the one shape a filtered-to-empty read must never be confused with.
|
|
372
|
+
if (parsed.lines > 0 && parsed.records.length === 0) {
|
|
373
|
+
return { map, salt, ok: false, reason: "corrupt" };
|
|
374
|
+
}
|
|
375
|
+
return { map, salt, ok: true, reason: "ok" };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Why the map came back the size it did — the shape `transcript.ts#readTranscript`
|
|
380
|
+
* already uses, and for the reason I32 taught: an empty answer that cannot say
|
|
381
|
+
* whether it was reading an idle table or a dead one is how a broken seam looks
|
|
382
|
+
* exactly like a quiet one on the daily.
|
|
383
|
+
*
|
|
384
|
+
* `ok` — the file was read (an empty live table is still `ok`)
|
|
385
|
+
* `absent` — no file yet; the ordinary state of a store nobody has
|
|
386
|
+
* expanded a handle in
|
|
387
|
+
* `unreadable` — the file is there and this process cannot open it
|
|
388
|
+
* `corrupt` — lines, and not one of them a record
|
|
389
|
+
*/
|
|
390
|
+
export type ExpansionsRead = "ok" | "absent" | "unreadable" | "corrupt";
|
|
391
|
+
|
|
392
|
+
export interface HandleResolutions {
|
|
393
|
+
/** `key → id | null`, filtered by TTL, scope and the session floor. */
|
|
394
|
+
readonly map: Map<string, string | null>;
|
|
395
|
+
/**
|
|
396
|
+
* The store's handle salt, carried so `translateExpansions` can key the
|
|
397
|
+
* caller's raw handles the same way the records were keyed — without a second
|
|
398
|
+
* read, and without a caller that has to remember which store it asked.
|
|
399
|
+
* Empty only when the salt could not be had, and then the map is empty too.
|
|
400
|
+
*/
|
|
401
|
+
readonly salt: string;
|
|
402
|
+
readonly ok: boolean;
|
|
403
|
+
readonly reason: ExpansionsRead;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Records are written canonical, so the string compare answers almost always;
|
|
407
|
+
* the `realpath` is the fallback for a line some other writer left raw. */
|
|
408
|
+
function scopeMatches(scope: string | undefined, want: string): boolean {
|
|
409
|
+
if (scope === undefined) return false;
|
|
410
|
+
return scope === want || canonicalScope(scope) === want;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Translate the raw expansion strings from a transcript slice.
|
|
415
|
+
*
|
|
416
|
+
* A string the log resolved becomes the id it reached; everything else — a
|
|
417
|
+
* handle nobody asked, and a handle whose newest answer is a SHADOW — passes
|
|
418
|
+
* through UNCHANGED, so it still reaches `reference.ts` as itself and still
|
|
419
|
+
* counts `unresolvedHandles`. A guess the tool answered "not-found" must go on
|
|
420
|
+
* being a guess that credited nothing.
|
|
421
|
+
*
|
|
422
|
+
* Literal ids are looked up too, not skipped: `Store.resolve` follows forwarding
|
|
423
|
+
* addresses, so a session that expanded a SUPERSEDED id by name read — and
|
|
424
|
+
* should be credited for — the live head, which is what the tool recorded.
|
|
425
|
+
*/
|
|
426
|
+
export function translateExpansions(
|
|
427
|
+
expansions: readonly string[],
|
|
428
|
+
resolutions: ReadonlyMap<string, string | null>,
|
|
429
|
+
salt: string,
|
|
430
|
+
): string[] {
|
|
431
|
+
if (resolutions.size === 0) return [...expansions];
|
|
432
|
+
return expansions.map((raw) => resolutions.get(handleKey(raw, salt)) ?? raw);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** How many of `expansions` the log actually translated — the boundary row's
|
|
436
|
+
* `resolvedHandles`, and the one number that proves this seam live. */
|
|
437
|
+
export function countTranslated(
|
|
438
|
+
expansions: readonly string[],
|
|
439
|
+
resolutions: ReadonlyMap<string, string | null>,
|
|
440
|
+
salt: string,
|
|
441
|
+
): number {
|
|
442
|
+
let n = 0;
|
|
443
|
+
for (const raw of expansions) {
|
|
444
|
+
const to = resolutions.get(handleKey(raw, salt));
|
|
445
|
+
if (to !== undefined && to !== null && to !== raw.trim()) n += 1;
|
|
446
|
+
}
|
|
447
|
+
return n;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Rewrite the file with the newest live resolutions — newest BY `at` — and
|
|
452
|
+
* nothing else.
|
|
453
|
+
*
|
|
454
|
+
* **The window is narrowed to re-read → rename, and that is not the same as
|
|
455
|
+
* closed.** The first draft read the whole file, wrote the temp copy, and
|
|
456
|
+
* renamed — so a line another process appended anywhere in between was gone,
|
|
457
|
+
* and the compacted file kept the OLDER answer for that handle. For a SHADOW
|
|
458
|
+
* that is not under-credit, it is the leak this module exists to prevent: the
|
|
459
|
+
* refusal disappears and the resolution it was overriding stands again. So the
|
|
460
|
+
* byte length read at the top is kept, the file is re-read from that offset
|
|
461
|
+
* immediately before the rename, and whatever arrived is appended to the temp
|
|
462
|
+
* file (in arrival order, after the sorted block — `readHandleResolutions` takes
|
|
463
|
+
* the last line for a key, so a late shadow still wins).
|
|
464
|
+
*
|
|
465
|
+
* A line appended after THAT read and before the rename is still lost. The
|
|
466
|
+
* window is now two syscalls wide instead of a whole file write, and the
|
|
467
|
+
* alternative — a lock file two long-lived processes share — is a new failure
|
|
468
|
+
* mode in the hot path of a tool that may not fail.
|
|
469
|
+
*
|
|
470
|
+
* Dropping an old entry is safe in the one direction that matters: the map is
|
|
471
|
+
* keyed by handle, so a shadow and the resolution it overrides ARE one entry.
|
|
472
|
+
* Compaction can drop them together; it can never drop the shadow and leave the
|
|
473
|
+
* resolution standing.
|
|
474
|
+
*
|
|
475
|
+
* Exported for `test/sessions.test.ts`, which is the only way to stage the race
|
|
476
|
+
* deterministically — see `duringWindow`.
|
|
477
|
+
*/
|
|
478
|
+
export function compactExpansions(
|
|
479
|
+
path: string,
|
|
480
|
+
now: number,
|
|
481
|
+
/**
|
|
482
|
+
* TEST SEAM, in the same spirit as the `now` injections this repo already
|
|
483
|
+
* uses: called once the temp file is written and before the tail is re-read,
|
|
484
|
+
* so a test can be the other process instead of hoping to be scheduled like
|
|
485
|
+
* one. Nothing in `src/` passes it.
|
|
486
|
+
*/
|
|
487
|
+
duringWindow?: () => void,
|
|
488
|
+
): void {
|
|
489
|
+
let buf: Buffer;
|
|
490
|
+
try {
|
|
491
|
+
buf = readFileSync(path);
|
|
492
|
+
} catch {
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
// BYTES, not characters: the tail is spliced back by offset below.
|
|
496
|
+
const offset = buf.length;
|
|
497
|
+
const live = new Map<string, HandleResolution>();
|
|
498
|
+
for (const record of parseLines(buf.toString("utf8")).records) {
|
|
499
|
+
if (now - record.at > EXPANSION_TTL_MS) continue;
|
|
500
|
+
live.set(record.key, record);
|
|
501
|
+
}
|
|
502
|
+
// SORTED BY `at`, because a Map is keyed by FIRST appearance and the slice is
|
|
503
|
+
// what pays for the bound. A handle resolved long ago and re-resolved a
|
|
504
|
+
// moment ago sits at the TOP of the map with the newest timestamp on it, so
|
|
505
|
+
// an unsorted `slice(-KEEP)` dropped exactly the entry the next boundary was
|
|
506
|
+
// about to ask for and kept 256 staler ones instead. The sort is stable, so
|
|
507
|
+
// records sharing an `at` keep their arrival order.
|
|
508
|
+
const keep = [...live.values()].sort((a, b) => a.at - b.at).slice(-EXPANSIONS_KEEP);
|
|
509
|
+
const tmp = `${path}.${String(process.pid)}.tmp`;
|
|
510
|
+
try {
|
|
511
|
+
writeFileSync(tmp, keep.map((r) => `${JSON.stringify(r)}\n`).join(""), {
|
|
512
|
+
encoding: "utf8",
|
|
513
|
+
mode: 0o600,
|
|
514
|
+
});
|
|
515
|
+
duringWindow?.();
|
|
516
|
+
// Anything appended since the read at the top. A file that SHRANK was
|
|
517
|
+
// replaced by another compaction; splicing its bytes at our offset would
|
|
518
|
+
// produce nonsense, so nothing is carried over.
|
|
519
|
+
const after = readFileSync(path);
|
|
520
|
+
if (after.length > offset) appendFileSync(tmp, after.subarray(offset), { mode: 0o600 });
|
|
521
|
+
renameSync(tmp, path);
|
|
522
|
+
} catch {
|
|
523
|
+
/* the log stays as it was, one compaction late */
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Lines that are not a record are skipped, never thrown over: a half-written
|
|
529
|
+
* line from a host that died mid-append is an ordinary thing to find here.
|
|
530
|
+
*
|
|
531
|
+
* `lines` counts the non-empty ones it was OFFERED, so a caller can tell a file
|
|
532
|
+
* with nothing in it from a file with nothing readable in it.
|
|
533
|
+
*/
|
|
534
|
+
function parseLines(raw: string): { records: HandleResolution[]; lines: number } {
|
|
535
|
+
const records: HandleResolution[] = [];
|
|
536
|
+
let lines = 0;
|
|
537
|
+
for (const line of raw.split("\n")) {
|
|
538
|
+
if (line.trim().length === 0) continue;
|
|
539
|
+
lines += 1;
|
|
540
|
+
let parsed: unknown;
|
|
541
|
+
try {
|
|
542
|
+
parsed = JSON.parse(line);
|
|
543
|
+
} catch {
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
const record = parseRecord(parsed);
|
|
547
|
+
if (record !== null) records.push(record);
|
|
548
|
+
}
|
|
549
|
+
return { records, lines };
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function parseRecord(raw: unknown): HandleResolution | null {
|
|
553
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
554
|
+
const rec = raw as Record<string, unknown>;
|
|
555
|
+
const key = rec["key"];
|
|
556
|
+
const id = rec["id"];
|
|
557
|
+
const at = rec["at"];
|
|
558
|
+
if (typeof key !== "string" || key.length === 0) return null;
|
|
559
|
+
// `null` is a RECORD, not a missing field: it is the shadow a refusal leaves.
|
|
560
|
+
if (id !== null && (typeof id !== "string" || id.length === 0)) return null;
|
|
561
|
+
if (typeof at !== "number" || !Number.isFinite(at)) return null;
|
|
562
|
+
const scope = rec["scope"];
|
|
563
|
+
return {
|
|
564
|
+
key,
|
|
565
|
+
id,
|
|
566
|
+
at,
|
|
567
|
+
...(typeof scope === "string" && scope.length > 0 ? { scope } : {}),
|
|
568
|
+
};
|
|
569
|
+
}
|